@fabrika/proxy-core 0.9.0-dev.3 → 0.9.0-dev.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/manifest.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  ANY_ORIGIN_KINDS,
3
3
  APP_ENVIRONMENT_SEPARATOR,
4
+ type BodyAdmission,
4
5
  type Caller,
5
6
  compileEndpointTable,
6
7
  type ContractArtifact,
@@ -15,12 +16,20 @@ import {
15
16
  FILE_RESPONSE_KINDS,
16
17
  type InstallationEndpointRow,
17
18
  type InstallationEndpointTable,
19
+ isAnyOfList,
18
20
  isDigest,
21
+ MAX_ANY_OF,
19
22
  MAX_CACHE_AGE_SECONDS,
23
+ OPS_CONTENT_TYPE,
24
+ OPS_METHOD,
25
+ OPS_PREFIX,
26
+ OPS_ROW_ID,
27
+ OPS_ROW_PATH,
20
28
  parseAppEnvironmentId,
21
29
  requirementDigest,
22
30
  } from '@fabrika/auth-core'
23
31
  import { z } from 'zod'
32
+ import { type InstallationBrand, installationBrandSchema } from './brand'
24
33
  import { type CspOrigins, cspOrigins, isCrossOrigin, isPolicyOrigin, MAX_CROSS_ORIGINS, MAX_CSP_ORIGINS, WORKER_BLOB_SOURCE } from './headers'
25
34
  import { type OAuthProtectedResource, oauthProtectedResourceSchema, oauthScopesSchema } from './oauth-resource'
26
35
 
@@ -56,12 +65,22 @@ export interface ContractProxyApp extends ProxyAppBase {
56
65
  * endpoints"), from Control's registry, never from the contract; absent when it lists none.
57
66
  */
58
67
  crossOrigins?: string[]
68
+ /** The IAM app id `<app>@<env>` a dev sandbox entry (`dev:<app>:<workspace>`) mints for; absent on every other entry. */
69
+ audience?: string
70
+ /** The `Host` the proxy sends upstream in place of the client's; absent, the client's passes. */
71
+ upstreamHost?: string
72
+ }
73
+
74
+ /** The IAM app id an entry's tokens are minted for and verified against: its `audience`, or else its id. */
75
+ export function audienceOf(entry: Pick<ContractProxyApp, 'id' | 'audience'>): string {
76
+ return entry.audience ?? entry.id
59
77
  }
60
78
 
61
79
  /**
62
80
  * An installation service protected by an endpoint table (ADR-0022 "Installation entries"). Only trusted platform
63
81
  * composition writes `installation: true`; its rows may use the forms no application may declare, and its hop keeps
64
- * `Authorization`, sets no proxy secret and leaves the service's answers untouched.
82
+ * `Authorization`, sets no proxy secret (IAM's session-owner route excepted, for attribution only) and leaves the
83
+ * service's answers untouched.
65
84
  */
66
85
  export interface InstallationProxyApp extends ProxyAppBase {
67
86
  installation: true
@@ -92,8 +111,8 @@ interface ProxyEndpointExtras {
92
111
  delegation: EndpointDelegation | null
93
112
  }
94
113
 
95
- /** An endpoint row as the proxy applies it: the rules without the schemas, plus the digest and the delegation. */
96
- export type ProxyEndpointRow =
114
+ /** A row a contract declares, as the proxy applies it: the rules without the schemas, plus the digest and the delegation. */
115
+ export type DeclaredProxyEndpointRow =
97
116
  | (
98
117
  & Pick<CredentialedEndpoint, 'id' | 'kind' | 'method' | 'path' | 'callers' | 'requirement' | 'admission' | 'crossOrigin' | 'response'>
99
118
  & ProxyEndpointExtras
@@ -109,6 +128,42 @@ export type ProxyEndpointRow =
109
128
  }
110
129
  )
111
130
 
