@coffre/core 0.10.2 → 0.11.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.
@@ -24,6 +24,9 @@
24
24
  * no GitHub binding matches `sub`: `ref` and `workflow_ref` stay as they were.
25
25
  */
26
26
 
27
+ import { shownMember } from '../schemas.ts';
28
+ import type { Constraints } from './constraints.ts';
29
+
27
30
  export const GITHUB_ISSUER = 'https://token.actions.githubusercontent.com';
28
31
  export const GITLAB_ISSUER = 'https://gitlab.com';
29
32
 
@@ -35,8 +38,29 @@ export const GITLAB_ISSUER = 'https://gitlab.com';
35
38
  * the organization: an explicit choice, never what a missing claim means.
36
39
  * - `gitlab`: a project's pipelines, outside merge requests.
37
40
  * - `custom`: any other issuer, by its subject, which the owner vouches for.
41
+ *
42
+ * Then the platforms of docs/design/workload-access.md, section 4, which
43
+ * sign in at `/api/auth/workload` alone, for a key-bound session:
44
+ *
45
+ * - `kubernetes`, `gcp`, `azure`, `fly`, `vercel`: the platform's ID token.
46
+ * - `aws`: a signed `GetCallerIdentity`, bound to the session's key.
47
+ * - `enrollment`: a code CI mints, for platforms that sign nothing.
48
+ * - `cloudflare`: a service binding's `props`, which no request carries.
38
49
  */
39
- export type WorkloadProfile = 'github' | 'github-reusable' | 'github-reusable-organization' | 'gitlab' | 'custom';
50
+ export type WorkloadProfile =
51
+ | 'github'
52
+ | 'github-reusable'
53
+ | 'github-reusable-organization'
54
+ | 'gitlab'
55
+ | 'custom'
56
+ | 'kubernetes'
57
+ | 'gcp'
58
+ | 'azure'
59
+ | 'fly'
60
+ | 'vercel'
61
+ | 'aws'
62
+ | 'enrollment'
63
+ | 'cloudflare';
40
64
 
