@fabrika/provider-cloudflare 0.0.26 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/provider.ts CHANGED
@@ -1,18 +1,26 @@
1
- import { createProvider, type ProviderDeploySession, type TypedProviderRun } from '@fabrika/provider-contract'
1
+ import { type DeployStepResult, type ProviderManagedEnvironment, runSteps } 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
- import { type CloudflareArtifact, cloudflareArtifactCodec, type CloudflareTarget, cloudflareTargetCodec } from './codec'
6
6
  import { type CloudflareCollaborators, defaultCloudflareCollaborators } from './collaborators'
7
- import { buildPlan, type CloudflareJobSpec, findMigratableDatabases } from './plan'
7
+ import { assertAuthoredGraph, buildPlan, type CloudflareStep, findMigratableDatabases } from './plan'
8
8
 
9
9
  const CANCELLED = 'deploy cancelled'
10
10
 
11
+ /** Every credential the platform hands the executor. The checkout's own build step must inherit none of them. */
12
+ const PLATFORM_CREDENTIAL_NAMES: readonly string[] = ['CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID', 'FABRIKA_IAM_PROVISIONING_KEY']
13
+
11
14
  const workerDir = (config: CloudflareAppConfig, cwd: string): string => resolve(cwd, config.pipeline?.workerDir ?? '.')
12
15
 
