@friggframework/core 2.0.0--canary.540.4653c0a.0 → 2.0.0--canary.663.9683f8b.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.
@@ -4,6 +4,7 @@ const {
4
4
  getFieldsToEncryptOnWrite,
5
5
  loadCustomEncryptionSchema,
6
6
  } = require('./encryption/encryption-schema-registry');
7
+ const { getEncryptionConfig } = require('./encryption/encryption-config');
7
8
 
8
9
  /**
9
10
  * Encryption service specifically for DocumentDB repositories
@@ -41,43 +42,29 @@ class DocumentDBEncryptionService {
41
42
  }
42
43
 
43
44
  /**
44
- * Initialize Cryptor with environment-based configuration.
45
- * Matches the logic from @friggframework/core/database/prisma.js
45
+ * Initialize Cryptor with environment-based configuration, using the
46
+ * same rule as the Prisma client (see encryption/encryption-config.js).
46
47
  *
47
- * Encryption is bypassed in dev/test/local stages.
48
- * Production uses AWS KMS (if available) or AES encryption.
48
+ * Local runs skip encryption on the dev, test and local stages. A
49
+ * deployed runtime with no key throws instead of writing plaintext.
49
50
  *
50
51
  * @private
52
+ * @throws {EncryptionConfigurationError} deployed with no usable key
51
53
  */
