-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkms.js
More file actions
258 lines (216 loc) · 6.78 KB
/
kms.js
File metadata and controls
258 lines (216 loc) · 6.78 KB
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/**
* This server generates Key Encryption Keys (KEKs) with their IDs, and it needs to store them somewhere.
* This file defines functions for storing KEKs.
*
* Therefore, a simple in-memory KMS implementation has been defined using a JavaScript Map.
*
* - It is the cheapest and easiest implementation and works fine if the server is always on.
* - This implementation does not persist KEKs, so all KEKs will be lost when the server restarts.
* - In-memory implementations do not work well in distributed systems (e.g. multiple server instances behind a load balancer).
* - In-memory implementations do not work well in serverless environments, because they are constantly closing and opening.
* - Redis, DynamoDB or similar are the best alternatives.
*
* A custom key rotation implementation with envelope encryption with a specialized KMS is recommended.
*/
import { BASE64URL_OPTIONS } from "#src/lib/base64";
import { KEK_ID_LENGTH } from "#src/lib/computed";
import { createKek, unwrapKey, WRAPPED_DEK_BYTES } from "#src/lib/crypto/symmetric/kek";
import { generateRandomId, isBase64UrlIdValid } from "#src/lib/id";
/**
* @typedef {[expires:number,rotate:number,key:CryptoKey]} KeyData
*/
const EXPIRES = 0;
const ROTATE = 1;
const KEY = 2;
const ROTATE_TIME = 7776000000; // 90 days in miliseconds.
/**
* @type {number}
*/
export const KEK_ID_BYTES = 12;
/**
* @type {number}
*/
export const MAX_KMS_STORE_ATTEMPTS = 3;
/**
* @async
* @function
* @param {number} ageMsAfterRotation - In milliseconds.
* @param {string} name - Give it a name. Useful when displaying warnings.
* @returns {Promise<KMS>}
*/
export default async function getKms(ageMsAfterRotation, name) {
/**
* Implement external key retrieval here and pass them in the `Map` storage.
*/
return new KMS(ageMsAfterRotation, name, new Map());
}
class KMS {
#ageMsAfterRotation;
#name;
/**
* Remember that looping Maps and deleting the current entry is safe in JavaScript.
*/
#storage;
/**
* @param {number} ageMsAfterRotation - In milliseconds.
* @param {string} name - Give it a name. Useful when displaying warnings.
* @param {Map<string,KeyData>} storage
*/
constructor(ageMsAfterRotation, name, storage) {
this.#ageMsAfterRotation = ageMsAfterRotation;
this.#name = name;
this.#storage = storage;
}
/**
* Retrieves an encryption key by its ID.
*
* @async
* @function getCurrentId
* @return {Promise<string>} A promise that resolves to the `CurrentKey`.
*/
async getCurrentId() {
/**
* @type {([string,KeyData]|undefined)}
*/
let currentKeyEntry;
const dateNow = Date.now();
/**
* Manually clean up expired keys, as this implementation cannot automatically delete them.
*/
for (const keyEntry of this.#storage) {
const expires = keyEntry[1][EXPIRES];
if (expires <= dateNow) {
this.#storage.delete(keyEntry[0]);
} else if (!currentKeyEntry || expires < currentKeyEntry[1][EXPIRES]) {
currentKeyEntry = keyEntry;
}
}
if (!currentKeyEntry || currentKeyEntry[1][ROTATE] <= dateNow) {
return await this.pushNewKey();
}
return currentKeyEntry[0];
}
/**
* Retrieves an encryption key by its ID.
*
* @async
* @function get
* @param {string} keyId - The ID of the encryption key to retrieve.
* @return {Promise<CryptoKey|undefined>} A promise that resolves to the `CryptoKey` if found, otherwise `undefined`.
*/
async get(keyId) {
if (!isBase64UrlIdValid(keyId, KEK_ID_LENGTH)) {
return;
}
const keyData = this.#storage.get(keyId);
if (!keyData) {
return;
}
if (keyData[EXPIRES] <= Date.now()) {
this.#storage.delete(keyId);
return;
}
return keyData[KEY];
}
/**
* @async
* @function getDek
* @param {string} keyId
* @param {string} wrappedDekString
* @returns {Promise<CryptoKey|undefined>}
*/
async getDek(keyId, wrappedDekString) {
const kek = await this.get(keyId);
if (!kek) {
return;
}
/**
* @type {Uint8Array<ArrayBuffer>}
*/
let wrappedDek;
try {
wrappedDek = Uint8Array.fromBase64(wrappedDekString, BASE64URL_OPTIONS);
} catch {
return;
}
if (wrappedDek.length !== WRAPPED_DEK_BYTES) {
return;
}
return await unwrapKey(wrappedDek, kek);
}
/**
* Pushes a new encryption key to the KMS.
*
* @async
* @function pushNewKey
* @return {Promise<string>} The ID of the stored key.
*/
async pushNewKey() {
let newKeyId = "";
let i = 0;
do {
newKeyId = generateRandomId(KEK_ID_BYTES).toBase64(BASE64URL_OPTIONS);
i++;
} while (!(await this.store(newKeyId, await createKek())) && i < MAX_KMS_STORE_ATTEMPTS);
if (i >= MAX_KMS_STORE_ATTEMPTS) {
throw new Error("Too many attempts to store a KEK in KMS: " + this.#name);
}
return newKeyId;
}
/**
* Retrieves an encryption key by its ID.
*
* @async
* @function rotate
* @param {string} keyId - The ID of the encryption key that is suspicious of being leaked.
* @return {Promise<string>} The ID of the stored key or an emptry string if the key rotation was not triggered.
*/
async rotate(keyId) {
/**
* @type {string}
*/
let newKeyId = "";
if (keyId === (await this.getCurrentId())) {
const prefix = this.#name + "/" + keyId + ": ";
console.warn(prefix + "An emergency rotation of the current KEK has been initiated.");
newKeyId = await this.pushNewKey();
console.log(prefix + "KEK rotation completed.");
}
/**
* Get or generate the key first to ensure that when the `keyId` is deleted, there is at least one key in the KMS.
*/
this.#storage.delete(keyId);
return newKeyId;
}
/**
* Stores an encryption key with the given ID and expiration time.
*
* If the key could not be saved due to a technical error, an error should be thrown.
*
* @async
* @function store
* @param {string} keyId - The ID of the encryption key to store.
* @param {CryptoKey} key - The encryption key to store.
* @return {Promise<boolean>} Whether the key was stored successfully.
*/
async store(keyId, key) {
const dateNow = Date.now();
/**
* New keys should not have the same ID as existing ones (including expired ones).
*/
if (this.#storage.has(keyId)) {
return false;
}
/**
* Manually clean up expired keys, as this implementation cannot automatically delete them.
*/
for (const [currentKeyId, [currentExpires]] of this.#storage) {
if (currentExpires <= dateNow) {
this.#storage.delete(currentKeyId);
}
}
const rotate = dateNow + ROTATE_TIME;
this.#storage.set(keyId, [rotate + this.#ageMsAfterRotation, rotate, key]);
return true;
}
}