@fabrika/provider-cloudflare 0.0.25 → 0.2.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/provider-cloudflare",
3
- "version": "0.0.25",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,11 +36,13 @@
36
36
  "test": "bun test"
37
37
  },
38
38
  "dependencies": {
39
- "@fabrika/auth": "^0.0.25",
40
- "@fabrika/engine": "^0.0.25",
41
- "@fabrika/proxy-core": "^0.0.25",
42
- "@fabrika/proxy-contract": "^0.0.25",
43
- "@fabrika/provider-contract": "^0.0.25",
39
+ "@fabrika/auth": "^0.2.0",
40
+ "@fabrika/auth-core": "^0.2.0",
41
+ "@fabrika/engine": "^0.2.0",
42
+ "@fabrika/proxy-core": "^0.2.0",
43
+ "@fabrika/proxy-contract": "^0.2.0",
44
+ "@fabrika/provider-contract": "^0.2.0",
45
+ "@fabrika/runner-contract": "^0.2.0",
44
46
  "oblaka-iac": "^0.0.18"
45
47
  }
46
48
  }
package/src/assets.ts ADDED
@@ -0,0 +1,87 @@
1
+ import type { Stats } from 'node:fs'
2
+ import { lstat, readdir } from 'node:fs/promises'
3
+ import { resolve } from 'node:path'
4
+ import { Worker } from 'oblaka-iac'
5
+
6
+ /** A ceiling on the walk, so a checkout cannot turn the check itself into the denial of service. */
7
+ const MAX_ASSET_ENTRIES = 50_000
8
+
9
+ /** A directory wrangler would refuse on its own; its error is better than one invented here. */
10
+ const lstatOrNull = async (path: string): Promise<Stats | null> => {
11
+ try {
12
+ return await lstat(path)
13
+ } catch (err) {
14
+ const code: unknown = err instanceof Error ? Reflect.get(err, 'code') : undefined
15
+ if (code === 'ENOENT' || code === 'ENOTDIR') return null
16
+ throw err
17
+ }
18
+ }
19
+
20
+ const graphWorkers = (root: Worker): readonly Worker[] => {
21
+ const workers = new Set<Worker>()
22
+ const visit = (worker: Worker): void => {
23
+ if (workers.has(worker)) return
24
+ workers.add(worker)
25
+ for (const value of Object.values(worker.options.bindings ?? {})) {
26
+ if (value instanceof Worker) visit(value)
27
+ }
28
+ }
29
+ visit(root)
30
+ return [...workers]
31
+ }
32
+
33
+ /** `assertBoundedAssets` has already bounded the value; this only needs to find it. */
34
+ const assetDirectory = (worker: Worker): string | null => {
35
+ const assets: unknown = worker.options.assets
36
+ if (typeof assets !== 'object' || assets === null) return null
37
+ const directory: unknown = Reflect.get(assets, 'directory')
38
+ return typeof directory === 'string' && directory !== '' ? directory : null
39
+ }
40
+
41
+ interface WalkBudget {
42
+ count: number
43
+ }
44
+
45
+ type Refuse = (detail: string) => Error
46
+
47
+ const walk = async (base: string, prefix: string, budget: WalkBudget, refuse: Refuse): Promise<void> => {
48
+ for (const name of await readdir(resolve(base, prefix))) {
49
+ budget.count += 1
50
+ if (budget.count > MAX_ASSET_ENTRIES) {
51
+ throw refuse(`holds more than ${MAX_ASSET_ENTRIES} entries and is refused rather than walked`)
52
+ }
53
+ const path = prefix === '' ? name : `${prefix}/${name}`
54
+ const stats = await lstat(resolve(base, path))
55
+ if (stats.isSymbolicLink()) {
56
+ throw refuse(`contains \`${path}\`, which is a symbolic link; wrangler follows it and would publish its target`)
57
+ }
58
+ if (stats.isDirectory()) {
59
+ await walk(base, path, budget, refuse)
60
+ } else if (!stats.isFile()) {
61
+ throw refuse(`contains \`${path}\`, which is neither a regular file nor a directory`)
62
+ }
63
+ }
64
+ }
65
+
66
+ /**
67
+ * wrangler `stat`s each asset rather than `lstat`ing it, so a committed symlink to `/proc/self/environ`
68
+ * (the deploy's own environment holds the account token) or to `.git/config` uploads publicly. Call this
69
+ * per `wrangler deploy` spawn, for the Worker whose config lives in `configDir`: the checkout's own build
70
+ * step runs between `open()` and the deploy, so that spawn is the only moment the tree is final.
71
+ */
72
+ export const assertLiteralAssets = async (root: Worker, rootDir: string, configDir: string): Promise<void> => {
73
+ for (const worker of graphWorkers(root)) {
74
+ if (resolve(rootDir, worker.options.dir) !== configDir) continue
75
+ const directory = assetDirectory(worker)
76
+ if (directory === null) continue
77
+ const base = resolve(configDir, directory)
78
+ const refuse = (detail: string): Error => new Error(`cloudflare: Worker \`${worker.options.name}\` assets directory \`${directory}\` ${detail}`)
79
+ const stats = await lstatOrNull(base)
80
+ if (stats === null) continue
81
+ if (stats.isSymbolicLink()) {
82
+ throw refuse('is a symbolic link; wrangler follows it and would publish its target')
83
+ }
84
+ if (!stats.isDirectory()) continue
85
+ await walk(base, '', { count: 0 }, refuse)
86
+ }
87
+ }
package/src/cli-args.ts CHANGED
@@ -5,6 +5,8 @@ export interface ParsedCloudflareArgs {
5
5
  readonly config: string
6
6
  readonly runnerConfig: string | undefined
7
7
  readonly workerConfig: string | undefined
8
+ /** The single-component form of `platform deploy|plan`: deploy exactly this one platform config. */
9
+ readonly componentConfig: string | undefined
8
10
  readonly managedVarNames: readonly string[]
9
11
  readonly dryRun: boolean
10
12
  readonly help: boolean
@@ -17,6 +19,7 @@ export const parseCloudflareArgs = (argv: readonly string[]): ParsedCloudflareAr
17
19
  let config = './fabrika.config.ts'
18
20
  let runnerConfig: string | undefined
19
21
  let workerConfig: string | undefined
22
+ let componentConfig: string | undefined
20
23
  const managedVarNames: string[] = []
21
24
  let dryRun = false
22
25
  let help = false
@@ -34,6 +37,8 @@ export const parseCloudflareArgs = (argv: readonly string[]): ParsedCloudflareAr
34
37
  runnerConfig = arg.slice('--runner-config='.length)
35
38
  } else if (arg.startsWith('--worker-config=')) {
36
39
  workerConfig = arg.slice('--worker-config='.length)
40
+ } else if (arg.startsWith('--component-config=')) {
41
+ componentConfig = arg.slice('--component-config='.length)
37
42
  } else if (arg.startsWith('--managed-var=')) {
38
43
  const name = arg.slice('--managed-var='.length)
39
44
  if (!/^[A-Z][A-Z0-9_]*$/.test(name)) {
@@ -49,7 +54,7 @@ export const parseCloudflareArgs = (argv: readonly string[]): ParsedCloudflareAr
49
54
  }
50
55
  }
51
56
 
52
- return { command, subcommand, env, config, runnerConfig, workerConfig, managedVarNames, dryRun, help }
57
+ return { command, subcommand, env, config, runnerConfig, workerConfig, componentConfig, managedVarNames, dryRun, help }
53
58
  }
54
59
 