41
65
  export const WORKLOAD_PROFILES: readonly WorkloadProfile[] = [
42
66
  'github',
@@ -44,15 +68,63 @@ export const WORKLOAD_PROFILES: readonly WorkloadProfile[] = [
44
68
  'github-reusable-organization',
45
69
  'gitlab',
46
70
  'custom',
71
+ 'kubernetes',
72
+ 'gcp',
73
+ 'azure',
74
+ 'fly',
75
+ 'vercel',
76
+ 'aws',
77
+ 'enrollment',
78
+ 'cloudflare',
47
79
  ];
48
80
 
49
- /** The claims each profile requires; a binding may add more, to narrow it. */
81
+ /**
82
+ * The profiles `/api/auth/oidc` exchanges for a bearer credential, and only
83
+ * on a binding with no policy: a platform's token bought at that route reads
84
+ * values, so a binding made for a key-bound session, policy and all, is never
85
+ * one it matches. Every binding of another profile carries a policy.
86
+ */
87
+ export const BEARER_PROFILES = ['github', 'github-reusable', 'github-reusable-organization', 'gitlab', 'custom'] as const satisfies readonly WorkloadProfile[];
88
+ export type BearerProfile = (typeof BEARER_PROFILES)[number];
89
+
90
+ /** Whether a binding's profile is one `/api/auth/oidc` takes; it takes the binding only if it has no policy, too. */
91
+ export function isBearerProfile(profile: string): profile is BearerProfile {
92
+ return (BEARER_PROFILES as readonly string[]).includes(profile);
93
+ }
94
+
95
+ /** The profiles whose proof is no ID token: their binding's issuer is this URN, which no token names, and its keys none. */
96
+ export const PROFILE_URNS = {
97
+ aws: 'urn:coffre:aws',
98
+ enrollment: 'urn:coffre:enrollment',
99
+ cloudflare: 'urn:coffre:cloudflare',
100
+ } as const satisfies Partial<Record<WorkloadProfile, string>>;
101
+
102
+ /** The profiles whose proof is a platform's ID token. */
103
+ export const OIDC_PROFILES: readonly WorkloadProfile[] = WORKLOAD_PROFILES.filter((profile) => !Object.hasOwn(PROFILE_URNS, profile));
104
+
105
+ /**
106
+ * Tokens a platform hands out again, the same one to every replica and
107
+ * restart for its lifetime: a managed identity's. Spending one would
108
+ * refuse them, so none is spent: it is a bearer until its own `exp`, which
109
+ * ends the session it makes (section 4.2).
110
+ */
111
+ export const REPEATING_PROFILES: readonly WorkloadProfile[] = ['azure'];
112
+
113
+ /** The claims each profile requires; a binding may add more, to narrow it. An `aws` binding's are the role's account and unique ID. */
50
114
  export const REQUIRED_CLAIMS: Record<WorkloadProfile, readonly string[]> = {
51
115
  github: ['repository_owner_id', 'repository_id', 'workflow_ref', 'ref', 'event_name'],
52
116
  'github-reusable': ['repository_owner_id', 'repository_id', 'ref', 'event_name', 'job_workflow_ref', 'job_workflow_sha'],
53
117
  'github-reusable-organization': ['repository_owner_id', 'ref', 'event_name', 'job_workflow_ref', 'job_workflow_sha'],
54
118
  gitlab: ['namespace_id', 'project_id', 'ref_type', 'ref', 'pipeline_source'],
55
119
  custom: ['sub'],
120
+ kubernetes: ['sub', 'kubernetes.io.serviceaccount.uid'],
121
+ gcp: ['sub'],
122
+ azure: ['tid', 'oid'],
123
+ fly: ['org_id', 'app_id'],
124
+ vercel: ['owner_id', 'project_id', 'environment'],
125
+ aws: ['account', 'role_id'],
126
+ enrollment: [],
127
+ cloudflare: [],
56
128
  };
57
129
 
58
130
  /**
@@ -98,6 +170,14 @@ const EVENT_CLAIM: Record<WorkloadProfile, { name: string; values: readonly stri
98
170
  'github-reusable-organization': GITHUB_EVENT,
99
171
  gitlab: { name: 'pipeline_source', values: GITLAB_PIPELINE_SOURCES, why: 'merge-request pipelines name another project' },
100
172
  custom: null,
173
+ kubernetes: null,
174
+ gcp: null,
175
+ azure: null,
176
+ fly: null,
177
+ vercel: null,
178
+ aws: null,
179
+ enrollment: null,
180
+ cloudflare: null,
101
181
  };
102
182
 
103
183
  /** At most this many live bindings per service, and claims per binding. */
@@ -131,7 +211,7 @@ export type BindingClaims = Record<string, ClaimValue>;
131
211
  * its keys (`uploaded`): then coffre fetches nothing, and it is any string,
132
212
  * matched exactly, such as a private Kubernetes cluster's.
133
213
  */
134
- export type BindingPolicy = { profile: WorkloadProfile; issuer: string; claims: BindingClaims };
214
+ export type CheckedBinding = { profile: WorkloadProfile; issuer: string; claims: BindingClaims };
135
215
 
136
216
  /** A binding that breaks a rule, said so an owner can fix it. */
137
217
  export class BindingInvalid extends Error {
@@ -145,13 +225,28 @@ export class BindingInvalid extends Error {
145
225
  function forcedProfiles(issuer: string): readonly WorkloadProfile[] | null {
146
226
  if (issuer === GITHUB_ISSUER) return ['github', 'github-reusable', 'github-reusable-organization'];
147
227
  if (issuer === GITLAB_ISSUER) return ['gitlab'];
228
+ // The platforms of workload access (section 4.2): a custom binding of theirs would drop the key-naming audience, or spend a token they repeat.
229
+ if (issuer === GOOGLE_ISSUER) return ['gcp'];
230
+ if (issuer.startsWith('https://oidc.fly.io/')) return ['fly'];
231
+ if (issuer === 'https://oidc.vercel.com' || issuer.startsWith('https://oidc.vercel.com/')) return ['vercel'];
232
+ if (issuer.startsWith('https://sts.windows.net/') || issuer.startsWith('https://login.microsoftonline.com/')) return ['azure'];
148
233
  return null;
149
234
  }
150
235
 
151
- /** The issuer a profile means when none is given: github.com's or gitlab.com's. A GitHub Enterprise Server or a self-managed GitLab names its own. */
236
+ /** Google's, for every `gcp` binding. */
237
+ export const GOOGLE_ISSUER = 'https://accounts.google.com';
238
+
239
+ /**
240
+ * The issuer a profile means when none is given: github.com's, gitlab.com's
241
+ * or Google's, or the URN of a profile that is no ID token. A GitHub
242
+ * Enterprise Server, a self-managed GitLab, a cluster, a tenant or a team
243
+ * names its own.
244
+ */
152
245
  export function defaultIssuer(profile: WorkloadProfile): string | null {
246
+ if (Object.hasOwn(PROFILE_URNS, profile)) return PROFILE_URNS[profile as keyof typeof PROFILE_URNS];
247
+ if (profile.startsWith('github')) return GITHUB_ISSUER;
153
248
  if (profile === 'gitlab') return GITLAB_ISSUER;
154
- return profile === 'custom' ? null : GITHUB_ISSUER;
249
+ return profile === 'gcp' ? GOOGLE_ISSUER : null;
155
250
  }
156
251
 
157
252
  /** The longest issuer a binding with uploaded keys names, in bytes. */
@@ -166,15 +261,22 @@ export const MAX_ISSUER_BYTES = 400;
166
261
  export function checkBinding(
167
262
  input: { profile: string; issuer: string | null; claims: Record<string, unknown> },
168
263
  options: { allowLoopback?: boolean; uploaded?: boolean } = {},
169
- ): BindingPolicy {
264
+ ): CheckedBinding {
170
265
  const profile = input.profile as WorkloadProfile;
171
266
  if (!WORKLOAD_PROFILES.includes(profile)) {
172
267
  throw new BindingInvalid(`unknown profile "${input.profile}": one of ${WORKLOAD_PROFILES.join(', ')}`);
173
268
  }
174
269
  const issuer = input.issuer ?? defaultIssuer(profile);
175
- if (issuer === null) throw new BindingInvalid('a custom binding names its issuer');
176
- if (options.uploaded === true) checkIssuerName(issuer);
270
+ if (issuer === null) throw new BindingInvalid(`a ${profile} binding names its issuer`);
271
+ const urn = defaultIssuer(profile);
272
+ if (Object.hasOwn(PROFILE_URNS, profile)) {
273
+ // No token names it, and coffre fetches nothing for it: the URN alone keeps one key source per issuer.
274
+ if (issuer !== urn) throw new BindingInvalid(`a ${profile} binding's issuer is ${urn}`);
275
+ if (options.uploaded === true) throw new BindingInvalid(`a ${profile} binding carries no keys: its proof is no ID token`);
276
+ } else if (options.uploaded === true) checkIssuerName(issuer);
177
277
  else checkFetchUrl(issuer, 'the issuer', { allowLoopback: options.allowLoopback, path: true, query: false });
278
+ // Google signs every service account's tokens, as one issuer.
279
+ if (profile === 'gcp' && issuer !== GOOGLE_ISSUER) throw new BindingInvalid(`a gcp binding's issuer is ${GOOGLE_ISSUER}`);
178
280
  const forced = forcedProfiles(issuer);
179
281
  if (forced !== null && !forced.includes(profile)) {
180
282
  throw new BindingInvalid(`${issuer} signs only for the ${forced[0]} profile${forced.length > 1 ? 's' : ''}`);
@@ -185,7 +287,8 @@ export function checkBinding(
185
287
  const event = EVENT_CLAIM[profile];
186
288
  const claims: BindingClaims = {};
187
289
  for (const [name, value] of entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
188
- if (!CLAIM_NAME.test(name)) throw new BindingInvalid(`"${name}" is not a claim name a binding can match`);
290
+ // `__proto__` too: assigned below, it would set the object's prototype, and the binding would silently lose the claim.
291
+ if (!CLAIM_NAME.test(name) || name === '__proto__') throw new BindingInvalid(`"${name}" is not a claim name a binding can match`);
189
292
  if (RESERVED.has(name)) throw new BindingInvalid(`a binding never names "${name}": the exchange checks it`);
190
293
  if (name === event?.name) {
191
294
  // Stored once each, in the profile's order, and a single one as a plain value.
@@ -205,6 +308,7 @@ export function checkBinding(
205
308
  }
206
309
  claims[name] = value;
207
310
  }
311
+ if (REQUIRED_CLAIMS[profile].length === 0 && entries.length > 0) throw new BindingInvalid(`a ${profile} binding names no claims: its proof carries none`);
208
312
  const missing = REQUIRED_CLAIMS[profile].filter((name) => claims[name] === undefined);
209
313
  if (missing.length > 0) throw new BindingInvalid(`the ${profile} profile requires ${missing.join(', ')}`);
210
314
  if (profile === 'github-reusable-organization' && claims.repository_id !== undefined) {
@@ -230,6 +334,7 @@ function checkIssuerName(issuer: string): void {
230
334
  if (issuer === GITHUB_ISSUER || issuer === GITLAB_ISSUER) {
231
335
  throw new BindingInvalid(`${issuer} publishes its keys and rotates them: coffre fetches them, so upload none`);
232
336
  }
337
+ if (issuer.startsWith('urn:coffre:')) throw new BindingInvalid(`${issuer} is coffre's own, for a binding that is no ID token's`);
233
338
  }
234
339
 
235
340
  /** A claim's values, one or several. */
@@ -351,7 +456,7 @@ function atBaseBranch(claims: Record<string, unknown>): Record<string, unknown>
351
456
  const { event_name: event, ref, base_ref: base, workflow_ref: workflow } = claims;
352
457
  if (event !== 'pull_request' || typeof ref !== 'string' || typeof base !== 'string' || base === '') return claims;
353
458
  const at = `refs/heads/${base}`;
354
- const file = typeof workflow === 'string' && workflow.endsWith(`@${ref}`) ? `${workflow.slice(0, -ref.length)}${at}` : workflow;
459
+ const file = typeof workflow === 'string' && workflow.endsWith(`@${ref}`) ? `${workflow.slice(0, workflow.length - ref.length)}${at}` : workflow;
355
460
  return { ...claims, ref: at, workflow_ref: file };
356
461
  }
357
462
 
@@ -402,6 +507,9 @@ export function checkFetchUrl(
402
507
  // in. They decide nothing: `checkBinding`, on the server, holds the result
403
508
  // to its profile, whoever built it.
404
509
 
510
+ /** What a preset fills in: a profile `/api/auth/oidc` takes, and its claims. */
511
+ export type Preset = { profile: BearerProfile; claims: BindingClaims };
512
+
405
513
  /** `refs/heads/main`, or `refs/tags/v1`, as GitHub names a ref. */
406
514
  export function fullRef(kind: 'branch' | 'tag', name: string): string {
407
515
  return `refs/${kind === 'branch' ? 'heads' : 'tags'}/${name}`;
@@ -450,7 +558,7 @@ export function githubWorkflow(input: {
450
558
  workflow: string;
451
559
  ref: string;
452
560
  environment?: string;
453
- } & Starts<'event', 'events'>): Omit<BindingPolicy, 'issuer'> {
561
+ } & Starts<'event', 'events'>): Preset {
454
562
  return {
455
563
  profile: 'github',
456
564
  claims: {
@@ -483,7 +591,7 @@ export function githubReusable(input: {
483
591
  sha: string;
484
592
  caller?: { repository: string; workflow: string };
485
593
  environment?: string;
486
- } & Starts<'event', 'events'>): Omit<BindingPolicy, 'issuer'> {
594
+ } & Starts<'event', 'events'>): Preset {
487
595
  const claims: BindingClaims = {
488
596
  repository_owner_id: input.ownerId,
489
597
  ...(input.repositoryId === null ? {} : { repository_id: input.repositoryId }),
@@ -503,7 +611,7 @@ export function gitlabProject(input: {
503
611
  projectId: string;
504
612
  refType: 'branch' | 'tag';
505
613
  ref: string;
506
- } & Starts<'source', 'sources'>): Omit<BindingPolicy, 'issuer'> {
614
+ } & Starts<'source', 'sources'>): Preset {
507
615
  return {
508
616
  profile: 'gitlab',
509
617
  claims: {
@@ -515,3 +623,405 @@ export function gitlabProject(input: {
515
623
  },
516
624
  };
517
625
  }
626
+
627
+ // --- policy --------------------------------------------------------------------
628
+ //
629
+ // What a binding says beyond its claims (docs/design/workload-access.md,
630
+ // section 11): stored beside them, under the binding's MAC, as canonical
631
+ // JSON, and as immutable as the rest of it. Each profile takes a fixed
632
+ // subset of the fields.
633
+
634
+ /**
635
+ * What a binding's sessions may read, by environment ID and key ID, so a
636
+ * rename moves nothing: `keys` lists keys, or `'*'` every key of the
637
+ * environment; `mints`, the minters whose children it is handed.
638
+ */
639
+ export type BindingReads = Readonly<Record<string, { readonly keys?: readonly string[] | '*'; readonly mints?: readonly string[] }>>;
640
+
641
+ /**
642
+ * A binding's policy, as `checkPolicy` returns it: a field left out holds
643
+ * its default (`POLICY_DEFAULTS`), so one policy has one spelling.
644
+ *
645
+ * - `audience`: the exact audience of an `azure` token, an Entra
646
+ * application ID URI, which Entra fixes; required for it, refused for
647
+ * every other profile.
648
+ * - `keyAudience`: the token's audience must name the session's key,
649
+ * `<publicUrl>#jkt=<thumbprint>`: always for the platforms whose caller
650
+ * picks the audience (`KEY_NAMING_PROFILES`), and where a `custom`
651
+ * binding says so.
652
+ * - `reads`: the escape hatch, by ID (section 6.1).
653
+ * - `sources`: CIDRs a session's client address must be within.
654
+ * - `sessionHours`: a session's hard end after its proof, at most 168.
655
+ * - An `enrollment` binding's codes: `replicas` (required), `sessionDays`,
656
+ * `overlapMinutes`, `mintedBy` (the service, never the binding's own,
657
+ * that may mint them), `approve` and `onContention` (section 4.4).
658
+ * - `unsignedUploads`: a streamed upload no digest binds may go through a
659
+ * credential that takes one (section 5.1), which leaves column B at use.
660
+ */
661
+ export type BindingPolicy = {
662
+ readonly audience?: string;
663
+ readonly keyAudience?: true;
664
+ readonly reads?: BindingReads;
665
+ readonly sources?: readonly string[];
666
+ readonly sessionHours?: number;
667
+ readonly replicas?: number;
668
+ readonly sessionDays?: number;
669
+ readonly overlapMinutes?: number;
670
+ readonly mintedBy?: string;
671
+ readonly approve?: true;
672
+ readonly onContention?: 'alert';
673
+ readonly unsignedUploads?: true;
674
+ };
675
+
676
+ /** What a field left out of a policy means. */
677
+ export const POLICY_DEFAULTS = {
678
+ keyAudience: false,
679
+ sessionHours: 24,
680
+ sessionDays: 30,
681
+ overlapMinutes: 15,
682
+ approve: false,
683
+ onContention: 'freeze',
684
+ unsignedUploads: false,
685
+ } as const;
686
+
687
+ /** The most environments, and keys in each, a binding's `reads` lists; the most `sources`. */
688
+ export const MAX_READ_PLACES = 64;
689
+ export const MAX_READ_KEYS = 256;
690
+ export const MAX_SOURCES = 16;
691
+
692
+ type PolicyField = keyof BindingPolicy;
693
+
694
+ const SESSION_FIELDS: readonly PolicyField[] = ['reads', 'sources', 'sessionHours', 'unsignedUploads'];
695
+ const KEY_AUDIENCE: readonly PolicyField[] = [...SESSION_FIELDS, 'keyAudience'];
696
+
697
+ /**
698
+ * The profiles whose caller picks the token's audience, so their binding's
699
+ * policy always says `keyAudience`: `checkPolicy` sets it, and refuses it off.
700
+ * A Vercel function picks one by exchanging its own token at
701
+ * `https://oidc.vercel.com/~token`, as `@vercel/oidc`'s
702
+ * `getVercelOidcToken({ audience })` does.
703
+ */
704
+ export const KEY_NAMING_PROFILES: readonly WorkloadProfile[] = ['github', 'github-reusable', 'github-reusable-organization', 'gcp', 'fly', 'vercel'];
705
+
706
+ /** The fields each profile's policy may hold. */
707
+ export const POLICY_FIELDS: Record<WorkloadProfile, readonly PolicyField[]> = {
708
+ github: KEY_AUDIENCE,
709
+ 'github-reusable': KEY_AUDIENCE,
710
+ 'github-reusable-organization': KEY_AUDIENCE,
711
+ gitlab: SESSION_FIELDS,
712
+ custom: KEY_AUDIENCE,
713
+ kubernetes: SESSION_FIELDS,
714
+ gcp: KEY_AUDIENCE,
715
+ azure: [...SESSION_FIELDS, 'audience'],
716
+ fly: KEY_AUDIENCE,
717
+ vercel: KEY_AUDIENCE,
718
+ aws: SESSION_FIELDS,
719
+ enrollment: ['reads', 'sources', 'replicas', 'sessionDays', 'overlapMinutes', 'mintedBy', 'approve', 'onContention', 'unsignedUploads'],
720
+ // A call from another Worker has no address of its own and no session to end.
721
+ cloudflare: ['reads'],
722
+ };
723
+
724
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
725
+ /** A credential's name in the proxy's config: a minter's, a signer's, an upstream's. */
726
+ export const CREDENTIAL_NAME = /^[a-z][a-z0-9-]{0,31}$/;
727
+ /** A service's name after `token:`, as a member names it. */
728
+ const SERVICE_NAME = /^[^\s\p{Cc}]{1,320}$/u;
729
+
730
+ function integer(value: unknown, name: string, min: number, max: number): number {
731
+ if (!Number.isSafeInteger(value) || (value as number) < min || (value as number) > max) {
732
+ throw new BindingInvalid(`${name} is a whole number from ${min} to ${max}`);
733
+ }
734
+ return value as number;
735
+ }
736
+
737
+ function sortedUnique(values: readonly string[]): string[] {
738
+ return [...new Set(values)].sort();
739
+ }
740
+
741
+ function uuidList(value: unknown, what: string, max: number): string[] {
742
+ if (!Array.isArray(value) || value.length > max || value.some((id) => typeof id !== 'string' || !UUID.test(id.toLowerCase()))) {
743
+ throw new BindingInvalid(`${what} lists at most ${max} IDs`);
744
+ }
745
+ return sortedUnique(value.map((id: string) => id.toLowerCase()));
746
+ }
747
+
748
+ function checkReads(value: unknown): BindingReads | undefined {
749
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new BindingInvalid('reads maps environment IDs to { keys, mints }');
750
+ const entries = Object.entries(value as Record<string, unknown>);
751
+ if (entries.length > MAX_READ_PLACES) throw new BindingInvalid(`reads names at most ${MAX_READ_PLACES} environments`);
752
+ const reads: Record<string, { keys?: readonly string[] | '*'; mints?: readonly string[] }> = {};
753
+ const seen = new Set<string>();
754
+ for (const [environment, entry] of entries) {
755
+ const id = environment.toLowerCase();
756
+ if (!UUID.test(id)) throw new BindingInvalid(`reads names environments by ID: ${environment} is none`);
757
+ if (seen.has(id)) throw new BindingInvalid(`reads names ${id} twice`);
758
+ seen.add(id);
759
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) throw new BindingInvalid('each environment of reads is { keys, mints }');
760
+ const { keys, mints, ...rest } = entry as Record<string, unknown>;
761
+ if (Object.keys(rest).length > 0) throw new BindingInvalid(`each environment of reads holds keys and mints, not ${Object.keys(rest).join(', ')}`);
762
+ const read: { keys?: readonly string[] | '*'; mints?: readonly string[] } = {};
763
+ if (keys !== undefined) {
764
+ const listed = keys === '*' ? '*' : uuidList(keys, 'reads.keys', MAX_READ_KEYS);
765
+ if (listed === '*' || listed.length > 0) read.keys = listed;
766
+ }
767
+ if (mints !== undefined) {
768
+ if (!Array.isArray(mints) || mints.length > MAX_READ_KEYS || mints.some((name) => typeof name !== 'string' || !CREDENTIAL_NAME.test(name))) {
769
+ throw new BindingInvalid('reads.mints lists minters by name');
770
+ }
771
+ if (mints.length > 0) read.mints = sortedUnique(mints as string[]);
772
+ }
773
+ // A place that lists nothing reads nothing: one spelling, left out.
774
+ if (read.keys !== undefined || read.mints !== undefined) reads[id] = read;
775
+ }
776
+ return Object.keys(reads).length === 0 ? undefined : reads;
777
+ }
778
+
779
+ /**
780
+ * Check a binding's policy against its profile and return it canonical:
781
+ * every field its profile allows, valid, those at their default left out,
782
+ * lists sorted and IDs in lower case, so that one policy has one spelling
783
+ * (`policyText`). `service` is the binding's own, `token:<name>`, which its
784
+ * `mintedBy` may not name: a session of the service would then mint codes
785
+ * for itself, and outlive every deploy. Throws `BindingInvalid`.
786
+ */
787
+ export function checkPolicy(profile: WorkloadProfile, input: unknown, options: { service: string }): BindingPolicy {
788
+ if (input === undefined || input === null) input = {};
789
+ if (typeof input !== 'object' || Array.isArray(input)) throw new BindingInvalid('a policy is an object');
790
+ const given = input as Record<string, unknown>;
791
+ const allowed = POLICY_FIELDS[profile];
792
+ const extra = Object.keys(given).filter((name) => given[name] !== undefined && !allowed.includes(name as PolicyField));
793
+ if (extra.length > 0) throw new BindingInvalid(`a ${profile} binding's policy holds ${allowed.join(', ') || 'nothing'}, not ${extra.join(', ')}`);
794
+ const policy: { -readonly [K in PolicyField]?: BindingPolicy[K] } = {};
795
+
796
+ if (given.audience !== undefined) {
797
+ if (typeof given.audience !== 'string' || given.audience === '' || given.audience.length > 400 || /\p{Cc}|^\s|\s$/u.test(given.audience)) {
798
+ throw new BindingInvalid('audience is the exact audience the platform puts in its tokens');
799
+ }
800
+ policy.audience = given.audience;
801
+ } else if (allowed.includes('audience')) {
802
+ throw new BindingInvalid(`a ${profile} binding names the audience its platform puts in its tokens: ${profile} lets no caller choose one`);
803
+ }
804
+ if (given.keyAudience !== undefined && typeof given.keyAudience !== 'boolean') throw new BindingInvalid('keyAudience is true or false');
805
+ if (KEY_NAMING_PROFILES.includes(profile)) {
806
+ // Its caller picks the audience, so the token names the key, or a copy of it would buy a session for any key.
807
+ if (given.keyAudience === false) {
808
+ throw new BindingInvalid(`a ${profile} binding's tokens name the session's key in their audience: ${profile} lets its caller choose one, so a copied token works for no other key`);
809
+ }
810
+ policy.keyAudience = true;
811
+ } else if (given.keyAudience === true) policy.keyAudience = true;
812
+ if (given.reads !== undefined) {
813
+ const reads = checkReads(given.reads);
814
+ if (reads !== undefined) policy.reads = reads;
815
+ }
816
+ if (given.sources !== undefined) {
817
+ if (!Array.isArray(given.sources) || given.sources.length > MAX_SOURCES) throw new BindingInvalid(`sources lists at most ${MAX_SOURCES} CIDRs`);
818
+ const sources = sortedUnique(given.sources.map((source: unknown) => {
819
+ const block = typeof source === 'string' ? parseCidr(source) : null;
820
+ if (block === null) throw new BindingInvalid(`sources lists CIDRs, such as 162.220.232.0/24 or 2001:db8::/32: ${String(source)} is none`);
821
+ return block.text;
822
+ }));
823
+ if (sources.length > 0) policy.sources = sources;
824
+ }
825
+ const number = (name: 'sessionHours' | 'sessionDays' | 'overlapMinutes' | 'replicas', min: number, max: number) => {
826
+ if (given[name] === undefined) return;
827
+ const value = integer(given[name], name, min, max);
828
+ if (name === 'replicas' || value !== POLICY_DEFAULTS[name]) policy[name] = value;
829
+ };
830
+ number('sessionHours', 1, 168);
831
+ number('sessionDays', 1, 90);
832
+ number('overlapMinutes', 1, 60);
833
+ number('replicas', 1, 64);
834
+ if (profile === 'enrollment' && policy.replicas === undefined) {
835
+ throw new BindingInvalid('an enrollment binding says how many replicas run, its replicas: a code admits twice that many sessions');
836
+ }
837
+ if (given.mintedBy !== undefined) {
838
+ const named = typeof given.mintedBy === 'string' ? (given.mintedBy.startsWith('token:') ? given.mintedBy : `token:${given.mintedBy}`) : '';
839
+ if (!SERVICE_NAME.test(named.slice('token:'.length))) throw new BindingInvalid('mintedBy names a service account');
840
+ if (named === options.service) throw new BindingInvalid(`mintedBy names another service than ${shownMember(options.service)}: a session of its own would mint codes for itself`);
841
+ policy.mintedBy = named;
842
+ }
843
+ for (const flag of ['approve', 'unsignedUploads'] as const) {
844
+ if (given[flag] === undefined) continue;
845
+ if (typeof given[flag] !== 'boolean') throw new BindingInvalid(`${flag} is true or false`);
846
+ if (given[flag]) policy[flag] = true;
847
+ }
848
+ if (given.onContention !== undefined) {
849
+ if (given.onContention !== 'freeze' && given.onContention !== 'alert') throw new BindingInvalid('onContention is freeze or alert');
850
+ if (given.onContention === 'alert') policy.onContention = 'alert';
851
+ }
852
+ return policy;
853
+ }
854
+
855
+ /** A value as canonical JSON: every object's keys sorted, at every depth. */
856
+ function canonicalJson(value: unknown): string {
857
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
858
+ if (typeof value === 'object' && value !== null) {
859
+ const entries = Object.entries(value).filter(([, item]) => item !== undefined).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
860
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(',')}}`;
861
+ }
862
+ return JSON.stringify(value);
863
+ }
864
+
865
+ /** A policy as the binding's `policy` column and its MAC hold it: `checkPolicy`'s result, as canonical JSON. */
866
+ export function policyText(policy: BindingPolicy): string {
867
+ return canonicalJson(policy);
868
+ }
869
+
870
+ // --- sources -------------------------------------------------------------------
871
+
872
+ /** An address block: its version, its network's bytes, its prefix length, and its one spelling. */
873
+ export type Cidr = { version: 4 | 6; bytes: Uint8Array; bits: number; text: string };
874
+
875
+ function ipv4(text: string): Uint8Array | null {
876
+ const parts = text.split('.');
877
+ if (parts.length !== 4 || parts.some((part) => !/^(0|[1-9][0-9]{0,2})$/.test(part) || Number(part) > 255)) return null;
878
+ return Uint8Array.from(parts.map(Number));
879
+ }
880
+
881
+ function ipv6(text: string): Uint8Array | null {
882
+ const halves = text.toLowerCase().split('::');
883
+ if (halves.length > 2) return null;
884
+ const groups = halves.map((half) => (half === '' ? [] : half.split(':')));
885
+ if (groups.flat().some((group) => !/^[0-9a-f]{1,4}$/.test(group))) return null;
886
+ const count = groups.flat().length;
887
+ if (halves.length === 1 ? count !== 8 : count > 7) return null;
888
+ const words = halves.length === 1 ? groups[0]! : [...groups[0]!, ...Array<string>(8 - count).fill('0'), ...groups[1]!];
889
+ const bytes = new Uint8Array(16);
890
+ words.forEach((word, i) => {
891
+ const value = parseInt(word, 16);
892
+ bytes[2 * i] = value >> 8;
893
+ bytes[2 * i + 1] = value & 0xff;
894
+ });
895
+ return bytes;
896
+ }
897
+
898
+ /** An address, IPv4 dotted or IPv6 in hex groups; null for anything else. */
899
+ export function parseAddress(text: string): { version: 4 | 6; bytes: Uint8Array } | null {
900
+ // An IPv4 client of a server listening on `::`, as Node reports it: the IPv4 address it is.
901
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(text);
902
+ if (mapped !== null) return parseAddress(mapped[1]!);
903
+ const v4 = ipv4(text);
904
+ if (v4 !== null) return { version: 4, bytes: v4 };
905
+ const v6 = text.includes(':') ? ipv6(text) : null;
906
+ return v6 === null ? null : { version: 6, bytes: v6 };
907
+ }
908
+
909
+ /** IPv6 as RFC 5952 writes it: lower case, no leading zeros, the longest run of two or more zero groups as `::`, the first of equals. */
910
+ function ipv6Text(bytes: Uint8Array): string {
911
+ const words = Array.from({ length: 8 }, (_, i) => (bytes[2 * i]! << 8) | bytes[2 * i + 1]!);
912
+ let best = { at: -1, length: 0 };
913
+ for (let i = 0; i < 8;) {
914
+ if (words[i] !== 0) {
915
+ i++;
916
+ continue;
917
+ }
918
+ let j = i;
919
+ while (j < 8 && words[j] === 0) j++;
920
+ if (j - i > best.length) best = { at: i, length: j - i };
921
+ i = j;
922
+ }
923
+ const hexes = words.map((word) => word.toString(16));
924
+ if (best.length < 2) return hexes.join(':');
925
+ return `${hexes.slice(0, best.at).join(':')}::${hexes.slice(best.at + best.length).join(':')}`;
926
+ }
927
+
928
+ /**
929
+ * A CIDR, `162.220.232.0/24` or `2001:db8::/32`, as its one spelling; null
930
+ * for anything else, a block with host bits set included, since
931
+ * `162.220.232.5/24` most likely means another block than it says.
932
+ */
933
+ export function parseCidr(text: string): Cidr | null {
934
+ const slash = text.indexOf('/');
935
+ if (slash < 0 || !/^(0|[1-9][0-9]{0,2})$/.test(text.slice(slash + 1))) return null;
936
+ const address = parseAddress(text.slice(0, slash));
937
+ const bits = Number(text.slice(slash + 1));
938
+ if (address === null || bits > address.bytes.length * 8) return null;
939
+ for (let bit = bits; bit < address.bytes.length * 8; bit++) {
940
+ if ((address.bytes[bit >> 3]! >> (7 - (bit & 7))) & 1) return null;
941
+ }
942
+ const shown = address.version === 4 ? Array.from(address.bytes).join('.') : ipv6Text(address.bytes);
943
+ return { ...address, bits, text: `${shown}/${bits}` };
944
+ }
945
+
946
+ /** Whether an address is within any of these blocks, each `parseCidr`'s: never for an address that does not parse, or of the other version. */
947
+ export function addressWithin(address: string, sources: readonly string[]): boolean {
948
+ const parsed = parseAddress(address);
949
+ if (parsed === null) return false;
950
+ return sources.some((source) => {
951
+ const block = parseCidr(source);
952
+ if (block === null || block.version !== parsed.version) return false;
953
+ for (let bit = 0; bit < block.bits; bit++) {
954
+ const mask = 1 << (7 - (bit & 7));
955
+ if ((block.bytes[bit >> 3]! & mask) !== (parsed.bytes[bit >> 3]! & mask)) return false;
956
+ }
957
+ return true;
958
+ });
959
+ }
960
+
961
+ // --- freezes -------------------------------------------------------------------
962
+
963
+ /**
964
+ * What a freeze names, in its one spelling (section 8.2): every workload's
965
+ * use, one service, one binding, one session, or one upstream credential of
966
+ * an environment, by the environment's ID so a rename moves nothing.
967
+ *
968
+ * freezeTarget('Binding:0F0E…') → null freezeTarget('binding:0f0e…') → 'binding:0f0e…'
969
+ * freezeTarget('credential:6B1C…-…/stripe') → 'credential:6b1c…-…/stripe'
970
+ */
971
+ export function freezeTarget(text: string): string | null {
972
+ if (text === 'instance') return text;
973
+ const colon = text.indexOf(':');
974
+ if (colon < 0) return null;
975
+ const kind = text.slice(0, colon);
976
+ const rest = text.slice(colon + 1);
977
+ switch (kind) {
978
+ // `service:<name>` is how the CLI and the pages name one: `token:<name>` is its one spelling.
979
+ case 'token':
980
+ case 'service':
981
+ return SERVICE_NAME.test(rest) ? `token:${rest}` : null;
982
+ case 'binding':
983
+ case 'session':
984
+ return UUID.test(rest.toLowerCase()) ? `${kind}:${rest.toLowerCase()}` : null;
985
+ case 'credential': {
986
+ const [environment, name, ...more] = rest.split('/');
987
+ if (more.length > 0 || environment === undefined || name === undefined) return null;
988
+ return UUID.test(environment.toLowerCase()) && CREDENTIAL_NAME.test(name) ? `credential:${environment.toLowerCase()}/${name}` : null;
989
+ }
990
+ default:
991
+ return null;
992
+ }
993
+ }
994
+
995
+ // --- callers -------------------------------------------------------------------
996
+
997
+ /**
998
+ * A workload, authenticated for one request (section 5.3): a key-bound
999
+ * session's, or a Cloudflare service binding's, which has no session row.
1000
+ * `PluginContext.workload(request, …)` returns it, so the proxy sees one
1001
+ * kind of caller whichever way it signed in, and never parses a proof.
1002
+ */
1003
+ export type WorkloadCaller = {
1004
+ readonly kind: 'workload';
1005
+ /** The service, `token:<name>`. */
1006
+ readonly principal: string;
1007
+ /** The session's credential ID, or `binding:<id>` for a Cloudflare call: what the log names. */
1008
+ readonly credentialId: string;
1009
+ readonly bindingId: string;
1010
+ readonly profile: WorkloadProfile;
1011
+ /** A `narrow` child's limits; null for a root, which only its scope bounds. */
1012
+ readonly constraints: Constraints | null;
1013
+ /** The headers the proof signs, which alone are forwarded; null for a Cloudflare call, whose request nobody in between could change. */
1014
+ readonly hdr: readonly string[] | null;
1015
+ readonly sourceIp: string | null;
1016
+ };
1017
+
1018
+ /** What a workload's alert says (section 8.3), to the log and to the deployment's `alert`. */
1019
+ export type WorkloadAlert = {
1020
+ readonly kind: 'enrolled' | 'contention' | 'limit' | 'expiring' | 'frozen';
1021
+ readonly service: string;
1022
+ readonly binding: string | null;
1023
+ readonly session: string | null;
1024
+ readonly ip: string | null;
1025
+ /** One line for a person: `api-prod enrolled from 203.0.113.9 (railway, code minted by deploy run 7001)`. */
1026
+ readonly text: string;
1027
+ };
package/src/kek/local.ts CHANGED
@@ -79,9 +79,11 @@ export class LocalKekProvider implements KekProvider {
79
79
 
80
80
  async unwrap(wrapped: WrappedDek, ctx: SecretContext, operation?: KeyOperation): Promise<Buffer> {
81
81
  checkOperation(operation);
82
- if (wrapped.kekProvider !== this.provider || wrapped.kekId !== this.keyId) {
82
+ // The version too: the wrap binds this key's, and a row claiming
83
+ // another would otherwise open, its claim never checked.
84
+ if (wrapped.kekProvider !== this.provider || wrapped.kekId !== this.keyId || wrapped.kekVersion !== this.keyVersion) {
83
85
  throw new KekBadClaimError(
84
- `wrapped DEK is for ${wrapped.kekProvider}:${wrapped.kekId}, not ${this.provider}:${this.keyId}`,
86
+ `wrapped DEK is for ${wrapped.kekProvider}:${wrapped.kekId} version ${wrapped.kekVersion}, not ${this.provider}:${this.keyId} version ${this.keyVersion}`,
85
87
  );
86
88
  }
87
89
  if (wrapped.bytes.length !== IV_BYTES + TAG_BYTES + DEK_BYTES) {