131
+ /** An endpoint row of an application table: a declared row, or the ops row that only platform composition adds. */
132
+ export type ProxyEndpointRow = DeclaredProxyEndpointRow | OpsProxyEndpointRow
133
+
134
+ /**
135
+ * The canonical ops row (ADR-0069): Control's channel to an environment's object, which platform composition adds to an
136
+ * application's table for a framework release that serves it. The parser admits only `opsProxyRow()`, field for field.
137
+ */
138
+ export interface OpsProxyEndpointRow {
139
+ id: string
140
+ kind: 'protocol'
141
+ method: typeof OPS_METHOD
142
+ path: string
143
+ callers: []
144
+ requirement: null
145
+ admission: BodyAdmission
146
+ delegation: null
147
+ digest: string
148
+ }
149
+
150
+ /** The ops row's body limit: every ops request is a small JSON object. */
151
+ export const OPS_ROW_MAX_BYTES = 64 * 1024
152
+
153
+ /** The ops row, digested like every row; the provider composes it and the framework checks `X-Fabrika-Endpoint` against it. */
154
+ export function opsProxyRow(): OpsProxyEndpointRow {
155
+ const rules = {
156
+ kind: 'protocol',
157
+ method: OPS_METHOD,
158
+ path: OPS_ROW_PATH,
159
+ callers: [],
160
+ requirement: null,
161
+ admission: { contentTypes: [OPS_CONTENT_TYPE], maxBytes: OPS_ROW_MAX_BYTES },
162
+ delegation: null,
163
+ } satisfies Omit<OpsProxyEndpointRow, 'id' | 'digest'>
164
+ return { id: OPS_ROW_ID, ...rules, digest: requirementDigest({ ...rules, oauth: null }) }
165
+ }
166
+
112
167
  /** An installation row as the proxy applies it: the row with its digest and no delegation. */
113
168
  export type InstallationProxyEndpointRow = InstallationEndpointRow & { digest: string; delegation: null }
114
169
 
@@ -117,6 +172,11 @@ export type ManifestEndpointRow = ProxyEndpointRow | InstallationProxyEndpointRo
117
172
 
118
173
  export interface ProxyManifest {
119
174
  apps: ProxyApp[]
175
+ /**
176
+ * The installation's client logo for the pages the proxy answers with (ADR-0066). Absent, a page draws the fabrika
177
+ * mark. A producer sends it only to a proxy whose source parses it: an older parser refuses the key.
178
+ */
179
+ brand?: InstallationBrand
120
180
  }
121
181
 
122
182
  const HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/
@@ -126,6 +186,48 @@ export function isProxyHost(host: string): boolean {
126
186
  return host.length > 0 && host.length <= 253 && host.split('.').every((label) => label.length <= 63 && HOST_LABEL.test(label))
127
187
  }
128
188
 
189
+ const DEV_SANDBOX_ID_PREFIX = 'dev'
190
+ /** The contract's application id rule (`CONTRACT_APP_ID_PATTERN` of `@fabrika/app`), which this module cannot import. */
191
+ const DEV_SANDBOX_APP_ID = /^[a-z0-9][a-z0-9-]*$/
192
+ const DEV_SANDBOX_WORKSPACE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
193
+
194
+ export interface DevSandboxEntryId {
195
+ readonly appId: string
196
+ readonly workspaceId: string
197
+ }
198
+
199
+ /** The entry id of one workspace's dev sandbox, `dev:<appId>:<workspaceId>`. Throws on a part that would not parse back. */
200
+ export function devSandboxEntryId(appId: string, workspaceId: string): string {
201
+ const id = `${DEV_SANDBOX_ID_PREFIX}:${appId}:${workspaceId}`
202
+ if (parseDevSandboxEntryId(id) === null) throw new Error('a dev sandbox entry id needs a contract application id and a workspace UUID')
203
+ return id
204
+ }
205
+
206
+ /** The parts of `dev:<appId>:<workspaceId>`, or null for any other string. */
207
+ export function parseDevSandboxEntryId(id: string): DevSandboxEntryId | null {
208
+ const parts = id.split(':')
209
+ if (parts.length !== 3) return null
210
+ const [prefix = '', appId = '', workspaceId = ''] = parts
211
+ return prefix === DEV_SANDBOX_ID_PREFIX && DEV_SANDBOX_APP_ID.test(appId) && DEV_SANDBOX_WORKSPACE_ID.test(workspaceId)
212
+ ? { appId, workspaceId }
213
+ : null
214
+ }
215
+
216
+ /**
217
+ * A dev sandbox entry names its application's audience, and only it does: the id itself is no IAM app id. An `@` id is
218
+ * already its own audience, and a plain id is a platform audience.
219
+ */
220
+ function checkAudience(app: Pick<ContractProxyApp, 'id' | 'audience'>, ctx: z.RefinementCtx): void {
221
+ const sandbox = parseDevSandboxEntryId(app.id)
222
+ if (sandbox === null) {
223
+ if (app.audience !== undefined) ctx.addIssue({ code: 'custom', path: ['audience'], message: 'only a dev sandbox entry names an audience' })
224
+ return
225
+ }
226
+ if (app.audience === undefined || parseAppEnvironmentId(app.audience)?.app !== sandbox.appId) {
227
+ ctx.addIssue({ code: 'custom', path: ['audience'], message: "a dev sandbox entry's audience is its application's environment" })
228
+ }
229
+ }
230
+
129
231
  /** An id that holds `@` must be a whole `<app>@<env>`; a malformed one would mint for an app IAM never registered. */
