@bostonuniversity/edge-origin-trust 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createAllowList = createAllowList;
4
+ exports.normalizeAllowList = normalizeAllowList;
5
+ exports.validateAllowListBody = validateAllowListBody;
6
+ exports.capabilitiesFor = capabilitiesFor;
7
+ /**
8
+ * Runtime TTL cache for a write allow-list, plus the pure helpers that interpret one.
9
+ *
10
+ * The parameter is owned by the consuming app's stack and holds one JSON object
11
+ * `{ "admins": [...], "editors": [...] }` of eppn identities.
12
+ *
13
+ * Why SSM Parameter Store: an allow-list is config, not a credential (Secrets Manager holds the
14
+ * shared challenge, and its rotation machinery is built for tokens), and not routing data. IAM on
15
+ * SSM is per-parameter and per-path, so a consuming app's list is grantable without widening anything
16
+ * else.
17
+ *
18
+ * Fail-closed throughout: a missing/unseeded parameter or a cold fetch failure yields an empty list,
19
+ * so no one is authorized. A transient failure AFTER a good load serves the last-good list, so a
20
+ * brief SSM blip does not revoke everyone mid-session.
21
+ *
22
+ * A factory rather than a module singleton, for the same reason as the challenge cache.
23
+ */
24
+ const client_ssm_1 = require("@aws-sdk/client-ssm");
25
+ /**
26
+ * Deep-freeze a list before it becomes cached authorization truth.
27
+ *
28
+ * `get` hands out the cache's own object rather than a copy, so without this a caller could mutate
29
+ * what the next authorization check reads — `list.admins.push(x)` would authorize `x` for the life
30
+ * of the container. A shared module-level empty list handed back by reference has the same problem on
31
+ * every fail-closed path, which is why `empty()` builds a fresh one each time.
32
+ *
33
+ * Frozen rather than copied on the way out, for two reasons: an authorization check runs on every
34
+ * request and should not allocate, and in a strict-mode module a stray `.push()` now throws at the
35
+ * offending line instead of quietly succeeding against a copy nobody reads.
36
+ */
37
+ function frozen(list) {
38
+ Object.freeze(list.admins);
39
+ Object.freeze(list.editors);
40
+ return Object.freeze(list);
41
+ }
42
+ /** A fresh, frozen empty list. Fail-closed: no one is authorized. */
43
+ function empty() {
44
+ return frozen({ admins: [], editors: [] });
45
+ }
46
+ function createAllowList(config) {
47
+ const { parameterName, refreshMs, region, label = 'edge-origin-trust' } = config;
48
+ let cached = empty();
49
+ let cachedAt = 0;
50
+ let everLoaded = false;
51
+ let client;
52
+ return {
53
+ async get(opts) {
54
+ const now = Date.now();
55
+ if (!opts?.fresh && everLoaded && now - cachedAt < refreshMs)
56
+ return cached;
57
+ if (!parameterName) {
58
+ console.error(`[${label}] allow-list parameter name is not set — no one is authorized to write.`);
59
+ return empty();
60
+ }
61
+ try {
62
+ if (!client)
63
+ client = new client_ssm_1.SSMClient({ region });
64
+ const resp = await client.send(new client_ssm_1.GetParameterCommand({ Name: parameterName }));
65
+ cached = resp.Parameter?.Value ? frozen(normalizeAllowList(JSON.parse(resp.Parameter.Value))) : empty();
66
+ cachedAt = now;
67
+ everLoaded = true;
68
+ return cached;
69
+ }
70
+ catch (e) {
71
+ const name = e?.name || 'error';
72
+ // ParameterNotFound = not yet seeded: fail closed, and cache the empty result so we do not
73
+ // hammer SSM on every request.
74
+ if (name === 'ParameterNotFound') {
75
+ cached = empty();
76
+ cachedAt = now;
77
+ everLoaded = true;
78
+ console.warn(`[${label}] allow-list parameter ${parameterName} not found — write access disabled until seeded.`);
79
+ return cached;
80
+ }
81
+ console.error(`[${label}] allow-list fetch failed:`, name);
82
+ return everLoaded ? cached : empty(); // last-good, or fail-closed on cold failure
83
+ }
84
+ },
85
+ async put(list) {
86
+ if (!parameterName)
87
+ throw new Error('allow-list parameter name is not set');
88
+ if (!client)
89
+ client = new client_ssm_1.SSMClient({ region });
90
+ await client.send(new client_ssm_1.PutParameterCommand({
91
+ Name: parameterName,
92
+ Value: JSON.stringify(list),
93
+ Type: 'String',
94
+ Overwrite: true,
95
+ }));
96
+ // Copy, then freeze: the caller keeps its own reference to `list`, and a later mutation of it
97
+ // must not rewrite what this cache serves as authorization truth.
98
+ cached = frozen({ admins: [...list.admins], editors: [...list.editors] });
99
+ cachedAt = Date.now();
100
+ everLoaded = true;
101
+ return list;
102
+ },
103
+ };
104
+ }
105
+ /**
106
+ * Coerce arbitrary parsed JSON into a well-formed, lowercased AllowList. Exported because a write
107
+ * must store the same canonical form the read path produces, so an eppn added through a UI compares
108
+ * equal to one seeded by hand. Silently drops non-strings and unknown keys; validate shape first
109
+ * (validateAllowListBody) so a caller gets feedback rather than a silent no-op, then normalize.
110
+ */
111
+ function normalizeAllowList(parsed) {
112
+ const obj = (parsed && typeof parsed === 'object' ? parsed : {});
113
+ const list = (v) => Array.isArray(v)
114
+ ? v.filter((x) => typeof x === 'string').map((s) => s.trim().toLowerCase())
115
+ : [];
116
+ return { admins: list(obj.admins), editors: list(obj.editors) };
117
+ }
118
+ /**
119
+ * Validate the body of an allow-list write (→ `422 { error, issues }`). Both `admins` and `editors`
120
+ * must be present arrays of strings: a write replaces the whole object, so an omitted key would
121
+ * silently wipe that tier — require both rather than treat absence as "empty". Entry-level
122
+ * normalization is left to normalizeAllowList; this only guards the shape.
123
+ */
124
+ function validateAllowListBody(input) {
125
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
126
+ return [{ field: 'body', message: 'Expected a JSON object { admins, editors }.' }];
127
+ }
128
+ const r = input;
129
+ const issues = [];
130
+ for (const field of ['admins', 'editors']) {
131
+ const v = r[field];
132
+ if (!Array.isArray(v)) {
133
+ issues.push({ field, message: `${field} must be an array of strings.` });
134
+ }
135
+ else if (!v.every((x) => typeof x === 'string')) {
136
+ issues.push({ field, message: `${field} must contain only strings.` });
137
+ }
138
+ }
139
+ return issues;
140
+ }
141
+ /**
142
+ * Derive the caller's capabilities from their eppn and the allow-list. Admins are implicitly editors.
143
+ * Comparison is case-insensitive (the list is stored lowercased; the caller is lowercased here too).
144
+ */
145
+ function capabilitiesFor(eppn, allowList) {
146
+ const id = eppn?.trim().toLowerCase();
147
+ const isAdmin = !!id && allowList.admins.includes(id);
148
+ const isEditor = isAdmin || (!!id && allowList.editors.includes(id));
149
+ return { canEditRules: isEditor, canManageAccess: isAdmin };
150
+ }
151
+ //# sourceMappingURL=allowList.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"allowList.js","sourceRoot":"","sources":["../src/allowList.ts"],"names":[],"mappings":";;AA8EA,0CA4DC;AAQD,gDAOC;AAQD,sDAeC;AAMD,0CAKC;AA3LD;;;;;;;;;;;;;;;;GAgBG;AACH,oDAA0F;AAsC1F;;;;;;;;;;;GAWG;AACH,SAAS,MAAM,CAAC,IAAe;IAC7B,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC3B,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC5B,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC;AAED,qEAAqE;AACrE,SAAS,KAAK;IACZ,OAAO,MAAM,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;AAC7C,CAAC;AAED,SAAgB,eAAe,CAAC,MAAuB;IACrD,MAAM,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,GAAG,mBAAmB,EAAE,GAAG,MAAM,CAAC;IAEjF,IAAI,MAAM,GAAc,KAAK,EAAE,CAAC;IAChC,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,IAAI,UAAU,GAAG,KAAK,CAAC;IACvB,IAAI,MAA6B,CAAC;IAElC,OAAO;QACL,KAAK,CAAC,GAAG,CAAC,IAA0B;YAClC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;YACvB,IAAI,CAAC,IAAI,EAAE,KAAK,IAAI,UAAU,IAAI,GAAG,GAAG,QAAQ,GAAG,SAAS;gBAAE,OAAO,MAAM,CAAC;YAE5E,IAAI,CAAC,aAAa,EAAE,CAAC;gBACnB,OAAO,CAAC,KAAK,CAAC,IAAI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AAC,CAAC;IACtD,MAAM,QAAQ,GAAG,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;IACrE,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,eAAe,EAAE,OAAO,EAAE,CAAC;AAC9D,CAAC","sourcesContent":["/**\n * Runtime TTL cache for a write allow-list, plus the pure helpers that interpret one.\n *\n * The parameter is owned by the consuming app's stack and holds one JSON object\n * `{ \"admins\": [...], \"editors\": [...] }` of eppn identities.\n *\n * Why SSM Parameter Store: an allow-list is config, not a credential (Secrets Manager holds the\n * shared challenge, and its rotation machinery is built for tokens), and not routing data. IAM on\n * SSM is per-parameter and per-path, so a consuming app's list is grantable without widening anything\n * else.\n *\n * Fail-closed throughout: a missing/unseeded parameter or a cold fetch failure yields an empty list,\n * so no one is authorized. A transient failure AFTER a good load serves the last-good list, so a\n * brief SSM blip does not revoke everyone mid-session.\n *\n * A factory rather than a module singleton, for the same reason as the challenge cache.\n */\nimport { GetParameterCommand, PutParameterCommand, SSMClient } from '@aws-sdk/client-ssm';\nimport type { AllowList, Capabilities, ValidationIssue } from './types';\n\nexport type { AllowList, Capabilities } from './types';\n\nexport interface AllowListConfig {\n /** Full SSM parameter name, starting with '/'. Absent → the cache fails closed and says so. */\n parameterName: string | undefined;\n /**\n * TTL before a refetch, in ms. REQUIRED, with no module default: this is how long a revocation\n * takes to propagate across warm containers, which is a per-app judgement call and should be\n * visible at the call site rather than inherited.\n */\n refreshMs: number;\n /** Region for the SSM client. */\n region: string;\n /** Log prefix, so an operator grepping CloudWatch can tell which app spoke. */\n label?: string;\n}\n\nexport interface AllowListCache {\n /**\n * The current allow-list, refetching only when cold or past the TTL. Never throws.\n *\n * `fresh: true` bypasses the TTL and reads ground truth (still updating the cache, still falling\n * back to last-good on a transient error). An authorization gate wants the cached path — a\n * few-minute propagation lag is intended — but a management view must show what was just\n * persisted, not a sibling warm container's stale copy.\n */\n get(opts?: { fresh?: boolean }): Promise<AllowList>;\n /**\n * Persist an ALREADY-NORMALIZED list and refresh the local cache, giving this container\n * read-your-writes. Other warm containers serve last-good until their TTL lapses — the same\n * eventual-propagation posture as challenge rotation. Last-write-wins; no version precondition.\n */\n put(list: AllowList): Promise<AllowList>;\n}\n\n/**\n * Deep-freeze a list before it becomes cached authorization truth.\n *\n * `get` hands out the cache's own object rather than a copy, so without this a caller could mutate\n * what the next authorization check reads — `list.admins.push(x)` would authorize `x` for the life\n * of the container. A shared module-level empty list handed back by reference has the same problem on\n * every fail-closed path, which is why `empty()` builds a fresh one each time.\n *\n * Frozen rather than copied on the way out, for two reasons: an authorization check runs on every\n * request and should not allocate, and in a strict-mode module a stray `.push()` now throws at the\n * offending line instead of quietly succeeding against a copy nobody reads.\n */\nfunction frozen(list: AllowList): AllowList {\n Object.freeze(list.admins);\n Object.freeze(list.editors);\n return Object.freeze(list);\n}\n\n/** A fresh, frozen empty list. Fail-closed: no one is authorized. */\nfunction empty(): AllowList {\n return frozen({ admins: [], editors: [] });\n}\n\nexport function createAllowList(config: AllowListConfig): AllowListCache {\n const { parameterName, refreshMs, region, label = 'edge-origin-trust' } = config;\n\n let cached: AllowList = empty();\n let cachedAt = 0;\n let everLoaded = false;\n let client: SSMClient | undefined;\n\n return {\n async get(opts?: { fresh?: boolean }): Promise<AllowList> {\n const now = Date.now();\n if (!opts?.fresh && everLoaded && now - cachedAt < refreshMs) return cached;\n\n if (!parameterName) {\n console.error(`[${label}] allow-list parameter name is not set — no one is authorized to write.`);\n return empty();\n }\n\n try {\n if (!client) client = new SSMClient({ region });\n const resp = await client.send(new GetParameterCommand({ Name: parameterName }));\n cached = resp.Parameter?.Value ? frozen(normalizeAllowList(JSON.parse(resp.Parameter.Value))) : empty();\n cachedAt = now;\n everLoaded = true;\n return cached;\n } catch (e) {\n const name = (e as Error)?.name || 'error';\n // ParameterNotFound = not yet seeded: fail closed, and cache the empty result so we do not\n // hammer SSM on every request.\n if (name === 'ParameterNotFound') {\n cached = empty();\n cachedAt = now;\n everLoaded = true;\n console.warn(`[${label}] allow-list parameter ${parameterName} not found — write access disabled until seeded.`);\n return cached;\n }\n console.error(`[${label}] allow-list fetch failed:`, name);\n return everLoaded ? cached : empty(); // last-good, or fail-closed on cold failure\n }\n },\n\n async put(list: AllowList): Promise<AllowList> {\n if (!parameterName) throw new Error('allow-list parameter name is not set');\n if (!client) client = new SSMClient({ region });\n await client.send(\n new PutParameterCommand({\n Name: parameterName,\n Value: JSON.stringify(list),\n Type: 'String',\n Overwrite: true,\n }),\n );\n // Copy, then freeze: the caller keeps its own reference to `list`, and a later mutation of it\n // must not rewrite what this cache serves as authorization truth.\n cached = frozen({ admins: [...list.admins], editors: [...list.editors] });\n cachedAt = Date.now();\n everLoaded = true;\n return list;\n },\n };\n}\n\n/**\n * Coerce arbitrary parsed JSON into a well-formed, lowercased AllowList. Exported because a write\n * must store the same canonical form the read path produces, so an eppn added through a UI compares\n * equal to one seeded by hand. Silently drops non-strings and unknown keys; validate shape first\n * (validateAllowListBody) so a caller gets feedback rather than a silent no-op, then normalize.\n */\nexport function normalizeAllowList(parsed: unknown): AllowList {\n const obj = (parsed && typeof parsed === 'object' ? parsed : {}) as Record<string, unknown>;\n const list = (v: unknown): string[] =>\n Array.isArray(v)\n ? v.filter((x): x is string => typeof x === 'string').map((s) => s.trim().toLowerCase())\n : [];\n return { admins: list(obj.admins), editors: list(obj.editors) };\n}\n\n/**\n * Validate the body of an allow-list write (→ `422 { error, issues }`). Both `admins` and `editors`\n * must be present arrays of strings: a write replaces the whole object, so an omitted key would\n * silently wipe that tier — require both rather than treat absence as \"empty\". Entry-level\n * normalization is left to normalizeAllowList; this only guards the shape.\n */\nexport function validateAllowListBody(input: unknown): ValidationIssue[] {\n if (!input || typeof input !== 'object' || Array.isArray(input)) {\n return [{ field: 'body', message: 'Expected a JSON object { admins, editors }.' }];\n }\n const r = input as Record<string, unknown>;\n const issues: ValidationIssue[] = [];\n for (const field of ['admins', 'editors'] as const) {\n const v = r[field];\n if (!Array.isArray(v)) {\n issues.push({ field, message: `${field} must be an array of strings.` });\n } else if (!v.every((x) => typeof x === 'string')) {\n issues.push({ field, message: `${field} must contain only strings.` });\n }\n }\n return issues;\n}\n\n/**\n * Derive the caller's capabilities from their eppn and the allow-list. Admins are implicitly editors.\n * Comparison is case-insensitive (the list is stored lowercased; the caller is lowercased here too).\n */\nexport function capabilitiesFor(eppn: string | null, allowList: AllowList): Capabilities {\n const id = eppn?.trim().toLowerCase();\n const isAdmin = !!id && allowList.admins.includes(id);\n const isEditor = isAdmin || (!!id && allowList.editors.includes(id));\n return { canEditRules: isEditor, canManageAccess: isAdmin };\n}\n"]}
@@ -0,0 +1,128 @@
1
+ /**
2
+ * `EdgeOriginApp` — the infrastructure half of the module: one Function-URL Lambda that serves a
3
+ * single-page app and a JSON API from one origin, reached because the edge routes to it.
4
+ *
5
+ * ## Why this is under cdk/ and not exported from the module index
6
+ *
7
+ * `../index.ts` is the RUNTIME surface and is bundled into every consumer's Lambda. This file imports
8
+ * `aws-cdk-lib`. Keeping them in separate entry points is what stops a consuming app's handler bundle
9
+ * from reaching CDK: import runtime code from `@bostonuniversity/edge-origin-trust`, and this
10
+ * construct from `@bostonuniversity/edge-origin-trust/cdk/EdgeOriginApp`.
11
+ *
12
+ * ## What the construct owns, and what it deliberately does not
13
+ *
14
+ * Owns: the function, its log group, its Function URL, and read access to the challenge secret and
15
+ * (optionally) an allow-list parameter. Those are the things every consuming app needs and would
16
+ * otherwise re-derive.
17
+ *
18
+ * Does NOT own: an audit table, a routing table, any DynamoDB at all, or any CloudFront resource. A
19
+ * consuming app's data is its own domain. Express it through `extraGrants`, and create it in the
20
+ * consuming stack where its removal policy and key schema are visible.
21
+ *
22
+ * ## Ingress, and the two classes of origin
23
+ *
24
+ * There are two ways to keep a consuming app's Function URL from being reached directly, and which one
25
+ * applies depends on HOW the edge routes to the app:
26
+ *
27
+ * - **Statically configured origin** (a CDK-declared additional behaviour on the distribution) can
28
+ * use `AWS_IAM` + Origin Access Control: CloudFront signs each origin request with SigV4 and
29
+ * Lambda rejects anything else before the handler runs. This is what the edge's own statically
30
+ * configured Function-URL origins do.
31
+ * - **Dynamically injected origin** — reached by a routing-table rule, where the routing Lambda@Edge
32
+ * rewrites `request.origin` — cannot. OAC does not sign an origin injected at origin-request time,
33
+ * so `AWS_IAM` would reject the very requests arriving through the edge. Such an app must be
34
+ * `NONE` and enforce the boundary in the handler by validating `cloudfront-challenge`.
35
+ *
36
+ * `ingress` is required and currently accepts only `'challenge'`, because that is the only class any
37
+ * consumer of this construct is in. It is a required prop rather than a default so that no app gets
38
+ * a publicly-reachable Function URL without saying so. Widening it to `'oac'` is a
39
+ * small change — set `AWS_IAM` and let the caller associate the OAC — and should be made when an
40
+ * actual static-behaviour consumer arrives, not before.
41
+ */
42
+ import { Duration } from 'aws-cdk-lib';
43
+ import { Construct } from 'constructs';
44
+ import { FunctionUrl, Runtime } from 'aws-cdk-lib/aws-lambda';
45
+ import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
46
+ import { LogGroup, RetentionDays } from 'aws-cdk-lib/aws-logs';
47
+ export interface EdgeOriginAppProps {
48
+ /**
49
+ * Absolute path to the handler entry (a .ts file; NodejsFunction bundles it).
50
+ *
51
+ * There is deliberately no `functionName` prop. A fixed physical name means any future change to
52
+ * this construct's path in the tree — the ordinary consequence of refactoring — produces a new
53
+ * logical id wanting the same physical name, and CloudFormation creates before it deletes, so the
54
+ * deploy fails on a name collision. CDK's generated name already embeds the stack name, and the
55
+ * consuming stack should output `app.fn.functionName` for operators, which is the only thing the
56
+ * explicit name was buying.
57
+ */
58
+ handlerEntry: string;
59
+ /** Exported handler symbol. Defaults to 'handler'. */
60
+ handlerName?: string;
61
+ /**
62
+ * Path to the built SPA, RELATIVE to the esbuild project root that CDK passes as `inputDir` —
63
+ * e.g. `frontend/dist`. Its contents are copied to `WEBAPP_DIR_NAME` beside the handler, which is
64
+ * where the module's SPA server reads them from. Omit for an app with no frontend.
65
+ *
66
+ * The destination is a shared constant rather than a second prop on purpose: the copy here and the
67
+ * read in the handler are two halves of one contract, and two independent literals is how those
68
+ * stop agreeing.
69
+ */
70
+ frontendDist?: string;
71
+ /** Complete ARN of the secret carrying the challenge field(s). Granted read. */
72
+ challengeSecretArn: string;
73
+ /** How long the handler caches the challenge secret before refetching (ms). */
74
+ challengeSecretRefreshMs: number;
75
+ /**
76
+ * SSM parameter holding the write allow-list. Optional: a read-only or wayfinding app may not need
77
+ * one. When set, the function is granted GetParameter and PutParameter on that parameter only —
78
+ * never a path wildcard.
79
+ */
80
+ allowListParamName?: string;
81
+ /** How long the handler caches the allow-list before refetching (ms). Required when the list is. */
82
+ allowListRefreshMs?: number;
83
+ /**
84
+ * The app's mount path under the edge (e.g. '/_routing-editor'). Passed to the handler as
85
+ * SELF_ROUTE_PATH.
86
+ *
87
+ * NOTE this is only half of the mount. A consumer whose SPA is served under a prefix must also
88
+ * build it with that prefix as the bundler's base, derived from the same value it passes here.
89
+ * Passing it here alone will produce an app whose asset URLs are wrong; that coupling lives in the
90
+ * consumer's build, not in this construct.
91
+ */
92
+ mountPath?: string;
93
+ /** See the class docstring. Required so no app gets a public URL without saying so. */
94
+ ingress: 'challenge';
95
+ /** Additional environment variables for the handler (a consuming app's own config). */
96
+ environment?: Record<string, string>;
97
+ /**
98
+ * Grant the function whatever domain access it needs — its own tables, buckets, parameters. This
99
+ * is the seam that keeps domain resources out of the construct.
100
+ */
101
+ extraGrants?: (fn: NodejsFunction) => void;
102
+ /**
103
+ * Concurrency cap. Defaults to 10, which is generous for a human-driven operator surface and is a
104
+ * real cost and abuse ceiling on a publicly-reachable `NONE` Function URL. Note this RESERVES the
105
+ * capacity from the account pool as well as capping it.
106
+ */
107
+ reservedConcurrentExecutions?: number;
108
+ /**
109
+ * Log retention. Defaults to one month rather than never: these logs can carry an eppn — the actor
110
+ * of an allow-list change — so an unbounded group accumulates identifiable data indefinitely.
111
+ */
112
+ logRetention?: RetentionDays;
113
+ /** Function shape. Defaults: Node 22, 10s, 256 MB. */
114
+ runtime?: Runtime;
115
+ timeout?: Duration;
116
+ memorySize?: number;
117
+ }
118
+ /**
119
+ * One deployable app. Exposes the function and its URL so the consuming stack can add its own grants
120
+ * and outputs — those belong to the stack, not here, because their descriptions are app-specific
121
+ * prose.
122
+ */
123
+ export declare class EdgeOriginApp extends Construct {
124
+ readonly fn: NodejsFunction;
125
+ readonly functionUrl: FunctionUrl;
126
+ readonly logGroup: LogGroup;
127
+ constructor(scope: Construct, id: string, props: EdgeOriginAppProps);
128
+ }
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EdgeOriginApp = void 0;
4
+ /**
5
+ * `EdgeOriginApp` — the infrastructure half of the module: one Function-URL Lambda that serves a
6
+ * single-page app and a JSON API from one origin, reached because the edge routes to it.
7
+ *
8
+ * ## Why this is under cdk/ and not exported from the module index
9
+ *
10
+ * `../index.ts` is the RUNTIME surface and is bundled into every consumer's Lambda. This file imports
11
+ * `aws-cdk-lib`. Keeping them in separate entry points is what stops a consuming app's handler bundle
12
+ * from reaching CDK: import runtime code from `@bostonuniversity/edge-origin-trust`, and this
13
+ * construct from `@bostonuniversity/edge-origin-trust/cdk/EdgeOriginApp`.
14
+ *
15
+ * ## What the construct owns, and what it deliberately does not
16
+ *
17
+ * Owns: the function, its log group, its Function URL, and read access to the challenge secret and
18
+ * (optionally) an allow-list parameter. Those are the things every consuming app needs and would
19
+ * otherwise re-derive.
20
+ *
21
+ * Does NOT own: an audit table, a routing table, any DynamoDB at all, or any CloudFront resource. A
22
+ * consuming app's data is its own domain. Express it through `extraGrants`, and create it in the
23
+ * consuming stack where its removal policy and key schema are visible.
24
+ *
25
+ * ## Ingress, and the two classes of origin
26
+ *
27
+ * There are two ways to keep a consuming app's Function URL from being reached directly, and which one
28
+ * applies depends on HOW the edge routes to the app:
29
+ *
30
+ * - **Statically configured origin** (a CDK-declared additional behaviour on the distribution) can
31
+ * use `AWS_IAM` + Origin Access Control: CloudFront signs each origin request with SigV4 and
32
+ * Lambda rejects anything else before the handler runs. This is what the edge's own statically
33
+ * configured Function-URL origins do.
34
+ * - **Dynamically injected origin** — reached by a routing-table rule, where the routing Lambda@Edge
35
+ * rewrites `request.origin` — cannot. OAC does not sign an origin injected at origin-request time,
36
+ * so `AWS_IAM` would reject the very requests arriving through the edge. Such an app must be
37
+ * `NONE` and enforce the boundary in the handler by validating `cloudfront-challenge`.
38
+ *
39
+ * `ingress` is required and currently accepts only `'challenge'`, because that is the only class any
40
+ * consumer of this construct is in. It is a required prop rather than a default so that no app gets
41
+ * a publicly-reachable Function URL without saying so. Widening it to `'oac'` is a
42
+ * small change — set `AWS_IAM` and let the caller associate the OAC — and should be made when an
43
+ * actual static-behaviour consumer arrives, not before.
44
+ */
45
+ const aws_cdk_lib_1 = require("aws-cdk-lib");
46
+ const constructs_1 = require("constructs");
47
+ const aws_lambda_1 = require("aws-cdk-lib/aws-lambda");
48
+ const aws_lambda_nodejs_1 = require("aws-cdk-lib/aws-lambda-nodejs");
49
+ const aws_logs_1 = require("aws-cdk-lib/aws-logs");
50
+ const aws_secretsmanager_1 = require("aws-cdk-lib/aws-secretsmanager");
51
+ const aws_iam_1 = require("aws-cdk-lib/aws-iam");
52
+ const spa_1 = require("../spa");
53
+ /**
54
+ * One deployable app. Exposes the function and its URL so the consuming stack can add its own grants
55
+ * and outputs — those belong to the stack, not here, because their descriptions are app-specific
56
+ * prose.
57
+ */
58
+ class EdgeOriginApp extends constructs_1.Construct {
59
+ constructor(scope, id, props) {
60
+ super(scope, id);
61
+ const { handlerEntry, handlerName = 'handler', frontendDist, challengeSecretArn, challengeSecretRefreshMs, allowListParamName, allowListRefreshMs, mountPath, environment = {}, extraGrants, reservedConcurrentExecutions = 10, logRetention = aws_logs_1.RetentionDays.ONE_MONTH, runtime = aws_lambda_1.Runtime.NODEJS_22_X, timeout = aws_cdk_lib_1.Duration.seconds(10), memorySize = 256, } = props;
62
+ if (allowListParamName && allowListRefreshMs === undefined) {
63
+ throw new Error('allowListRefreshMs is required when allowListParamName is set');
64
+ }
65
+ // Explicit group rather than the deprecated `logRetention` prop. Note this gives the function a
66
+ // NEW group: an existing deployment's `/aws/lambda/<name>` group keeps its own (never-expiring)
67
+ // retention and its history until someone removes it.
68
+ this.logGroup = new aws_logs_1.LogGroup(this, 'LogGroup', {
69
+ retention: logRetention,
70
+ removalPolicy: aws_cdk_lib_1.RemovalPolicy.RETAIN,
71
+ });
72
+ this.fn = new aws_lambda_nodejs_1.NodejsFunction(this, 'Function', {
73
+ runtime,
74
+ entry: handlerEntry,
75
+ handler: handlerName,
76
+ timeout,
77
+ memorySize,
78
+ reservedConcurrentExecutions,
79
+ logGroup: this.logGroup,
80
+ environment: {
81
+ CHALLENGE_SECRET_ARN: challengeSecretArn,
82
+ CHALLENGE_SECRET_REFRESH_INTERVAL: String(challengeSecretRefreshMs),
83
+ ...(allowListParamName
84
+ ? {
85
+ ALLOW_LIST_PARAM_NAME: allowListParamName,
86
+ ALLOW_LIST_REFRESH_INTERVAL: String(allowListRefreshMs),
87
+ }
88
+ : {}),
89
+ ...(mountPath ? { SELF_ROUTE_PATH: mountPath } : {}),
90
+ ...environment,
91
+ },
92
+ bundling: {
93
+ // Node 22 ships the AWS SDK v3 in the runtime; keep it out of the bundle.
94
+ externalModules: ['@aws-sdk/*'],
95
+ minify: false,
96
+ sourceMap: true,
97
+ commandHooks: {
98
+ beforeBundling: () => [],
99
+ beforeInstall: () => [],
100
+ // Copy the built SPA beside the handler. If it is not there, warn and continue — the app
101
+ // then serves its own no-bundle response, so a deploy that forgot the frontend build still
102
+ // succeeds and says why.
103
+ afterBundling: (inputDir, outputDir) => frontendDist
104
+ ? [
105
+ `if [ -d "${inputDir}/${frontendDist}" ]; then ` +
106
+ `mkdir -p "${outputDir}/${spa_1.WEBAPP_DIR_NAME}" && ` +
107
+ `cp -R "${inputDir}/${frontendDist}/." "${outputDir}/${spa_1.WEBAPP_DIR_NAME}/"; ` +
108
+ `else echo "WARNING: ${frontendDist} not found — build the frontend before deploy; ` +
109
+ `the Lambda will serve a placeholder."; fi`,
110
+ ]
111
+ : [],
112
+ },
113
+ },
114
+ });
115
+ // See the class docstring: NONE is correct for a routing-rule-reached app, and the boundary is
116
+ // enforced in the handler by requireTrustedEdge.
117
+ this.functionUrl = this.fn.addFunctionUrl({ authType: aws_lambda_1.FunctionUrlAuthType.NONE });
118
+ aws_secretsmanager_1.Secret.fromSecretCompleteArn(this, 'ChallengeSecret', challengeSecretArn).grantRead(this.fn);
119
+ if (allowListParamName) {
120
+ // IAM on the ARN only. Deliberately NOT StringParameter.fromStringParameterName — that resolves
121
+ // the parameter's VALUE at deploy time and fails if it is not yet seeded. The parameter is
122
+ // seeded by hand and may not exist at deploy; the handler reads it at runtime and fails closed
123
+ // if absent, so it must never be a deploy-time dependency.
124
+ //
125
+ // Two actions only — GetParameters (plural) and GetParameterHistory are not on any code path
126
+ // here, so granting them would widen the role for nothing.
127
+ const stack = aws_cdk_lib_1.Stack.of(this);
128
+ this.fn.addToRolePolicy(new aws_iam_1.PolicyStatement({
129
+ actions: ['ssm:GetParameter', 'ssm:PutParameter'],
130
+ resources: [
131
+ `arn:${stack.partition}:ssm:${stack.region}:${stack.account}:parameter${allowListParamName}`,
132
+ ],
133
+ }));
134
+ }
135
+ extraGrants?.(this.fn);
136
+ }
137
+ }
138
+ exports.EdgeOriginApp = EdgeOriginApp;
139
+ //# sourceMappingURL=EdgeOriginApp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EdgeOriginApp.js","sourceRoot":"","sources":["../../src/cdk/EdgeOriginApp.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,6CAA6D;AAC7D,2CAAuC;AACvC,uDAAmF;AACnF,qEAA+D;AAC/D,mDAA+D;AAC/D,uEAAwD;AACxD,iDAAsD;AACtD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AC3D,MAAM,KAAK,GAAG,mBAAK,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;YAC7B,IAAI,CAAC,EAAE,CAAC,eAAe,CACrB,IAAI,yBAAe,CAAC;gBAClB,OAAO,EAAE,CAAC,kBAAkB,EAAE,kBAAkB,CAAC;gBACjD,SAAS,EAAE;oBACT,OAAO,KAAK,CAAC,SAAS,QAAQ,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,OAAO,aAAa,kBAAkB,EAAE;iBAC7F;aACF,CAAC,CACH,CAAC;QACJ,CAAC;QAED,WAAW,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACzB,CAAC;CACF;AA9GD,sCA8GC","sourcesContent":["/**\n * `EdgeOriginApp` — the infrastructure half of the module: one Function-URL Lambda that serves a\n * single-page app and a JSON API from one origin, reached because the edge routes to it.\n *\n * ## Why this is under cdk/ and not exported from the module index\n *\n * `../index.ts` is the RUNTIME surface and is bundled into every consumer's Lambda. This file imports\n * `aws-cdk-lib`. Keeping them in separate entry points is what stops a consuming app's handler bundle\n * from reaching CDK: import runtime code from `@bostonuniversity/edge-origin-trust`, and this\n * construct from `@bostonuniversity/edge-origin-trust/cdk/EdgeOriginApp`.\n *\n * ## What the construct owns, and what it deliberately does not\n *\n * Owns: the function, its log group, its Function URL, and read access to the challenge secret and\n * (optionally) an allow-list parameter. Those are the things every consuming app needs and would\n * otherwise re-derive.\n *\n * Does NOT own: an audit table, a routing table, any DynamoDB at all, or any CloudFront resource. A\n * consuming app's data is its own domain. Express it through `extraGrants`, and create it in the\n * consuming stack where its removal policy and key schema are visible.\n *\n * ## Ingress, and the two classes of origin\n *\n * There are two ways to keep a consuming app's Function URL from being reached directly, and which one\n * applies depends on HOW the edge routes to the app:\n *\n * - **Statically configured origin** (a CDK-declared additional behaviour on the distribution) can\n * use `AWS_IAM` + Origin Access Control: CloudFront signs each origin request with SigV4 and\n * Lambda rejects anything else before the handler runs. This is what the edge's own statically\n * configured Function-URL origins do.\n * - **Dynamically injected origin** — reached by a routing-table rule, where the routing Lambda@Edge\n * rewrites `request.origin` — cannot. OAC does not sign an origin injected at origin-request time,\n * so `AWS_IAM` would reject the very requests arriving through the edge. Such an app must be\n * `NONE` and enforce the boundary in the handler by validating `cloudfront-challenge`.\n *\n * `ingress` is required and currently accepts only `'challenge'`, because that is the only class any\n * consumer of this construct is in. It is a required prop rather than a default so that no app gets\n * a publicly-reachable Function URL without saying so. Widening it to `'oac'` is a\n * small change — set `AWS_IAM` and let the caller associate the OAC — and should be made when an\n * actual static-behaviour consumer arrives, not before.\n */\nimport { Duration, RemovalPolicy, Stack } from 'aws-cdk-lib';\nimport { Construct } from 'constructs';\nimport { FunctionUrl, FunctionUrlAuthType, Runtime } from 'aws-cdk-lib/aws-lambda';\nimport { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';\nimport { LogGroup, RetentionDays } from 'aws-cdk-lib/aws-logs';\nimport { Secret } from 'aws-cdk-lib/aws-secretsmanager';\nimport { PolicyStatement } from 'aws-cdk-lib/aws-iam';\nimport { WEBAPP_DIR_NAME } from '../spa';\n\nexport interface EdgeOriginAppProps {\n /**\n * Absolute path to the handler entry (a .ts file; NodejsFunction bundles it).\n *\n * There is deliberately no `functionName` prop. A fixed physical name means any future change to\n * this construct's path in the tree — the ordinary consequence of refactoring — produces a new\n * logical id wanting the same physical name, and CloudFormation creates before it deletes, so the\n * deploy fails on a name collision. CDK's generated name already embeds the stack name, and the\n * consuming stack should output `app.fn.functionName` for operators, which is the only thing the\n * explicit name was buying.\n */\n handlerEntry: string;\n /** Exported handler symbol. Defaults to 'handler'. */\n handlerName?: string;\n\n /**\n * Path to the built SPA, RELATIVE to the esbuild project root that CDK passes as `inputDir` —\n * e.g. `frontend/dist`. Its contents are copied to `WEBAPP_DIR_NAME` beside the handler, which is\n * where the module's SPA server reads them from. Omit for an app with no frontend.\n *\n * The destination is a shared constant rather than a second prop on purpose: the copy here and the\n * read in the handler are two halves of one contract, and two independent literals is how those\n * stop agreeing.\n */\n frontendDist?: string;\n\n /** Complete ARN of the secret carrying the challenge field(s). Granted read. */\n challengeSecretArn: string;\n /** How long the handler caches the challenge secret before refetching (ms). */\n challengeSecretRefreshMs: number;\n\n /**\n * SSM parameter holding the write allow-list. Optional: a read-only or wayfinding app may not need\n * one. When set, the function is granted GetParameter and PutParameter on that parameter only —\n * never a path wildcard.\n */\n allowListParamName?: string;\n /** How long the handler caches the allow-list before refetching (ms). Required when the list is. */\n allowListRefreshMs?: number;\n\n /**\n * The app's mount path under the edge (e.g. '/_routing-editor'). Passed to the handler as\n * SELF_ROUTE_PATH.\n *\n * NOTE this is only half of the mount. A consumer whose SPA is served under a prefix must also\n * build it with that prefix as the bundler's base, derived from the same value it passes here.\n * Passing it here alone will produce an app whose asset URLs are wrong; that coupling lives in the\n * consumer's build, not in this construct.\n */\n mountPath?: string;\n\n /** See the class docstring. Required so no app gets a public URL without saying so. */\n ingress: 'challenge';\n\n /** Additional environment variables for the handler (a consuming app's own config). */\n environment?: Record<string, string>;\n\n /**\n * Grant the function whatever domain access it needs — its own tables, buckets, parameters. This\n * is the seam that keeps domain resources out of the construct.\n */\n extraGrants?: (fn: NodejsFunction) => void;\n\n /**\n * Concurrency cap. Defaults to 10, which is generous for a human-driven operator surface and is a\n * real cost and abuse ceiling on a publicly-reachable `NONE` Function URL. Note this RESERVES the\n * capacity from the account pool as well as capping it.\n */\n reservedConcurrentExecutions?: number;\n\n /**\n * Log retention. Defaults to one month rather than never: these logs can carry an eppn — the actor\n * of an allow-list change — so an unbounded group accumulates identifiable data indefinitely.\n */\n logRetention?: RetentionDays;\n\n /** Function shape. Defaults: Node 22, 10s, 256 MB. */\n runtime?: Runtime;\n timeout?: Duration;\n memorySize?: number;\n}\n\n/**\n * One deployable app. Exposes the function and its URL so the consuming stack can add its own grants\n * and outputs — those belong to the stack, not here, because their descriptions are app-specific\n * prose.\n */\nexport class EdgeOriginApp extends Construct {\n public readonly fn: NodejsFunction;\n public readonly functionUrl: FunctionUrl;\n public readonly logGroup: LogGroup;\n\n constructor(scope: Construct, id: string, props: EdgeOriginAppProps) {\n super(scope, id);\n\n const {\n handlerEntry,\n handlerName = 'handler',\n frontendDist,\n challengeSecretArn,\n challengeSecretRefreshMs,\n allowListParamName,\n allowListRefreshMs,\n mountPath,\n environment = {},\n extraGrants,\n reservedConcurrentExecutions = 10,\n logRetention = RetentionDays.ONE_MONTH,\n runtime = Runtime.NODEJS_22_X,\n timeout = Duration.seconds(10),\n memorySize = 256,\n } = props;\n\n if (allowListParamName && allowListRefreshMs === undefined) {\n throw new Error('allowListRefreshMs is required when allowListParamName is set');\n }\n\n // Explicit group rather than the deprecated `logRetention` prop. Note this gives the function a\n // NEW group: an existing deployment's `/aws/lambda/<name>` group keeps its own (never-expiring)\n // retention and its history until someone removes it.\n this.logGroup = new LogGroup(this, 'LogGroup', {\n retention: logRetention,\n removalPolicy: RemovalPolicy.RETAIN,\n });\n\n this.fn = new NodejsFunction(this, 'Function', {\n runtime,\n entry: handlerEntry,\n handler: handlerName,\n timeout,\n memorySize,\n reservedConcurrentExecutions,\n logGroup: this.logGroup,\n environment: {\n CHALLENGE_SECRET_ARN: challengeSecretArn,\n CHALLENGE_SECRET_REFRESH_INTERVAL: String(challengeSecretRefreshMs),\n ...(allowListParamName\n ? {\n ALLOW_LIST_PARAM_NAME: allowListParamName,\n ALLOW_LIST_REFRESH_INTERVAL: String(allowListRefreshMs),\n }\n : {}),\n ...(mountPath ? { SELF_ROUTE_PATH: mountPath } : {}),\n ...environment,\n },\n bundling: {\n // Node 22 ships the AWS SDK v3 in the runtime; keep it out of the bundle.\n externalModules: ['@aws-sdk/*'],\n minify: false,\n sourceMap: true,\n commandHooks: {\n beforeBundling: () => [],\n beforeInstall: () => [],\n // Copy the built SPA beside the handler. If it is not there, warn and continue — the app\n // then serves its own no-bundle response, so a deploy that forgot the frontend build still\n // succeeds and says why.\n afterBundling: (inputDir: string, outputDir: string) =>\n frontendDist\n ? [\n `if [ -d \"${inputDir}/${frontendDist}\" ]; then ` +\n `mkdir -p \"${outputDir}/${WEBAPP_DIR_NAME}\" && ` +\n `cp -R \"${inputDir}/${frontendDist}/.\" \"${outputDir}/${WEBAPP_DIR_NAME}/\"; ` +\n `else echo \"WARNING: ${frontendDist} not found — build the frontend before deploy; ` +\n `the Lambda will serve a placeholder.\"; fi`,\n ]\n : [],\n },\n },\n });\n\n // See the class docstring: NONE is correct for a routing-rule-reached app, and the boundary is\n // enforced in the handler by requireTrustedEdge.\n this.functionUrl = this.fn.addFunctionUrl({ authType: FunctionUrlAuthType.NONE });\n\n Secret.fromSecretCompleteArn(this, 'ChallengeSecret', challengeSecretArn).grantRead(this.fn);\n\n if (allowListParamName) {\n // IAM on the ARN only. Deliberately NOT StringParameter.fromStringParameterName — that resolves\n // the parameter's VALUE at deploy time and fails if it is not yet seeded. The parameter is\n // seeded by hand and may not exist at deploy; the handler reads it at runtime and fails closed\n // if absent, so it must never be a deploy-time dependency.\n //\n // Two actions only — GetParameters (plural) and GetParameterHistory are not on any code path\n // here, so granting them would widen the role for nothing.\n const stack = Stack.of(this);\n this.fn.addToRolePolicy(\n new PolicyStatement({\n actions: ['ssm:GetParameter', 'ssm:PutParameter'],\n resources: [\n `arn:${stack.partition}:ssm:${stack.region}:${stack.account}:parameter${allowListParamName}`,\n ],\n }),\n );\n }\n\n extraGrants?.(this.fn);\n }\n}\n"]}
@@ -0,0 +1,39 @@
1
+ export interface ChallengeCacheConfig {
2
+ /** Full ARN of the secret holding the challenge fields. The region is read out of it. */
3
+ secretArn: string | undefined;
4
+ /**
5
+ * TTL before a refetch, in ms. REQUIRED, with no module default: this is the window during which
6
+ * a rotated-away value is still accepted, so each consumer states its own tolerance rather than
7
+ * inheriting someone else's.
8
+ */
9
+ refreshMs: number;
10
+ /** JSON field key for the current value. Defaults to the edge's own literal. */
11
+ currentField?: string;
12
+ /** JSON field key for the previous value — present only inside a rotation window. */
13
+ previousField?: string;
14
+ /**
15
+ * JSON field key for the edge's JWT public key. Present only where the secret has been given one;
16
+ * absent secrets simply yield `undefined` from `getPublicKey()`.
17
+ */
18
+ publicKeyField?: string;
19
+ /** Log prefix, so an operator grepping CloudWatch can tell which app spoke. */
20
+ label?: string;
21
+ }
22
+ export interface ChallengeCache {
23
+ /**
24
+ * Every currently-valid challenge value, current first. Refetches only when empty or past the TTL.
25
+ * On a fetch failure serves the last-good list if there is one — a brief Secrets Manager blip
26
+ * should not break a request that just succeeded — else returns `[]`, which callers treat as
27
+ * "cannot validate" and reject.
28
+ */
29
+ getValues(): Promise<string[]>;
30
+ /**
31
+ * The edge's JWT public key in PEM, or `undefined` if the secret carries no such field.
32
+ *
33
+ * Served from the SAME fetch and the SAME TTL as `getValues`. That is the point: an app that
34
+ * verifies tokens acquires no dependency it did not already have, and no second way to be
35
+ * unavailable. A public key is not a credential, so carrying it here widens nothing.
36
+ */
37
+ getPublicKey(): Promise<string | undefined>;
38
+ }
39
+ export declare function createChallengeCache(config: ChallengeCacheConfig): ChallengeCache;
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createChallengeCache = createChallengeCache;
4
+ /**
5
+ * Runtime TTL cache for the shared `cloudfront-challenge` secret.
6
+ *
7
+ * The TTL is what makes challenge rotation free for an app that reads the secret this way. Secrets
8
+ * Manager is read at RUNTIME behind that TTL and both `current` and `previous` values are accepted,
9
+ * so a rotation propagates with no deploy at all. An ALB listener rule, by contrast, has its accepted
10
+ * values baked in at CDK synth — which is why every cluster that checks the header is a redeploy in
11
+ * the rotation dance, and an app using this cache is not.
12
+ *
13
+ * A factory rather than a module singleton: config arrives as arguments, and the cache state lives
14
+ * on the instance. A second app in the same process — or a second test in the same file — can hold
15
+ * its own without a module-registry reset.
16
+ */
17
+ const client_secrets_manager_1 = require("@aws-sdk/client-secrets-manager");
18
+ function createChallengeCache(config) {
19
+ const { secretArn, refreshMs,
20
+ // In shibboleth-sp-at-edge these are the literals in SECRET_FIELD_NAMES. Both cross the
21
+ // edge↔origin boundary: rotation widens checkers to accept {current, previous}, flips the
22
+ // senders, then narrows.
23
+ currentField = 'cloudfront-challenge', previousField = 'cloudfront-challenge-previous', publicKeyField = 'wp-jwt-pubkey', label = 'edge-origin-trust', } = config;
24
+ let cachedValues = [];
25
+ let cachedPublicKey;
26
+ let cachedAt = 0;
27
+ // Memoized across fetches: a fresh client per cache miss re-resolves credentials each time for no
28
+ // benefit.
29
+ let client;
30
+ /**
31
+ * One fetch populates every field this cache serves, under one TTL. Both getters go through here,
32
+ * so a consumer that reads the public key makes no additional request and inherits the same
33
+ * fail-closed behaviour. On failure the last-good values stand.
34
+ */
35
+ async function refresh() {
36
+ const now = Date.now();
37
+ if (cachedValues.length && now - cachedAt < refreshMs)
38
+ return;
39
+ if (!secretArn) {
40
+ console.error(`[${label}] challenge secret ARN is not set — cannot validate challenge.`);
41
+ return;
42
+ }
43
+ try {
44
+ if (!client)
45
+ client = new client_secrets_manager_1.SecretsManagerClient({ region: secretArn.split(':')[3] });
46
+ const resp = await client.send(new client_secrets_manager_1.GetSecretValueCommand({ SecretId: secretArn }));
47
+ if (!resp.SecretString)
48
+ throw new Error('empty secret');
49
+ const fields = JSON.parse(resp.SecretString);
50
+ const current = fields[currentField];
51
+ if (!current)
52
+ throw new Error(`secret field "${currentField}" missing`);
53
+ // `previous` is optional and usually absent; an empty value is not an accepted challenge.
54
+ const previous = fields[previousField];
55
+ cachedValues = previous && previous !== current ? [current, previous] : [current];
56
+ // Optional. A secret without it simply yields undefined, and a consumer that asked to verify
57
+ // tokens then fails closed rather than falling back to trusting the header.
58
+ cachedPublicKey = fields[publicKeyField] || undefined;
59
+ cachedAt = now;
60
+ }
61
+ catch (e) {
62
+ console.error(`[${label}] challenge secret fetch failed:`, e?.name || 'error');
63
+ // leave last-good in place; cold failure leaves [] / undefined, which both callers reject
64
+ }
65
+ }
66
+ return {
67
+ async getValues() {
68
+ await refresh();
69
+ return cachedValues;
70
+ },
71
+ async getPublicKey() {
72
+ await refresh();
73
+ return cachedPublicKey;
74
+ },
75
+ };
76
+ }
77
+ //# sourceMappingURL=challengeCache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"challengeCache.js","sourceRoot":"","sources":["../src/challengeCache.ts"],"names":[],"mappings":";;AAuDA,oDAmEC;AA1HD;;;;;;;;;;;;GAYG;AACH,4EAA8F;AA0C9F,SAAgB,oBAAoB,CAAC,MAA4B;IAC/D,MAAM,EACJ,SAAS,EACT,SAAS;IACT,wFAAwF;IACxF,0FAA0F;IAC1F,yBAAyB;IACzB,YAAY,GAAG,sBAAsB,EACrC,aAAa,GAAG,+BAA+B,EAC/C,cAAc,GAAG,eAAe,EAChC,KAAK,GAAG,mBAAmB,GAC5B,GAAG,MAAM,CAAC;IAEX,IAAI,YAAY,GAAa,EAAE,CAAC;IAChC,IAAI,eAAmC,CAAC;IACxC,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,kGAAkG;IAClG,WAAW;IACX,IAAI,MAAwC,CAAC;IAE7C;;;;OAIG;IACH,KAAK,UAAU,OAAO;QACpB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IAAI,YAAY,CAAC,MAAM,IAAI,GAAG,GAAG,QAAQ,GAAG,SAAS;YAAE,OAAO;QAE9D,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,gEAAgE,CAAC,CAAC;YACzF,OAAO;QACT,CAAC;QAED,IAAI,CAAC;YACH,IAAI,CAAC,MAAM;gBAAE,MAAM,GAAG,IAAI,6CAAoB,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;YACpF,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,IAAI,8CAAqB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC;YACnF,IAAI,CAAC,IAAI,CAAC,YAAY;gBAAE,MAAM,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC;YAExD,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,YAAY,CAA2B,CAAC;YACvE,MAAM,OAAO,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;YACrC,IAAI,CAAC,OAAO;gBAAE,MAAM,IAAI,KAAK,CAAC,iBAAiB,YAAY,WAAW,CAAC,CAAC;YAExE,0FAA0F;YAC1F,MAAM,QAAQ,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;YACvC,YAAY,GAAG,QAAQ,IAAI,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;YAClF,6FAA6F;YAC7F,4EAA4E;YAC5E,eAAe,GAAG,MAAM,CAAC,cAAc,CAAC,IAAI,SAAS,CAAC;YACtD,QAAQ,GAAG,GAAG,CAAC;QACjB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,kCAAkC,EAAG,CAAW,EAAE,IAAI,IAAI,OAAO,CAAC,CAAC;YAC1F,0FAA0F;QAC5F,CAAC;IACH,CAAC;IAED,OAAO;QACL,KAAK,CAAC,SAAS;YACb,MAAM,OAAO,EAAE,CAAC;YAChB,OAAO,YAAY,CAAC;QACtB,CAAC;QAED,KAAK,CAAC,YAAY;YAChB,MAAM,OAAO,EAAE,CAAC;YAChB,OAAO,eAAe,CAAC;QACzB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Runtime TTL cache for the shared `cloudfront-challenge` secret.\n *\n * The TTL is what makes challenge rotation free for an app that reads the secret this way. Secrets\n * Manager is read at RUNTIME behind that TTL and both `current` and `previous` values are accepted,\n * so a rotation propagates with no deploy at all. An ALB listener rule, by contrast, has its accepted\n * values baked in at CDK synth — which is why every cluster that checks the header is a redeploy in\n * the rotation dance, and an app using this cache is not.\n *\n * A factory rather than a module singleton: config arrives as arguments, and the cache state lives\n * on the instance. A second app in the same process — or a second test in the same file — can hold\n * its own without a module-registry reset.\n */\nimport { GetSecretValueCommand, SecretsManagerClient } from '@aws-sdk/client-secrets-manager';\n\nexport interface ChallengeCacheConfig {\n /** Full ARN of the secret holding the challenge fields. The region is read out of it. */\n secretArn: string | undefined;\n /**\n * TTL before a refetch, in ms. REQUIRED, with no module default: this is the window during which\n * a rotated-away value is still accepted, so each consumer states its own tolerance rather than\n * inheriting someone else's.\n */\n refreshMs: number;\n /** JSON field key for the current value. Defaults to the edge's own literal. */\n currentField?: string;\n /** JSON field key for the previous value — present only inside a rotation window. */\n previousField?: string;\n /**\n * JSON field key for the edge's JWT public key. Present only where the secret has been given one;\n * absent secrets simply yield `undefined` from `getPublicKey()`.\n */\n publicKeyField?: string;\n /** Log prefix, so an operator grepping CloudWatch can tell which app spoke. */\n label?: string;\n}\n\nexport interface ChallengeCache {\n /**\n * Every currently-valid challenge value, current first. Refetches only when empty or past the TTL.\n * On a fetch failure serves the last-good list if there is one — a brief Secrets Manager blip\n * should not break a request that just succeeded — else returns `[]`, which callers treat as\n * \"cannot validate\" and reject.\n */\n getValues(): Promise<string[]>;\n /**\n * The edge's JWT public key in PEM, or `undefined` if the secret carries no such field.\n *\n * Served from the SAME fetch and the SAME TTL as `getValues`. That is the point: an app that\n * verifies tokens acquires no dependency it did not already have, and no second way to be\n * unavailable. A public key is not a credential, so carrying it here widens nothing.\n */\n getPublicKey(): Promise<string | undefined>;\n}\n\nexport function createChallengeCache(config: ChallengeCacheConfig): ChallengeCache {\n const {\n secretArn,\n refreshMs,\n // In shibboleth-sp-at-edge these are the literals in SECRET_FIELD_NAMES. Both cross the\n // edge↔origin boundary: rotation widens checkers to accept {current, previous}, flips the\n // senders, then narrows.\n currentField = 'cloudfront-challenge',\n previousField = 'cloudfront-challenge-previous',\n publicKeyField = 'wp-jwt-pubkey',\n label = 'edge-origin-trust',\n } = config;\n\n let cachedValues: string[] = [];\n let cachedPublicKey: string | undefined;\n let cachedAt = 0;\n // Memoized across fetches: a fresh client per cache miss re-resolves credentials each time for no\n // benefit.\n let client: SecretsManagerClient | undefined;\n\n /**\n * One fetch populates every field this cache serves, under one TTL. Both getters go through here,\n * so a consumer that reads the public key makes no additional request and inherits the same\n * fail-closed behaviour. On failure the last-good values stand.\n */\n async function refresh(): Promise<void> {\n const now = Date.now();\n if (cachedValues.length && now - cachedAt < refreshMs) return;\n\n if (!secretArn) {\n console.error(`[${label}] challenge secret ARN is not set — cannot validate challenge.`);\n return;\n }\n\n try {\n if (!client) client = new SecretsManagerClient({ region: secretArn.split(':')[3] });\n const resp = await client.send(new GetSecretValueCommand({ SecretId: secretArn }));\n if (!resp.SecretString) throw new Error('empty secret');\n\n const fields = JSON.parse(resp.SecretString) as Record<string, string>;\n const current = fields[currentField];\n if (!current) throw new Error(`secret field \"${currentField}\" missing`);\n\n // `previous` is optional and usually absent; an empty value is not an accepted challenge.\n const previous = fields[previousField];\n cachedValues = previous && previous !== current ? [current, previous] : [current];\n // Optional. A secret without it simply yields undefined, and a consumer that asked to verify\n // tokens then fails closed rather than falling back to trusting the header.\n cachedPublicKey = fields[publicKeyField] || undefined;\n cachedAt = now;\n } catch (e) {\n console.error(`[${label}] challenge secret fetch failed:`, (e as Error)?.name || 'error');\n // leave last-good in place; cold failure leaves [] / undefined, which both callers reject\n }\n }\n\n return {\n async getValues(): Promise<string[]> {\n await refresh();\n return cachedValues;\n },\n\n async getPublicKey(): Promise<string | undefined> {\n await refresh();\n return cachedPublicKey;\n },\n };\n}\n"]}