55
60
  export interface PlatformComponent {
@@ -57,10 +62,23 @@ export interface PlatformComponent {
57
62
  readonly configPath: string
58
63
  }
59
64
 
60
- /** The executor must exist before the control plane binds to it. */
61
- export const platformComponents = (runnerConfig: string | undefined, workerConfig: string | undefined): readonly PlatformComponent[] => {
65
+ /** What `platformComponents` needs off a parsed command line. */
66
+ export type PlatformComponentSelection = Pick<ParsedCloudflareArgs, 'runnerConfig' | 'workerConfig' | 'componentConfig'>
67
+
68
+ /**
69
+ * One config (`--component-config`) or the executor-then-control pair, never mixed. Both run with
70
+ * `platformResources: 'allow'`, which is why the single form lives here and not on `app deploy`.
71
+ */
72
+ export const platformComponents = (selection: PlatformComponentSelection): readonly PlatformComponent[] => {
73
+ const { runnerConfig, workerConfig, componentConfig } = selection
74
+ if (componentConfig !== undefined && componentConfig !== '') {
75
+ if (runnerConfig !== undefined || workerConfig !== undefined) {
76
+ throw new Error('`--component-config` deploys one component and cannot be combined with --runner-config/--worker-config')
77
+ }
78
+ return [{ label: componentConfig, configPath: componentConfig }]
79
+ }
62
80
  if (runnerConfig === undefined || runnerConfig === '') {
63
- throw new Error('Missing --runner-config=<path> for `platform deploy`')
81
+ throw new Error('Missing --runner-config=<path> (or --component-config=<path>) for `platform deploy`')
64
82
  }
65
83
  if (workerConfig === undefined || workerConfig === '') {
66
84
  throw new Error('Missing --worker-config=<path> for `platform deploy`')
package/src/codec.ts CHANGED
@@ -1,12 +1,10 @@
1
1
  import type { JsonValue, ProviderCodec } from '@fabrika/provider-contract'
2
2
 
3
- /** Ephemeral credentials and handles used by one Cloudflare deploy. */
3
+ /** Ephemeral credentials and handles used by one Cloudflare deploy. IAM's key is never among them (ADR-0022). */
4
4
  export interface CloudflareTarget {
5
5
  readonly accountId: string
6
6
  readonly apiToken: string
7
7
  readonly stateNamespace?: string
8
- readonly propustkaUrl?: string
9
- readonly adminKey?: string
10
8
  }
11
9
 
12
10
  /** A checkout recipe. The Oblaka graph stays executable code in the referenced config module. */
@@ -53,8 +51,6 @@ export const cloudflareTargetCodec: ProviderCodec<CloudflareTarget> = {
53
51
  accountId: target.accountId,
54
52
  apiToken: target.apiToken,
55
53
  ...(target.stateNamespace === undefined ? {} : { stateNamespace: target.stateNamespace }),
56
- ...(target.propustkaUrl === undefined ? {} : { propustkaUrl: target.propustkaUrl }),
57
- ...(target.adminKey === undefined ? {} : { adminKey: target.adminKey }),
58
54
  }),
59
55
  decode: (payload) => ({
60
56
  accountId: stringProperty(payload, 'accountId'),
@@ -62,10 +58,6 @@ export const cloudflareTargetCodec: ProviderCodec<CloudflareTarget> = {
62
58
  ...(optionalStringProperty(payload, 'stateNamespace') === undefined
63
59
  ? {}
64
60
  : { stateNamespace: optionalStringProperty(payload, 'stateNamespace') }),
65
- ...(optionalStringProperty(payload, 'propustkaUrl') === undefined
66
- ? {}
67
- : { propustkaUrl: optionalStringProperty(payload, 'propustkaUrl') }),
68
- ...(optionalStringProperty(payload, 'adminKey') === undefined ? {} : { adminKey: optionalStringProperty(payload, 'adminKey') }),
69
61
  }),
70
62
  }
71
63
 
@@ -1,14 +1,17 @@
1
1
  import type { SchemaReconciler } from '@fabrika/provider-contract'
2
+ import { RUNNER_OUTCOME_FILE_ENV, type RunnerOutcomeFile } from '@fabrika/runner-contract'
3
+ import { writeFile } from 'node:fs/promises'
2
4
  import { resolve } from 'node:path'
3
5
  import { type Definition, deploy as oblakaDeploy, type DeployResult as OblakaDeployResult } from 'oblaka-iac'
4
6
  import { type CloudflareAppConfig, isCloudflareAppConfig } from './authoring'
5
- import { defaultReconcileSchema } from './schema'
6
7
 
7
8
  export interface CommandSpec {
8
9
  readonly command: string
9
10
  readonly args: string[]
10
11
  readonly cwd: string
11
12
  readonly env?: Record<string, string>
13
+ /** Names dropped from the INHERITED environment: a child that runs checkout code gets no platform credential. */
14
+ readonly omitEnv?: readonly string[]
12
15
  readonly stdin?: string
13
16
  readonly signal?: AbortSignal
14
17
  }
@@ -33,6 +36,9 @@ export interface ProvisionInput {
33
36
 
34
37
  export type OblakaProvisioner = (input: ProvisionInput) => Promise<OblakaDeployResult>
35
38
 
39
+ /** Hand the run's outcome back to the runner, which folds it into the terminal status the control plane reads. */
40
+ export type OutcomeWriter = (outcome: RunnerOutcomeFile) => Promise<void>
41
+
36
42
  export interface LoadedCloudflareConfig {
37
43
  readonly config: CloudflareAppConfig
38
44
  readonly cwd: string
@@ -44,7 +50,7 @@ export interface CloudflareCollaborators {
44
50
  readonly loadConfig: CloudflareConfigLoader
45
51
  readonly runCommand: CommandRunner
46
52
  readonly provision: OblakaProvisioner
47
- readonly reconcileSchema: SchemaReconciler
53
+ readonly writeOutcome: OutcomeWriter
48
54
  }
49
55
 
50
56
  const defaultLoadConfig: CloudflareConfigLoader = async (cwd, configPath) => {
@@ -56,10 +62,18 @@ const defaultLoadConfig: CloudflareConfigLoader = async (cwd, configPath) => {
56
62
  return { config: loaded.default, cwd: resolve(absolute, '..') }
57
63
  }
58
64
 
65
+ const childEnvironment = (spec: CommandSpec): Record<string, string | undefined> => {
66
+ const inherited: Record<string, string | undefined> = { ...process.env }
67
+ for (const name of spec.omitEnv ?? []) {
68
+ delete inherited[name]
69
+ }
70
+ return { ...inherited, ...spec.env }
71
+ }
72
+
59
73
  const defaultRunCommand: CommandRunner = async (spec) => {
60
74
  const proc = Bun.spawn([spec.command, ...spec.args], {
61
75
  cwd: spec.cwd,
62
- env: { ...process.env, ...spec.env },
76
+ env: childEnvironment(spec),
63
77
  stdin: spec.stdin === undefined ? 'inherit' : new TextEncoder().encode(spec.stdin),
64
78
  stdout: 'pipe',
65
79
  stderr: 'pipe',
@@ -94,11 +108,19 @@ const defaultProvision: OblakaProvisioner = (input) =>
94
108
  dryRun: input.dryRun,
95
109
  })
96
110
 
111
+ const defaultWriteOutcome: OutcomeWriter = async (outcome) => {
112
+ const path = process.env[RUNNER_OUTCOME_FILE_ENV]
113
+ if (path === undefined || path === '') {
114
+ throw new Error(`${RUNNER_OUTCOME_FILE_ENV} is not set: this run has nowhere to report its outcome`)
115
+ }
116
+ await writeFile(path, JSON.stringify(outcome), 'utf8')
117
+ }
118
+
97
119
  export const defaultCloudflareCollaborators: CloudflareCollaborators = {
98
120
  loadConfig: defaultLoadConfig,
99
121
  runCommand: defaultRunCommand,
100
122
  provision: defaultProvision,
101
- reconcileSchema: defaultReconcileSchema,
123
+ writeOutcome: defaultWriteOutcome,
102
124
  }
103
125
 
104
126
  export type { SchemaReconciler }
package/src/command.ts CHANGED
@@ -3,7 +3,8 @@ import type { ProviderDeployResult, ProviderRunEvents, RuntimeProviderRun } from
3
3
  import { resolve } from 'node:path'
4
4
  import { type CloudflareAppConfig, isCloudflareAppConfig } from './authoring'
5
5
  import { cloudflareArtifact } from './codec'
6
- import { cloudflareProvider } from './provider'
6
+ import { defaultCloudflareCollaborators } from './collaborators'
7
+ import { createCloudflareProvider } from './provider'
7
8
 
8
9
  const requiredEnvironmentValue = (name: string): string => {
9
10
  const value = environmentValue(name)
@@ -67,6 +68,8 @@ export interface CloudflareCommandDeployOptions {
67
68
  readonly dryRun?: boolean
68
69
  readonly stateNamespace?: string
69
70
  readonly managedVarNames?: readonly string[]
71
+ /** Defaults to `refuse`: only fabrika deploying its own components may name a platform resource. */
72
+ readonly platformResources?: 'refuse' | 'allow'
70
73
  readonly signal?: AbortSignal
71
74
  readonly log?: (line: string) => void
72
75
  }
@@ -80,9 +83,10 @@ export const deployCloudflareConfig = async (options: CloudflareCommandDeployOpt
80
83
  externalId: async () => {},
81
84
  checkpoint: async () => {},
82
85
  }
86
+ const provider = createCloudflareProvider(defaultCloudflareCollaborators, {
87
+ platformResources: options.platformResources ?? 'refuse',
88
+ })
83
89
  const domain = environmentValue('FABRIKA_CONTROL_DOMAIN')
84
- const iamUrl = environmentValue('FABRIKA_IAM_ISSUER')
85
- const iamProvisioningKey = environmentValue('FABRIKA_IAM_PROVISIONING_KEY')
86
90
  const returnOrigins = parseReturnOrigins(environmentValue('FABRIKA_IAM_RETURN_ORIGINS'))
87
91
  const run: RuntimeProviderRun = {
88
92
  appId: loaded.config.id,
@@ -96,14 +100,12 @@ export const deployCloudflareConfig = async (options: CloudflareCommandDeployOpt
96
100
  dryRun: options.dryRun ?? false,
97
101
  signal: options.signal ?? new AbortController().signal,
98
102
  events,
99
- target: cloudflareProvider.encodeTarget({
103
+ target: provider.encodeTarget({
100
104
  accountId: requiredEnvironmentValue('CLOUDFLARE_ACCOUNT_ID'),
101
105
  apiToken: requiredEnvironmentValue('CLOUDFLARE_API_TOKEN'),
102
106
  ...(options.stateNamespace === undefined ? {} : { stateNamespace: options.stateNamespace }),
103
- ...(iamUrl === undefined ? {} : { propustkaUrl: iamUrl }),
104
- ...(iamProvisioningKey === undefined ? {} : { adminKey: iamProvisioningKey }),
105
107
  }),
106
- artifact: cloudflareProvider.encodeArtifact(cloudflareArtifact(loaded.absolutePath)),
108
+ artifact: provider.encodeArtifact(cloudflareArtifact(loaded.absolutePath)),
107
109
  }
108
- return deploy(cloudflareProvider.runtime, run)
110
+ return deploy(provider.runtime, run)
109
111
  }
package/src/control.ts CHANGED
@@ -8,8 +8,14 @@ import type {
8
8
  ProviderRegistrationInput,
9
9
  ProviderSource,
10
10
  ProviderTerminalOutcome,
11
+ SchemaReconciler,
11
12
  } from '@fabrika/provider-contract'
13
+ import { isProxyHost } from '@fabrika/proxy-contract'
14
+ import type { RunnerIamReconcile } from '@fabrika/runner-contract'
12
15
  import { cloudflareArtifactCodec } from './codec'
16
+ // `./runner` is this module: keep every import here clear of `oblaka-iac`, which the runner packages
17
+ // cannot typecheck (they do not relax the two strict flags the raw TS needs).
18
+ import { defaultReconcileSchema, parseAppSchema } from './schema'
13
19
 
14
20
  /** Persisted Cloudflare target data. Installation credentials never enter this envelope. */
15
21
  export interface CloudflareStoredTarget {
@@ -57,11 +63,15 @@ export interface CloudflareRunnerJob {
57
63
  /** Every origin IAM may hand this app a session at, projected by the control plane (ADR-0021). */
58
64
  readonly returnOrigins?: readonly string[]
59
65
  readonly dryRun?: boolean
66
+ /**
67
+ * Shared secret the runner verifies before it touches D1 or the container; the binding alone proves
68
+ * nothing. Optional in the type because the wire boundary may omit it — the Worker refuses it there.
69
+ */
70
+ readonly runnerKey?: string
71
+ /** Exactly the Cloudflare account credential. IAM's admin key stays in the control plane (ADR-0022). */
60
72
  readonly credentials: {
61
73
  readonly CLOUDFLARE_ACCOUNT_ID: string
62
74
  readonly CLOUDFLARE_API_TOKEN: string
63
- readonly FABRIKA_IAM_ISSUER?: string
64
- readonly FABRIKA_IAM_PROVISIONING_KEY?: string
65
75
  }
66
76
  readonly secrets?: Readonly<Record<string, string>>
67
77
  readonly vars?: Readonly<Record<string, string>>
@@ -94,15 +104,40 @@ const isArtifactUpload = (value: unknown): boolean =>
94
104
  return typeof field === 'string' && field !== ''
95
105
  })
96
106
 
97
- /** Minimal structural validation for the Worker-to-runner JSON boundary. */
107
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
108
+ const ENV_NAME = /^[a-z0-9-]+$/
109
+
110
+ /** Whitespace or a control character in a value that becomes an argv element or a filesystem path. */
111
+ const hasUnsafeChars = (value: string): boolean =>
112
+ /\s/.test(value) || [...value].some((char) => {
113
+ const code = char.codePointAt(0) ?? 0
114
+ return code < 0x20 || code === 0x7f
115
+ })
116
+
117
+ const isHttpsUrl = (value: string): boolean => {
118
+ try {
119
+ return new URL(value).protocol === 'https:'
120
+ } catch {
121
+ return false
122
+ }
123
+ }
124
+
125
+ /** A path that stays inside the checkout: relative, and with no `..` segment to climb out of it. */
126
+ const isContainedPath = (value: string): boolean =>
127
+ value !== '' && !value.startsWith('/') && !hasUnsafeChars(value) && !value.split('/').includes('..')
128
+
129
+ /**
130
+ * Validate the Worker-to-runner JSON boundary by VALUE, not only by type: every field here becomes an
131
+ * argv element, a filesystem path or a hostname inside the deploy container.
132
+ */
98
133
  export const isCloudflareRunnerJob = (value: unknown): value is CloudflareRunnerJob => {
99
134
  if (
100
135
  typeof value !== 'object'
101
136
  || value === null
102
- || !('runId' in value && typeof value.runId === 'string')
103
- || !('repoUrl' in value && typeof value.repoUrl === 'string')
104
- || !('ref' in value && typeof value.ref === 'string')
105
- || !('env' in value && typeof value.env === 'string')
137
+ || !('runId' in value && typeof value.runId === 'string' && UUID.test(value.runId))
138
+ || !('repoUrl' in value && typeof value.repoUrl === 'string' && !hasUnsafeChars(value.repoUrl) && isHttpsUrl(value.repoUrl))
139
+ || !('ref' in value && typeof value.ref === 'string' && value.ref !== '' && !value.ref.startsWith('-') && !hasUnsafeChars(value.ref))
140
+ || !('env' in value && typeof value.env === 'string' && ENV_NAME.test(value.env))
106
141
  || !('credentials' in value && typeof value.credentials === 'object' && value.credentials !== null)
107
142
  ) {
108
143
  return false
@@ -114,18 +149,19 @@ export const isCloudflareRunnerJob = (value: unknown): value is CloudflareRunner
114
149
  && 'CLOUDFLARE_API_TOKEN' in credentials
115
150
  && typeof credentials.CLOUDFLARE_API_TOKEN === 'string'
116
151
  && credentials.CLOUDFLARE_API_TOKEN !== ''
117
- if (!requiredCredentials) {
152
+ // Exactly these two: a job carrying any other credential is refused rather than forwarded into the
153
+ // child environment, which is where the container's own code would read it.
154
+ if (!requiredCredentials || Object.keys(credentials).length !== 2) {
118
155
  return false
119
156
  }
120
157
  if (
121
- ('FABRIKA_IAM_ISSUER' in credentials && credentials.FABRIKA_IAM_ISSUER !== undefined && typeof credentials.FABRIKA_IAM_ISSUER !== 'string')
122
- || ('FABRIKA_IAM_PROVISIONING_KEY' in credentials
123
- && credentials.FABRIKA_IAM_PROVISIONING_KEY !== undefined
124
- && typeof credentials.FABRIKA_IAM_PROVISIONING_KEY !== 'string')
125
- || ('workerDir' in value && value.workerDir !== undefined && typeof value.workerDir !== 'string')
126
- || ('configPath' in value && value.configPath !== undefined && typeof value.configPath !== 'string')
127
- || ('stateNamespace' in value && value.stateNamespace !== undefined && typeof value.stateNamespace !== 'string')
128
- || ('domain' in value && value.domain !== undefined && typeof value.domain !== 'string')
158
+ // OPTIONAL: the runner Worker strips the key before the container hop, so a job that reaches the
159
+ // container carries none. Present means it must be usable; the Worker is what REQUIRES it.
160
+ ('runnerKey' in value && value.runnerKey !== undefined && (typeof value.runnerKey !== 'string' || value.runnerKey === ''))
161
+ || ('workerDir' in value && value.workerDir !== undefined && (typeof value.workerDir !== 'string' || !isContainedPath(value.workerDir)))
162
+ || ('configPath' in value && value.configPath !== undefined && (typeof value.configPath !== 'string' || !isContainedPath(value.configPath)))
163
+ || ('stateNamespace' in value && value.stateNamespace !== undefined && (typeof value.stateNamespace !== 'string' || value.stateNamespace === ''))
164
+ || ('domain' in value && value.domain !== undefined && (typeof value.domain !== 'string' || !isProxyHost(value.domain.toLowerCase())))
129
165
  || ('returnOrigins' in value && value.returnOrigins !== undefined && !isStringArray(value.returnOrigins))
130
166
  || ('dryRun' in value && value.dryRun !== undefined && typeof value.dryRun !== 'boolean')
131
167
  || ('secrets' in value && value.secrets !== undefined && !isStringRecord(value.secrets))
@@ -143,13 +179,19 @@ export interface ResolvedCloudflareSource {
143
179
  readonly ref: string
144
180
  }
145
181
 
182
+ /** A run's terminal outcome plus the IAM reconcile the executor compiled, if the plan reached that step. */
183
+ export type CloudflareRunOutcome = ProviderTerminalOutcome & { readonly iamReconcile?: RunnerIamReconcile }
184
+
146
185
  export interface CloudflareControlOptions {
147
186
  readonly accountId: string
148
187
  readonly apiToken: string
149
188
  readonly propustkaUrl?: string
150
189
  readonly propustkaProvisioningKey?: string
190
+ readonly runnerKey: string
191
+ /** Overridable for tests; production reconciles over HTTPS with the control plane's own admin key. */
192
+ readonly reconcileSchema?: SchemaReconciler
151
193
  resolveSource(source: ProviderSource, signal: AbortSignal): Promise<ResolvedCloudflareSource>
152
- startRun(job: CloudflareRunnerJob): Promise<ProviderTerminalOutcome>
194
+ startRun(job: CloudflareRunnerJob): Promise<CloudflareRunOutcome>
153
195
  cancelRun(runId: string): Promise<void>
154
196
  }
155
197
 
@@ -198,13 +240,10 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
198
240
  repoUrl: source.repoUrl,
199
241
  ref: source.ref,
200
242
  env: input.environment.env,
243
+ runnerKey: options.runnerKey,
201
244
  credentials: {
202
245
  CLOUDFLARE_ACCOUNT_ID: options.accountId,
203
246
  CLOUDFLARE_API_TOKEN: options.apiToken,
204
- ...(options.propustkaUrl === undefined ? {} : { FABRIKA_IAM_ISSUER: options.propustkaUrl }),
205
- ...(options.propustkaProvisioningKey === undefined
206
- ? {}
207
- : { FABRIKA_IAM_PROVISIONING_KEY: options.propustkaProvisioningKey }),
208
247
  },
209
248
  ...(input.app.source.workerDir === undefined ? {} : { workerDir: input.app.source.workerDir }),
210
249
  configPath: artifact.configPath,
@@ -219,13 +258,69 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
219
258
  }
220
259
  }
221
260
 
261
+ /** A megabyte of vocabulary is already absurd; beyond it the control plane refuses to parse at all. */
262
+ const MAX_SCHEMA_JSON_CHARS = 1024 * 1024
263
+
264
+ /**
265
+ * Apply the schema the executor compiled, with the control plane's own IAM key. The container runs the
266
+ * checkout's code and nothing validates its `/status` body on the way, so every field of the report is
267
+ * type-checked, bounded and parsed here before IAM hears about it.
268
+ */
269
+ const applyIamReconcile = async (
270
+ options: CloudflareControlOptions,
271
+ input: ProviderDeployInput,
272
+ reconcile: RunnerIamReconcile,
273
+ ): Promise<void> => {
274
+ // Typed, but not validated by any transport between the container and here.
275
+ if (typeof reconcile.app !== 'string' || typeof reconcile.schemaJson !== 'string') {
276
+ throw new Error('reported an authz schema whose app id or body is not a string')
277
+ }
278
+ if (reconcile.app !== input.app.id) {
279
+ throw new Error(`reported an authz schema for app "${reconcile.app}", expected "${input.app.id}"`)
280
+ }
281
+ if (reconcile.schemaJson.length > MAX_SCHEMA_JSON_CHARS) {
282
+ throw new Error(`reported an authz schema of ${reconcile.schemaJson.length} characters, over the ${MAX_SCHEMA_JSON_CHARS} limit`)
283
+ }
284
+ let parsed: unknown
285
+ try {
286
+ parsed = JSON.parse(reconcile.schemaJson)
287
+ } catch {
288
+ throw new Error('reported an authz schema that is not valid JSON')
289
+ }
290
+ const schema = parseAppSchema(parsed)
291
+ if (!schema.ok) {
292
+ throw new Error(`reported a malformed authz schema: ${schema.message}`)
293
+ }
294
+ if (options.propustkaUrl === undefined) return
295
+ // Return origins ride this call because `apps.setReturnOrigins` 404s for an app IAM has never heard
296
+ // of, and the schema reconcile is what registers it. Separate call, same moment.
297
+ const returnOrigins = input.returnOrigins !== undefined && input.returnOrigins.length > 0 ? input.returnOrigins : undefined
298
+ await (options.reconcileSchema ?? defaultReconcileSchema)({
299
+ url: options.propustkaUrl,
300
+ app: input.app.id,
301
+ schema: schema.schema,
302
+ ...(returnOrigins === undefined ? {} : { returnOrigins }),
303
+ ...(options.propustkaProvisioningKey === undefined ? {} : { adminKey: options.propustkaProvisioningKey }),
304
+ signal: input.signal,
305
+ })
306
+ }
307
+
222
308
  /** Build the Cloudflare control capability over its runner and source-resolution ports. */
223
309
  export const createCloudflareControlProvider = (options: CloudflareControlOptions): ControlProvider => ({
224
310
  id: 'cloudflare',
225
311
  normalizeRegistration,
226
312
  deploy: async (input) => {
227
313
  await input.events.externalId(input.runId)
228
- return options.startRun(await buildJob(options, input))
314
+ const outcome = await options.startRun(await buildJob(options, input))
315
+ const reconcile = outcome.iamReconcile
316
+ if (reconcile === undefined || input.dryRun) return outcome
317
+ try {
318
+ await applyIamReconcile(options, input, reconcile)
319
+ } catch (error) {
320
+ input.events.log(`reconcile-schema failed: ${error instanceof Error ? error.message : 'unknown error'}`)
321
+ return { state: 'failed', ...(outcome.artifactState === undefined ? {} : { artifactState: outcome.artifactState }) }
322
+ }
323
+ return outcome
229
324
  },
230
325
  cancel: (input) => options.cancelRun(input.runId),
231
326
  })
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ export {
12
12
  defaultCloudflareCollaborators,
13
13
  type LoadedCloudflareConfig,
14
14
  type OblakaProvisioner,
15
+ type OutcomeWriter,
15
16
  type ProvisionInput,
16
17
  type SchemaReconciler,
17
18
  } from './collaborators'
@@ -19,8 +20,9 @@ export { deployCloudflareConfig, loadCloudflareCommandConfig } from './command'
19
20
  export type { CloudflareCommandDeployOptions, LoadedCloudflareCommandConfig } from './command'
20
21
  export { cloudflareStoredTargetCodec, createCloudflareControlProvider, isCloudflareRunnerJob } from './control'
21
22
  export type { CloudflareControlOptions, CloudflareRunnerJob, CloudflareStoredTarget, ResolvedCloudflareSource } from './control'
22
- export { buildPlan, findMigratableDatabases } from './plan'
23
- export type { CloudflareJobSpec, CloudflarePlan, CloudflarePlanInput, CloudflareStepKind, MigratableDatabase } from './plan'
24
- export { cloudflareProvider, createCloudflareProvider } from './provider'
23
+ export { assertAuthoredGraph, buildPlan, findMigratableDatabases, PLATFORM_RESOURCE_NAMES } from './plan'
24
+ export type { AuthoredGraphLimits, CloudflareJobSpec, CloudflarePlan, CloudflarePlanInput, CloudflareStepKind, MigratableDatabase } from './plan'
25
+ export { cloudflareProvider, type CloudflareProviderOptions, createCloudflareProvider } from './provider'
25
26
  export { createCloudflareProxyWorker } from './proxy'
26
27
  export type { CloudflareProxyWorkerOptions } from './proxy'
28
+ export { type AppSchemaParse, parseAppSchema } from './schema'
package/src/plan.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { ProviderDeployPlan, ProviderJobSpec } from '@fabrika/provider-contract'
2
- import { Worker } from 'oblaka-iac'
2
+ import { isProxyHost } from '@fabrika/proxy-contract'
3
+ import { Container, D1Database, KVNamespace, Queue, R2Bucket, ServiceReference, Worker } from 'oblaka-iac'
3
4
  import type { CloudflareAppConfig } from './authoring'
4
5
 
5
6
  export type CloudflareStepKind = 'build' | 'provision-resources' | 'migrate' | 'deploy-worker' | 'reconcile-schema' | 'sync-secrets'
@@ -49,10 +50,221 @@ export const findMigratableDatabases = (worker: Worker): MigratableDatabase[] =>
49
50
  return databases
50
51
  }
51
52
 
53
+ /**
54
+ * Every resource name fabrika's own components declare (control, IAM, Operations, the runner and the
55
+ * installation's oblaka state). oblaka ADOPTS an existing `${env}-${name}`, so a checkout that names
56
+ * one would take over the platform's own Worker, database or bucket.
57
+ */
58
+ export const PLATFORM_RESOURCE_NAMES: ReadonlySet<string> = new Set([
59
+ 'vozka',
60
+ 'vozka-proxy',
61
+ 'vozka-runner',
62
+ 'vozka-deploy',
63
+ 'vozka-deploy-runner',
64
+ 'vozka-run-logs',
65
+ 'propustka',
66
+ 'propustka-worker',
67
+ 'propustka-state',
68
+ 'operations',
69
+ 'operations-proxy',
70
+ 'operations-payloads',
71
+ 'operations-ingest',
72
+ 'operations-ingest-dlq',
73
+ ])
74
+
75
+ const namedResource = (value: unknown): { readonly kind: string; readonly name: string } | null => {
76
+ if (value instanceof Worker) return { kind: 'Worker', name: value.options.name }
77
+ if (value instanceof D1Database) return { kind: 'D1 database', name: value.options.name }
78
+ if (value instanceof KVNamespace) return { kind: 'KV namespace', name: value.options.name }
79
+ if (value instanceof R2Bucket) return { kind: 'R2 bucket', name: value.options.name }
80
+ if (value instanceof Queue) return { kind: 'queue', name: value.options.name }
81
+ if (value instanceof Container) return { kind: 'container', name: value.options.name }
82
+ return null
83
+ }
84
+
85
+ /**
86
+ * A `ServiceReference` binds `${env}-${name}` without declaring it, so it never reaches `namedResource`
87
+ * — it is how an app would call the control plane or the runner directly. IAM is the one exception:
88
+ * every app binds `propustka-worker` (`proxy.ts`), which is the platform's intended front door.
89
+ */
90
+ const serviceReferenceTarget = (value: unknown): string | null => {
91
+ if (!(value instanceof ServiceReference)) return null
92
+ const target = Reflect.get(value, 'serviceName')
93
+ return typeof target === 'string' && target !== '' ? target : '(unreadable)'
94
+ }
95
+
96
+ const routeHostname = (route: unknown): string | null => {
97
+ const pattern = typeof route === 'string' ? route : typeof route === 'object' && route !== null ? Reflect.get(route, 'pattern') : undefined
98
+ if (typeof pattern !== 'string') return null
99
+ const host = pattern.split('/')[0]
100
+ return host === undefined ? null : host.toLowerCase()
101
+ }
102
+
103
+ const applicationChain = (root: Worker): ReadonlySet<Worker> => {
104
+ const chain = new Set<Worker>()
105
+ let current: unknown = root
106
+ while (current instanceof Worker) {
107
+ chain.add(current)
108
+ current = current.options.bindings?.['APP']
109
+ }
110
+ return chain
111
+ }
112
+
113
+ /**
114
+ * The only `Worker` options an app may set. oblaka's `ResourceProcessor` spreads everything but
115
+ * `dir`/`bindings`/`deleteDurableObjectsOnRemoval` verbatim into the generated wrangler config, so any
116
+ * other key — `services`, `durable_objects`, `r2_buckets`, `build` — binds or runs something the typed
117
+ * `bindings` walk never sees. Fail closed: a new wrangler key is refused until reviewed.
118
+ */
119
+ const APP_WORKER_OPTIONS: ReadonlySet<string> = new Set([
120
+ 'assets',
121
+ 'bindings',
122
+ 'compatibility_date',
123
+ 'compatibility_flags',
124
+ 'deleteDurableObjectsOnRemoval',
125
+ 'dir',
126
+ 'main',
127
+ 'name',
128
+ 'observability',
129
+ 'preview_urls',
130
+ 'routes',
131
+ 'triggers',
132
+ 'vars',
133
+ 'workers_dev',
134
+ // Every other key is deliberately absent: `build` runs a command, the rest bind a resource by raw name.
135
+ ])
136
+
137
+ /** Everything wrangler reads out of `assets`. `directory` is the only one that names a path. */
138
+ const APP_ASSETS_OPTIONS: ReadonlySet<string> = new Set(['binding', 'directory', 'html_handling', 'not_found_handling', 'run_worker_first'])
139
+
140
+ /**
141
+ * `assets.directory` is resolved against the generated `wrangler.jsonc`'s own directory and uploaded
142
+ * PUBLICLY: wrangler walks it recursively and ignores only `.assetsignore`/`_redirects`/`_headers`, so
143
+ * `.` on a root `workerDir` would publish the checkout's `.git/config` and the clone token in it.
144
+ */
145
+ const isContainedAssetDirectory = (value: unknown): value is string => {
146
+ if (typeof value !== 'string' || value.startsWith('/')) return false
147
+ const segments = value.split('/')
148
+ if (segments.includes('..') || segments.includes('.git')) return false
149
+ return segments.some((segment) => segment !== '' && segment !== '.')
150
+ }
151
+
152
+ /** `assets` is the one raw key that names a path, so it is bounded rather than refused outright. */
153
+ const assertBoundedAssets = (worker: Worker): void => {
154
+ const assets: unknown = worker.options.assets
155
+ if (assets === undefined) return
156
+ if (typeof assets !== 'object' || assets === null || Array.isArray(assets)) {
157
+ throw new Error(`cloudflare: Worker \`${worker.options.name}\` sets \`assets\` to something that is not an object`)
158
+ }
159
+ for (const key of Object.keys(assets)) {
160
+ if (!APP_ASSETS_OPTIONS.has(key)) {
161
+ throw new Error(`cloudflare: Worker \`${worker.options.name}\` sets \`assets.${key}\`, which an app may not configure`)
162
+ }
163
+ }
164
+ const directory: unknown = Reflect.get(assets, 'directory')
165
+ if (!isContainedAssetDirectory(directory)) {
166
+ throw new Error(
167
+ `cloudflare: Worker \`${worker.options.name}\` sets \`assets.directory\` to \`${
168
+ typeof directory === 'string' ? directory : '(not a string)'
169
+ }\`; it must be a relative path strictly inside the worker directory, with no \`..\` or \`.git\` segment`,
170
+ )
171
+ }
172
+ }
173
+
174
+ interface PlatformAdoption {
175
+ readonly adopted: string
176
+ readonly platform: string
177
+ }
178
+
179
+ /**
180
+ * Every oblaka resource kind adopts the remote name `${env}-${name}`, and an env name may contain `-`
181
+ * (`ENV_NAME` in `control.ts`), so an app in env `prod-propustka` naming `worker` lands on IAM's
182
+ * `prod-propustka-worker`. Bound the ADOPTED name, which holds wherever the env/name boundary falls.
183
+ */
184
+ const platformAdoption = (env: string, name: string): PlatformAdoption | null => {
185
+ const adopted = `${env}-${name}`
186
+ for (const platform of PLATFORM_RESOURCE_NAMES) {
187
+ if (adopted === platform || adopted.endsWith(`-${platform}`)) {
188
+ return { adopted, platform }
189
+ }
190
+ }
191
+ return null
192
+ }
193
+
194
+ export interface AuthoredGraphLimits {
195
+ /** The environment oblaka provisions into. Every remote name is `${env}-${name}`, so the bound is on that. */
196
+ readonly env: string
197
+ /** The one hostname this environment may route; a route on any other host belongs to another app. */
198
+ readonly domain?: string
199
+ /** The KV namespace oblaka keeps this deploy's state in; naming the platform's own would clobber it. */
200
+ readonly stateNamespace: string
201
+ /** Fabrika deploying its own components is the one caller allowed to name a platform resource. */
202
+ readonly platformResources: 'refuse' | 'allow'
203
+ }
204
+
205
+ /**
206
+ * Refuse an authored graph before any Cloudflare call: the config comes from the checkout and the
207
+ * deploy holds an account-wide token, so the names and routes it may claim are bounded here (ADR-0014).
208
+ */
209
+ export const assertAuthoredGraph = (root: Worker, limits: AuthoredGraphLimits): void => {
210
+ const deployable = applicationChain(root)
211
+ const refuse = limits.platformResources === 'refuse'
212
+ const assertAdoptable = (kind: string, name: string): void => {
213
+ const adoption = refuse ? platformAdoption(limits.env, name) : null
214
+ if (adoption !== null) {
215
+ throw new Error(
216
+ `cloudflare: ${kind} \`${name}\` becomes \`${adoption.adopted}\` on Cloudflare, which would take over the Fabrika platform resource \`${adoption.platform}\``,
217
+ )
218
+ }
219
+ }
220
+ const visit = (worker: Worker): void => {
221
+ for (const key of refuse ? Object.keys(worker.options) : []) {
222
+ if (!APP_WORKER_OPTIONS.has(key)) {
223
+ throw new Error(
224
+ `cloudflare: Worker \`${worker.options.name}\` sets \`${key}\`, which an app may not configure; declare resources in \`bindings\``,
225
+ )
226
+ }
227
+ }
228
+ if (refuse) {
229
+ assertBoundedAssets(worker)
230
+ }
231
+ for (const route of worker.options.routes ?? []) {
232
+ const host = routeHostname(route)
233
+ if (host === null || !isProxyHost(host) || host !== limits.domain?.toLowerCase()) {
234
+ throw new Error(`cloudflare: Worker \`${worker.options.name}\` routes \`${host ?? '(unreadable)'}\`, which is not this environment's domain`)
235
+ }
236
+ }
237
+ for (const value of Object.values(worker.options.bindings ?? {})) {
238
+ const resource = namedResource(value)
239
+ if (resource !== null) {
240
+ assertAdoptable(resource.kind, resource.name)
241
+ }
242
+ const service = serviceReferenceTarget(value)
243
+ if (service !== null && refuse && service !== 'propustka-worker') {
244
+ if (service === '(unreadable)') {
245
+ throw new Error('cloudflare: service binding to `(unreadable)` cannot be checked against the Fabrika platform services')
246
+ }
247
+ assertAdoptable('service binding to', service)
248
+ }
249
+ if (value instanceof Worker) {
250
+ if (!deployable.has(value)) {
251
+ throw new Error(`cloudflare: config declares Worker \`${value.options.name}\`; only the application Worker and its proxy are deployable`)
252
+ }
253
+ visit(value)
254
+ }
255
+ }
256
+ }
257
+ assertAdoptable('Worker', root.options.name)
258
+ // The state namespace is the ONE name oblaka uses verbatim (`KVStateStorage`), so no env prefix applies.
259
+ if (refuse && PLATFORM_RESOURCE_NAMES.has(limits.stateNamespace)) {
260
+ throw new Error(`cloudflare: state namespace \`${limits.stateNamespace}\` is a Fabrika platform resource and cannot be used by an app`)
261
+ }
262
+ visit(root)
263
+ }
264
+
52
265
  export interface CloudflarePlanInput {
53
266
  readonly appId: string
54
267
  readonly env: string
55
- readonly propustkaUrl?: string
56
268
  }
57
269
 
58
270
  export const buildPlan = (
@@ -80,8 +292,8 @@ export const buildPlan = (
80
292
 
81
293
  add({ id: 'deploy-worker', kind: 'deploy-worker', description: 'Deploy the Worker (`wrangler deploy`)' })
82
294
 
83
- if (config.schema !== undefined && input.propustkaUrl !== undefined) {
84
- add({ id: 'reconcile-schema', kind: 'reconcile-schema', description: 'Reconcile authz schema into IAM' })
295
+ if (config.schema !== undefined) {
296
+ add({ id: 'reconcile-schema', kind: 'reconcile-schema', description: 'Report the authz schema for the control plane to reconcile into IAM' })
85
297
  }
86
298
 
87
299
  if (config.pipeline?.secrets !== undefined && config.pipeline.secrets.length > 0) {
package/src/provider.ts CHANGED
@@ -1,15 +1,22 @@
1
1
  import { createProvider, type ProviderDeploySession, type TypedProviderRun } from '@fabrika/provider-contract'
2
2
  import { dirname, resolve } from 'node:path'
3
3
  import { type GeneratedConfig, Worker } from 'oblaka-iac'
4
+ import { assertLiteralAssets } from './assets'
4
5
  import type { CloudflareAppConfig } from './authoring'
5
6
  import { type CloudflareArtifact, cloudflareArtifactCodec, type CloudflareTarget, cloudflareTargetCodec } from './codec'
6
7
  import { type CloudflareCollaborators, defaultCloudflareCollaborators } from './collaborators'
7
- import { buildPlan, type CloudflareJobSpec, findMigratableDatabases } from './plan'
8
+ import { assertAuthoredGraph, buildPlan, type CloudflareJobSpec, findMigratableDatabases } from './plan'
8
9
 
9
10
  const CANCELLED = 'deploy cancelled'
10
11
 
12
+ /** Every credential the platform hands the executor. The checkout's own build step must inherit none of them. */
13
+ const PLATFORM_CREDENTIAL_NAMES: readonly string[] = ['CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID', 'FABRIKA_IAM_PROVISIONING_KEY']
14
+
11
15
  const workerDir = (config: CloudflareAppConfig, cwd: string): string => resolve(cwd, config.pipeline?.workerDir ?? '.')
12
16
 
17
+ /** The KV namespace oblaka keeps deploy state in. One definition, so the check and the call cannot drift. */
18
+ const stateNamespace = (config: CloudflareAppConfig, target: CloudflareTarget): string => target.stateNamespace ?? `${config.id}-state`
19
+
13
20
  const wranglerEnv = (target: CloudflareTarget): Record<string, string> => ({
14
21
  CLOUDFLARE_API_TOKEN: target.apiToken,
15
22
  CLOUDFLARE_ACCOUNT_ID: target.accountId,
@@ -91,6 +98,7 @@ interface StepEnv {
91
98
  readonly worker: Worker
92
99
  readonly dir: string
93
100
  readonly cf: CloudflareCollaborators
101
+ readonly platformResources: 'refuse' | 'allow'
94
102
  generatedConfigs: readonly GeneratedConfig[]
95
103
  }
96
104
 
@@ -107,7 +115,7 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
107
115
  return
108
116
  }
109
117
  assertRunning(signal)
110
- const result = await cf.runCommand({ command: 'sh', args: ['-c', build], cwd: dir, signal })
118
+ const result = await cf.runCommand({ command: 'sh', args: ['-c', build], cwd: dir, omitEnv: PLATFORM_CREDENTIAL_NAMES, signal })
111
119
  if (result.exitCode !== 0) throw commandError(`build (\`${build}\`)`, result)
112
120
  return
113
121
  }
@@ -119,7 +127,7 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
119
127
  apiToken: target.apiToken,
120
128
  env: run.env,
121
129
  cwd: dir,
122
- stateNamespace: target.stateNamespace ?? `${config.id}-state`,
130
+ stateNamespace: stateNamespace(config, target),
123
131
  dryRun,
124
132
  })
125
133
  env.generatedConfigs = result.wranglerConfigs
@@ -150,7 +158,12 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
150
158
  }
151
159
  case 'deploy-worker': {
152
160
  const configs = env.generatedConfigs
161
+ // The checkout's own build step has run by now, so this is the last moment the tree is still ours to check.
162
+ const assertAssets = async (configDir: string): Promise<void> => {
163
+ if (env.platformResources === 'refuse') await assertLiteralAssets(worker, dir, configDir)
164
+ }
153
165
  if (configs.length === 0) {
166
+ await assertAssets(dir)
154
167
  if (dryRun) {
155
168
  run.events.log(` [dry-run] would run: wrangler deploy in ${dir}`)
156
169
  return
@@ -162,6 +175,7 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
162
175
  }
163
176
  for (const generated of configs) {
164
177
  const generatedDir = dirname(resolve(dir, generated.path))
178
+ await assertAssets(generatedDir)
165
179
  if (dryRun) {
166
180
  run.events.log(` [dry-run] would run: wrangler deploy in ${generatedDir}`)
167
181
  continue
@@ -173,26 +187,19 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
173
187
  return
174
188
  }
175
189
  case 'reconcile-schema': {
176
- if (config.schema === undefined || target.propustkaUrl === undefined) return
177
- // Return origins ride this step because `apps.setReturnOrigins` 404s for an app IAM has never
178
- // heard of, and the schema reconcile is what registers it. Separate call, same moment.
190
+ if (config.schema === undefined) return
179
191
  const returnOrigins = run.returnOrigins !== undefined && run.returnOrigins.length > 0 ? run.returnOrigins : undefined
180
192
  if (dryRun) {
181
- run.events.log(` [dry-run] would reconcile schema for \`${config.id}\` against ${target.propustkaUrl}`)
193
+ run.events.log(` [dry-run] would report the authz schema for \`${config.id}\` to the control plane`)
182
194
  if (returnOrigins !== undefined) {
183
195
  run.events.log(` [dry-run] would register return origins for \`${config.id}\`: ${returnOrigins.join(', ')}`)
184
196
  }
185
197
  return
186
198
  }
187
199
  assertRunning(signal)
188
- await cf.reconcileSchema({
189
- url: target.propustkaUrl,
190
- app: config.id,
191
- schema: config.schema,
192
- ...(returnOrigins === undefined ? {} : { returnOrigins }),
193
- adminKey: target.adminKey,
194
- signal,
195
- })
200
+ // The reconcile itself happens in the CONTROL plane, which holds IAM's admin key; this
201
+ // container runs the checkout's own code and never sees it (ADR-0022).
202
+ await cf.writeOutcome({ iamReconcile: { app: config.id, schemaJson: JSON.stringify(config.schema) } })
196
203
  return
197
204
  }
198
205
  case 'sync-secrets': {
@@ -220,7 +227,18 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
220
227
  }
221
228
  }
222
229
 
223
- export const createCloudflareProvider = (cf: CloudflareCollaborators = defaultCloudflareCollaborators) =>
230
+ export interface CloudflareProviderOptions {
231
+ /**
232
+ * `refuse` (the default) rejects a config that names one of fabrika's own resources. Only the
233
+ * operator deploying fabrika itself passes `allow`; a checkout is never trusted with it.
234
+ */
235
+ readonly platformResources?: 'refuse' | 'allow'
236
+ }
237
+
238
+ export const createCloudflareProvider = (
239
+ cf: CloudflareCollaborators = defaultCloudflareCollaborators,
240
+ options: CloudflareProviderOptions = {},
241
+ ) =>
224
242
  createProvider({
225
243
  id: 'cloudflare',
226
244
  target: cloudflareTargetCodec,
@@ -235,10 +253,17 @@ export const createCloudflareProvider = (cf: CloudflareCollaborators = defaultCl
235
253
  loaded.config.resources({ env: run.env, domain: run.domain }),
236
254
  run,
237
255
  )
256
+ const platformResources = options.platformResources ?? 'refuse'
257
+ assertAuthoredGraph(worker, {
258
+ env: run.env,
259
+ ...(run.domain === undefined ? {} : { domain: run.domain }),
260
+ stateNamespace: stateNamespace(loaded.config, run.target),
261
+ platformResources,
262
+ })
238
263
  const dir = workerDir(loaded.config, loaded.cwd)
239
- const plan = buildPlan(loaded.config, { appId: run.appId, env: run.env, propustkaUrl: run.target.propustkaUrl }, worker)
264
+ const plan = buildPlan(loaded.config, { appId: run.appId, env: run.env }, worker)
240
265
  const byId = new Map(plan.steps.map((step): [string, CloudflareJobSpec] => [step.id, step]))
241
- const env: StepEnv = { config: loaded.config, run, worker, dir, cf, generatedConfigs: [] }
266
+ const env: StepEnv = { config: loaded.config, run, worker, dir, cf, platformResources, generatedConfigs: [] }
242
267
  return {
243
268
  plan,
244
269
  execute: async (stepId): Promise<void> => {
package/src/schema.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import type { AppActionDef, AppSchema, AppScopeDef, RoleDef } from '@fabrika/auth'
1
2
  import { reconcileSchema } from '@fabrika/auth'
3
+ import { isActionAllowed } from '@fabrika/auth-core'
2
4
  import type { SchemaReconciler } from '@fabrika/provider-contract'
3
5
 
4
6
  /** Default IAM schema reconciler shared by production Cloudflare sessions. */
@@ -11,3 +13,96 @@ export const defaultReconcileSchema: SchemaReconciler = (input) =>
11
13
  adminKey: input.adminKey,
12
14
  signal: input.signal,
13
15
  })
16
+
17
+ const prop = (value: unknown, key: string): unknown =>
18
+ typeof value === 'object' && value !== null && Object.hasOwn(value, key) ? Reflect.get(value, key) : undefined
19
+
20
+ const nonEmptyString = (value: unknown, key: string): string | undefined => {
21
+ const field = prop(value, key)
22
+ return typeof field === 'string' && field !== '' ? field : undefined
23
+ }
24
+
25
+ /** `null` distinguishes "absent" (ok) from "present but malformed" (rejects the whole schema). */
26
+ const optionalString = (value: unknown, key: string): string | null | undefined => {
27
+ const field = prop(value, key)
28
+ if (field === undefined) return undefined
29
+ return typeof field === 'string' && field !== '' ? field : null
30
+ }
31
+
32
+ /** Quote an untrusted fragment for an error message the run log will carry. */
33
+ const token = (value: string): string => `\`${value.slice(0, 80)}\``
34
+
35
+ const parseScope = (value: unknown): AppScopeDef | null => {
36
+ const type = nonEmptyString(value, 'type')
37
+ const label = optionalString(value, 'label')
38
+ if (type === undefined || label === null) return null
39
+ return label === undefined ? { type } : { type, label }
40
+ }
41
+
42
+ const parseAction = (value: unknown): AppActionDef | null => {
43
+ const action = nonEmptyString(value, 'action')
44
+ const description = optionalString(value, 'description')
45
+ if (action === undefined || description === null) return null
46
+ return description === undefined ? { action } : { action, description }
47
+ }
48
+
49
+ const parseRole = (value: unknown): RoleDef | null => {
50
+ const name = nonEmptyString(value, 'name')
51
+ const description = optionalString(value, 'description')
52
+ const permissions = prop(value, 'permissions')
53
+ if (name === undefined || description === null || !Array.isArray(permissions)) return null
54
+ const patterns: string[] = []
55
+ for (const entry of permissions) {
56
+ if (typeof entry !== 'string' || entry === '') return null
57
+ patterns.push(entry)
58
+ }
59
+ return description === undefined ? { name, permissions: patterns } : { name, description, permissions: patterns }
60
+ }
61
+
62
+ /** A parsed vocabulary, or the reason the deploy is refused — the message names the offending field. */
63
+ export type AppSchemaParse = { readonly ok: true; readonly schema: AppSchema } | { readonly ok: false; readonly message: string }
64
+
65
+ /**
66
+ * Narrow an untrusted authz vocabulary — it arrives as JSON text compiled inside the deploy container —
67
+ * to the `AppSchema` the reconcile sends IAM, applying IAM's own rule that every role permission must
68
+ * name an action the same body declares. IAM validates it again on the way in.
69
+ */
70
+ export const parseAppSchema = (value: unknown): AppSchemaParse => {
71
+ const rawScopes = prop(value, 'scopes')
72
+ const rawActions = prop(value, 'actions')
73
+ const rawRoles = prop(value, 'roles')
74
+ if (!Array.isArray(rawScopes) || !Array.isArray(rawActions)) {
75
+ return { ok: false, message: 'scopes and actions must be arrays' }
76
+ }
77
+ if (typeof rawRoles !== 'object' || rawRoles === null || Array.isArray(rawRoles)) {
78
+ return { ok: false, message: 'roles must be an object (role_key -> def)' }
79
+ }
80
+ const scopes: AppScopeDef[] = []
81
+ for (const raw of rawScopes) {
82
+ const scope = parseScope(raw)
83
+ if (scope === null) return { ok: false, message: 'each scope needs a string `type` and, when present, a string `label`' }
84
+ scopes.push(scope)
85
+ }
86
+ const actions: AppActionDef[] = []
87
+ const catalog: string[] = []
88
+ for (const raw of rawActions) {
89
+ const action = parseAction(raw)
90
+ if (action === null) return { ok: false, message: 'each action needs a string `action` and, when present, a string `description`' }
91
+ actions.push(action)
92
+ catalog.push(action.action)
93
+ }
94
+ const roles: Record<string, RoleDef> = {}
95
+ for (const [key, raw] of Object.entries(rawRoles)) {
96
+ // `roles[key] = …` would reach the prototype setter, so the key is refused rather than assigned.
97
+ if (key === '' || key === '__proto__') return { ok: false, message: `role key ${token(key)} is not usable` }
98
+ const role = parseRole(raw)
99
+ if (role === null) return { ok: false, message: `role ${token(key)} needs a string name and an array of non-empty permissions` }
100
+ for (const pattern of role.permissions) {
101
+ if (!isActionAllowed(pattern, catalog)) {
102
+ return { ok: false, message: `role ${token(key)} references unknown action: ${token(pattern)}` }
103
+ }
104
+ }
105
+ roles[key] = role
106
+ }
107
+ return { ok: true, schema: { scopes, actions, roles } }
108
+ }