@friggframework/devtools 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.
Files changed (30) hide show
  1. package/frigg-cli/README.md +41 -1
  2. package/frigg-cli/generate-command/__tests__/generate-command.test.js +36 -0
  3. package/frigg-cli/generate-command/index.js +3 -1
  4. package/frigg-cli/generate-command/terraform-generator.js +48 -0
  5. package/frigg-cli/generate-iam-command.js +1 -0
  6. package/frigg-cli/index.js +8 -0
  7. package/frigg-cli/templates/backend/README.md +3 -2
  8. package/frigg-cli/tls-check-command/__tests__/check-post-quantum-tls.test.js +396 -0
  9. package/frigg-cli/tls-check-command/__tests__/tls-check-command.test.js +182 -0
  10. package/frigg-cli/tls-check-command/check-post-quantum-tls.js +194 -0
  11. package/frigg-cli/tls-check-command/index.js +136 -0
  12. package/frigg-cli/validate-command/__tests__/validate-app-definition.test.js +69 -0
  13. package/frigg-cli/validate-command/checks/config.js +59 -0
  14. package/infrastructure/app-definition-schema-contract.test.js +10 -0
  15. package/infrastructure/domains/admin-scripts/admin-script-builder.js +8 -16
  16. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +0 -27
  17. package/infrastructure/domains/edge/cloudfront-builder.js +237 -0
  18. package/infrastructure/domains/edge/cloudfront-builder.test.js +273 -0
  19. package/infrastructure/domains/security/iam-generator.js +45 -2
  20. package/infrastructure/domains/security/iam-generator.test.js +23 -0
  21. package/infrastructure/domains/security/templates/iam-policy-full.json +30 -1
  22. package/infrastructure/domains/shared/builder-orchestrator.js +6 -0
  23. package/infrastructure/domains/shared/builder-orchestrator.test.js +30 -0
  24. package/infrastructure/domains/shared/function-environments.js +6 -10
  25. package/infrastructure/domains/shared/function-environments.test.js +0 -9
  26. package/infrastructure/domains/shared/utilities/base-definition-factory.js +9 -2
  27. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +11 -0
  28. package/infrastructure/infrastructure-composer.js +8 -0
  29. package/infrastructure/infrastructure-composer.test.js +35 -0
  30. package/package.json +7 -7
