@friggframework/core 2.0.0--canary.744.e18e27f.0 → 2.0.0--canary.745.0209482d.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,119 @@
1
+ const {
2
+ EncryptedFieldStoreInterface,
3
+ assertIdentifiers,
4
+ getPath,
5
+ } = require('./encrypted-field-store-interface');
6
+
7
+ const JSON_TYPES = new Set(['jsonb', 'json']);
8
+ const INTEGER_TYPES = new Set(['integer', 'bigint', 'smallint']);
9
+
10
+ /**
11
+ * PostgreSQL EncryptedFieldStore. Raw SQL ($queryRawUnsafe /
12
+ * $executeRawUnsafe), which the field-encryption extension does not
13
+ * intercept. Table and column names are the Prisma model and field names
14
+ * (the prisma-postgresql schema maps none of them); identifiers are checked
15
+ * before they are quoted into SQL, values are always bound parameters.
16
+ */
17
+ class EncryptedFieldStorePostgres extends EncryptedFieldStoreInterface {
18
+ constructor({ prismaClient } = {}) {
19
+ super();
20
+ this.prisma = prismaClient || require('../prisma').prisma;
21
+ this.columnTypes = new Map();
22
+ }
23
+
24
+ async _columns(model) {
25
+ if (!this.columnTypes.has(model)) {
26
+ const rows = await this.prisma.$queryRawUnsafe(
27
+ `SELECT column_name, data_type FROM information_schema.columns
28
+ WHERE table_schema = current_schema() AND table_name = $1`,
29
+ model
30
+ );
31
+ if (!rows.length) {
32
+ throw new Error(`Table "${model}" not found`);
33
+ }
34
+ this.columnTypes.set(
35
+ model,
36
+ new Map(rows.map((row) => [row.column_name, row.data_type]))
37
+ );
38
+ }
39
+ return this.columnTypes.get(model);
40
+ }
41
+
42
+ _id(columns, id) {
43
+ return INTEGER_TYPES.has(columns.get('id')) ? Number(id) : String(id);
44
+ }
45
+
46
+ async scan(model, paths, { after = null, limit }) {
47
+ assertIdentifiers(model, paths);
48
+ const columns = await this._columns(model);
49
+ const selected = [...new Set(paths.map((path) => path.split('.')[0]))];
50
+ const missing = selected.find((column) => !columns.has(column));
51
+ if (missing) {
52
+ throw new Error(`Column "${model}"."${missing}" not found`);
53
+ }
54
+ const select = ['id', ...selected].map((c) => `"${c}"`).join(', ');
55
+ const rows =
56
+ after === null || after === undefined
57
+ ? await this.prisma.$queryRawUnsafe(
58
+ `SELECT ${select} FROM "${model}" ORDER BY "id" LIMIT $1`,
59
+ limit
60
+ )
61
+ : await this.prisma.$queryRawUnsafe(
62
+ `SELECT ${select} FROM "${model}" WHERE "id" > $1 ORDER BY "id" LIMIT $2`,
63
+ this._id(columns, after),
64
+ limit
65
+ );
66
+ return rows.map((row) => ({
67
+ id: row.id,
68
+ values: Object.fromEntries(
69
+ paths.map((path) => [path, getPath(row, path)])
70
+ ),
71
+ }));
72
+ }
73
+
74
+ async replaceIfUnchanged(model, id, path, expected, replacement) {
75
+ assertIdentifiers(model, [path]);
76
+ const columns = await this._columns(model);
77
+ const [column, ...nested] = path.split('.');
78
+ const type = columns.get(column);
79
+ if (!type) {
80
+ throw new Error(`Column "${model}"."${column}" not found`);
81
+ }
82
+ const rowId = this._id(columns, id);
83
+
84
+ let count;
85
+ if (nested.length) {
86
+ if (type !== 'jsonb') {
87
+ throw new Error(`Column "${model}"."${column}" is not jsonb`);
88
+ }
89
+ count = await this.prisma.$executeRawUnsafe(
90
+ `UPDATE "${model}"
91
+ SET "${column}" = jsonb_set("${column}", $4::text[], to_jsonb($1::text))
92
+ WHERE "id" = $2 AND "${column}" #>> $4::text[] = $3`,
93
+ replacement,
94
+ rowId,
95
+ expected,
96
+ nested
97
+ );
98
+ } else if (JSON_TYPES.has(type)) {
99
+ count = await this.prisma.$executeRawUnsafe(
100
+ `UPDATE "${model}" SET "${column}" = to_jsonb($1::text)
101
+ WHERE "id" = $2 AND "${column}" #>> '{}' = $3`,
102
+ replacement,
103
+ rowId,
104
+ expected
105
+ );
106
+ } else {
107
+ count = await this.prisma.$executeRawUnsafe(
108
+ `UPDATE "${model}" SET "${column}" = $1
109
+ WHERE "id" = $2 AND "${column}" = $3`,
110
+ replacement,
111
+ rowId,
112
+ expected
113
+ );
114
+ }
115
+ return count === 1;
116
+ }
117
+ }
118
+
119
+ module.exports = { EncryptedFieldStorePostgres };
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Rewrites stored ciphertext that Cryptor.needsReencryption() flags: values
3
+ * in an older envelope version (v1, aes-256-ctr) and, in AES mode, values
4
+ * under DEPRECATED_AES_KEY_ID. Each one is decrypted and encrypted again with
5
+ * the current envelope version and key.
6
+ *
7
+ * Works on one page of one model per call, in id order, so a caller can run
8
+ * it in bounded steps and resume from `next` (null after an empty page). A value is replaced only if it
9
+ * is still the ciphertext that was read (compare-and-swap), so a concurrent
10
+ * write by the app always wins.
11
+ *
12
+ * The plaintext is the stored string, as it was serialized when written; it
13
+ * is not parsed, so legacy raw strings and JSON-encoded values keep their
14
+ * exact form.
15
+ */
16
+ const MAX_LIMIT = 500;
17
+
18
+ class ReencryptLegacyFieldsUseCase {
19
+ /**
20
+ * @param {Object} params
21
+ * @param {import('../repositories/encrypted-field-store-interface').EncryptedFieldStoreInterface} params.encryptedFieldStore
22
+ * @param {import('../../encrypt/Cryptor').Cryptor} params.cryptor
23
+ * @param {(model: string) => string[]} params.getFieldPaths encrypted field paths of a model
24
+ */
25
+ constructor({ encryptedFieldStore, cryptor, getFieldPaths }) {
26
+ this.store = encryptedFieldStore;
27
+ this.cryptor = cryptor;
28
+ this.getFieldPaths = getFieldPaths;
29
+ }
30
+
31
+ /**
32
+ * @param {Object} params
33
+ * @param {string} params.model Prisma model name, e.g. 'Credential'
34
+ * @param {string|number|null} [params.after] id to resume after (the `next` of the previous page)
35
+ * @param {number} [params.limit] rows per page, 1..500
36
+ * @param {boolean} [params.dryRun] count without writing
37
+ */
38
+ async execute({ model, after = null, limit = 100, dryRun = false }) {
39
+ // While the upgrade switch writes v1, a rewrite would write v1 again
40
+ // (and in AES mode turn a v2 value under the old key into v1).
41
+ if (
42
+ typeof this.cryptor.getWriteVersion === 'function' &&
43
+ this.cryptor.getWriteVersion() !== 'v2'
44
+ ) {
45
+ throw new Error(
46
+ 'Re-encryption writes v2 values: remove FRIGG_ENCRYPTION_WRITE_VERSION=v1 and deploy before you run it'
47
+ );
48
+ }
49
+ const paths = this.getFieldPaths(model);
50
+ if (!paths.length) {
51
+ throw new Error(`Model ${model} has no encrypted fields`);
52
+ }
53
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
54
+ throw new Error(`limit must be an integer from 1 to ${MAX_LIMIT}`);
55
+ }
56
+
57
+ const rows = await this.store.scan(model, paths, { after, limit });
58
+ const result = {
59
+ model,
60
+ dryRun,
61
+ scanned: rows.length,
62
+ needingReencryption: 0,
63
+ reencrypted: 0,
64
+ changedConcurrently: 0,
65
+ failed: [],
66
+ // Only an empty page ends the scan. A store can return fewer rows
67
+ // than `limit` before the end: MongoDB caps one batch at 16 MB.
68
+ next: rows.length > 0 ? rows[rows.length - 1].id : null,
69
+ };
70
+
71
+ for (const row of rows) {
72
+ for (const path of paths) {
73
+ const stored = row.values[path];
74
+ if (!this.cryptor.needsReencryption(stored)) {
75
+ continue;
76
+ }
77
+ result.needingReencryption += 1;
78
+ if (dryRun) {
79
+ continue;
80
+ }
81
+ let replacement;
82
+ try {
83
+ replacement = await this.cryptor.encrypt(
84
+ await this.cryptor.decrypt(stored)
85
+ );
86
+ } catch (error) {
87
+ // Cryptor errors carry no key or plaintext material.
88
+ result.failed.push({
89
+ id: row.id,
90
+ path,
91
+ reason: error.message,
92
+ });
93
+ continue;
94
+ }
95
+ const replaced = await this.store.replaceIfUnchanged(
96
+ model,
97
+ row.id,
98
+ path,
99
+ stored,
100
+ replacement
101
+ );
102
+ if (replaced) {
103
+ result.reencrypted += 1;
104
+ } else {
105
+ result.changedConcurrently += 1;
106
+ }
107
+ }
108
+ }
109
+
110
+ return result;
111
+ }
112
+ }
113
+
114
+ module.exports = { ReencryptLegacyFieldsUseCase, MAX_LIMIT };
@@ -5,10 +5,28 @@
5
5
  * Provides envelope encryption pattern for field-level encryption.