13
- const wranglerEnv = (target: CloudflareTarget): Record<string, string> => ({
14
- CLOUDFLARE_API_TOKEN: target.apiToken,
15
- CLOUDFLARE_ACCOUNT_ID: target.accountId,
16
+ /** The KV namespace oblaka keeps deploy state in. One definition, so the check and the call cannot drift. */
17
+ // An empty CLOUDFLARE_STATE_NAMESPACE means unset, never an empty oblaka state namespace.
18
+ const stateNamespace = (config: CloudflareAppConfig, run: CloudflareDeployRun): string =>
19
+ run.stateNamespace === undefined || run.stateNamespace === '' ? `${config.id}-state` : run.stateNamespace
20
+
21
+ const wranglerEnv = (credentials: CloudflareCredentials): Record<string, string> => ({
22
+ CLOUDFLARE_API_TOKEN: credentials.apiToken,
23
+ CLOUDFLARE_ACCOUNT_ID: credentials.accountId,
16
24
  })
17
25
 
18
26
  const commandError = (label: string, result: { exitCode: number; stdout: string; stderr: string }): Error => {
@@ -26,9 +34,7 @@ const assertRunning = (signal: AbortSignal): void => {
26
34
  }
27
35
  }
28
36
 
29
- type CloudflareRun = TypedProviderRun<CloudflareTarget, CloudflareArtifact>
30
-
31
- const withManagedEnvironment = (config: CloudflareAppConfig, authored: Worker, run: CloudflareRun): Worker => {
37
+ const withManagedEnvironment = (config: CloudflareAppConfig, authored: Worker, run: CloudflareDeployRun): Worker => {
32
38
  const managed = run.managedEnvironment
33
39
  const present: Record<string, string> = {}
34
40
  const declared = new Set(config.pipeline?.vars ?? [])
@@ -87,27 +93,29 @@ const migrationBinding = (binding: string): string => {
87
93
 
88
94
  interface StepEnv {
89
95
  readonly config: CloudflareAppConfig
90
- readonly run: CloudflareRun
96
+ readonly run: CloudflareDeployRun
97
+ readonly credentials: CloudflareCredentials
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
 
97
- const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> => {
98
- const { config, run, worker, dir, cf } = env
99
- const { target, signal, dryRun } = run
105
+ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
106
+ const { config, run, credentials, worker, dir, cf } = env
107
+ const { signal, dryRun } = run
100
108
 
101
109
  switch (spec.kind) {
102
110
  case 'build': {
103
111
  const build = config.pipeline?.build
104
112
  if (build === undefined) return
105
113
  if (dryRun) {
106
- run.events.log(` [dry-run] would run build: \`${build}\` in ${dir}`)
114
+ run.log(` [dry-run] would run build: \`${build}\` in ${dir}`)
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
  }
@@ -115,16 +123,16 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
115
123
  assertRunning(signal)
116
124
  const result = await cf.provision({
117
125
  definition: worker,
118
- accountId: target.accountId,
119
- apiToken: target.apiToken,
126
+ accountId: credentials.accountId,
127
+ apiToken: credentials.apiToken,
120
128
  env: run.env,
121
129
  cwd: dir,
122
- stateNamespace: target.stateNamespace ?? `${config.id}-state`,
130
+ stateNamespace: stateNamespace(config, run),
123
131
  dryRun,
124
132
  })
125
133
  env.generatedConfigs = result.wranglerConfigs
126
134
  const names = result.wranglerConfigs.map((item) => item.config.name ?? '(unnamed)').join(', ')
127
- run.events.log(dryRun ? ` [dry-run] provisioned (plan-only): ${names}` : ` provisioned: ${names}`)
135
+ run.log(dryRun ? ` [dry-run] provisioned (plan-only): ${names}` : ` provisioned: ${names}`)
128
136
  return
129
137
  }
130
138
  case 'migrate': {
@@ -134,7 +142,7 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
134
142
  const commandBinding = migrationBinding(database.binding)
135
143
  const migrationDir = databaseOwnerDir(worker, database.binding, dir)
136
144
  if (dryRun) {
137
- run.events.log(` [dry-run] would run: wrangler d1 migrations apply ${commandBinding} --remote in ${migrationDir}`)
145
+ run.log(` [dry-run] would run: wrangler d1 migrations apply ${commandBinding} --remote in ${migrationDir}`)
138
146
  return
139
147
  }
140
148
  assertRunning(signal)
@@ -142,7 +150,7 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
142
150
  command: 'wrangler',
143
151
  args: ['d1', 'migrations', 'apply', commandBinding, '--remote'],
144
152
  cwd: migrationDir,
145
- env: wranglerEnv(target),
153
+ env: wranglerEnv(credentials),
146
154
  signal,
147
155
  })
148
156
  if (result.exitCode !== 0) throw commandError(`wrangler d1 migrations apply ${commandBinding}`, result)
@@ -150,49 +158,48 @@ 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
- run.events.log(` [dry-run] would run: wrangler deploy in ${dir}`)
168
+ run.log(` [dry-run] would run: wrangler deploy in ${dir}`)
156
169
  return
157
170
  }
158
171
  assertRunning(signal)
159
- const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: dir, env: wranglerEnv(target), signal })
172
+ const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: dir, env: wranglerEnv(credentials), signal })
160
173
  if (result.exitCode !== 0) throw commandError('wrangler deploy', result)
161
174
  return
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
- run.events.log(` [dry-run] would run: wrangler deploy in ${generatedDir}`)
180
+ run.log(` [dry-run] would run: wrangler deploy in ${generatedDir}`)
167
181
  continue
168
182
  }
169
183
  assertRunning(signal)
170
- const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: generatedDir, env: wranglerEnv(target), signal })
184
+ const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: generatedDir, env: wranglerEnv(credentials), signal })
171
185
  if (result.exitCode !== 0) throw commandError('wrangler deploy', result)