52
54
  _initializeCryptor() {
53
55
  // Load custom encryption schema from app definition BEFORE checking configuration
54
56
  // This ensures custom fields (like User.username) are registered before any encryption operations
55
57
  loadCustomEncryptionSchema();
56
58
 
57
- // Match logic from packages/core/database/prisma.js
58
- const stage = process.env.STAGE || process.env.NODE_ENV || 'development';
59
- const bypassEncryption = ['dev', 'test', 'local'].includes(stage.toLowerCase());
59
+ const config = getEncryptionConfig();
60
60
 
61
- if (bypassEncryption) {
61
+ if (!config.enabled) {
62
62
  this.cryptor = null;
63
63
  this.enabled = false;
64
64
  return;
65
65
  }
66
66
 
67
- // Determine encryption method (ensure boolean values)
68
- const hasKMS = !!(process.env.KMS_KEY_ARN && process.env.KMS_KEY_ARN.trim() !== '');
69
- const hasAES = !!(process.env.AES_KEY_ID && process.env.AES_KEY_ID.trim() !== '');
70
-
71
- if (!hasKMS && !hasAES) {
72
- console.warn('[DocumentDBEncryptionService] No encryption keys configured. Encryption disabled.');
73
- this.cryptor = null;
74
- this.enabled = false;
75
- return;
76
- }
77
-
78
- // KMS takes precedence over AES
79
- const shouldUseAws = hasKMS;
80
- this.cryptor = new Cryptor({ shouldUseAws });
67
+ this.cryptor = new Cryptor({ shouldUseAws: config.method === 'kms' });
81
68
  this.enabled = true;
82
69
  }
83
70
 
@@ -13,7 +13,7 @@ This module provides **transparent field-level encryption** for sensitive data i
13
13
  - ✅ **Hexagonal architecture**: Clean separation of concerns
14
14
  - ✅ **AWS KMS support**: Enterprise-grade encryption with AWS Key Management Service
15
15
  - ✅ **Local AES fallback**: Development mode using local encryption keys
16
- - ✅ **Environment-based**: Automatic bypass in dev/test/local environments
16
+ - ✅ **Fails closed**: A deployed stage with no key refuses to start; only local runs (`frigg start`, tests) skip encryption
17
17
  - ✅ **Envelope encryption**: Secure key management pattern
18
18
 
19
19
  ## Architecture
@@ -107,18 +107,46 @@ AES_KEY=your-32-character-secret-key-here
107
107
  STAGE=production # or development, staging, etc.
108
108
  ```
109
109
 
110
- **⚠️ Important**: Encryption is automatically **disabled** when `STAGE` is set to `dev`, `test`, or `local`, regardless of key configuration.
110
+ ### When Encryption Runs
111
111
 
112
- ### Bypass Encryption
112
+ The rule lives in `encryption-config.js` and is shared by the Prisma client, the DocumentDB encryption service, the integration-mapping helpers and the `/health/detailed` check. It depends on **where the code runs**, not on the stage name.
113
113
 
114
- To explicitly disable encryption:
114
+ A process is **deployed** when it runs in AWS Lambda (`AWS_LAMBDA_FUNCTION_NAME` or `LAMBDA_TASK_ROOT` is set, or `AWS_EXECUTION_ENV` starts with `AWS_Lambda_`) and is **not** a local run (`IS_OFFLINE=true` from serverless-offline / `frigg start`, `IS_LOCAL=true` from `serverless invoke local`, or `JEST_WORKER_ID` from Jest). Everything else is **local**.
115
115
 
116
- ```bash
117
- # Disable encryption (development only)
118
- STAGE=development # or dev, test, local
116
+ | Runtime | Key configured | `FRIGG_ENCRYPTION_DISABLED=true` | Result |
117
+ | --- | --- | --- | --- |
118
+ | Deployed, any stage (including `dev`) | `KMS_KEY_ARN` | any | Encrypt with KMS |
119
+ | Deployed, any stage | `AES_KEY_ID` + `AES_KEY` | any | Encrypt with AES |
120
+ | Deployed, any stage | `AES_KEY_ID` without `AES_KEY` | no | **Refuses to start** (`EncryptionConfigurationError`) |
121
+ | Deployed, any stage | none | no | **Refuses to start** (`EncryptionConfigurationError`) |
122
+ | Deployed, any stage | none | yes | Plaintext, with a warning on every cold start |
123
+ | Local, `STAGE` (or `NODE_ENV`) is `dev`, `test` or `local` | any | any | Skipped |
124
+ | Local, any other stage | `KMS_KEY_ARN` or `AES_KEY_ID` | any | Encrypt |
125
+ | Local, any other stage | none | any | Plaintext, with a warning |
126
+
127
+ KMS wins when both keys are set. A configured key always wins over `FRIGG_ENCRYPTION_DISABLED`: switching encryption off while a key exists would leave already-encrypted data unreadable, so the opt-out is ignored (with a warning).
128
+
129
+ "Refuses to start" means the Prisma client is never created: the first database access on a cold start throws
130
+
131
+ ```
132
+ EncryptionConfigurationError: [Frigg] No field-level encryption key is configured for stage "dev". A deployed Frigg app will not write credentials and other sensitive fields in plaintext. Fix: ...
133
+ ```
134
+
135
+ and `/health/detailed` reports `checks.encryption.status: "unhealthy"` with the same message. If a key is configured but the encryption extension fails to initialise, the client also refuses to start rather than continuing without encryption.
136
+
137
+ To encrypt a local run, use a stage other than `dev`, `test` or `local` and configure a key.
138
+
139
+ ### Running a Deployed Stage Without Encryption
140
+
141
+ Only do this on purpose, for a stage that never holds real credentials. Either set it in the app definition:
142
+
143
+ ```javascript
144
+ const appDefinition = {
145
+ encryption: { fieldLevelEncryptionMethod: 'none' },
146
+ };
119
147
  ```
120
148
 
121
- Or simply don't configure any encryption keys. In Production field level encryption **must** be enabled.
149
+ which the infrastructure builders turn into `FRIGG_ENCRYPTION_DISABLED=true` on every function, or set `FRIGG_ENCRYPTION_DISABLED=true` in the Lambda environment yourself. Every cold start logs a warning that sensitive fields are stored in plaintext. There is no default that does this.
122
150
 
123
151
  ## Encrypted Fields
124
152
 
@@ -553,8 +581,8 @@ class MyRepositoryDocumentDB {
553
581
 
554
582
  #### Configuration
555
583
 
556
- Uses the same environment variables and Cryptor as the Prisma Extension:
557
- - `STAGE`: Bypasses encryption for dev/test/local
584
+ Uses the same rule (`encryption-config.js`, see [When Encryption Runs](#when-encryption-runs)) and Cryptor as the Prisma Extension. Constructing the service in a deployed runtime with no key throws `EncryptionConfigurationError`.
585
+ - `STAGE`: Skips encryption for dev/test/local on local runs only
558
586
  - `KMS_KEY_ARN`: AWS KMS encryption (production)
559
587
  - `AES_KEY_ID` + `AES_KEY`: AES encryption (fallback)
560
588
 
@@ -615,10 +643,27 @@ curl http://localhost:3000/health/test-encryption
615
643
  "encryptionWorks": true
616
644
  }
617
645
 
618
- # Response when encryption disabled:
646
+ # Response on a local run with STAGE=dev:
619
647
  {
620
648
  "status": "disabled",
621
- "reason": "Encryption bypassed for stage: development"
649
+ "bypassed": true,
650
+ "runtime": "local",
651
+ "testResult": "Encryption bypassed for this stage"
652
+ }
653
+
654
+ # Response in a deployed stage with no key (the app itself refuses to start):
655
+ {
656
+ "status": "unhealthy",
657
+ "mode": "none",
658
+ "runtime": "deployed",
659
+ "testResult": "[Frigg] No field-level encryption key is configured for stage \"dev\". ..."
660
+ }
661
+
662
+ # Response in a deployed stage with FRIGG_ENCRYPTION_DISABLED=true and no key:
663
+ {
664
+ "status": "disabled",
665
+ "optedOut": true,
666
+ "testResult": "Encryption explicitly disabled (FRIGG_ENCRYPTION_DISABLED=true); sensitive fields are stored in plaintext"
622
667
  }
623
668
  ```
624
669
 
@@ -732,9 +777,10 @@ FRIGG_LOG_LEVEL=INFO
732
777
  **Check environment variables:**
733
778
 
734
779
  ```bash
735
- echo $STAGE # Should be 'production' (not dev/test/local)
736
780
  echo $KMS_KEY_ARN # Should be set (for KMS)
737
- echo $AES_KEY_ID # Should be set (for AES)
781
+ echo $AES_KEY_ID $AES_KEY # Both should be set (for AES)
782
+ echo $STAGE # Local runs only: dev/test/local skip encryption
783
+ echo $FRIGG_ENCRYPTION_DISABLED # Should be unset
738
784
  ```
739
785
 
740
786
  **Check console logs:**
@@ -749,6 +795,22 @@ or
749
795
  [Frigg] Field-level encryption disabled
750
796
  ```
751
797
 
798
+ ### Deployed Stage Refuses to Start
799
+
800
+ **Error: "EncryptionConfigurationError: [Frigg] No field-level encryption key is configured for stage ..."**
801
+
802
+ The function runs in AWS and has neither `KMS_KEY_ARN` nor `AES_KEY_ID` + `AES_KEY`. Earlier versions skipped encryption on stages named `dev`, `test` or `local` and wrote plaintext when no key was set; deployed stages now refuse instead. Fix one of:
803
+
804
+ 1. Set `encryption: { fieldLevelEncryptionMethod: 'kms' }` in the app definition and redeploy. Frigg creates or discovers a KMS key and sets `KMS_KEY_ARN` on every function, whatever the stage name.
805
+ 2. Provide `AES_KEY_ID` and `AES_KEY` (32 characters) through the app definition's `environment` and the deploy environment.
806
+ 3. To keep the stage in plaintext on purpose, set `encryption: { fieldLevelEncryptionMethod: 'none' }` (or `FRIGG_ENCRYPTION_DISABLED=true`).
807
+
808
+ Data written in plaintext before the key existed stays readable: reads leave values that are not in the encrypted `keyId:iv:cipher:encKey` format untouched, and the next write of each record encrypts it. Records that are never rewritten stay in plaintext until you re-save them.
809
+
810
+ **Error: "[Frigg] AES_KEY_ID is set but AES_KEY is not"**
811
+
812
+ Provide `AES_KEY` alongside `AES_KEY_ID`, or switch to KMS.
813
+
752
814
  ### AWS KMS Errors
753
815
 
754
816
  **Error: "User is not authorized to perform: kms:GenerateDataKey"**
@@ -225,7 +225,84 @@ Database (ENCRYPTED STORAGE) ✅ SECURE
225
225
  1. **Consistency**: Same encryption format and Cryptor as Prisma Extension
226
226
  2. **Reusability**: Single service used by all DocumentDB repositories
227
227
  3. **Schema-Driven**: Uses `encryption-schema-registry.js` (same as Prisma)
228
- 4. **Environment-Aware**: Respects STAGE-based bypass (dev/test/local)
228
+ 4. **Fails Closed**: Same rule as the Prisma client; a deployed runtime with no key throws, only local runs skip encryption
229
+ 5. **Error-Tolerant**: Graceful handling of decryption failures
230
+ 6. **Testable**: Can be unit tested independently of repositories
231
+
232
+ ---
233
+
234
+ ## Technical Specification
235
+
236
+ ### Class Design
237
+
238
+ ```javascript
239
+ /**
240
+ * Encryption service specifically for DocumentDB repositories
241
+ * that use $runCommandRaw and bypass Prisma Extensions.
242
+ *
243
+ * Provides document-level encryption/decryption,
244
+ * handling nested fields according to the encryption schema registry.
245
+ */
246
+ class DocumentDBEncryptionService {
247
+ constructor()
248
+ _initializeCryptor()
249
+ async encryptFields(modelName, document)
250
+ async decryptFields(modelName, document)
251
+ async _encryptFieldPath(document, fieldPath, modelName)
252
+ async _decryptFieldPath(document, fieldPath, modelName)
253
+ _isEncryptedValue(value)
254
+ }
255
+ ```
256
+
257
+ ### Method Specifications
258
+
259
+ #### `constructor()`
260
+
261
+ **Purpose**: Initialize the service and configure Cryptor
262
+
263
+ **Behavior**:
264
+
265
+ - Calls `_initializeCryptor()` immediately
266
+ - Sets up `this.cryptor` and `this.enabled` properties
267
+
268
+ **No parameters**
269
+
270
+ ---
271
+
272
+ #### `_initializeCryptor()`
273
+
274
+ **Purpose**: Initialize Cryptor with environment-based configuration
275
+
276
+ **Logic**:
277
+
278
+ ```javascript
279
+ 1. loadCustomEncryptionSchema()
280
+ 2. config = getEncryptionConfig() // encryption/encryption-config.js, shared with the Prisma client
281
+ - throws EncryptionConfigurationError in a deployed runtime with no key
282
+ 3. If !config.enabled (local dev/test/local stage, local run without keys,
283
+ or FRIGG_ENCRYPTION_DISABLED=true opt-out):
284
+ - Set this.cryptor = null
285
+ - Set this.enabled = false
286
+ - Return
287
+ 4. Create Cryptor({ shouldUseAws: config.method === 'kms' })
288
+ 5. Set this.enabled = true
289
+ ```
290
+
291
+ **Environment Variables Used** (see "When Encryption Runs" in README.md):
292
+
293
+ - `AWS_LAMBDA_FUNCTION_NAME` / `LAMBDA_TASK_ROOT` / `AWS_EXECUTION_ENV=AWS_Lambda_*`, minus `IS_OFFLINE` / `IS_LOCAL` / `JEST_WORKER_ID`: deployed or local run
294
+ - `STAGE` or `NODE_ENV`: dev/test/local skip encryption on local runs only
295
+ - `KMS_KEY_ARN`: AWS KMS key ARN (enables KMS encryption)
296
+ - `AES_KEY_ID`: AES key identifier (enables AES encryption)
297
+ - `AES_KEY`: AES encryption key (required with AES_KEY_ID in a deployed runtime)
298
+ - `FRIGG_ENCRYPTION_DISABLED`: explicit plaintext opt-out for a deployed stage with no key
299
+
300
+ ### Design Principles
301
+
302
+ 1. **Consistency**: Same encryption format and Cryptor as Prisma Extension
303
+ 2. **Reusability**: Single service used by all DocumentDB repositories
304
+ 3. **Schema-Driven**: Uses `encryption-schema-registry.js` (same as Prisma)
305
+ 4. **Fails Closed**: Same rule as the Prisma client; a deployed runtime with no key throws, only local runs skip encryption
229
306
  5. **Error-Tolerant**: Graceful handling of decryption failures
230
307
  6. **Testable**: Can be unit tested independently of repositories
231
308
 
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Field-level encryption configuration: decides whether sensitive fields are
3
+ * encrypted, and with which key, from the process environment.
4
+ *
5
+ * The rule fails closed:
6
+ *
7
+ * - **Deployed** (running in AWS Lambda, and not under
8
+ * serverless-offline, `serverless invoke local` or Jest): the stage name is
9
+ * ignored. A configured key (KMS_KEY_ARN, or AES_KEY_ID with AES_KEY) turns
10
+ * encryption on. With no key, the configuration is an error and the Prisma
11
+ * client refuses to start, unless FRIGG_ENCRYPTION_DISABLED=true opts out
12
+ * explicitly.
13
+ * - **Local** (`frigg start`, tests, scripts on a laptop): the stages dev,
14
+ * test and local skip encryption. Any other stage encrypts when a key is
15
+ * configured and stays plaintext, with a warning, when none is.
16
+ *
17
+ * Every module that encrypts or reports on encryption reads this one rule.
18
+ */
19
+
20
+ const { logger } = require('./logger');
21
+
22
+ const LOCAL_BYPASS_STAGES = ['dev', 'test', 'local'];
23
+ const OPT_OUT_VAR = 'FRIGG_ENCRYPTION_DISABLED';
24
+
25
+ class EncryptionConfigurationError extends Error {
26
+ constructor(message) {
27
+ super(message);
28
+ this.name = 'EncryptionConfigurationError';
29
+ }
30
+ }
31
+
32
+ function isSet(value) {
33
+ return typeof value === 'string' && value.trim() !== '';
34
+ }
35
+
36
+ function isTrue(value) {
37
+ if (typeof value !== 'string') return false;
38
+ const normalized = value.trim().toLowerCase();
39
+ return normalized === 'true' || normalized === '1';
40
+ }
41
+
42
+ /**
43
+ * True when the process runs in AWS Lambda for real. The Lambda runtime sets
44
+ * AWS_LAMBDA_FUNCTION_NAME, LAMBDA_TASK_ROOT and AWS_EXECUTION_ENV
45
+ * (AWS_Lambda_<runtime>). serverless-offline sets the first two as well, so
46
+ * IS_OFFLINE, IS_LOCAL and Jest mark a local run. Other AWS hosts (CloudShell,
47
+ * CodeBuild, ECS) set AWS_EXECUTION_ENV to other values and count as local:
48
+ * Frigg deploys its handlers to Lambda only, and CLI commands run from CI must
49
+ * not trip the deployed-stage check.
50
+ *
51
+ * @param {Object} [env=process.env]
52
+ * @returns {boolean}
53
+ */
54
+ function isDeployedRuntime(env = process.env) {
55
+ const onAwsRuntime =
56
+ isSet(env.AWS_LAMBDA_FUNCTION_NAME) ||
57
+ isSet(env.LAMBDA_TASK_ROOT) ||
58
+ String(env.AWS_EXECUTION_ENV ?? '').startsWith('AWS_Lambda_');
59
+ if (!onAwsRuntime) return false;
60
+
61
+ const localRun =
62
+ isTrue(env.IS_OFFLINE) ||
63
+ isTrue(env.IS_LOCAL) ||
64
+ isSet(env.JEST_WORKER_ID);
65
+ return !localRun;
66
+ }
67
+
68
+ function missingKeyMessage(stage) {
69
+ return (
70
+ `[Frigg] No field-level encryption key is configured for stage "${stage}". ` +
71
+ 'A deployed Frigg app will not write credentials and other sensitive fields in plaintext. ' +
72
+ "Fix: set encryption: { fieldLevelEncryptionMethod: 'kms' } in the app definition and redeploy " +
73
+ '(Frigg creates or discovers a KMS key and sets KMS_KEY_ARN), ' +
74
+ 'or provide AES_KEY_ID and AES_KEY (32 characters) in the Lambda environment. ' +
75
+ `To run this stage without encryption on purpose, set ${OPT_OUT_VAR}=true ` +
76
+ "(or encryption: { fieldLevelEncryptionMethod: 'none' } in the app definition)."
77
+ );
78
+ }
79
+
80
+ function incompleteAesMessage(stage) {
81
+ return (
82
+ `[Frigg] AES_KEY_ID is set but AES_KEY is not (stage "${stage}"). ` +
83
+ 'Provide AES_KEY (32 characters) alongside AES_KEY_ID, ' +
84
+ "or use KMS with encryption: { fieldLevelEncryptionMethod: 'kms' }."
85
+ );
86
+ }
87
+
88
+ /**
89
+ * Resolves the encryption configuration without side effects.
90
+ *
91
+ * @param {Object} [env=process.env]
92
+ * @returns {{
93
+ * enabled: boolean,
94
+ * method: 'kms'|'aes'|undefined,
95
+ * mode: 'kms'|'aes'|'none',
96
+ * runtime: 'deployed'|'local',
97
+ * stage: string,
98
+ * bypassed: boolean,
99
+ * optedOut: boolean,
100
+ * optOutIgnored: boolean,
101
+ * hasKMS: boolean,
102
+ * hasAES: boolean,
103
+ * error: string|null,
104
+ * }} `error` is set when a deployed runtime has no usable key.
105
+ */
106
+ function resolveEncryptionConfig(env = process.env) {
107
+ const stage = env.STAGE || env.NODE_ENV || 'development';
108
+ const runtime = isDeployedRuntime(env) ? 'deployed' : 'local';
109
+ const hasKMS = isSet(env.KMS_KEY_ARN);
110
+ const hasAES = isSet(env.AES_KEY_ID);
111
+ const optOutRequested = isTrue(env[OPT_OUT_VAR]);
112
+
113
+ const base = {
114
+ enabled: false,
115
+ method: undefined,
116
+ mode: 'none',
117
+ runtime,
118
+ stage,
119
+ bypassed: false,
120
+ optedOut: false,
121
+ optOutIgnored: false,
122
+ hasKMS,
123
+ hasAES,
124
+ error: null,
125
+ };
126
+
127
+ if (runtime === 'local') {
128
+ if (LOCAL_BYPASS_STAGES.includes(String(stage).toLowerCase())) {
129
+ return { ...base, bypassed: true };
130
+ }
131
+ if (hasKMS || hasAES) {
132
+ const method = hasKMS ? 'kms' : 'aes';
133
+ return { ...base, enabled: true, method, mode: method };
134
+ }
135
+ return base;
136
+ }
137
+
138
+ const hasCompleteAES = hasAES && isSet(env.AES_KEY);
139
+ if (hasKMS || hasCompleteAES) {
140
+ const method = hasKMS ? 'kms' : 'aes';
141
+ return {
142
+ ...base,
143
+ enabled: true,
144
+ method,
145
+ mode: method,
146
+ optOutIgnored: optOutRequested,
147
+ };
148
+ }
149
+
150
+ if (optOutRequested) {
151
+ return { ...base, optedOut: true };
152
+ }
153
+
154
+ return {
155
+ ...base,
156
+ error: hasAES ? incompleteAesMessage(stage) : missingKeyMessage(stage),
157
+ };
158
+ }
159
+
160
+ const warned = new Set();
161
+
162
+ function warnOnce(key, message) {
163
+ if (warned.has(key)) return;
164
+ warned.add(key);
165
+ logger.warn(message);
166
+ }
167
+
168
+ /**
169
+ * Resolves the encryption configuration for use: throws when a deployed
170
+ * runtime has no usable key, and warns once per process (once per Lambda
171
+ * cold start) when encryption is explicitly disabled.
172
+ *
173
+ * @param {Object} [env=process.env]
174
+ * @returns {ReturnType<typeof resolveEncryptionConfig>}
175
+ * @throws {EncryptionConfigurationError}
176
+ */
177
+ function getEncryptionConfig(env = process.env) {
178
+ const config = resolveEncryptionConfig(env);
179
+
180
+ if (config.error) {
181
+ throw new EncryptionConfigurationError(config.error);
182
+ }
183
+
184
+ if (config.optedOut) {
185
+ warnOnce(
186
+ 'opted-out',
187
+ `[Frigg] ${OPT_OUT_VAR}=true: field-level encryption is OFF for stage "${config.stage}". ` +
188
+ 'Credentials and other sensitive fields are stored in PLAINTEXT. ' +
189
+ `Remove ${OPT_OUT_VAR} and configure a key (fieldLevelEncryptionMethod: 'kms') to encrypt them.`
190
+ );
191
+ }
192
+
193
+ if (config.optOutIgnored) {
194
+ warnOnce(
195
+ 'opt-out-ignored',
196
+ `[Frigg] ${OPT_OUT_VAR}=true is ignored because an encryption key is configured; ` +
197
+ `fields are encrypted with ${config.method.toUpperCase()}. ` +
198
+ 'Turning encryption off while a key is present would leave encrypted data unreadable.'
199
+ );
200
+ }
201
+
202
+ if (config.runtime === 'local' && !config.enabled && !config.bypassed) {
203
+ warnOnce(
204
+ 'local-no-keys',
205
+ `No encryption keys configured (KMS_KEY_ARN or AES_KEY_ID) for local stage "${config.stage}". ` +
206
+ 'Field-level encryption disabled for this local run. ' +
207
+ 'A deployed stage without a key refuses to start.'
208
+ );
209
+ }
210
+
211
+ return config;
212
+ }
213
+
214
+ /** Test helper: let the once-per-process warnings fire again. */
215
+ function resetEncryptionConfigWarnings() {
216
+ warned.clear();
217
+ }
218
+
219
+ module.exports = {
220
+ EncryptionConfigurationError,
221
+ LOCAL_BYPASS_STAGES,
222
+ OPT_OUT_VAR,
223
+ getEncryptionConfig,
224
+ isDeployedRuntime,
225
+ resetEncryptionConfigWarnings,
226
+ resolveEncryptionConfig,
227
+ };
@@ -1,4 +1,4 @@
1
- const { getEncryptionConfig } = require('../prisma');
1
+ const { getEncryptionConfig } = require('./encryption-config');
2
2
  const { Cryptor } = require('../../encrypt/Cryptor');
3
3
  const {
4
4
  getFieldsToDecryptOnRead,
@@ -4,6 +4,7 @@ const {
4
4
  const { loadCustomEncryptionSchema } = require('./encryption/encryption-schema-registry');
5
5
  const { logger } = require('./encryption/logger');
6
6
  const { Cryptor } = require('../encrypt/Cryptor');
7
+ const { getEncryptionConfig } = require('./encryption/encryption-config');
7
8
  const config = require('./config');
8
9
 
9
10
  /**
@@ -32,33 +33,6 @@ function ensureMongoDbUrl() {
32
33
  );
33
34
  }
34
35
 
35
- function getEncryptionConfig() {
36
- const STAGE = process.env.STAGE || process.env.NODE_ENV || 'development';
37
- const shouldBypassEncryption = ['dev', 'test', 'local'].includes(STAGE);
38
-
39
- if (shouldBypassEncryption) {
40
- return { enabled: false };
41
- }
42
-
43
- const hasKMS =
44
- process.env.KMS_KEY_ARN && process.env.KMS_KEY_ARN.trim() !== '';
45
- const hasAES =
46
- process.env.AES_KEY_ID && process.env.AES_KEY_ID.trim() !== '';
47
-
48
- if (!hasKMS && !hasAES) {
49
- logger.warn(
50
- 'No encryption keys configured (KMS_KEY_ARN or AES_KEY_ID). ' +
51
- 'Field-level encryption disabled. Set STAGE=production and configure keys to enable.'
52
- );
53
- return { enabled: false };
54
- }
55
-
56
- return {
57
- enabled: true,
58
- method: hasKMS ? 'kms' : 'aes',
59
- };
60
- }
61
-
62
36
  const prismaClientSingleton = () => {
63
37
  let PrismaClient;
64
38
 
@@ -103,9 +77,13 @@ const prismaClientSingleton = () => {
103
77
  errorFormat: 'pretty',
104
78
  });
105
79
 
80
+ // Throws when a deployed runtime has no encryption key: the app must not
81
+ // start and write sensitive fields in plaintext.
106
82
  const encryptionConfig = getEncryptionConfig();
107
83
 
108
84
  if (encryptionConfig.enabled) {
85
+ // Fail closed: if the extension cannot be installed, do not hand out
86
+ // a client that would write plaintext.
109
87
  try {
110
88
  // Load custom encryption schema from appDefinition before creating extension
111
89
  loadCustomEncryptionSchema();
@@ -120,17 +98,14 @@ const prismaClientSingleton = () => {
120
98
  enabled: true,
121
99
  })
122
100
  );
123
-
124
- logger.info(
125
- `Field-level encryption enabled using ${encryptionConfig.method.toUpperCase()}`
126
- );
127
101
  } catch (error) {
128
- logger.error(
129
- 'Failed to initialize encryption extension:',
130
- error
131
- );
132
- logger.warn('Continuing without encryption...');
102
+ logger.error('Failed to initialize encryption extension:', error);
103
+ throw error;
133
104
  }
105
+
106
+ logger.info(
107
+ `Field-level encryption enabled using ${encryptionConfig.method.toUpperCase()}`
108
+ );
134
109
  } else {
135
110
  logger.info('Field-level encryption disabled');
136
111
  }
@@ -1,3 +1,12 @@
1
+ const {
2
+ resolveEncryptionConfig,
3
+ OPT_OUT_VAR,
4
+ } = require('../encryption/encryption-config');
5
+
6
+ /**
7
+ * Reports whether field-level encryption is on and working, using the same
8
+ * rule the Prisma client applies at startup (encryption/encryption-config.js).
9
+ */
1
10
  class CheckEncryptionHealthUseCase {
2
11
  constructor({ testEncryptionUseCase }) {
3
12
  this.testEncryptionUseCase = testEncryptionUseCase;
@@ -5,78 +14,60 @@ class CheckEncryptionHealthUseCase {
5
14
 
6
15
  async execute() {
7
16
  const config = this._getEncryptionConfiguration();
17
+ const summary = {
18
+ mode: config.mode,
19
+ bypassed: config.bypassed,
20
+ optedOut: config.optedOut,
21
+ runtime: config.runtime,
22
+ stage: config.stage,
23
+ debug: {
24
+ hasKMS: config.hasKMS,
25
+ hasAES: config.hasAES,
26
+ },
27
+ };
8
28
 
9
- if (config.isBypassed || config.mode === 'none') {
10
- const testResult = config.isBypassed
11
- ? 'Encryption bypassed for this stage'
12
- : 'No encryption keys configured';
29
+ if (config.error) {
30
+ return {
31
+ status: 'unhealthy',
32
+ ...summary,
33
+ testResult: config.error,
34
+ encryptionWorks: false,
35
+ };
36
+ }
13
37
 
38
+ if (!config.enabled) {
14
39
  return {
15
40
  status: 'disabled',
16
- mode: config.mode,
17
- bypassed: config.isBypassed,
18
- stage: config.stage,
19
- testResult,
41
+ ...summary,
42
+ testResult: this._disabledReason(config),
20
43
  encryptionWorks: false,
21
- debug: {
22
- hasKMS: config.hasKMS,
23
- hasAES: config.hasAES,
24
- },
25
44
  };
26
45
  }
27
46
 
28
47
  try {
29
48
  const testResults = await this.testEncryptionUseCase.execute();
30
-
31
- return {
32
- ...testResults,
33
- mode: config.mode,
34
- bypassed: config.isBypassed,
35
- stage: config.stage,
36
- debug: {
37
- hasKMS: config.hasKMS,
38
- hasAES: config.hasAES,
39
- },
40
- };
49
+ return { ...testResults, ...summary };
41
50
  } catch (error) {
42
51
  return {
43
52
  status: 'unhealthy',
44
- mode: config.mode,
45
- bypassed: config.isBypassed,
46
- stage: config.stage,
53
+ ...summary,
47
54
  testResult: `Encryption test failed: ${error.message}`,
48
55
  encryptionWorks: false,
49
- debug: {
50
- hasKMS: config.hasKMS,
51
- hasAES: config.hasAES,
52
- },
53
56
  };
54
57
  }
55
58
  }
56
59
 
57
- _getEncryptionConfiguration() {
58
- const { STAGE, BYPASS_ENCRYPTION_STAGE, KMS_KEY_ARN, AES_KEY_ID } =
59
- process.env;
60
-
61
- const defaultBypassStages = ['dev', 'test', 'local'];
62
- const useEnv = BYPASS_ENCRYPTION_STAGE !== undefined;
63
- const bypassStages = useEnv
64
- ? BYPASS_ENCRYPTION_STAGE.split(',').map((s) => s.trim())
65
- : defaultBypassStages;
66
-
67
- const isBypassed = bypassStages.includes(STAGE);
68
- const hasAES = AES_KEY_ID && AES_KEY_ID.trim() !== '';
69
- const hasKMS = KMS_KEY_ARN && KMS_KEY_ARN.trim() !== '';
70
- // Prefer KMS over AES when both are configured (KMS is more secure)
71
- const mode = hasKMS ? 'kms' : hasAES ? 'aes' : 'none';
60
+ _disabledReason(config) {
61
+ if (config.bypassed) return 'Encryption bypassed for this stage';
62
+ if (config.optedOut) {
63
+ return `Encryption explicitly disabled (${OPT_OUT_VAR}=true); sensitive fields are stored in plaintext`;
64
+ }
65
+ return 'No encryption keys configured';
66
+ }
72
67
 
73
- return {
74
- stage: STAGE || null,
75
- isBypassed,
76
- hasAES,
77
- hasKMS,
78
- mode,
79
- };
68
+ _getEncryptionConfiguration() {
69
+ const config = resolveEncryptionConfig(process.env);
70
+ return { ...config, stage: process.env.STAGE || null };
80
71
  }
81
72
  }
82
73
 
@@ -1,5 +1,8 @@
1
1
  const { Module } = require('../module');
2
2
  const { ModuleConstants } = require('../ModuleConstants');
3
+ const { getLogger } = require('../../logs');
4
+
5
+ const log = getLogger('frigg.modules.authorization_callback');
3
6
 
4
7
  // Statuses considered "broken" for an integration whose credentials have just
5
8
  // been successfully re-authorized. Both ERROR (system-driven auth failure) and
@@ -28,10 +31,12 @@ class ProcessAuthorizationCallback {
28
31
  }
29
32
 
30
33
  async execute(userId, entityType, params) {
31
- const hasCode = Boolean(params && params.code);
32
- console.log(
33
- `[Frigg] processAuthorizationCallback start userId=${userId} entityType=${entityType} hasCode=${hasCode}`
34
- );
34
+ log.debug('Authorization callback started', {
35
+ eventName: `${log.name}.started`,
36
+ userId,
37
+ entityType,
38
+ hasCode: Boolean(params && params.code),
39
+ });
35
40
 
36
41
  const moduleDefinition = this.moduleDefinitions.find((def) => {
37
42
  return entityType === def.moduleName;
@@ -58,9 +63,11 @@ class ProcessAuthorizationCallback {
58
63
  : null;
59
64
 
60
65
  if (existingEntity) {
61
- console.log(
62
- `[Frigg] processAuthorizationCallback found existing entity id=${existingEntity.id} credentialId=${existingEntity.credential?.id}`
63
- );
66
+ log.debug('Existing entity found', {
67
+ eventName: `${log.name}.existing_entity_found`,
68
+ entityId: existingEntity.id,
69
+ credentialId: existingEntity.credential?.id,
70
+ });
64
71
  }
65
72
 
66
73
  const module = new Module({
@@ -70,18 +77,25 @@ class ProcessAuthorizationCallback {
70
77
  });
71
78
 
72
79
  const authType = module.apiClass.requesterType;
73
- console.log(`[Frigg][OAuth] Module created: name=${module.getName()}, authType=${authType}`);
80
+ log.debug('Module created', {
81
+ eventName: `${log.name}.module_created`,
82
+ moduleName: module.getName(),
83
+ authType,
84
+ });
74
85
 
75
86
  let tokenResponse;
76
87
  if (authType === ModuleConstants.authType.oauth2) {
77
- console.log(`[Frigg][OAuth] Exchanging authorization code for token...`);
88
+ log.debug('Exchanging authorization code for token', {
89
+ eventName: `${log.name}.token_exchanging`,
90
+ });
78
91
  tokenResponse = await moduleDefinition.requiredAuthMethods.getToken(
79
92
  module.api,
80
93
  params
81
94
  );
82
- console.log(
83
- `[Frigg] processAuthorizationCallback OAuth getToken complete userId=${userId} entityType=${entityType}`
84
- );
95
+ log.debug('Token exchange completed', {
96
+ eventName: `${log.name}.token_exchanged`,
97
+ tokenKeys: Object.keys(tokenResponse || {}),
98
+ });
85
99
  // Belt-and-suspenders: persist tokens explicitly here rather than
86
100
  // relying solely on the DLGT_TOKEN_UPDATE notification chain
87
101
  // inside setTokens. The notification path remains in place but
@@ -90,29 +104,35 @@ class ProcessAuthorizationCallback {
90
104
  // OAuth flow appears to succeed.
91
105
  await this.onTokenUpdate(module, moduleDefinition, userId);
92
106
  } else {
93
- console.log(`[Frigg][OAuth] Setting auth params (non-OAuth2)...`);
107
+ log.debug('Setting auth params', {
108
+ eventName: `${log.name}.auth_params_setting`,
109
+ });
94
110
  tokenResponse =
95
111
  await moduleDefinition.requiredAuthMethods.setAuthParams(
96
112
  module.api,
97
113
  params
98
114
  );
99
115
  await this.onTokenUpdate(module, moduleDefinition, userId);
100
- console.log(`[Frigg][OAuth] Auth params set and credential persisted`);
101
116
  }
102
117
 
103
- console.log(
104
- `[Frigg] processAuthorizationCallback credential persisted credentialId=${module.credential?.id} authIsValid=${module.credential?.authIsValid}`
105
- );
118
+ log.debug('Credential persisted', {
119
+ eventName: `${log.name}.credential_persisted`,
120
+ credentialId: module.credential?.id,
121
+ authIsValid: module.credential?.authIsValid,
122
+ });
106
123
 
107
- console.log(`[Frigg][OAuth] Testing auth...`);
124
+ log.debug('Testing auth', { eventName: `${log.name}.auth_testing` });
108
125
  const authRes = await module.testAuth();
109
126
  if (!authRes) {
110
- console.error(`[Frigg][OAuth] testAuth() returned false — authorization failed`);
111
127
  throw new Error('Authorization failed');
112
128
  }
113
- console.log(`[Frigg][OAuth] Auth test passed`);
129
+ log.debug('Auth test passed', {
130
+ eventName: `${log.name}.auth_test_passed`,
131
+ });
114
132
 
115
- console.log(`[Frigg][OAuth] Fetching entity details...`);
133
+ log.debug('Fetching entity details', {
134
+ eventName: `${log.name}.entity_details_fetching`,
135
+ });
116
136
  const entityDetails =
117
137
  await moduleDefinition.requiredAuthMethods.getEntityDetails(
118
138
  module.api,
@@ -120,20 +140,29 @@ class ProcessAuthorizationCallback {
120
140
  tokenResponse,
121
141
  userId
122
142
  );
123
- console.log(`[Frigg][OAuth] Entity details received: identifiers=${JSON.stringify(entityDetails.identifiers)}`);
143
+ log.debug('Entity details received', {
144
+ eventName: `${log.name}.entity_details_received`,
145
+ externalId: entityDetails.identifiers?.externalId,
146
+ });
124
147
 
125
148
  Object.assign(
126
149
  entityDetails.details,
127
150
  module.apiParamsFromEntity(module.api)
128
151
  );
129
152
 
130
- console.log(`[Frigg][OAuth] Finding or creating entity...`);
153
+ log.debug('Finding or creating entity', {
154
+ eventName: `${log.name}.entity_resolving`,
155
+ });
131
156
  const persistedEntity = await this.findOrCreateEntity(
132
157
  entityDetails,
133
158
  entityType,
134
159
  module.credential.id
135
160
  );
136
- console.log(`[Frigg][OAuth] Done — entity_id=${persistedEntity.id}, credential_id=${module.credential.id}`);
161
+ log.debug('Authorization callback completed', {
162
+ eventName: `${log.name}.completed`,
163
+ entityId: persistedEntity.id,
164
+ credentialId: module.credential.id,
165
+ });
137
166
 
138
167
  // Best-effort: a hiccup here must not fail a successful re-auth whose
139
168
  // credential + entity are already persisted. Operators can recover
@@ -142,14 +171,17 @@ class ProcessAuthorizationCallback {
142
171
  const restoredCount = await this.restoreIntegrationsForEntity(
143
172
  persistedEntity.id
144
173
  );
145
- console.log(
146
- `[Frigg] processAuthorizationCallback restored ${restoredCount} integration(s) for entityId=${persistedEntity.id}`
147
- );
174
+ log.debug('Integrations restored', {
175
+ eventName: `${log.name}.integrations_restored`,
176
+ entityId: persistedEntity.id,
177
+ restoredCount,
178
+ });
148
179
  } catch (err) {
149
- console.error(
150
- `[Frigg] Failed to restore integrations for entity ${persistedEntity.id} after successful re-auth — manual intervention may be needed`,
151
- err
152
- );
180
+ log.error('Failed to restore integrations after re-auth', {
181
+ eventName: `${log.name}.integrations_restore_failed`,
182
+ entityId: persistedEntity.id,
183
+ error: err,
184
+ });
153
185
  }
154
186
 
155
187
  return {
@@ -168,9 +200,12 @@ class ProcessAuthorizationCallback {
168
200
  let restored = 0;
169
201
  for (const integration of integrations) {
170
202
  if (STATUSES_RESET_ON_REAUTH.includes(integration.status)) {
171
- console.log(
172
- `[Frigg] Restoring integration ${integration.id} from ${integration.status} to ENABLED after successful re-auth (entityId=${entityId})`
173
- );
203
+ log.info('Integration restored to ENABLED after re-auth', {
204
+ eventName: `${log.name}.integration_restored`,
205
+ integrationId: integration.id,
206
+ previousStatus: integration.status,
207
+ entityId,
208
+ });
174
209
  await this.integrationRepository.updateIntegrationStatus(
175
210
  integration.id,
176
211
  'ENABLED'
@@ -232,9 +267,12 @@ class ProcessAuthorizationCallback {
232
267
  credentialId &&
233
268
  String(existingCredentialId) !== String(credentialId)
234
269
  ) {
235
- console.log(
236
- `[Frigg] Repointing entity ${existingEntity.id} credentialId ${existingCredentialId} -> ${credentialId} after re-auth`
237
- );
270
+ log.info('Entity credential repointed after re-auth', {
271
+ eventName: `${log.name}.entity_credential_repointed`,
272
+ entityId: existingEntity.id,
273
+ previousCredentialId: existingCredentialId,
274
+ credentialId,
275
+ });
238
276
  const updated = await this.moduleRepository.updateEntity(
239
277
  existingEntity.id,
240
278
  { credential: credentialId }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@friggframework/core",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.540.4653c0a.0",
4
+ "version": "2.0.0--canary.663.9683f8b.0",
5
5
  "dependencies": {
6
6
  "@aws-sdk/client-apigatewaymanagementapi": "^3.588.0",
7
7
  "@aws-sdk/client-kms": "^3.588.0",
@@ -47,9 +47,9 @@
47
47
  }
48
48
  },
49
49
  "devDependencies": {
50
- "@friggframework/eslint-config": "2.0.0--canary.540.4653c0a.0",
51
- "@friggframework/prettier-config": "2.0.0--canary.540.4653c0a.0",
52
- "@friggframework/test": "2.0.0--canary.540.4653c0a.0",
50
+ "@friggframework/eslint-config": "2.0.0--canary.663.9683f8b.0",
51
+ "@friggframework/prettier-config": "2.0.0--canary.663.9683f8b.0",
52
+ "@friggframework/test": "2.0.0--canary.663.9683f8b.0",
53
53
  "@prisma/client": "^6.19.3",
54
54
  "@types/lodash": "4.17.15",
55
55
  "@typescript-eslint/eslint-plugin": "^8.0.0",
@@ -89,5 +89,5 @@
89
89
  "publishConfig": {
90
90
  "access": "public"
91
91
  },
92
- "gitHead": "4653c0a949b5a88591424a8114a071a96af35b7d"
92
+ "gitHead": "9683f8b4ecbbb8a91b497c63e04277490769bad8"
93
93
  }
@@ -1,4 +1,7 @@
1
1
  const Boom = require('@hapi/boom');
2
+ const { getLogger } = require('../../logs');
3
+
4
+ const log = getLogger('frigg.user.authentication');
2
5
 
3
6
  /**
4
7
  * Use case for authenticating a user using multiple authentication strategies.
@@ -50,18 +53,18 @@ class AuthenticateUser {
50
53
  const authModes = this.userConfig.authModes || { friggToken: true };
51
54
  const appUserId = req.headers['x-frigg-appuserid'];
52
55
  const appOrgId = req.headers['x-frigg-apporgid'];
53
- console.log(
54
- '[Frigg] header list:',
55
- JSON.stringify(Object.keys(req.headers))
56
- );
56
+ log.debug('Request headers received', {
57
+ eventName: `${log.name}.headers_received`,
58
+ headerNames: Object.keys(req.headers),
59
+ });
57
60
 
58
61
  // Priority 1: Shared Secret (backend-to-backend with API key)
59
62
  if (authModes.sharedSecret !== false) {
60
63
  const apiKey = req.headers['x-frigg-api-key'];
61
64
  if (apiKey) {
62
- console.log(
63
- '[Frigg] Attempting shared secret authentication with API key'
64
- );
65
+ log.debug('Attempting shared secret authentication', {
66
+ eventName: `${log.name}.shared_secret_attempted`,
67
+ });
65
68
  // Validate the API key (authentication)
66
69
  await this.authenticateWithSharedSecret.execute(apiKey);
67
70
  // Get user from x-frigg headers (authorization)
@@ -70,9 +73,9 @@ class AuthenticateUser {
70
73
  appOrgId
71
74
  );
72
75
  }
73
- console.log(
74
- '[Frigg] No x-frigg-api-key header found, skipping shared secret authentication'
75
- );
76
+ log.debug('No x-frigg-api-key header, skipping shared secret', {
77
+ eventName: `${log.name}.shared_secret_skipped`,
78
+ });
76
79
  }
77
80
 
78
81
  // Priority 2: Adopter JWT (if enabled)
@@ -80,7 +83,9 @@ class AuthenticateUser {
80
83
  authModes.adopterJwt === true &&
81
84
  req.headers.authorization?.startsWith('Bearer ')
82
85
  ) {
83
- console.log('[Frigg] Attempting Adopter JWT authentication');
86
+ log.debug('Attempting adopter JWT authentication', {
87
+ eventName: `${log.name}.adopter_jwt_attempted`,
88
+ });
84
89
  const token = req.headers.authorization.split(' ')[1];
85
90
  // Detect JWT format (3 parts separated by dots)
86
91
  if (token && token.split('.').length === 3) {
@@ -95,7 +100,9 @@ class AuthenticateUser {
95
100
 
96
101
  // Priority 3: Frigg native token (default)
97
102
  if (authModes.friggToken !== false && req.headers.authorization) {
98
- console.log('[Frigg] Attempting Frigg native token authentication');
103
+ log.debug('Attempting Frigg native token authentication', {
104
+ eventName: `${log.name}.frigg_token_attempted`,
105
+ });
99
106
  const user = await this.getUserFromBearerToken.execute(
100
107
  req.headers.authorization
101
108
  );