6
6
  *
7
7
  * Envelope Encryption Pattern:
8
- * 1. Generate Data Encryption Key (DEK) via KMS or locally
9
- * 2. Encrypt field value with DEK using AES-256-CTR
10
- * 3. Encrypt DEK with Master Key (KMS CMK or AES_KEY)
11
- * 4. Return format: "keyId:encryptedText:encryptedKey"
8
+ * 1. Generate a 32-byte Data Encryption Key (DEK), via KMS GenerateDataKey
9
+ * (AES_256) or locally with crypto.randomBytes(32)
10
+ * 2. Encrypt the field value with the DEK using AES-256-GCM
11
+ * 3. Encrypt the DEK with the master key: the KMS key, or AES_KEY with
12
+ * AES-256-GCM
13
+ * 4. Return a versioned envelope (see ./envelope.js):
14
+ * "v2:keyId:iv:ciphertext:tag:encryptedKey"
15
+ *
16
+ * Crypto-agility: the version marker names the algorithms. decrypt() reads
17
+ * every version it knows (v1 aes-256-ctr values written before v2 included);
18
+ * encrypt() writes the current one. needsReencryption() tells a migration
19
+ * which stored values to rewrite.
20
+ *
21
+ * Upgrade of a running app: a core before v2 reads a v2 value as plaintext.
22
+ * For the deploy that brings v2 into an app with old functions still
23
+ * running, set FRIGG_ENCRYPTION_WRITE_VERSION=v1 so new code writes what old
24
+ * code reads; remove it on the next deploy. decrypt() also repairs a value
25
+ * that old code already encrypted twice (v1 around v2).
26
+ *
27
+ * KMS mode binds v2 data keys to the encryption context
28
+ * {"frigg:envelope": "v2"}, so a v2 value cannot be rewritten as a v1 value
29
+ * (which has no authentication tag) and still decrypt.
12
30
  *