172
186
  }
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.log(` [dry-run] would report the authz schema for \`${config.id}\` to the control plane`)
182
194
  if (returnOrigins !== undefined) {
183
- run.events.log(` [dry-run] would register return origins for \`${config.id}\`: ${returnOrigins.join(', ')}`)
195
+ run.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': {
@@ -201,7 +208,7 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
201
208
  const value = run.secrets[name]
202
209
  if (value === undefined) throw new Error(`sync-secrets: missing value for secret \`${name}\` (not in run.secrets)`)
203
210
  if (dryRun) {
204
- run.events.log(` [dry-run] would run: wrangler secret put ${name} (value piped from run.secrets)`)
211
+ run.log(` [dry-run] would run: wrangler secret put ${name} (value piped from run.secrets)`)
205
212
  continue
206
213
  }
207
214
  assertRunning(signal)
@@ -209,7 +216,7 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
209
216
  command: 'wrangler',
210
217
  args: ['secret', 'put', name],
211
218
  cwd: secretsDir,
212
- env: wranglerEnv(target),
219
+ env: wranglerEnv(credentials),
213
220
  stdin: value,
214
221
  signal,
215
222
  })
@@ -220,34 +227,72 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
220
227
  }
221
228
  }
222
229
 
223
- export const createCloudflareProvider = (cf: CloudflareCollaborators = defaultCloudflareCollaborators) =>
224
- createProvider({
225
- id: 'cloudflare',
226
- target: cloudflareTargetCodec,
227
- artifact: cloudflareArtifactCodec,
228
- open: async (run): Promise<ProviderDeploySession> => {
229
- const loaded = await cf.loadConfig(run.cwd, run.artifact.configPath)
230
- if (loaded.config.id !== run.appId) {
231
- throw new Error(`Cloudflare config declares app "${loaded.config.id}", expected "${run.appId}"`)
232
- }
233
- const worker = withManagedEnvironment(
234
- loaded.config,
235
- loaded.config.resources({ env: run.env, domain: run.domain }),
236
- run,
237
- )
238
- const dir = workerDir(loaded.config, loaded.cwd)
239
- const plan = buildPlan(loaded.config, { appId: run.appId, env: run.env, propustkaUrl: run.target.propustkaUrl }, worker)
240
- 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: [] }
242
- return {
243
- plan,
244
- execute: async (stepId): Promise<void> => {
245
- const spec = byId.get(stepId)
246
- if (spec === undefined) throw new Error(`cloudflare: no step \`${stepId}\` in this plan`)
247
- await runStep(spec, env)
248
- },
249
- }
250
- },
251
- })
230
+ type CloudflareCredentials = Pick<CloudflareDeployerOptions, 'accountId' | 'apiToken'>
252
231
 