130
232
  const proxyAppIdSchema = z.string().min(1).refine((id) => !id.includes(APP_ENVIRONMENT_SEPARATOR) || parseAppEnvironmentId(id) !== null)
131
233
 
@@ -173,6 +275,11 @@ const capabilitySchema = z.object({ action: nameSchema, access: capabilityFormSc
173
275
  const requirementSchema = z.discriminatedUnion('kind', [
174
276
  z.object({ kind: z.literal('member') }).strict(),
175
277
  z.object({ kind: z.literal('action'), action: nameSchema, access: accessFormSchema }).strict(),
278
+ z.object({
279
+ kind: z.literal('anyOf'),
280
+ actions: z.tuple([nameSchema, nameSchema]).rest(nameSchema).refine(isAnyOfList, `two to ${MAX_ANY_OF} distinct actions, sorted`),
281
+ access: z.object({ form: z.literal('app') }).strict(),
282
+ }).strict(),
176
283
  z.object({
177
284
  kind: z.literal('capabilities'),
178
285
  capabilities: z.record(nameSchema, capabilitySchema).refine((capabilities) => Object.keys(capabilities).length >= 2, 'at least two capabilities'),
@@ -189,7 +296,10 @@ const endpointRuleFields = {
189
296
  admission: admissionSchema.nullable(),
190
297
  digest: z.string().refine(isDigest),
191
298
  }
192
- /** One row of a contract app's endpoint table; it refuses a digest that does not describe the row's rules. */
299
+ /**
300
+ * One row a contract declares, of a contract app's endpoint table; it refuses a digest that does not describe the row's
301
+ * rules. It never admits the ops row, which only `contractProxyAppSchema` reads.
302
+ */
193
303
  export const proxyEndpointRowSchema = z.union([
194
304
  z.object({
195
305
  ...endpointRuleFields,
@@ -198,7 +308,7 @@ export const proxyEndpointRowSchema = z.union([
198
308
  requirement: requirementSchema,
199
309
  delegation: z.enum(['members', 'creates']).nullable(),
200
310
  crossOrigin: z.literal('environment').optional(),
201
- response: z.literal('file').optional(),
311
+ response: z.enum(['file', 'inline-file']).optional(),
202
312
  }).strict(),
203
313
  z.object({
204
314
  ...endpointRuleFields,
@@ -207,7 +317,7 @@ export const proxyEndpointRowSchema = z.union([
207
317
  requirement: z.null(),
208
318
  delegation: z.null(),
209
319
  crossOrigin: z.enum(['environment', 'any']).optional(),
210
- response: z.literal('file').optional(),
320
+ response: z.enum(['file', 'inline-file']).optional(),
211
321
  cache: z.union([z.literal('immutable'), z.object({ maxAgeSeconds: z.number().int().min(1).max(MAX_CACHE_AGE_SECONDS) }).strict()]).optional(),
212
322
  authorization: z.literal('forward').optional(),
213
323
  }).strict(),
@@ -237,13 +347,28 @@ export const proxyEndpointRowSchema = z.union([
237
347
  (row) => row.digest === requirementDigest(row),
238
348
  'endpoint digest does not match its rules',
239
349
  ) satisfies z.ZodType<
240
- ProxyEndpointRow,
350
+ DeclaredProxyEndpointRow,
241
351
  z.ZodTypeDef,
242
352
  unknown
243
353
  >
244
354
 
355
+ const OPS_ROW = opsProxyRow()
356
+
357
+ /** The ops row exactly as `opsProxyRow()` builds it: every field a literal, its digest included. */
358
+ const opsProxyEndpointRowSchema = z.object({
359
+ id: z.literal(OPS_ROW_ID),
360
+ kind: z.literal('protocol'),
361
+ method: z.literal(OPS_METHOD),
362
+ path: z.literal(OPS_ROW_PATH),
363
+ callers: z.tuple([]),
364
+ requirement: z.null(),
365
+ admission: z.object({ contentTypes: z.tuple([z.literal(OPS_CONTENT_TYPE)]), maxBytes: z.literal(OPS_ROW_MAX_BYTES) }).strict(),
366
+ delegation: z.null(),
367
+ digest: z.literal(OPS_ROW.digest),
368
+ }).strict() satisfies z.ZodType<OpsProxyEndpointRow, z.ZodTypeDef, unknown>
369
+
245
370
  /** Only an RPC procedure, a public procedure and a form open to another origin, and only the anonymous two to any (ADR-0022). */
246
- function crossOriginAllowed(kind: ProxyEndpointRow['kind'], form: CrossOriginForm | undefined): boolean {
371
+ function crossOriginAllowed(kind: DeclaredProxyEndpointRow['kind'], form: CrossOriginForm | undefined): boolean {
247
372
  return form === undefined || (CROSS_ORIGIN_KINDS.includes(kind) && (form !== 'any' || ANY_ORIGIN_KINDS.includes(kind)))
248
373
  }
249
374
 
@@ -275,14 +400,21 @@ const cspOriginsSchema = z.object({
275
400
  export const contractProxyAppSchema = z.object({
276
401
  ...proxyAppFields,
277
402
  scheme: proxyAppScheme,
278
- endpoints: z.array(proxyEndpointRowSchema),
403
+ endpoints: z.array(z.union([proxyEndpointRowSchema, opsProxyEndpointRowSchema])),
279
404
  reservedPrefixes: z.array(z.string()),
280
405
  snapshot: z.string().refine(isDigest),
281
406
  csp: cspOriginsSchema,
282
407
  operationsOrigin: z.string().refine((value) => isPolicyOrigin(value, ['https:', 'http:'])).optional(),
283
408
  crossOrigins: z.array(z.string().refine(isCrossOrigin)).nonempty().max(MAX_CROSS_ORIGINS).optional(),
409
+ audience: z.string().refine((value) => parseAppEnvironmentId(value) !== null).optional(),
410
+ upstreamHost: z.string().refine(isProxyHost).optional(),
284
411
  }).strict().superRefine((app, ctx) => {
412
+ checkAudience(app, ctx)
285
413
  checkCrossOrigins(app, ctx)
414
+ // Only the ops row lies under the ops prefix: another row there would be an application route at a platform path.
415
+ if (app.endpoints.some((row) => row.path.startsWith(OPS_PREFIX) && row.kind !== 'protocol')) {
416
+ ctx.addIssue({ code: 'custom', message: 'only the ops row serves the ops prefix' })
417
+ }
286
418
  checkEndpointTable(app, ctx)
287
419
  }) satisfies z.ZodType<ContractProxyApp, z.ZodTypeDef, unknown>
288
420
 
@@ -373,9 +505,14 @@ export const proxyAppSchema = z.union([contractProxyAppSchema, installationProxy
373
505
  * The manifest form of a compiled contract: every endpoint's rules with their digest and delegation, the reserved
374
506
  * prefixes, the contract digest and the named CSP origins. Producers call this; they never assemble rows by hand.
375
507
  * `digest` is the one the application's own release computes; Control passes it for an artifact it upcast from an
376
- * older release's (ADR-0062).
508
+ * older release's (ADR-0062). `ops` adds the ops row, which only platform composition asks for and the artifact never
509
+ * carries.
377
510
  */
378
- export function contractProxyTable(artifact: ContractArtifact, digest: string = contractDigest(artifact)): ContractProxyTable {
511
+ export function contractProxyTable(
512
+ artifact: ContractArtifact,
513
+ digest: string = contractDigest(artifact),
514
+ options: { readonly ops?: boolean } = {},
515
+ ): ContractProxyTable {
379
516
  return {
380
517
  endpoints: artifact.endpoints.map((row): ProxyEndpointRow => {
381
518
  const rules = {
@@ -400,13 +537,73 @@ export function contractProxyTable(artifact: ContractArtifact, digest: string =
400
537
  delegation: endpointDelegation(artifact, row),
401
538
  }
402
539
  return { ...credentialed, digest: requirementDigest(credentialed) }
403
- }),
540
+ }).concat(options.ops === true ? [opsProxyRow()] : []),
404
541
  reservedPrefixes: [...artifact.reservedPrefixes],
405
542
  snapshot: digest,
406
543
  csp: cspOrigins(artifact.csp),
407
544
  }
408
545
  }
409
546
 
547
+ /** Where and how a producer serves one contract application. */
548
+ export interface ContractEntryPlacement {
549
+ readonly id: string
550
+ readonly hosts: readonly string[]
551
+ readonly upstream: string
552
+ readonly scheme: 'http' | 'https'
553
+ /** The approved contract's table, from `contractProxyTable`. */
554
+ readonly table: ContractProxyTable
555
+ readonly operationsOrigin?: string
556
+ /** The environment's list from Control's registry; an empty one is omitted. */
557
+ readonly crossOrigins?: readonly string[]
558
+ /** A dev sandbox entry's `<app>@<env>`; see `ContractProxyApp.audience`. */
559
+ readonly audience?: string
560
+ readonly upstreamHost?: string
561
+ }
562
+
563
+ /**
564
+ * What the proxy of one older platform release parses of an application's manifest entry: a row, and the entry's CSP
565
+ * directives, each by that release's own parser (ADR-0062); and whether it serves the sign-out (ADR-0067 §5).
566
+ */
567
+ export interface OlderProxyReader {
568
+ readonly row: (row: ProxyEndpointRow) => boolean
569
+ readonly csp: (csp: CspOrigins) => boolean
570
+ readonly signsOut: boolean
571
+ }
572
+
573
+ /**
574
+ * The proxies of the older releases a pin may run whose parsers Control holds. A pin's release is not recorded, so what
575
+ * any of them reads is what the pin may read.
576
+ */
577
+ export type OlderProxyReaders = readonly [OlderProxyReader, ...OlderProxyReader[]]
578
+
579
+ /**
580
+ * A contract application's manifest entry: the one form every producer builds. Refused when the proxy's own parser
581
+ * would refuse it, naming the fields and never their values, because an origin with userinfo may carry a key.
582
+ */
583
+ export function contractProxyEntry(placement: ContractEntryPlacement): ContractProxyApp {
584
+ const { table, operationsOrigin, crossOrigins = [], audience, upstreamHost } = placement
585
+ const entry: ContractProxyApp = {
586
+ id: placement.id,
587
+ hosts: [...placement.hosts],
588
+ upstream: placement.upstream,
589
+ scheme: placement.scheme,
590
+ endpoints: table.endpoints,
591
+ reservedPrefixes: table.reservedPrefixes,
592
+ snapshot: table.snapshot,
593
+ csp: table.csp,
594
+ ...(operationsOrigin === undefined ? {} : { operationsOrigin }),
595
+ ...(crossOrigins.length === 0 ? {} : { crossOrigins: [...crossOrigins] }),
596
+ ...(audience === undefined ? {} : { audience }),
597
+ ...(upstreamHost === undefined ? {} : { upstreamHost }),
598
+ }
599
+ const parsed = contractProxyAppSchema.safeParse(entry)
600
+ if (!parsed.success) {
601
+ const fields = new Set(parsed.error.issues.map((issue) => issue.path.length === 0 ? issue.message : issue.path.join('.')))
602
+ throw new Error(`proxy entry \`${placement.id}\` is one the proxy manifest refuses (${[...fields].join('; ')})`)
603
+ }
604
+ return entry
605
+ }
606
+
410
607
  /** What a producer adds to an installation service's placement: the output of `serviceProxyTable`. */
411
608
  export type InstallationProxyTable = Pick<InstallationProxyApp, 'installation' | 'endpoints' | 'reservedPrefixes'>
412
609
 
@@ -440,6 +637,7 @@ export function findDuplicateProxyHost(apps: readonly Pick<ProxyApp, 'hosts'>[])
440
637
 
441
638
  export const proxyManifestSchema = z.object({
442
639
  apps: z.array(proxyAppSchema),
640
+ brand: installationBrandSchema.optional(),
443
641
  }).strict().superRefine(({ apps }, ctx) => {
444
642
  if (new Set(apps.map((app) => app.id)).size !== apps.length) ctx.addIssue({ code: 'custom', message: 'duplicate proxy app id' })
445
643
  if (findDuplicateProxyHost(apps) !== null) ctx.addIssue({ code: 'custom', message: 'duplicate proxy host' })