13
31
  * Benefits:
14
32
  * - Reduces KMS API calls (unique DEK per operation)
@@ -17,12 +35,52 @@
17
35
  */
18
36
 
19
37
  const crypto = require('crypto');
20
- const { KMSClient, GenerateDataKeyCommand, DecryptCommand } = require('@aws-sdk/client-kms');
38
+ const {
39
+ KMSClient,
40
+ GenerateDataKeyCommand,
41
+ DecryptCommand,
42
+ } = require('@aws-sdk/client-kms');
21
43
  const aes = require('./aes');
44
+ const { parseAesKey, KEY_BYTES } = require('./key-material');
45
+ const {
46
+ CURRENT_ENVELOPE_VERSION,
47
+ getEnvelopeVersion,
48
+ parseEnvelope,
49
+ formatEnvelope,
50
+ v2Header,
51
+ } = require('./envelope');
52
+ const { getLogger } = require('../logs');
53
+
54
+ const log = getLogger('frigg.encrypt');
22
55
 
23
56
  const DATA_KEY_TTL_MS = 60 * 60 * 1000;
24
57
  const DATA_KEY_CACHE_MAX_ENTRIES = 10000;
25
58
 
59
+ const toBase64 = (value) => Buffer.from(value).toString('base64');
60
+
61
+ /** KMS encryption context of v2 data keys. v1 data keys have none. */
62
+ const KMS_CONTEXT = { v2: { 'frigg:envelope': 'v2' } };
63
+
64
+ const WRITE_VERSIONS = ['v1', 'v2'];
65
+
66
+ /** The envelope version encrypt() writes: v2, or v1 during an upgrade. */
67
+ function getWriteVersion() {
68
+ const value = process.env.FRIGG_ENCRYPTION_WRITE_VERSION;
69
+ if (value === undefined || value === '') {
70
+ return CURRENT_ENVELOPE_VERSION;
71
+ }
72
+ if (!WRITE_VERSIONS.includes(value)) {
73
+ throw new Error(
74
+ `FRIGG_ENCRYPTION_WRITE_VERSION must be v1 or v2 (got "${value}")`
75
+ );
76
+ }
77
+ return value;
78
+ }
79
+
80
+ /** v1 value: keyId:ivHex:ciphertextHex:encryptedKey (aes-256-ctr). */
81
+ const formatV1 = ({ keyIdB64, text, dataKey, encryptedKey }) =>
82
+ `${keyIdB64}:${aes.encryptCtr(text, dataKey)}:${encryptedKey}`;
83
+
26
84
  function createKmsDataKeys() {
27
85
  let client = null;
28
86
  const cache = new Map();
@@ -32,65 +90,79 @@ function createKmsDataKeys() {
32
90
  return client;
33
91
  };
34
92
 
35
- const remember = (encryptedKeyB64, promise) => {
36
- cache.delete(encryptedKeyB64);
93
+ // Keyed by envelope version and wrapped key: a v2 data key must never
94
+ // serve a v1 value (that would skip the KMS context check).
95
+ const cacheKey = (version, encryptedKeyB64) =>
96
+ `${version}:${encryptedKeyB64}`;
97
+
98
+ const remember = (key, promise) => {
99
+ cache.delete(key);
37
100
  if (cache.size >= DATA_KEY_CACHE_MAX_ENTRIES) {
38
101
  cache.delete(cache.keys().next().value);
39
102
  }
40
- cache.set(encryptedKeyB64, {
103
+ cache.set(key, {
41
104
  promise,
42
105
  expiresAt: Date.now() + DATA_KEY_TTL_MS,
43
106
  });
44
107
  };
45
108
 
46
- const lookup = (encryptedKeyB64) => {
47
- const entry = cache.get(encryptedKeyB64);
109
+ const lookup = (key) => {
110
+ const entry = cache.get(key);
48
111
  if (!entry) {
49
112
  return undefined;
50
113
  }
51
- cache.delete(encryptedKeyB64);
114
+ cache.delete(key);
52
115
  if (entry.expiresAt <= Date.now()) {
53
116
  return undefined;
54
117
  }
55
- cache.set(encryptedKeyB64, entry);
118
+ cache.set(key, entry);
56
119
  return entry.promise;
57
120
  };
58
121
 
59
122
  return {
60
- async generate() {
123
+ async generate(version = CURRENT_ENVELOPE_VERSION) {
124
+ const context = KMS_CONTEXT[version];
61
125
  const dataKey = await getClient().send(
62
126
  new GenerateDataKeyCommand({
63
127
  KeyId: process.env.KMS_KEY_ARN,
64
128
  KeySpec: 'AES_256',
129
+ ...(context && { EncryptionContext: context }),
65
130
  })
66
131
  );
67
- const encryptedKey = Buffer.from(dataKey.CiphertextBlob).toString('base64');
68
- remember(encryptedKey, Promise.resolve(dataKey.Plaintext));
132
+ const encryptedKey = toBase64(dataKey.CiphertextBlob);
133
+ remember(
134
+ cacheKey(version, encryptedKey),
135
+ Promise.resolve(dataKey.Plaintext)
136
+ );
69
137
  return {
70
- keyId: Buffer.from(dataKey.KeyId).toString('base64'),
138
+ keyIdB64: toBase64(dataKey.KeyId),
71
139
  encryptedKey,
72
140
  plaintext: dataKey.Plaintext,
73
141
  };
74
142
  },
75
143
 
76
- async decrypt(keyId, encryptedKeyB64) {
77
- const cached = lookup(encryptedKeyB64);
144
+ /** v2 data keys unwrap only with the v2 context, v1 keys without. */
145
+ async decrypt({ version, keyId, encryptedKey: encryptedKeyB64 }) {
146
+ const key = cacheKey(version, encryptedKeyB64);
147
+ const cached = lookup(key);
78
148
  if (cached) {
79
149
  return cached;
80
150
  }
81
151
 
152
+ const context = KMS_CONTEXT[version];
82
153
  const pending = getClient()
83
154
  .send(
84
155
  new DecryptCommand({
85
156
  KeyId: keyId,
86
157
  CiphertextBlob: Buffer.from(encryptedKeyB64, 'base64'),
158
+ ...(context && { EncryptionContext: context }),
87
159
  })
88
160
  )
89
161
  .then((dataKey) => dataKey.Plaintext);
90
- remember(encryptedKeyB64, pending);
162
+ remember(key, pending);
91
163
  pending.catch(() => {
92
- if (cache.get(encryptedKeyB64)?.promise === pending) {
93
- cache.delete(encryptedKeyB64);
164
+ if (cache.get(key)?.promise === pending) {
165
+ cache.delete(key);
94
166
  }
95
167
  });
96
168
  return pending;
@@ -98,37 +170,134 @@ function createKmsDataKeys() {
98
170
  };
99
171
  }
100
172
 
101
- const localDataKeys = {
102
- async generate() {
173
+ function createLocalDataKeys() {
174
+ const warnedLegacyKeyIds = new Set();
175
+
176
+ // The wrapped data key is bound to its key id, so it cannot be moved
177
+ // under another id that maps to the same master key.
178
+ const dataKeyAad = (keyIdB64) =>
179
+ Buffer.from(`frigg-dek:${v2Header(keyIdB64)}`);
180
+
181
+ const currentKey = () => {
103
182
  const { AES_KEY, AES_KEY_ID } = process.env;
104
- const randomKey = crypto.randomBytes(32).toString('hex').slice(0, 32);
105
-
106
- return {
107
- keyId: Buffer.from(AES_KEY_ID).toString('base64'),
108
- encryptedKey: Buffer.from(aes.encrypt(randomKey, AES_KEY)).toString(
109
- 'base64'
110
- ),
111
- plaintext: randomKey,
112
- };
113
- },
114
-
115
- async decrypt(keyId, encryptedKeyB64) {
116
- const availableKeys = {
117
- [process.env.AES_KEY_ID]: process.env.AES_KEY,
118
- [process.env.DEPRECATED_AES_KEY_ID]: process.env.DEPRECATED_AES_KEY,
119
- };
120
-
121
- const key = availableKeys[keyId];
122
-
123
- if (!key) {
183
+ if (!AES_KEY_ID) {
184
+ throw new Error('AES_KEY_ID is not set');
185
+ }
186
+ const { key, strength } = parseAesKey(AES_KEY, { name: 'AES_KEY' });
187
+ if (strength === 'legacy' && !warnedLegacyKeyIds.has(AES_KEY_ID)) {
188
+ warnedLegacyKeyIds.add(AES_KEY_ID);
189
+ log.warn(
190
+ 'AES_KEY is a legacy 32-character key with at most 128 bits of entropy',
191
+ {
192
+ eventName: 'frigg.encrypt.legacy_aes_key',
193
+ keyId: AES_KEY_ID,
194
+ hint: 'Rotate to a key from `openssl rand -hex 32`: move the current pair to DEPRECATED_AES_KEY_ID / DEPRECATED_AES_KEY and set a new AES_KEY_ID / AES_KEY.',
195
+ }
196
+ );
197
+ }
198
+ return { keyId: AES_KEY_ID, key, strength };
199
+ };
200
+
201
+ // Parsed on use, so a bad DEPRECATED_AES_KEY only fails reads of the
202
+ // values under its own key id.
203
+ const keyFor = (keyId) => {
204
+ const available = [
205
+ [process.env.AES_KEY_ID, 'AES_KEY'],
206
+ [process.env.DEPRECATED_AES_KEY_ID, 'DEPRECATED_AES_KEY'],
207
+ ];
208
+ const match = available.find(([id]) => id && id === keyId);
209
+ if (!match) {
124
210
  throw new Error('Encryption key not found');
125
211
  }
212
+ const [, name] = match;
213
+ return parseAesKey(process.env[name], { name }).key;
214
+ };
126
215
 
127
- return aes.decrypt(Buffer.from(encryptedKeyB64, 'base64'), key);
128
- },
129
- };
216
+ return {
217
+ async generate(version = CURRENT_ENVELOPE_VERSION) {
218
+ const { keyId, key, strength } = currentKey();
219
+ const keyIdB64 = toBase64(keyId);
220
+ if (version === 'v1') {
221
+ if (strength !== 'legacy') {
222
+ throw new Error(
223
+ 'FRIGG_ENCRYPTION_WRITE_VERSION=v1 needs the legacy 32-character AES_KEY: a core before v2 cannot use a full-strength key. Remove FRIGG_ENCRYPTION_WRITE_VERSION, or keep the legacy key until every function runs the new core.'
224
+ );
225
+ }
226
+ // The pre-v2 reader uses the data key as a 32-character UTF-8
227
+ // string. 24 random bytes in base64 give 32 characters and
228
+ // 192 bits (the old 32 hex characters gave 128).
229
+ const dataKey = crypto.randomBytes(24).toString('base64');
230
+ return {
231
+ keyIdB64,
232
+ encryptedKey: toBase64(aes.encryptCtr(dataKey, key)),
233
+ plaintext: dataKey,
234
+ };
235
+ }
236
+ const dataKey = crypto.randomBytes(KEY_BYTES);
237
+ return {
238
+ keyIdB64,
239
+ encryptedKey: aes
240
+ .wrapKey(dataKey, key, dataKeyAad(keyIdB64))
241
+ .toString('base64'),
242
+ plaintext: dataKey,
243
+ };
244
+ },
245
+
246
+ async decrypt(envelope) {
247
+ const masterKey = keyFor(envelope.keyId);
248
+ const wrapped = Buffer.from(envelope.encryptedKey, 'base64');
249
+ if (envelope.version === 'v1') {
250
+ // v1 data keys are 32 hex characters, used as a UTF-8 key.
251
+ return aes.decryptCtr(wrapped, masterKey);
252
+ }
253
+ return aes.unwrapKey(
254
+ wrapped,
255
+ masterKey,
256
+ dataKeyAad(envelope.keyIdB64)
257
+ );
258
+ },
259
+ };
260
+ }
261
+
262
+ /** A complete v2 envelope: right marker, part count, IV and tag sizes. */
263
+ function isStrictV2Envelope(value) {
264
+ if (getEnvelopeVersion(value) !== 'v2') {
265
+ return false;
266
+ }
267
+ try {
268
+ parseEnvelope(value);
269
+ return true;
270
+ } catch {
271
+ return false;
272
+ }
273
+ }
274
+
275
+ /**
276
+ * The v2 envelope inside the plaintext of a v1 value, or null. It is bare
277
+ * (Cryptor used directly) or a JSON string: FieldEncryptionService stores
278
+ * every value with JSON.stringify, strings included.
279
+ */
280
+ function nestedV2Envelope(plaintext) {
281
+ if (isStrictV2Envelope(plaintext)) {
282
+ return plaintext;
283
+ }
284
+ if (
285
+ typeof plaintext === 'string' &&
286
+ plaintext.startsWith('"v2:') &&
287
+ plaintext.endsWith('"')
288
+ ) {
289
+ try {
290
+ const parsed = JSON.parse(plaintext);
291
+ return isStrictV2Envelope(parsed) ? parsed : null;
292
+ } catch {
293
+ return null;
294
+ }
295
+ }
296
+ return null;
297
+ }
130
298
 
131
299
  const kmsDataKeys = createKmsDataKeys();
300
+ const localDataKeys = createLocalDataKeys();
132
301
 
133
302
  class Cryptor {
134
303
  constructor({ shouldUseAws }) {
@@ -136,18 +305,97 @@ class Cryptor {
136
305
  this.dataKeys = shouldUseAws ? kmsDataKeys : localDataKeys;
137
306
  }
138
307
 
308
+ /**
309
+ * The envelope version encrypt() writes now: 'v2', or 'v1' while
310
+ * FRIGG_ENCRYPTION_WRITE_VERSION=v1 (the upgrade deploy).
311
+ * @returns {'v1'|'v2'}
312
+ */
313
+ getWriteVersion() {
314
+ return getWriteVersion();
315
+ }
316
+
317
+ /**
318
+ * @param {string} text
319
+ * @returns {Promise<string>} a v2 envelope (a v1 envelope while
320
+ * FRIGG_ENCRYPTION_WRITE_VERSION=v1)
321
+ */
139
322
  async encrypt(text) {
140
- const { keyId, encryptedKey, plaintext } = await this.dataKeys.generate();
141
- const encryptedText = aes.encrypt(text, plaintext);
142
- return `${keyId}:${encryptedText}:${encryptedKey}`;
323
+ const version = getWriteVersion();
324
+ const { keyIdB64, encryptedKey, plaintext } =
325
+ await this.dataKeys.generate(version);
326
+ if (version === 'v1') {
327
+ return formatV1({
328
+ keyIdB64,
329
+ text,
330
+ dataKey: this.shouldUseAws ? Buffer.from(plaintext) : plaintext,
331
+ encryptedKey,
332
+ });
333
+ }
334
+ const { iv, ciphertext, tag } = aes.encryptGcm(
335
+ text,
336
+ Buffer.from(plaintext),
337
+ Buffer.from(v2Header(keyIdB64))
338
+ );
339
+ return formatEnvelope({ keyIdB64, iv, ciphertext, tag, encryptedKey });
143
340
  }
144
341
 
342
+ /**
343
+ * @param {string} text a v1 or v2 envelope
344
+ * @returns {Promise<string>}
345
+ * @throws when a v2 value fails authentication, the key id is unknown,
346
+ * or the envelope version is not supported.
347
+ */
145
348
  async decrypt(text) {
146
- const split = text.split(':');
147
- const keyId = Buffer.from(split[0], 'base64').toString();
148
- const encryptedText = `${split[1]}:${split[2]}`;
149
- const plaintext = await this.dataKeys.decrypt(keyId, split[3]);
150
- return aes.decrypt(encryptedText, plaintext);
349
+ const envelope = parseEnvelope(text);
350
+ const plaintext = await this._decryptEnvelope(envelope);
351
+ const inner =
352
+ envelope.version === 'v1' ? nestedV2Envelope(plaintext) : null;
353
+ if (inner) {
354
+ // A core before v2 read a v2 value as plaintext and encrypted it
355
+ // again. Read the inner value; re-encryption rewrites the field.
356
+ log.warn('Read a v2 value that an older core encrypted again', {
357
+ eventName: 'frigg.encrypt.nested_envelope_repaired',
358
+ hint: 'Run the frigg-reencrypt-legacy-fields admin script to rewrite such values.',
359
+ });
360
+ return this._decryptEnvelope(parseEnvelope(inner));
361
+ }
362
+ return plaintext;
363
+ }
364
+
365
+ async _decryptEnvelope(envelope) {
366
+ const dataKey = await this.dataKeys.decrypt(envelope);
367
+ if (envelope.version === 'v1') {
368
+ return aes.decryptCtr(envelope.encryptedText, dataKey);
369
+ }
370
+ return aes
371
+ .decryptGcm(
372
+ envelope,
373
+ Buffer.from(dataKey),
374
+ Buffer.from(envelope.header)
375
+ )
376
+ .toString('utf8');
377
+ }
378
+
379
+ /**
380
+ * Whether a stored value should be rewritten by encrypt(): a v1 value,
381
+ * or (AES mode) a v2 value under a key id other than AES_KEY_ID, such as
382
+ * DEPRECATED_AES_KEY_ID after a rotation. False for anything that is not
383
+ * an envelope this version can read, a damaged v2 value included
384
+ * (decrypt() reports those).
385
+ */
386
+ needsReencryption(value) {
387
+ const version = getEnvelopeVersion(value);
388
+ if (version === 'v1') {
389
+ return true;
390
+ }
391
+ if (version !== 'v2' || this.shouldUseAws) {
392
+ return false;
393
+ }
394
+ try {
395
+ return parseEnvelope(value).keyId !== process.env.AES_KEY_ID;
396
+ } catch {
397
+ return false;
398
+ }
151
399
  }
152
400
  }
153
401