253
- export const cloudflareProvider = createCloudflareProvider()
232
+ export interface CloudflareDeployerOptions {
233
+ readonly accountId: string
234
+ readonly apiToken: string
235
+ readonly collaborators?: CloudflareCollaborators
236
+ /**
237
+ * `refuse` (the default) rejects a config that names one of fabrika's own resources. Only the
238
+ * operator deploying fabrika itself passes `allow`; a checkout is never trusted with it.
239
+ */
240
+ readonly platformResources?: 'refuse' | 'allow'
241
+ }
242
+
243
+ export interface CloudflareDeployRun {
244
+ readonly appId: string
245
+ readonly env: string
246
+ readonly domain?: string
247
+ /** Every origin IAM may hand this app a session at; app-wide, because IAM's registry is keyed by app id. */
248
+ readonly returnOrigins?: readonly string[]
249
+ readonly cwd: string
250
+ readonly configPath: string
251
+ readonly stateNamespace?: string
252
+ readonly secrets: Readonly<Record<string, string>>
253
+ readonly vars: Readonly<Record<string, string>>
254
+ /** Platform-owned runtime configuration, separate from operator-managed application vars. */
255
+ readonly managedEnvironment: ProviderManagedEnvironment
256
+ readonly dryRun: boolean
257
+ readonly signal: AbortSignal
258
+ readonly log: (line: string) => void
259
+ }
260
+
261
+ export interface CloudflareDeployResult {
262
+ readonly appId: string
263
+ readonly env: string
264
+ readonly status: 'succeeded' | 'failed'
265
+ readonly steps: readonly DeployStepResult[]
266
+ }
267
+
268
+ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) => async (run: CloudflareDeployRun): Promise<CloudflareDeployResult> => {
269
+ const cf = options.collaborators ?? defaultCloudflareCollaborators
270
+ const loaded = await cf.loadConfig(run.cwd, run.configPath)
271
+ if (loaded.config.id !== run.appId) {
272
+ throw new Error(`Cloudflare config declares app "${loaded.config.id}", expected "${run.appId}"`)
273
+ }
274
+ const worker = withManagedEnvironment(
275
+ loaded.config,
276
+ loaded.config.resources({ env: run.env, domain: run.domain }),
277
+ run,
278
+ )
279
+ const platformResources = options.platformResources ?? 'refuse'
280
+ assertAuthoredGraph(worker, {
281
+ env: run.env,
282
+ ...(run.domain === undefined ? {} : { domain: run.domain }),
283
+ stateNamespace: stateNamespace(loaded.config, run),
284
+ platformResources,
285
+ })
286
+ const env: StepEnv = {
287
+ config: loaded.config,
288
+ run,
289
+ credentials: { accountId: options.accountId, apiToken: options.apiToken },
290
+ worker,
291
+ dir: workerDir(loaded.config, loaded.cwd),
292
+ cf,
293
+ platformResources,
294
+ generatedConfigs: [],
295
+ }
296
+ const result = await runSteps(buildPlan(loaded.config, worker), run, (step) => runStep(step, env))
297
+ return { appId: run.appId, env: run.env, ...result }
298
+ }
@@ -1,4 +1,3 @@
1
- import { parseProxyManifestJson, type ProxyApp, type ProxyManifest } from '@fabrika/proxy-contract'
2
1
  import type { IamGateway, ProxyLogger, VerifyService } from '@fabrika/proxy-core'
3
2
  import {
4
3
  CLIENT_ADDRESS_HEADER,
@@ -15,6 +14,7 @@ import {
15
14
  stripFabrikaCookies,
16
15
  UNTRUSTED_FORWARD_HEADERS,
17
16
  } from '@fabrika/proxy-core'
17
+ import { parseProxyManifestJson, type ProxyApp, type ProxyManifest } from '@fabrika/proxy-core/manifest'
18
18
 
19
19
  /**
20
20
  * Cloudflare's managed client address — this composition's answer to "who is the client".
package/src/proxy.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { AppGates } from '@fabrika/auth'
2
- import { encodeProxyManifestJson, type ProxyManifest } from '@fabrika/proxy-contract'
2
+ import { encodeProxyManifestJson, type ProxyManifest } from '@fabrika/proxy-core/manifest'
3
3
  import { ServiceReference, Worker } from 'oblaka-iac'
4
4
 
5
5
  export interface CloudflareProxyWorkerOptions {
@@ -0,0 +1,40 @@
1
+ import { z } from 'zod'
2
+
3
+ export const runnerStateSchema = z.enum(['pending', 'cloning', 'installing', 'deploying', 'succeeded', 'failed'])
4
+
5
+ /** The lifecycle a run moves through inside the transport container. */
6
+ export type RunnerState = z.infer<typeof runnerStateSchema>
7
+
8
+ /** The IAM schema the executor compiled from the checkout, as JSON text; the control plane parses, validates and applies it with its own key. */
9
+ export const runnerIamReconcileSchema = z.object({ app: z.string(), schemaJson: z.string() })
10
+
11
+ export type RunnerIamReconcile = z.infer<typeof runnerIamReconcileSchema>
12
+
13
+ /** What the executor leaves at `$FABRIKA_RUNNER_OUTCOME_FILE` for the runner to fold into its terminal status. */
14
+ export interface RunnerOutcomeFile {
15
+ readonly iamReconcile?: RunnerIamReconcile
16
+ }
17
+
18
+ export const RUNNER_OUTCOME_FILE_ENV = 'FABRIKA_RUNNER_OUTCOME_FILE'
19
+
20
+ /** The terminal and in-progress status polled from the container, and persisted by the runner Worker once terminal. */
21
+ export const runnerStatusSchema = z.object({
22
+ runId: z.string(),
23
+ state: runnerStateSchema,
24
+ exitCode: z.number().finite().optional(),
25
+ error: z.string().optional(),
26
+ artifactState: z.enum(['complete', 'incomplete', 'not_applicable']).optional(),
27
+ iamReconcile: runnerIamReconcileSchema.optional(),
28
+ /** A preview: nothing was deployed and nothing may be applied from it. */
29
+ dryRun: z.boolean().optional(),
30
+ startedAt: z.number().finite(),
31
+ finishedAt: z.number().finite().optional(),
32
+ })
33
+
34
+ export type RunnerStatus = z.infer<typeof runnerStatusSchema>
35
+
36
+ export const RUNNER_PORT = 8080
37
+ export const RUNNER_RUN_PATH = '/run'
38
+ export const RUNNER_LOGS_PATH = '/logs'
39
+ export const RUNNER_STATUS_PATH = '/status'
40
+ export const RUNNER_HEALTH_PATH = '/health'
package/src/schema.ts CHANGED
@@ -1,5 +1,7 @@
1
- import { reconcileSchema } from '@fabrika/auth'
1
+ import type { AppSchema } from '@fabrika/auth'
2
+ import { appSchemaSchema, reconcileSchema } from '@fabrika/auth'
2
3
  import type { SchemaReconciler } from '@fabrika/provider-contract'
4
+ import type { z } from 'zod'
3
5
 
4
6
  /** Default IAM schema reconciler shared by production Cloudflare sessions. */
5
7
  export const defaultReconcileSchema: SchemaReconciler = (input) =>
@@ -11,3 +13,34 @@ export const defaultReconcileSchema: SchemaReconciler = (input) =>
11
13
  adminKey: input.adminKey,
12
14
  signal: input.signal,
13
15
  })
