/
index.js
201 lines (176 loc) · 5.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
const AWS = require("aws-sdk");
const { generateKeyPair } = require("crypto");
const region = process.env.REGION;
const secretName = process.env.SECRET_NAME;
const keyGroupId = process.env.KEY_GROUP_ID;
const prefix = process.env.PREFIX;
const dummyKeyName = prefix + "-DUMMY_KEY";
const key1Name = prefix + "-KEY_1";
const key2Name = prefix + "-KEY_2";
const ssmParmeterName = process.env.SSM_PARAM;
const cloudFrontClient = new AWS.CloudFront({ region });
const ssm = new AWS.SSM({ region: "us-east-1" });
async function createAndUploadKeyPair() {
const { privateKey, publicKey } = await getRSAKeyPair();
const secretsManagerClient = new AWS.SecretsManager({ region });
const keys = await listPublicKeys();
const key1 = keys.find((key) => key.Name === key1Name);
const key2 = keys.find((key) => key.Name === key2Name);
const dummyKey = keys.find((key) => key.Name === dummyKeyName);
let keyToCreate = key1Name;
let keyIdToKeep;
if (key1 && key2) {
const key1WithEtag = await getPublicKey(key1.Id);
const key2WithEtag = await getPublicKey(key2.Id);
let keyToDelete = key1WithEtag;
let itemsInKeyGroup = [key2.Id];
// Pick the oldest one to remove
if (
key1WithEtag.PublicKey.CreatedTime > key2WithEtag.PublicKey.CreatedTime
) {
keyToDelete = key2WithEtag;
keyToCreate = key2Name;
keyIdToKeep = key1WithEtag.PublicKey.Id;
itemsInKeyGroup = [key1.Id];
} else {
keyIdToKeep = key2WithEtag.PublicKey.Id;
}
// Removes the key from keygroup before removal
await updateKeyGroup(itemsInKeyGroup);
const params = {
Id: keyToDelete.PublicKey.Id,
IfMatch: keyToDelete.ETag,
};
await cloudFrontClient.deletePublicKey(params).promise();
console.log(
`Old public key "${keyToDelete.PublicKey.PublicKeyConfig.Name}" "${keyToDelete.PublicKey.Id}" deleted.`
);
} else if (key1) {
keyToCreate = key2Name;
}
const publicKeyConfig = {
PublicKeyConfig: {
CallerReference: Date.now().toString(),
Name: keyToCreate,
EncodedKey: publicKey,
},
};
const newKey = await cloudFrontClient
.createPublicKey(publicKeyConfig)
.promise();
console.log(
`New public key "${keyToCreate}" "${newKey.PublicKey.Id}" created.`
);
const items = keyIdToKeep
? [keyIdToKeep, newKey.PublicKey.Id]
: [newKey.PublicKey.Id];
// Final update to keygroup with newly created key
await updateKeyGroup(items);
await secretsManagerClient
.updateSecret({
SecretId: secretName,
SecretString: privateKey,
})
.promise();
await updateParameter(ssmParmeterName, newKey.PublicKey.Id);
// If we have updated through Terraform there will be a dummy key.
// Its not used, so we remove it.
if (dummyKey) {
const dummyKeyWithEtag = await getPublicKey(dummyKey.Id);
const params = {
Id: dummyKey.Id,
IfMatch: dummyKeyWithEtag.ETag,
};
await cloudFrontClient.deletePublicKey(params).promise();
console.log(
`Public key dummy "${dummyKey.Name}" "${dummyKey.Id}" deleted.`
);
}
}
async function updateParameter(name, privateKey) {
var params = {
Name: name,
Value: privateKey,
Type: "String",
Overwrite: true,
Tier: "Standard",
};
const res = await ssm.putParameter(params).promise();
}
async function updateKeyGroup(items) {
const keygroup = await cloudFrontClient
.getKeyGroup({ Id: keyGroupId })
.promise();
const trustedKeyConfig = {
KeyGroupConfig: {
Items: items,
Name: keygroup.KeyGroup.KeyGroupConfig.Name,
},
Id: keygroup.KeyGroup.Id,
IfMatch: keygroup.ETag,
};
await cloudFrontClient.updateKeyGroup(trustedKeyConfig).promise();
console.log(
`CloudFront trusted key group "${keyGroupId}" is updated with the public key items "${JSON.stringify(
items
)}".`
);
}
async function listPublicKeys() {
return new Promise((resolve, reject) => {
cloudFrontClient.listPublicKeys(null, function (err, data) {
if (err) {
console.log(err, err.stack);
reject(err);
} else {
resolve(data.PublicKeyList.Items);
}
});
});
}
async function getPublicKey(id) {
return new Promise((resolve, reject) => {
cloudFrontClient.getPublicKey({ Id: id }, function (err, data) {
if (err) {
console.log(err, err.stack);
reject(err);
} else {
resolve(data);
}
});
});
}
async function getRSAKeyPair() {
return new Promise((resolve, reject) => {
generateKeyPair(
"rsa",
{
modulusLength: 2048,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
},
},
(err, publicKey, privateKey) => {
if (!err) {
resolve({ publicKey, privateKey });
} else {
console.log("Err is: ", err);
reject(err);
}
}
);
});
}
exports.handler = async (event, context, callback) => {
try {
await createAndUploadKeyPair();
} catch (err) {
console.log(err);
callback(err);
}
};