@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.
- package/CLAUDE.md +13 -6
- package/README.md +4 -1
- package/application/commands/encryption-commands.js +135 -0
- package/database/encryption/README.md +158 -13
- package/database/encryption/ciphertext-format.js +11 -16
- package/database/encryption/documentdb-encryption-service.md +14 -15
- package/database/repositories/encrypted-field-store-factory.js +27 -0
- package/database/repositories/encrypted-field-store-interface.js +53 -0
- package/database/repositories/encrypted-field-store-mongo.js +69 -0
- package/database/repositories/encrypted-field-store-postgres.js +119 -0
- package/database/use-cases/reencrypt-legacy-fields-use-case.js +114 -0
- package/encrypt/Cryptor.js +302 -54
- package/encrypt/aes.js +111 -10
- package/encrypt/envelope.js +200 -0
- package/encrypt/key-material.js +73 -0
- package/handlers/routers/HEALTHCHECK.md +30 -0
- package/handlers/routers/health.js +22 -0
- package/handlers/use-cases/check-transport-security-health-use-case.js +137 -0
- package/integrations/repositories/integration-repository-mongo.js +15 -34
- package/modules/requester/oauth-2.js +0 -56
- package/modules/requester/requester.js +0 -125
- package/package.json +6 -6
- package/types/encrypt/index.d.ts +9 -0
- package/types/module-plugin/index.d.ts +0 -13
package/CLAUDE.md
CHANGED
|
@@ -485,10 +485,15 @@ class MyWorker extends Worker {
|
|
|
485
485
|
**Purpose**: Cryptor adapter for AWS KMS and AES encryption.
|
|
486
486
|
|
|
487
487
|
**Key Class**: `Cryptor.js`
|
|
488
|
-
- Envelope encryption
|
|
489
|
-
-
|
|
490
|
-
-
|
|
491
|
-
-
|
|
488
|
+
- Envelope encryption: one 32-byte data key per value, wrapped by AWS KMS or by `AES_KEY`
|
|
489
|
+
- Writes envelope `v2:keyId:iv:ciphertext:tag:encryptedKey` (AES-256-GCM, 12-byte IV, 16-byte tag, header as AAD); `envelope.js` owns the format
|
|
490
|
+
- Reads v1 (`keyId:iv:ciphertext:encryptedKey`, aes-256-ctr, no tag) for data written before v2; writes it only while `FRIGG_ENCRYPTION_WRITE_VERSION=v1` (upgrade deploy)
|
|
491
|
+
- `AES_KEY` parsing lives in `key-material.js`: 64 hex characters or base64 of 32 bytes (full), any other 32-character string (legacy, WARN `frigg.encrypt.legacy_aes_key`), anything else is an error
|
|
492
|
+
- Key rotation: `DEPRECATED_AES_KEY_ID` / `DEPRECATED_AES_KEY`; `needsReencryption(value)` tells v1 and old-key values apart
|
|
493
|
+
- New algorithm = new envelope version + one decrypt branch; markers `v3`+ are reserved and fail loudly on older code
|
|
494
|
+
- Re-encryption: `ReencryptLegacyFieldsUseCase` + `encrypted-field-store-*` (compare-and-swap per field) behind `createEncryptionCommands()`; admin script `frigg-reencrypt-legacy-fields`. Only an empty page ends a model (MongoDB caps a batch at 16 MB)
|
|
495
|
+
- KMS mode: v2 data keys carry the encryption context `{"frigg:envelope": "v2"}`, v1 keys none; the data-key cache is keyed by version + wrapped key (no v2-to-v1 downgrade)
|
|
496
|
+
- Upgrade of a running app: `FRIGG_ENCRYPTION_WRITE_VERSION=v1` for one deploy; `decrypt()` repairs v1-around-v2 values (bare or JSON string), WARN `frigg.encrypt.nested_envelope_repaired`
|
|
492
497
|
|
|
493
498
|
**Usage**:
|
|
494
499
|
|
|
@@ -937,8 +942,10 @@ Use test doubles from `@friggframework/test` package for consistent mocking.
|
|
|
937
942
|
### Encryption
|
|
938
943
|
|
|
939
944
|
- `KMS_KEY_ARN` - AWS KMS key ARN (production)
|
|
940
|
-
- `AES_KEY_ID` - AES key ID (
|
|
941
|
-
- `AES_KEY` - AES
|
|
945
|
+
- `AES_KEY_ID` - AES key ID (any stage)
|
|
946
|
+
- `AES_KEY` - AES-256 key: `openssl rand -hex 32` (64 hex characters) or base64 of 32 bytes
|
|
947
|
+
- `DEPRECATED_AES_KEY_ID` / `DEPRECATED_AES_KEY` - Previous AES key pair during a rotation
|
|
948
|
+
- `FRIGG_ENCRYPTION_WRITE_VERSION` - `v1` only for the deploy that brings v2 into a running app (old functions read v1); unset = `v2`
|
|
942
949
|
- `STAGE` - Environment stage (dev, test, local bypass encryption)
|
|
943
950
|
|
|
944
951
|
### Optional
|
package/README.md
CHANGED
|
@@ -178,7 +178,10 @@ await user.save();
|
|
|
178
178
|
|
|
179
179
|
### 4. Encryption (`/encrypt`)
|
|
180
180
|
|
|
181
|
-
AES-256-GCM
|
|
181
|
+
Envelope encryption for sensitive data: AES-256-GCM with a 256-bit data key per
|
|
182
|
+
value, wrapped by AWS KMS or by `AES_KEY` (`openssl rand -hex 32`). Stored
|
|
183
|
+
values carry a version marker (`v2:`); values from older releases still
|
|
184
|
+
decrypt. See `database/encryption/README.md`.
|
|
182
185
|
|
|
183
186
|
**Usage:**
|
|
184
187
|
```javascript
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
const {
|
|
2
|
+
getEncryptedModels,
|
|
3
|
+
getFieldsToDecryptOnRead,
|
|
4
|
+
loadCustomEncryptionSchema,
|
|
5
|
+
} = require('../../database/encryption/encryption-schema-registry');
|
|
6
|
+
const {
|
|
7
|
+
ReencryptLegacyFieldsUseCase,
|
|
8
|
+
MAX_LIMIT,
|
|
9
|
+
} = require('../../database/use-cases/reencrypt-legacy-fields-use-case');
|
|
10
|
+
|
|
11
|
+
const ERROR_CODE_MAP = {
|
|
12
|
+
ENCRYPTION_DISABLED: 400,
|
|
13
|
+
INVALID_REENCRYPTION_INPUT: 400,
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
function mapErrorToResponse(error) {
|
|
17
|
+
const status = ERROR_CODE_MAP[error?.code] || 500;
|
|
18
|
+
return {
|
|
19
|
+
error: status,
|
|
20
|
+
reason: error?.message,
|
|
21
|
+
code: error?.code,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function codedError(message, code) {
|
|
26
|
+
return Object.assign(new Error(message), { code });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Field-level encryption maintenance commands.
|
|
31
|
+
*
|
|
32
|
+
* NOTE: Internal API, used by admin scripts (see
|
|
33
|
+
* @friggframework/admin-scripts ReencryptLegacyFieldsScript).
|
|
34
|
+
*
|
|
35
|
+
* @param {Object} [deps] injected for tests; defaults use the app's database
|
|
36
|
+
* and encryption configuration
|
|
37
|
+
*/
|
|
38
|
+
function createEncryptionCommands({
|
|
39
|
+
encryptedFieldStore,
|
|
40
|
+
cryptor,
|
|
41
|
+
getEncryptionConfig,
|
|
42
|
+
loadEncryptionSchema = loadCustomEncryptionSchema,
|
|
43
|
+
} = {}) {
|
|
44
|
+
const encryptionConfig = () =>
|
|
45
|
+
(
|
|
46
|
+
getEncryptionConfig ||
|
|
47
|
+
require('../../database/prisma').getEncryptionConfig
|
|
48
|
+
)();
|
|
49
|
+
|
|
50
|
+
// App-registered fields (encryption.schema, module credentialFields)
|
|
51
|
+
// must be known before the field paths are read.
|
|
52
|
+
let schemaLoaded = false;
|
|
53
|
+
const loadSchemaOnce = () => {
|
|
54
|
+
if (!schemaLoaded) {
|
|
55
|
+
loadEncryptionSchema();
|
|
56
|
+
schemaLoaded = true;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
/** Models with encrypted fields (core and app-registered). */
|
|
62
|
+
listEncryptedModels() {
|
|
63
|
+
loadSchemaOnce();
|
|
64
|
+
return getEncryptedModels();
|
|
65
|
+
},
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Rewrite one page of a model's legacy ciphertext (v1 envelopes, and
|
|
69
|
+
* in AES mode values under DEPRECATED_AES_KEY_ID) with the current
|
|
70
|
+
* envelope version and key. Resume with `after: result.next` until
|
|
71
|
+
* `next` is null.
|
|
72
|
+
*
|
|
73
|
+
* @param {Object} params
|
|
74
|
+
* @param {string} params.model e.g. 'Credential'
|
|
75
|
+
* @param {string|number|null} [params.after]
|
|
76
|
+
* @param {number} [params.limit=100] 1..500
|
|
77
|
+
* @param {boolean} [params.dryRun=false]
|
|
78
|
+
* @returns {Promise<Object>} the page result, or { error, reason, code }
|
|
79
|
+
*/
|
|
80
|
+
async reencryptLegacyFields({
|
|
81
|
+
model,
|
|
82
|
+
after = null,
|
|
83
|
+
limit = 100,
|
|
84
|
+
dryRun = false,
|
|
85
|
+
} = {}) {
|
|
86
|
+
try {
|
|
87
|
+
const config = cryptor ? { enabled: true } : encryptionConfig();
|
|
88
|
+
if (!config.enabled) {
|
|
89
|
+
throw codedError(
|
|
90
|
+
'Field-level encryption is disabled (no KMS_KEY_ARN or AES_KEY_ID, or a dev/test/local STAGE): there is nothing to re-encrypt with.',
|
|
91
|
+
'ENCRYPTION_DISABLED'
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
loadSchemaOnce();
|
|
95
|
+
const paths = model ? getFieldsToDecryptOnRead(model) : [];
|
|
96
|
+
if (!paths.length) {
|
|
97
|
+
throw codedError(
|
|
98
|
+
`model must be one of: ${getEncryptedModels().join(
|
|
99
|
+
', '
|
|
100
|
+
)}`,
|
|
101
|
+
'INVALID_REENCRYPTION_INPUT'
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
if (
|
|
105
|
+
!Number.isInteger(limit) ||
|
|
106
|
+
limit < 1 ||
|
|
107
|
+
limit > MAX_LIMIT
|
|
108
|
+
) {
|
|
109
|
+
throw codedError(
|
|
110
|
+
`limit must be an integer from 1 to ${MAX_LIMIT}`,
|
|
111
|
+
'INVALID_REENCRYPTION_INPUT'
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const { Cryptor } = require('../../encrypt/Cryptor');
|
|
116
|
+
const {
|
|
117
|
+
createEncryptedFieldStore,
|
|
118
|
+
} = require('../../database/repositories/encrypted-field-store-factory');
|
|
119
|
+
const useCase = new ReencryptLegacyFieldsUseCase({
|
|
120
|
+
encryptedFieldStore:
|
|
121
|
+
encryptedFieldStore || createEncryptedFieldStore(),
|
|
122
|
+
cryptor:
|
|
123
|
+
cryptor ||
|
|
124
|
+
new Cryptor({ shouldUseAws: config.method === 'kms' }),
|
|
125
|
+
getFieldPaths: getFieldsToDecryptOnRead,
|
|
126
|
+
});
|
|
127
|
+
return await useCase.execute({ model, after, limit, dryRun });
|
|
128
|
+
} catch (error) {
|
|
129
|
+
return mapErrorToResponse(error);
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
module.exports = { createEncryptionCommands };
|
|
@@ -15,6 +15,8 @@ This module provides **transparent field-level encryption** for sensitive data i
|
|
|
15
15
|
- ✅ **Local AES fallback**: Development mode using local encryption keys
|
|
16
16
|
- ✅ **Environment-based**: Automatic bypass in dev/test/local environments
|
|
17
17
|
- ✅ **Envelope encryption**: Secure key management pattern
|
|
18
|
+
- ✅ **Authenticated encryption**: AES-256-GCM with full 256-bit data keys in KMS and AES mode
|
|
19
|
+
- ✅ **Crypto-agile format**: Versioned ciphertext envelope (`v2:`), older versions still read
|
|
18
20
|
|
|
19
21
|
## Architecture
|
|
20
22
|
|
|
@@ -102,11 +104,28 @@ The `KMS_KEY_ARN` is usually auto-discovered by Frigg infrastructure:
|
|
|
102
104
|
|
|
103
105
|
```bash
|
|
104
106
|
# AES encryption (can be used in any environment including production)
|
|
105
|
-
AES_KEY_ID=
|
|
106
|
-
AES_KEY
|
|
107
|
+
AES_KEY_ID=aes-key-2026-12
|
|
108
|
+
AES_KEY=$(openssl rand -hex 32) # 64 hex characters = 32 bytes = 256 bits
|
|
107
109
|
STAGE=production # or development, staging, etc.
|
|
108
110
|
```
|
|
109
111
|
|
|
112
|
+
`AES_KEY` must hold 32 random bytes, written as:
|
|
113
|
+
|
|
114
|
+
| Format | Example command | Strength |
|
|
115
|
+
| --- | --- | --- |
|
|
116
|
+
| 64 hex characters | `openssl rand -hex 32` | 256 bits |
|
|
117
|
+
| base64 of 32 bytes (44 characters) | `openssl rand -base64 32` | 256 bits |
|
|
118
|
+
| legacy: any 32-character string | (old docs: `openssl rand -hex 16`) | at most 128 bits |
|
|
119
|
+
|
|
120
|
+
A legacy 32-character key still works, so existing data stays readable, but
|
|
121
|
+
AES-256 then has at most 128 bits of key entropy. Core logs a WARN
|
|
122
|
+
(`frigg.encrypt.legacy_aes_key`) once per process and `frigg validate` warns
|
|
123
|
+
(`weak-encryption-key`). Replace it with a 256-bit key: see
|
|
124
|
+
[Rotating AES keys](#rotating-aes-keys). Any other length is refused.
|
|
125
|
+
|
|
126
|
+
For a rotation, the previous pair stays readable through
|
|
127
|
+
`DEPRECATED_AES_KEY_ID` and `DEPRECATED_AES_KEY` (same formats).
|
|
128
|
+
|
|
110
129
|
**⚠️ Important**: Encryption is automatically **disabled** when `STAGE` is set to `dev`, `test`, or `local`, regardless of key configuration.
|
|
111
130
|
|
|
112
131
|
### Bypass Encryption
|
|
@@ -397,7 +416,7 @@ await prisma.credential.create({
|
|
|
397
416
|
// 2. FieldEncryptionService encrypts matching fields
|
|
398
417
|
// 3. Cryptor generates data key via KMS
|
|
399
418
|
// 4. Cryptor encrypts value with data key
|
|
400
|
-
// 5. Database stores: { data: { access_token: 'keyId:iv:cipher:encKey' }}
|
|
419
|
+
// 5. Database stores: { data: { access_token: 'v2:keyId:iv:cipher:tag:encKey' }}
|
|
401
420
|
// 6. Extension decrypts return value
|
|
402
421
|
// 7. Application receives: { data: { access_token: 'secret123' }}
|
|
403
422
|
```
|
|
@@ -421,12 +440,41 @@ const credential = await prisma.credential.findUnique({
|
|
|
421
440
|
|
|
422
441
|
### Encryption Format
|
|
423
442
|
|
|
424
|
-
Encrypted values use **envelope encryption**:
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
443
|
+
Encrypted values use **envelope encryption**: each value gets its own 32-byte
|
|
444
|
+
data encryption key (DEK). The DEK comes from KMS `GenerateDataKey`
|
|
445
|
+
(`AES_256`) or, in AES mode, from `crypto.randomBytes(32)`; the master key
|
|
446
|
+
(the KMS key, or `AES_KEY`) encrypts the DEK.
|
|
447
|
+
|
|
448
|
+
Every stored value starts with a version marker, so the algorithm can change
|
|
449
|
+
without guessing which format a value has (crypto-agility):
|
|
450
|
+
|
|
451
|
+
| Version | Stored format | Cipher | Written |
|
|
452
|
+
| --- | --- | --- | --- |
|
|
453
|
+
| `v2` | `v2:keyId:iv:ciphertext:tag:encryptedKey` | AES-256-GCM, 12-byte IV, 16-byte tag | all new values |
|
|
454
|
+
| v1 (no marker) | `keyId:iv:ciphertext:encryptedKey` | AES-256-CTR, no tag | before v2, and during an upgrade deploy with `FRIGG_ENCRYPTION_WRITE_VERSION=v1` |
|
|
455
|
+
|
|
456
|
+
- `v2` parts after the marker are base64. The header `v2:keyId` is
|
|
457
|
+
authenticated as associated data: a changed ciphertext, IV, tag or key id
|
|
458
|
+
fails the read with `Ciphertext failed authentication` instead of
|
|
459
|
+
returning altered data. In AES mode the wrapped DEK is also AES-256-GCM
|
|
460
|
+
(`encryptedKey` = IV + encrypted DEK + tag).
|
|
461
|
+
- v1 values have no integrity protection (bit-flipping goes undetected), and
|
|
462
|
+
in AES mode their DEK had only 128 bits of entropy. Rewrite them as v2
|
|
463
|
+
with the [re-encryption script](#re-encrypting-legacy-values).
|
|
464
|
+
- Markers `v3` and later are reserved. A Frigg that does not know a marker
|
|
465
|
+
fails the read ("Upgrade @friggframework/core") instead of taking the
|
|
466
|
+
value for plaintext.
|
|
467
|
+
|
|
468
|
+
- In KMS mode, v2 data keys carry the KMS encryption context
|
|
469
|
+
`{"frigg:envelope": "v2"}`. KMS refuses to unwrap them without it, so a
|
|
470
|
+
v2 value cannot be rewritten as a v1 value (no tag) and still decrypt.
|
|
471
|
+
Grants or key policies that limit `kms:EncryptionContext*` must allow
|
|
472
|
+
this context.
|
|
473
|
+
|
|
474
|
+
The format lives in `encrypt/envelope.js`; `Cryptor.decrypt()` reads every
|
|
475
|
+
version it knows and `Cryptor.encrypt()` writes the current one. A
|
|
476
|
+
future algorithm (for example a new KEM for the data key) is one more
|
|
477
|
+
envelope version plus one decrypt branch.
|
|
430
478
|
|
|
431
479
|
**Why Envelope Encryption?**
|
|
432
480
|
|
|
@@ -435,6 +483,81 @@ Example: "base64KeyId:iv:ciphertext:base64EncryptedDataKey"
|
|
|
435
483
|
- Enables key rotation without re-encrypting all data
|
|
436
484
|
- Better performance at scale
|
|
437
485
|
|
|
486
|
+
### Upgrading a running app to v2
|
|
487
|
+
|
|
488
|
+
A core before v2 does not know the `v2` marker: it returns a v2 value as
|
|
489
|
+
plaintext (a token that is really ciphertext), and a write-back stores it as
|
|
490
|
+
v1 around v2. During a rolling deploy, old and new functions run at the same
|
|
491
|
+
time. To upgrade an app that already has encrypted data:
|
|
492
|
+
|
|
493
|
+
1. Set `FRIGG_ENCRYPTION_WRITE_VERSION=v1` and deploy the new core. New code
|
|
494
|
+
writes v1 values that old code reads. To pass the variable to the
|
|
495
|
+
functions, add `FRIGG_ENCRYPTION_WRITE_VERSION: true` to `environment` in
|
|
496
|
+
the app definition and set it in the deploy environment. (AES mode: this needs the legacy
|
|
497
|
+
32-character `AES_KEY`, the only key the old core can use. Rotate the key
|
|
498
|
+
after step 2.)
|
|
499
|
+
2. Remove `FRIGG_ENCRYPTION_WRITE_VERSION` and deploy again. New values are v2.
|
|
500
|
+
3. Run the [re-encryption script](#re-encrypting-legacy-values).
|
|
501
|
+
|
|
502
|
+
If a value was already encrypted twice (v1 around v2), the new core reads the
|
|
503
|
+
inner value, logs WARN `frigg.encrypt.nested_envelope_repaired`, and the
|
|
504
|
+
re-encryption script rewrites it. A new app needs none of this.
|
|
505
|
+
|
|
506
|
+
### Rotating AES keys
|
|
507
|
+
|
|
508
|
+
1. Move the current pair to `DEPRECATED_AES_KEY_ID` / `DEPRECATED_AES_KEY`.
|
|
509
|
+
2. Set a new `AES_KEY_ID` and `AES_KEY=$(openssl rand -hex 32)`. Use a new key
|
|
510
|
+
id: values are found by key id, not by trying keys.
|
|
511
|
+
3. Deploy. New writes use the new key; values under the old key id still read.
|
|
512
|
+
4. Run the re-encryption script (below). It rewrites the values under
|
|
513
|
+
`DEPRECATED_AES_KEY_ID`, and v1 values, under the new key.
|
|
514
|
+
5. When a dry run reports no values left, remove the `DEPRECATED_*` pair.
|
|
515
|
+
|
|
516
|
+
With KMS, rotate the KMS key itself (automatic key rotation keeps the key ARN),
|
|
517
|
+
and run the script only to rewrite v1 values.
|
|
518
|
+
|
|
519
|
+
### Re-encrypting legacy values
|
|
520
|
+
|
|
521
|
+
Values written before v2 stay v1 until the app writes them again. To rewrite
|
|
522
|
+
them all, register the built-in admin script in the app definition:
|
|
523
|
+
|
|
524
|
+
```javascript
|
|
525
|
+
const { ReencryptLegacyFieldsScript } = require('@friggframework/admin-scripts');
|
|
526
|
+
|
|
527
|
+
const Definition = {
|
|
528
|
+
// ...
|
|
529
|
+
adminScripts: [ReencryptLegacyFieldsScript],
|
|
530
|
+
};
|
|
531
|
+
```
|
|
532
|
+
|
|
533
|
+
Then run `frigg-reencrypt-legacy-fields`, first with `"dryRun": true` to
|
|
534
|
+
count the values:
|
|
535
|
+
|
|
536
|
+
```bash
|
|
537
|
+
curl -X POST https://<your-app>/admin/scripts/frigg-reencrypt-legacy-fields \
|
|
538
|
+
-H "x-frigg-admin-api-key: $ADMIN_API_KEY" -H "Content-Type: application/json" \
|
|
539
|
+
-d '{ "params": { "dryRun": true }, "mode": "async" }'
|
|
540
|
+
```
|
|
541
|
+
|
|
542
|
+
The script walks every model with encrypted fields (or `params.models`) in id
|
|
543
|
+
order, `batchSize` rows per page (default 100, at most 500), `maxBatches`
|
|
544
|
+
pages per execution (default 50), and queues a continuation for the rest.
|
|
545
|
+
Only an empty page ends a model (a MongoDB batch can be short before the end:
|
|
546
|
+
the server caps one batch at 16 MB).
|
|
547
|
+
For each value that needs it (v1, or in AES mode a key id other than
|
|
548
|
+
`AES_KEY_ID`) it decrypts, encrypts as v2 under the current key, and replaces
|
|
549
|
+
the stored value only if it is still the ciphertext it read, so a concurrent
|
|
550
|
+
write by the app always wins. The script refuses to run while
|
|
551
|
+
`FRIGG_ENCRYPTION_WRITE_VERSION=v1` is set, because it would write v1 again.
|
|
552
|
+
Values it cannot decrypt (for example under a
|
|
553
|
+
key id nobody has any more) are listed in `failed` and left alone. The output
|
|
554
|
+
gives `needingReencryption`, `reencrypted`, `changedConcurrently` and
|
|
555
|
+
`failed` per execution.
|
|
556
|
+
|
|
557
|
+
Without admin scripts, the same work is one command per page:
|
|
558
|
+
`createEncryptionCommands().reencryptLegacyFields({ model, after, limit, dryRun })`
|
|
559
|
+
(`@friggframework/core/application/commands/encryption-commands`).
|
|
560
|
+
|
|
438
561
|
### Known Limitations
|
|
439
562
|
|
|
440
563
|
#### Prisma Relations with `include` Bypass Decryption
|
|
@@ -451,7 +574,7 @@ const entity = await prisma.entity.findUnique({
|
|
|
451
574
|
});
|
|
452
575
|
|
|
453
576
|
// entity.credential.data.access_token will be encrypted:
|
|
454
|
-
// "keyId:iv:ciphertext:encKey" instead of plain text
|
|
577
|
+
// "v2:keyId:iv:ciphertext:tag:encKey" instead of plain text
|
|
455
578
|
```
|
|
456
579
|
|
|
457
580
|
**Root Cause:**
|
|
@@ -773,15 +896,32 @@ aws kms describe-key --key-id $KMS_KEY_ARN
|
|
|
773
896
|
|
|
774
897
|
### Local AES Errors
|
|
775
898
|
|
|
776
|
-
**Error: "
|
|
899
|
+
**Error: "AES_KEY is not set" or "AES_KEY must be 32 random bytes ..."**
|
|
777
900
|
|
|
778
|
-
Solution: Set both `AES_KEY_ID` and `AES_KEY
|
|
901
|
+
Solution: Set both `AES_KEY_ID` and `AES_KEY`, with a 256-bit key:
|
|
779
902
|
|
|
780
903
|
```bash
|
|
781
904
|
export AES_KEY_ID=local-dev-key
|
|
782
|
-
export AES_KEY=$(openssl rand -hex
|
|
905
|
+
export AES_KEY=$(openssl rand -hex 32) # 64 hex characters = 256 bits
|
|
783
906
|
```
|
|
784
907
|
|
|
908
|
+
**Error: "Encryption key not found"**
|
|
909
|
+
|
|
910
|
+
The value was encrypted under a key id that is neither `AES_KEY_ID` nor
|
|
911
|
+
`DEPRECATED_AES_KEY_ID`. After a rotation, keep the old pair in
|
|
912
|
+
`DEPRECATED_AES_KEY_ID` / `DEPRECATED_AES_KEY` until the re-encryption
|
|
913
|
+
script has rewritten its values.
|
|
914
|
+
|
|
915
|
+
**Error: "Ciphertext failed authentication"**
|
|
916
|
+
|
|
917
|
+
A v2 value was changed after it was written (or the key under its key id is
|
|
918
|
+
not the key that wrote it). Frigg refuses to return it.
|
|
919
|
+
|
|
920
|
+
**Warning: `frigg.encrypt.legacy_aes_key`**
|
|
921
|
+
|
|
922
|
+
`AES_KEY` is a legacy 32-character key (at most 128 bits of entropy). See
|
|
923
|
+
[Rotating AES keys](#rotating-aes-keys).
|
|
924
|
+
|
|
785
925
|
### Performance Issues
|
|
786
926
|
|
|
787
927
|
**Symptom: Slow queries with encryption**
|
|
@@ -792,6 +932,9 @@ export AES_KEY=$(openssl rand -hex 16) # Generate 32-char key
|
|
|
792
932
|
|
|
793
933
|
### Data Migration
|
|
794
934
|
|
|
935
|
+
**Upgrading ciphertext to v2 (AES-256-GCM):** see
|
|
936
|
+
[Re-encrypting legacy values](#re-encrypting-legacy-values).
|
|
937
|
+
|
|
795
938
|
**Migrating from Mongoose encryption:**
|
|
796
939
|
|
|
797
940
|
1. Export data with old encryption
|
|
@@ -804,6 +947,8 @@ export AES_KEY=$(openssl rand -hex 16) # Generate 32-char key
|
|
|
804
947
|
### DO
|
|
805
948
|
|
|
806
949
|
✅ Use AWS KMS for production (recommended) or AES encryption (valid alternative)
|
|
950
|
+
✅ Generate `AES_KEY` with `openssl rand -hex 32` (256 bits), never a passphrase
|
|
951
|
+
✅ After upgrading Frigg or rotating keys, run the re-encryption script so no v1 ciphertext stays behind
|
|
807
952
|
✅ Rotate KMS keys regularly (AWS handles automatically)
|
|
808
953
|
✅ Restrict KMS key access to Lambda execution role only
|
|
809
954
|
✅ Use VPC endpoints for KMS (reduce NAT costs)
|
|
@@ -1,24 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Recognises values produced by Cryptor.encrypt()
|
|
3
|
-
*
|
|
4
|
-
* keyId
|
|
5
|
-
*
|
|
6
|
-
*
|
|
2
|
+
* Recognises values produced by Cryptor.encrypt(), in every envelope version
|
|
3
|
+
* (see ../../encrypt/envelope.js):
|
|
4
|
+
* v1 (legacy): keyId:iv:ciphertext:encryptedKey
|
|
5
|
+
* v2 (current): v2:keyId:iv:ciphertext:tag:encryptedKey
|
|
6
|
+
* A later version marker (v3, ...) is also reported as encrypted, so a value
|
|
7
|
+
* written by a newer Frigg is never mistaken for plaintext.
|
|
7
8
|
*
|
|
8
9
|
* Shared by the Prisma (FieldEncryptionService) and DocumentDB paths so a
|
|
9
10
|
* plaintext value that happens to contain colons (`a:b:c:d`, a URL with
|
|
10
11
|
* userinfo and a port) is never mistaken for ciphertext: on write it gets
|
|
11
12
|
* encrypted, on read it is returned as plaintext.
|
|
12
13
|
*/
|
|
13
|
-
const
|
|
14
|
-
|
|
14
|
+
const {
|
|
15
|
+
isEncryptedEnvelope,
|
|
16
|
+
getEnvelopeVersion,
|
|
17
|
+
} = require('../../encrypt/envelope');
|
|
15
18
|
|
|
16
|
-
|
|
17
|
-
if (typeof value !== 'string' || value.length < MIN_ENVELOPE_LENGTH) {
|
|
18
|
-
return false;
|
|
19
|
-
}
|
|
20
|
-
const parts = value.split(':');
|
|
21
|
-
return parts.length === 4 && parts.every((part) => BASE64_PART.test(part));
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
module.exports = { isEncryptedEnvelope };
|
|
19
|
+
module.exports = { isEncryptedEnvelope, getEnvelopeVersion };
|
|
@@ -504,7 +504,7 @@ const decrypted = await service.decryptFields('Credential', encryptedDoc);
|
|
|
504
504
|
3. Return parts.length >= 4
|
|
505
505
|
```
|
|
506
506
|
|
|
507
|
-
**Encrypted Format**: `"keyId:iv:cipher:encKey"` (envelope encryption)
|
|
507
|
+
**Encrypted Format**: `"v2:keyId:iv:cipher:tag:encKey"` (envelope encryption, AES-256-GCM); v1 `"keyId:iv:cipher:encKey"` from older releases is still recognized
|
|
508
508
|
|
|
509
509
|
**Examples**:
|
|
510
510
|
|
|
@@ -1587,7 +1587,7 @@ echo "🎉 All files synced successfully"
|
|
|
1587
1587
|
```bash
|
|
1588
1588
|
export STAGE=production
|
|
1589
1589
|
export AES_KEY_ID=local-test-key
|
|
1590
|
-
export AES_KEY
|
|
1590
|
+
export AES_KEY=$(openssl rand -hex 32) # 256-bit key
|
|
1591
1591
|
```
|
|
1592
1592
|
|
|
1593
1593
|
- [ ] Start backend:
|
|
@@ -3023,24 +3023,23 @@ For large deployments:
|
|
|
3023
3023
|
|
|
3024
3024
|
### Encryption Format
|
|
3025
3025
|
|
|
3026
|
-
**Envelope Encryption Pattern
|
|
3026
|
+
**Envelope Encryption Pattern** (v2, written by current releases):
|
|
3027
3027
|
|
|
3028
3028
|
```
|
|
3029
|
-
keyId:iv:cipher:encKey
|
|
3029
|
+
v2:keyId:iv:cipher:tag:encKey
|
|
3030
3030
|
```
|
|
3031
3031
|
|
|
3032
|
-
**Components
|
|
3032
|
+
**Components** (all base64 after the `v2` marker):
|
|
3033
3033
|
|
|
3034
3034
|
- `keyId`: Identifier for the encryption key (e.g., "aes-key-1", KMS key ID)
|
|
3035
|
-
- `iv`:
|
|
3036
|
-
- `cipher`: Encrypted data
|
|
3037
|
-
- `
|
|
3035
|
+
- `iv`: 12-byte AES-256-GCM initialization vector
|
|
3036
|
+
- `cipher`: Encrypted data
|
|
3037
|
+
- `tag`: 16-byte GCM authentication tag (`v2:keyId` is authenticated as AAD)
|
|
3038
|
+
- `encKey`: Encrypted 32-byte data encryption key
|
|
3038
3039
|
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
aes-key-1:MTIzNDU2Nzg5MGFiY2RlZg==:ZW5jcnlwdGVkX2RhdGFfaGVyZQ==:ZGVrX2VuY3J5cHRlZA==
|
|
3043
|
-
```
|
|
3040
|
+
v1 values (`keyId:iv:cipher:encKey`, aes-256-ctr, no tag) from older releases
|
|
3041
|
+
are still recognized and decrypted; see `README.md` ("Encryption Format") for
|
|
3042
|
+
how to rewrite them as v2.
|
|
3044
3043
|
|
|
3045
3044
|
---
|
|
3046
3045
|
|
|
@@ -3068,9 +3067,9 @@ export STAGE=production
|
|
|
3068
3067
|
**Alternative (AES - Any Environment)**:
|
|
3069
3068
|
|
|
3070
3069
|
```bash
|
|
3071
|
-
# Generate a
|
|
3070
|
+
# Generate a 256-bit key
|
|
3072
3071
|
export AES_KEY_ID=my-app-key-v1
|
|
3073
|
-
export AES_KEY=$(openssl rand -hex
|
|
3072
|
+
export AES_KEY=$(openssl rand -hex 32) # 64 hex chars = 32 bytes
|
|
3074
3073
|
|
|
3075
3074
|
# Can be used in production
|
|
3076
3075
|
export STAGE=production
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const {
|
|
2
|
+
EncryptedFieldStorePostgres,
|
|
3
|
+
} = require('./encrypted-field-store-postgres');
|
|
4
|
+
const { EncryptedFieldStoreMongo } = require('./encrypted-field-store-mongo');
|
|
5
|
+
const config = require('../config');
|
|
6
|
+
|
|
7
|
+
function createEncryptedFieldStore({ prismaClient } = {}) {
|
|
8
|
+
const dbType = config.DB_TYPE;
|
|
9
|
+
|
|
10
|
+
switch (dbType) {
|
|
11
|
+
case 'postgresql':
|
|
12
|
+
return new EncryptedFieldStorePostgres({ prismaClient });
|
|
13
|
+
case 'mongodb':
|
|
14
|
+
case 'documentdb':
|
|
15
|
+
return new EncryptedFieldStoreMongo({ prismaClient });
|
|
16
|
+
default:
|
|
17
|
+
throw new Error(
|
|
18
|
+
`Unsupported database type: ${dbType}. Supported values: 'mongodb', 'documentdb', 'postgresql'`
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
module.exports = {
|
|
24
|
+
createEncryptedFieldStore,
|
|
25
|
+
EncryptedFieldStorePostgres,
|
|
26
|
+
EncryptedFieldStoreMongo,
|
|
27
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Port: raw access to the stored (encrypted) values of encrypted fields.
|
|
3
|
+
*
|
|
4
|
+
* Unlike the model repositories, an EncryptedFieldStore reads and writes the
|
|
5
|
+
* ciphertext as stored, around the field-encryption extension. Only the
|
|
6
|
+
* re-encryption use case uses it.
|
|
7
|
+
*
|
|
8
|
+
* Field paths are the ones of the encryption schema registry: 'hashword',
|
|
9
|
+
* 'mapping', 'data.access_token'.
|
|
10
|
+
*/
|
|
11
|
+
class EncryptedFieldStoreInterface {
|
|
12
|
+
/**
|
|
13
|
+
* One page of rows of a model, in id order.
|
|
14
|
+
*
|
|
15
|
+
* @param {string} model Prisma model name (table / collection)
|
|
16
|
+
* @param {string[]} paths encrypted field paths
|
|
17
|
+
* @param {{ after: string|number|null, limit: number }} page
|
|
18
|
+
* @returns {Promise<Array<{ id: string|number, values: Object<string, *> }>>}
|
|
19
|
+
* `values` maps each path to the stored value (undefined when absent)
|
|
20
|
+
*/
|
|
21
|
+
async scan(model, paths, page) {
|
|
22
|
+
throw new Error('Method scan must be implemented by subclass');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Set the value at `path` to `replacement`, only if it still is `expected`.
|
|
27
|
+
*
|
|
28
|
+
* @returns {Promise<boolean>} false when the row is gone or the value changed
|
|
29
|
+
*/
|
|
30
|
+
async replaceIfUnchanged(model, id, path, expected, replacement) {
|
|
31
|
+
throw new Error(
|
|
32
|
+
'Method replaceIfUnchanged must be implemented by subclass'
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
38
|
+
|
|
39
|
+
/** Model names and path segments become SQL identifiers / Mongo keys. */
|
|
40
|
+
function assertIdentifiers(model, paths) {
|
|
41
|
+
const names = [model, ...paths.flatMap((path) => path.split('.'))];
|
|
42
|
+
const invalid = names.find((name) => !IDENTIFIER.test(name));
|
|
43
|
+
if (invalid !== undefined) {
|
|
44
|
+
throw new Error(
|
|
45
|
+
`Invalid model or field name: ${JSON.stringify(invalid)}`
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const getPath = (document, path) =>
|
|
51
|
+
path.split('.').reduce((value, key) => value?.[key], document);
|
|
52
|
+
|
|
53
|
+
module.exports = { EncryptedFieldStoreInterface, assertIdentifiers, getPath };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
const {
|
|
2
|
+
EncryptedFieldStoreInterface,
|
|
3
|
+
assertIdentifiers,
|
|
4
|
+
getPath,
|
|
5
|
+
} = require('./encrypted-field-store-interface');
|
|
6
|
+
const { fromObjectId } = require('../documentdb-utils');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* MongoDB and DocumentDB EncryptedFieldStore. Raw commands
|
|
10
|
+
* ($runCommandRaw), which the field-encryption extension does not intercept.
|
|
11
|
+
* Only `find` with a range filter, projection, sort and limit, and `update`
|
|
12
|
+
* with `$set`: both are supported by Amazon DocumentDB.
|
|
13
|
+
*/
|
|
14
|
+
class EncryptedFieldStoreMongo extends EncryptedFieldStoreInterface {
|
|
15
|
+
constructor({ prismaClient } = {}) {
|
|
16
|
+
super();
|
|
17
|
+
this.prisma = prismaClient || require('../prisma').prisma;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async scan(model, paths, { after = null, limit }) {
|
|
21
|
+
assertIdentifiers(model, paths);
|
|
22
|
+
// Project whole top-level fields: projecting both 'data' and
|
|
23
|
+
// 'data.x' would be a path collision.
|
|
24
|
+
const projection = Object.fromEntries(
|
|
25
|
+
[...new Set(paths.map((path) => path.split('.')[0]))].map(
|
|
26
|
+
(field) => [field, 1]
|
|
27
|
+
)
|
|
28
|
+
);
|
|
29
|
+
const result = await this.prisma.$runCommandRaw({
|
|
30
|
+
find: model,
|
|
31
|
+
filter:
|
|
32
|
+
after === null || after === undefined
|
|
33
|
+
? {}
|
|
34
|
+
: { _id: { $gt: { $oid: String(after) } } },
|
|
35
|
+
projection,
|
|
36
|
+
sort: { _id: 1 },
|
|
37
|
+
limit,
|
|
38
|
+
batchSize: limit,
|
|
39
|
+
});
|
|
40
|
+
const documents = result?.cursor?.firstBatch || [];
|
|
41
|
+
return documents.map((document) => ({
|
|
42
|
+
id: fromObjectId(document._id),
|
|
43
|
+
values: Object.fromEntries(
|
|
44
|
+
paths.map((path) => [path, getPath(document, path)])
|
|
45
|
+
),
|
|
46
|
+
}));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async replaceIfUnchanged(model, id, path, expected, replacement) {
|
|
50
|
+
assertIdentifiers(model, [path]);
|
|
51
|
+
const result = await this.prisma.$runCommandRaw({
|
|
52
|
+
update: model,
|
|
53
|
+
updates: [
|
|
54
|
+
{
|
|
55
|
+
q: { _id: { $oid: String(id) }, [path]: expected },
|
|
56
|
+
u: { $set: { [path]: replacement } },
|
|
57
|
+
},
|
|
58
|
+
],
|
|
59
|
+
});
|
|
60
|
+
if (result?.writeErrors?.length) {
|
|
61
|
+
throw new Error(
|
|
62
|
+
`Update of ${model}.${path} failed: ${result.writeErrors[0].errmsg}`
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
return result?.n === 1;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
module.exports = { EncryptedFieldStoreMongo };
|