16
+
17
+ /** Quote an untrusted fragment for an error message the run log will carry. */
18
+ const token = (value: string): string => `\`${value.slice(0, 80)}\``
19
+
20
+ /** A parsed vocabulary, or the reason the deploy is refused — the message names the offending field. */
21
+ export type AppSchemaParse = { readonly ok: true; readonly schema: AppSchema } | { readonly ok: false; readonly message: string }
22
+
23
+ const refusalMessage = (issues: readonly z.ZodIssue[]): string => {
24
+ // A wrong envelope is the more useful report than the first bad element inside it.
25
+ const issue = issues.find((candidate) => candidate.path.length === 1) ?? issues[0]
26
+ const [field, key] = issue?.path ?? []
27
+ if (field === 'roles') {
28
+ if (typeof key !== 'string') return 'roles must be an object (role_key -> def)'
29
+ if (key === '' || key === '__proto__') return `role ${token(key)} is not usable`
30
+ if (issue?.code === 'custom') return issue.message
31
+ return `role ${token(key)} needs a non-empty name and an array of non-empty permissions`
32
+ }
33
+ if (key === undefined) return 'scopes and actions must be arrays'
34
+ return field === 'scopes'
35
+ ? 'each scope needs a non-empty `type` and, when present, a non-empty `label`'
36
+ : 'each action needs a non-empty `action` and, when present, a non-empty `description`'
37
+ }
38
+
39
+ /**
40
+ * Narrow an untrusted authz vocabulary — it arrives as JSON text compiled inside the deploy container —
41
+ * to the `AppSchema` the reconcile sends IAM. IAM validates it again on the way in.
42
+ */
43
+ export const parseAppSchema = (value: unknown): AppSchemaParse => {
44
+ const parsed = appSchemaSchema.safeParse(value)
45
+ return parsed.success ? { ok: true, schema: parsed.data } : { ok: false, message: refusalMessage(parsed.error.issues) }
46
+ }