@@ -0,0 +1,182 @@
1
+ const { tlsCheckCommand } = require('..');
2
+
3
+ const stripAnsi = (text) => text.replace(/\u001b\[[0-9;]*m/g, '');
4
+
5
+ function run(endpoints, options, results) {
6
+ const lines = [];
7
+ const check = jest.fn(async ({ host, port }) => ({
8
+ host,
9
+ port,
10
+ ...results[host],
11
+ }));
12
+ const previousExitCode = process.exitCode;
13
+ process.exitCode = undefined;
14
+ return tlsCheckCommand(endpoints, options, {
15
+ check,
16
+ log: (line) => lines.push(stripAnsi(String(line))),
17
+ }).then((report) => {
18
+ const exitCode = process.exitCode;
19
+ process.exitCode = previousExitCode;
20
+ return { report, lines, check, exitCode };
21
+ });
22
+ }
23
+
24
+ describe('frigg tls-check', () => {
25
+ it('checks every endpoint and exits 0 when all accept the hybrid group', async () => {
26
+ const { lines, check, exitCode } = await run(
27
+ ['https://d111.cloudfront.net/api', 'kms.us-east-1.amazonaws.com'],
28
+ {},
29
+ {
30
+ 'd111.cloudfront.net': {
31
+ result: 'accepted',
32
+ tlsVersion: 'TLSv1.3',
33
+ },
34
+ 'kms.us-east-1.amazonaws.com': {
35
+ result: 'accepted',
36
+ tlsVersion: 'TLSv1.3',
37
+ },
38
+ }
39
+ );
40
+
41
+ expect(check).toHaveBeenCalledTimes(2);
42
+ expect(check).toHaveBeenCalledWith(
43
+ expect.objectContaining({
44
+ host: 'd111.cloudfront.net',
45
+ port: 443,
46
+ timeoutMs: 10000,
47
+ })
48
+ );
49
+ expect(exitCode).toBeUndefined();
50
+ const text = lines.join('\n');
51
+ expect(text).toMatch(
52
+ /d111\.cloudfront\.net:443.*accepts X25519MLKEM768/
53
+ );
54
+ expect(text).toMatch(/2 of 2 endpoints accept/);
55
+ });
56
+
57
+ it('exits 1 and explains when an endpoint refuses the group', async () => {
58
+ const { lines, exitCode } = await run(
59
+ ['https://abc.execute-api.us-east-1.amazonaws.com/prod'],
60
+ {},
61
+ {
62
+ 'abc.execute-api.us-east-1.amazonaws.com': {
63
+ result: 'refused',
64
+ detail: 'The server refused X25519MLKEM768 over TLS 1.3, so clients get classical key exchange only.',
65
+ },
66
+ }
67
+ );
68
+
69
+ expect(exitCode).toBe(1);
70
+ const text = lines.join('\n');
71
+ expect(text).toMatch(/classical key exchange only/);
72
+ expect(text).toMatch(/0 of 1 endpoints accept/);
73
+ });
74
+
75
+ it('shows a certificate warning but still counts the endpoint as accepted', async () => {
76
+ const { lines, exitCode } = await run(
77
+ ['internal.example.com'],
78
+ {},
79
+ {
80
+ 'internal.example.com': {
81
+ result: 'accepted',
82
+ tlsVersion: 'TLSv1.3',
83
+ certificateError:
84
+ 'DEPTH_ZERO_SELF_SIGNED_CERT: self-signed certificate',
85
+ },
86
+ }
87
+ );
88
+
89
+ expect(exitCode).toBeUndefined();
90
+ expect(lines.join('\n')).toMatch(/certificate.*self-signed/i);
91
+ });
92
+
93
+ it('exits 2 when this Node.js cannot offer the group', async () => {
94
+ const { lines, exitCode } = await run(
95
+ ['example.com'],
96
+ {},
97
+ {
98
+ 'example.com': {
99
+ result: 'unsupported-client',
100
+ detail: 'This Node.js cannot offer X25519MLKEM768.',
101
+ },
102
+ }
103
+ );
104
+
105
+ expect(exitCode).toBe(2);
106
+ expect(lines.join('\n')).toMatch(/cannot offer/);
107
+ });
108
+
109
+ it('prints JSON with --json', async () => {
110
+ const { lines, report } = await run(
111
+ ['example.com'],
112
+ { json: true },
113
+ {
114
+ 'example.com': { result: 'accepted', tlsVersion: 'TLSv1.3' },
115
+ }
116
+ );
117
+
118
+ const parsed = JSON.parse(lines.join('\n'));
119
+ expect(parsed).toEqual(report);
120
+ expect(parsed).toEqual({
121
+ group: 'X25519MLKEM768',
122
+ results: [
123
+ {
124
+ host: 'example.com',
125
+ port: 443,
126
+ result: 'accepted',
127
+ tlsVersion: 'TLSv1.3',
128
+ },
129
+ ],
130
+ });
131
+ });
132
+
133
+ it('passes --timeout to the check', async () => {
134
+ const { check } = await run(
135
+ ['example.com'],
136
+ { timeout: '2500' },
137
+ {
138
+ 'example.com': { result: 'accepted' },
139
+ }
140
+ );
141
+
142
+ expect(check).toHaveBeenCalledWith(
143
+ expect.objectContaining({ timeoutMs: 2500 })
144
+ );
145
+ });
146
+
147
+ it.each(['-5', '0', 'abc', '1.5'])(
148
+ 'refuses the timeout %s with a clear message and exits 1',
149
+ async (timeout) => {
150
+ const { lines, check, exitCode } = await run(
151
+ ['example.com'],
152
+ { timeout },
153
+ {}
154
+ );
155
+
156
+ expect(check).not.toHaveBeenCalled();
157
+ expect(exitCode).toBe(1);
158
+ expect(lines.join('\n')).toMatch(
159
+ /--timeout must be a whole number of milliseconds/
160
+ );
161
+ }
162
+ );
163
+
164
+ it('reports a bad endpoint value without a stack trace and exits 1', async () => {
165
+ const { lines, check, exitCode } = await run(
166
+ ['http://plain.example.com'],
167
+ {},
168
+ {}
169
+ );
170
+
171
+ expect(check).not.toHaveBeenCalled();
172
+ expect(exitCode).toBe(1);
173
+ expect(lines.join('\n')).toMatch(/does not use TLS/);
174
+ });
175
+
176
+ it('asks for at least one endpoint', async () => {
177
+ const { lines, exitCode } = await run([], {}, {});
178
+
179
+ expect(exitCode).toBe(1);
180
+ expect(lines.join('\n')).toMatch(/Give at least one endpoint/);
181
+ });
182
+ });
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Checks whether a TLS endpoint accepts hybrid post-quantum key exchange.
3
+ *
4
+ * The client offers only the hybrid group X25519MLKEM768 (X25519 + ML-KEM-768,
5
+ * FIPS 203) and only TLS 1.3. A server that accepts the group completes the
6
+ * handshake. A server that knows only classical groups, or has no TLS 1.3,
7
+ * answers with a TLS alert.
8
+ *
9
+ * In TLS 1.3 the client checks the certificate after the server has accepted a
10
+ * key share, so a certificate error still means "accepted".
11
+ *
12
+ * The check connects directly. It does not use HTTPS_PROXY, and a
13
+ * TLS-intercepting proxy on the path is what it then measures.
14
+ */
15
+
16
+ const net = require('net');
17
+ const nodeTls = require('tls');
18
+
19
+ const HYBRID_POST_QUANTUM_GROUP = 'X25519MLKEM768';
20
+ const DEFAULT_TIMEOUT_MS = 10000;
21
+
22
+ const UNREACHABLE_CODES = new Set([
23
+ 'ENOTFOUND',
24
+ 'EAI_AGAIN',
25
+ 'ECONNREFUSED',
26
+ 'ETIMEDOUT',
27
+ 'EHOSTUNREACH',
28
+ 'ENETUNREACH',
29
+ ]);
30
+
31
+ /**
32
+ * @param {string} value an https:// or wss:// URL, a host, or host:port
33
+ * @returns {{ host: string, port: number }}
34
+ */
35
+ function parseEndpoint(value) {
36
+ const text = String(value || '').trim();
37
+ if (!text) {
38
+ throw new Error(
39
+ 'Give an endpoint: an https:// URL, a host, or host:port.'
40
+ );
41
+ }
42
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(text);
43
+ const url = new URL(hasScheme ? text : `https://${text}`);
44
+ if (url.protocol !== 'https:' && url.protocol !== 'wss:') {
45
+ throw new Error(
46
+ `"${text}" does not use TLS. Give an https:// or wss:// URL.`
47
+ );
48
+ }
49
+ return {
50
+ // URL keeps the brackets of an IPv6 address ("[::1]").
51
+ host: url.hostname.replace(/^\[(.*)\]$/, '$1'),
52
+ port: url.port ? Number(url.port) : 443,
53
+ };
54
+ }
55
+
56
+ function describeError(error) {
57
+ const code = error && error.code ? `${error.code}: ` : '';
58
+ return `${code}${error && error.message ? error.message : String(error)}`;
59
+ }
60
+
61
+ /**
62
+ * A TLS alert from the server, or a key share the client cannot use (a
63
+ * HelloRetryRequest that asks for a classical group), means "no hybrid group".
64
+ */
65
+ function isRefusal(error) {
66
+ const code = String((error && error.code) || '');
67
+ return (
68
+ code.startsWith('ERR_SSL_') &&
69
+ (code.includes('ALERT') || code.includes('KEY_SHARE'))
70
+ );
71
+ }
72
+
73
+ function isCertificateError(error) {
74
+ // Node reports certificate problems with OpenSSL X509 verify codes, for
75
+ // example CERT_HAS_EXPIRED, DEPTH_ZERO_SELF_SIGNED_CERT,
76
+ // UNABLE_TO_VERIFY_LEAF_SIGNATURE or ERR_TLS_CERT_ALTNAME_INVALID.
77
+ const code = String((error && error.code) || '');
78
+ return (
79
+ code === 'ERR_TLS_CERT_ALTNAME_INVALID' ||
80
+ /CERT|UNABLE_TO_(GET|VERIFY|DECRYPT|DECODE)|SELF_SIGNED/.test(code)
81
+ );
82
+ }
83
+
84
+ function canOfferGroup(tlsModule) {
85
+ try {
86
+ tlsModule.createSecureContext({ ecdhCurve: HYBRID_POST_QUANTUM_GROUP });
87
+ return true;
88
+ } catch {
89
+ return false;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * @param {object} params
95
+ * @param {string} params.host
96
+ * @param {number} [params.port=443]
97
+ * @param {number} [params.timeoutMs=10000]
98
+ * @param {object} [params.tlsOptions] extra tls.connect options (for example `ca`)
99
+ * @param {object} [params.tlsModule] Node's tls module (injectable for tests)
100
+ * @returns {Promise<{host: string, port: number, result: 'accepted'|'refused'|'unreachable'|'unsupported-client'|'error', tlsVersion?: string, certificateError?: string, detail?: string}>}
101
+ */
102
+ function checkPostQuantumTls({
103
+ host,
104
+ port = 443,
105
+ timeoutMs = DEFAULT_TIMEOUT_MS,
106
+ tlsOptions = {},
107
+ tlsModule = nodeTls,
108
+ }) {
109
+ const base = { host, port };
110
+
111
+ if (!canOfferGroup(tlsModule)) {
112
+ return Promise.resolve({
113
+ ...base,
114
+ result: 'unsupported-client',
115
+ detail:
116
+ `This Node.js (${process.version}, OpenSSL ` +
117
+ `${process.versions.openssl}) cannot offer ` +
118
+ `${HYBRID_POST_QUANTUM_GROUP}. Run the check with OpenSSL 3.5 ` +
119
+ 'or later: Node.js 22.20 or later, or Node.js 24.5 or later.',
120
+ });
121
+ }
122
+
123
+ return new Promise((resolve) => {
124
+ let settled = false;
125
+ let socket;
126
+ const finish = (outcome) => {
127
+ if (settled) return;
128
+ settled = true;
129
+ if (socket) socket.destroy();
130
+ resolve({ ...base, ...outcome });
131
+ };
132
+
133
+ socket = tlsModule.connect({
134
+ ...tlsOptions,
135
+ host,
136
+ port,
137
+ // RFC 6066: SNI carries host names only, never IP addresses.
138
+ ...(net.isIP(host) ? {} : { servername: host }),
139
+ ecdhCurve: HYBRID_POST_QUANTUM_GROUP,
140
+ minVersion: 'TLSv1.3',
141
+ });
142
+
143
+ socket.setTimeout(timeoutMs, () =>
144
+ finish({
145
+ result: 'unreachable',
146
+ detail: `No TLS handshake within ${timeoutMs} ms.`,
147
+ })
148
+ );
149
+
150
+ socket.on('secureConnect', () =>
151
+ finish({ result: 'accepted', tlsVersion: socket.getProtocol() })
152
+ );
153
+
154
+ socket.on('error', (error) => {
155
+ if (isRefusal(error)) {
156
+ finish({
157
+ result: 'refused',
158
+ detail:
159
+ `The server refused ${HYBRID_POST_QUANTUM_GROUP} over ` +
160
+ 'TLS 1.3, so clients get classical key exchange only ' +
161
+ `(${error.code}: ${error.reason || 'TLS alert'}).`,
162
+ });
163
+ } else if (isCertificateError(error)) {
164
+ finish({
165
+ result: 'accepted',
166
+ tlsVersion: 'TLSv1.3',
167
+ certificateError: describeError(error),
168
+ });
169
+ } else if (error && error.code === 'ECONNRESET') {
170
+ // A reset needs an open TCP connection (a refused one is
171
+ // ECONNREFUSED), so the server or a device on the path
172
+ // dropped the handshake.
173
+ finish({
174
+ result: 'error',
175
+ detail:
176
+ 'The connection closed during the TLS handshake. A ' +
177
+ 'firewall or proxy that cannot handle the larger ' +
178
+ 'post-quantum ClientHello (over 1 KB) can cause this. ' +
179
+ `(${describeError(error)})`,
180
+ });
181
+ } else if (UNREACHABLE_CODES.has(error && error.code)) {
182
+ finish({ result: 'unreachable', detail: describeError(error) });
183
+ } else {
184
+ finish({ result: 'error', detail: describeError(error) });
185
+ }
186
+ });
187
+ });
188
+ }
189
+
190
+ module.exports = {
191
+ checkPostQuantumTls,
192
+ parseEndpoint,
193
+ HYBRID_POST_QUANTUM_GROUP,
194
+ };
@@ -0,0 +1,136 @@
1
+ /**
2
+ * `frigg tls-check <endpoint...>`: tells you whether each endpoint accepts
3
+ * hybrid post-quantum TLS key exchange (X25519MLKEM768).
4
+ *
5
+ * Use it on a deployed Frigg API (the API Gateway URL or a CloudFront URL in
6
+ * front of it), on AWS endpoints, or on a partner API.
7
+ *
8
+ * Exit codes: 0 all endpoints accept the group, 1 at least one does not (or
9
+ * a value is not a TLS endpoint), 2 this Node.js cannot offer the group.
10
+ */
11
+
12
+ const chalk = require('chalk');
13
+ const {
14
+ checkPostQuantumTls,
15
+ parseEndpoint,
16
+ HYBRID_POST_QUANTUM_GROUP,
17
+ } = require('./check-post-quantum-tls');
18
+
19
+ const DEFAULT_TIMEOUT_MS = 10000;
20
+
21
+ function formatResult(entry) {
22
+ const target = `${entry.host}:${entry.port}`;
23
+ switch (entry.result) {
24
+ case 'accepted': {
25
+ const lines = [
26
+ `${chalk.green(
27
+ '✔'
28
+ )} ${target} accepts ${HYBRID_POST_QUANTUM_GROUP} (${
29
+ entry.tlsVersion || 'TLSv1.3'
30
+ })`,
31
+ ];
32
+ if (entry.certificateError) {
33
+ lines.push(
34
+ chalk.yellow(
35
+ ` ! The certificate is not trusted: ${entry.certificateError}`
36
+ )
37
+ );
38
+ }
39
+ return lines.join('\n');
40
+ }
41
+ case 'refused':
42
+ return `${chalk.red('✖')} ${target} ${entry.detail}`;
43
+ case 'unsupported-client':
44
+ return `${chalk.red('✖')} ${target} not checked. ${entry.detail}`;
45
+ default:
46
+ return `${chalk.red('✖')} ${target} ${entry.result}: ${
47
+ entry.detail
48
+ }`;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * @param {string[]} endpoints https:// or wss:// URLs, hosts, or host:port
54
+ * @param {object} [options]
55
+ * @param {boolean} [options.json] print JSON
56
+ * @param {string|number} [options.timeout] handshake timeout in ms
57
+ * @param {object} [deps] injectable for tests
58
+ */
59
+ async function tlsCheckCommand(
60
+ endpoints = [],
61
+ options = {},
62
+ { check = checkPostQuantumTls, log = console.log } = {}
63
+ ) {
64
+ if (!endpoints || endpoints.length === 0) {
65
+ log(
66
+ chalk.red(
67
+ 'Give at least one endpoint, for example: frigg tls-check https://abc123.execute-api.us-east-1.amazonaws.com'
68
+ )
69
+ );
70
+ process.exitCode = 1;
71
+ return { group: HYBRID_POST_QUANTUM_GROUP, results: [] };
72
+ }
73
+
74
+ const timeoutMs =
75
+ options.timeout === undefined
76
+ ? DEFAULT_TIMEOUT_MS
77
+ : Number(options.timeout);
78
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) {
79
+ log(
80
+ chalk.red(
81
+ `--timeout must be a whole number of milliseconds above 0 (got "${options.timeout}").`
82
+ )
83
+ );
84
+ process.exitCode = 1;
85
+ return { group: HYBRID_POST_QUANTUM_GROUP, results: [] };
86
+ }
87
+ const results = [];
88
+ for (const value of endpoints) {
89
+ let target;
90
+ try {
91
+ target = parseEndpoint(value);
92
+ } catch (error) {
93
+ results.push({
94
+ endpoint: value,
95
+ result: 'error',
96
+ detail: error.message,
97
+ });
98
+ continue;
99
+ }
100
+ results.push(await check({ ...target, timeoutMs }));
101
+ }
102
+
103
+ const report = { group: HYBRID_POST_QUANTUM_GROUP, results };
104
+
105
+ if (options.json) {
106
+ log(JSON.stringify(report, null, 2));
107
+ } else {
108
+ log(
109
+ chalk.bold(
110
+ `Hybrid post-quantum TLS check (${HYBRID_POST_QUANTUM_GROUP}, TLS 1.3)`
111
+ )
112
+ );
113
+ for (const entry of results) {
114
+ log(
115
+ entry.endpoint
116
+ ? `${chalk.red('✖')} ${entry.endpoint}: ${entry.detail}`
117
+ : formatResult(entry)
118
+ );
119
+ }
120
+ const accepted = results.filter(
121
+ (entry) => entry.result === 'accepted'
122
+ ).length;
123
+ log(
124
+ `${accepted} of ${results.length} endpoints accept ${HYBRID_POST_QUANTUM_GROUP}.`
125
+ );
126
+ }
127
+
128
+ if (results.some((entry) => entry.result === 'unsupported-client')) {
129
+ process.exitCode = 2;
130
+ } else if (results.some((entry) => entry.result !== 'accepted')) {
131
+ process.exitCode = 1;
132
+ }
133
+ return report;
134
+ }
135
+
136
+ module.exports = { tlsCheckCommand };
@@ -213,6 +213,75 @@ describe('semantic checks', () => {
213
213
  );
214
214
  });
215
215
 
216
+ describe('AES_KEY strength', () => {
217
+ const aes = {
218
+ encryption: { fieldLevelEncryptionMethod: 'aes' },
219
+ environment: {
220
+ DATABASE_URL: true,
221
+ AES_KEY_ID: true,
222
+ AES_KEY: true,
223
+ },
224
+ };
225
+ const withKey = (AES_KEY, stage = 'prod') =>
226
+ run(aes, { stage, env: { AES_KEY_ID: 'k1', AES_KEY } });
227
+ const hex64 = 'a1'.repeat(32);
228
+ const base64of32 = Buffer.alloc(32, 7).toString('base64');
229
+
230
+ it.each([
231
+ ['64 hex characters', hex64],
232
+ ['base64 of 32 bytes', base64of32],
233
+ ])('accepts a full-strength key: %s', (_label, key) => {
234
+ const result = withKey(key);
235
+
236
+ expect(result.errors).toEqual([]);
237
+ expect(result.warnings).toEqual([]);
238
+ });
239
+
240
+ it('warns that a legacy 32-character key has only 128 bits of entropy', () => {
241
+ const result = validateDefinition({
242
+ definition: scaffold(aes),
243
+ stage: 'prod',
244
+ env: { AES_KEY_ID: 'k1', AES_KEY: 'f'.repeat(32) },
245
+ });
246
+ const warning = result.warnings.find(
247
+ (w) => w.code === 'weak-encryption-key'
248
+ );
249
+
250
+ expect(result.errors).toEqual([]);
251
+ expect(warning).toMatchObject({
252
+ pointer: '/environment/AES_KEY',
253
+ });
254
+ expect(warning.message).toMatch(/128 bits/);
255
+ expect(warning.hint).toMatch(/openssl rand -hex 32/);
256
+ expect(warning.hint).toMatch(/DEPRECATED_AES_KEY/);
257
+ });
258
+
259
+ it('rejects a key of the wrong size, without printing it', () => {
260
+ const result = validateDefinition({
261
+ definition: scaffold(aes),
262
+ stage: 'prod',
263
+ env: { AES_KEY_ID: 'k1', AES_KEY: 'my-secret-short-key' },
264
+ });
265
+ const error = result.errors.find(
266
+ (e) => e.code === 'invalid-encryption-key'
267
+ );
268
+
269
+ expect(error).toMatchObject({
270
+ pointer: '/environment/AES_KEY',
271
+ });
272
+ expect(error.hint).toMatch(/openssl rand -hex 32/);
273
+ expect(JSON.stringify(result)).not.toContain(
274
+ 'my-secret-short-key'
275
+ );
276
+ });
277
+
278
+ it('does not judge the key on a stage that skips encryption', () => {
279
+ expect(withKey('f'.repeat(32), 'dev').warnings).not.toContain(
280
+ 'weak-encryption-key /environment/AES_KEY'
281
+ );
282
+ });
283
+ });
284
+
216
285
  it('warns that a deployed stage without a method stores plaintext', () => {
217
286
  expect(
218
287
  run({ encryption: undefined }, { stage: 'prod' }).warnings
@@ -266,12 +266,71 @@ function checkDatabase({ raw }) {
266
266
  return [];
267
267
  }
268
268
 
269
+ const AES_KEY_HINT =
270
+ 'Generate a key with `openssl rand -hex 32` (64 hex characters = 256 bits) or `openssl rand -base64 32`.';
271
+
272
+ /**
273
+ * Strength of an AES_KEY value, by the rules of core's
274
+ * encrypt/key-material.js (kept here so `frigg validate` does not depend on
275
+ * the installed core version): 64 hex characters or base64 of 32 bytes is a
276
+ * full 256-bit key; any other 32-byte string is a legacy key, used as its
277
+ * UTF-8 bytes (the old `openssl rand -hex 16` advice gives 32 hex characters,
278
+ * 128 bits of entropy); anything else core refuses.
279
+ */
280
+ function aesKeyStrength(value) {
281
+ if (/^[0-9a-fA-F]{64}$/.test(value)) return 'full';
282
+ if (
283
+ /^[A-Za-z0-9+/]{43}=$/.test(value) &&
284
+ Buffer.from(value, 'base64').length === 32
285
+ ) {
286
+ return 'full';
287
+ }
288
+ if (Buffer.byteLength(value, 'utf8') === 32) return 'legacy';
289
+ return 'invalid';
290
+ }
291
+
292
+ function checkAesKeyStrength(value) {
293
+ const strength = aesKeyStrength(value);
294
+ if (strength === 'legacy') {
295
+ return [
296
+ issue(
297
+ 'warning',
298
+ 'weak-encryption-key',
299
+ '/environment/AES_KEY',
300
+ 'AES_KEY is a legacy 32-character key: AES-256 uses it as 32 bytes, but it has at most 128 bits of entropy (and only 128 bits if it came from `openssl rand -hex 16`). CNSA 2.0 calls for a full 256-bit AES key.',
301
+ `${AES_KEY_HINT} Rotate without losing data: move the current pair to DEPRECATED_AES_KEY_ID / DEPRECATED_AES_KEY, set a new AES_KEY_ID and AES_KEY, deploy, then run the frigg-reencrypt-legacy-fields admin script.`
302
+ ),
303
+ ];
304
+ }
305
+ if (strength === 'invalid') {
306
+ return [
307
+ issue(
308
+ 'error',
309
+ 'invalid-encryption-key',
310
+ '/environment/AES_KEY',
311
+ `AES_KEY in this shell has ${value.length} characters: core accepts 64 hex characters, base64 of 32 bytes, or a legacy 32-character key, and refuses to encrypt with anything else.`,
312
+ AES_KEY_HINT
313
+ ),
314
+ ];
315
+ }
316
+ return [];
317
+ }
318
+
269
319
  function checkEncryption({ raw, stage, env }) {
270
320
  const issues = [];
271
321
  const method = raw.encryption?.fieldLevelEncryptionMethod;
272
322
  const environment = raw.environment || {};
273
323
  const deployedStage = stage && !ENCRYPTION_BYPASS_STAGES.includes(stage);
274
324
 
325
+ if (
326
+ method === 'aes' &&
327
+ environment.AES_KEY === true &&
328
+ env.AES_KEY &&
329
+ !ENCRYPTION_BYPASS_STAGES.includes(stage)
330
+ ) {
331
+ issues.push(...checkAesKeyStrength(env.AES_KEY));
332
+ }
333
+
275
334
  if (method === 'aes') {
276
335
  for (const key of ['AES_KEY_ID', 'AES_KEY']) {
277
336
  if (environment[key] !== true) {
@@ -339,6 +339,16 @@ const MATRIX = {
339
339
  exporter: { type: 'otlp', endpoint: 'https://otel.example.com' },
340
340
  },
341
341
  }),
342
+ 'cloudfront edge with a custom domain': () => ({
343
+ ...base(),
344
+ cloudFront: {
345
+ enable: true,
346
+ priceClass: 'PriceClass_200',
347
+ domainNames: ['api.example.com'],
348
+ certificateArn:
349
+ 'arn:aws:acm:us-east-1:123456789012:certificate/0f1e2d3c-4b5a-6978-8a9b-0c1d2e3f4a5b',
350
+ },
351
+ }),
342
352
  'vpc create-new + aurora managed': () => ({
343
353
  ...base(),
344
354
  vpc: {