@fabrika/provider-cloudflare 0.2.0 → 0.3.2
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 +12 -8
- package/src/cli.ts +7 -8
- package/src/codec.ts +4 -57
- package/src/collaborators.ts +11 -6
- package/src/command.ts +16 -34
- package/src/control.ts +237 -119
- package/src/index.ts +5 -5
- package/src/installation/cloudflare.ts +158 -0
- package/src/installation/envfile.ts +180 -0
- package/src/installation/index.ts +2 -0
- package/src/installation/init-options.ts +326 -0
- package/src/installation/init.ts +559 -0
- package/src/installation/installation.ts +95 -0
- package/src/installation/scaffold.ts +101 -0
- package/src/installation/templates/README.md +72 -0
- package/src/installation/templates/fabrika.ref +1 -0
- package/src/installation/templates/gitignore +2 -0
- package/src/installation/templates/platform.yml +181 -0
- package/src/plan.ts +21 -31
- package/src/provider.ts +90 -70
- package/src/proxy-worker.ts +1 -1
- package/src/proxy.ts +1 -1
- package/src/runner-protocol.ts +40 -0
- package/src/schema.ts +21 -83
package/src/provider.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import {
|
|
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
4
|
import { assertLiteralAssets } from './assets'
|
|
5
5
|
import type { CloudflareAppConfig } from './authoring'
|
|
6
|
-
import { type CloudflareArtifact, cloudflareArtifactCodec, type CloudflareTarget, cloudflareTargetCodec } from './codec'
|
|
7
6
|
import { type CloudflareCollaborators, defaultCloudflareCollaborators } from './collaborators'
|
|
8
|
-
import { assertAuthoredGraph, buildPlan, type
|
|
7
|
+
import { assertAuthoredGraph, buildPlan, type CloudflareStep, findMigratableDatabases } from './plan'
|
|
9
8
|
|
|
10
9
|
const CANCELLED = 'deploy cancelled'
|
|
11
10
|
|
|
@@ -15,11 +14,13 @@ const PLATFORM_CREDENTIAL_NAMES: readonly string[] = ['CLOUDFLARE_API_TOKEN', 'C
|
|
|
15
14
|
const workerDir = (config: CloudflareAppConfig, cwd: string): string => resolve(cwd, config.pipeline?.workerDir ?? '.')
|
|
16
15
|
|
|
17
16
|
/** The KV namespace oblaka keeps deploy state in. One definition, so the check and the call cannot drift. */
|
|
18
|
-
|
|
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
|
|
19
20
|
|
|
20
|
-
const wranglerEnv = (
|
|
21
|
-
CLOUDFLARE_API_TOKEN:
|
|
22
|
-
CLOUDFLARE_ACCOUNT_ID:
|
|
21
|
+
const wranglerEnv = (credentials: CloudflareCredentials): Record<string, string> => ({
|
|
22
|
+
CLOUDFLARE_API_TOKEN: credentials.apiToken,
|
|
23
|
+
CLOUDFLARE_ACCOUNT_ID: credentials.accountId,
|
|
23
24
|
})
|
|
24
25
|
|
|
25
26
|
const commandError = (label: string, result: { exitCode: number; stdout: string; stderr: string }): Error => {
|
|
@@ -33,9 +34,7 @@ const assertRunning = (signal: AbortSignal): void => {
|
|
|
33
34
|
}
|
|
34
35
|
}
|
|
35
36
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const withManagedEnvironment = (config: CloudflareAppConfig, authored: Worker, run: CloudflareRun): Worker => {
|
|
37
|
+
const withManagedEnvironment = (config: CloudflareAppConfig, authored: Worker, run: CloudflareDeployRun): Worker => {
|
|
39
38
|
const managed = run.managedEnvironment
|
|
40
39
|
const present: Record<string, string> = {}
|
|
41
40
|
const declared = new Set(config.pipeline?.vars ?? [])
|
|
@@ -94,7 +93,8 @@ const migrationBinding = (binding: string): string => {
|
|
|
94
93
|
|
|
95
94
|
interface StepEnv {
|
|
96
95
|
readonly config: CloudflareAppConfig
|
|
97
|
-
readonly run:
|
|
96
|
+
readonly run: CloudflareDeployRun
|
|
97
|
+
readonly credentials: CloudflareCredentials
|
|
98
98
|
readonly worker: Worker
|
|
99
99
|
readonly dir: string
|
|
100
100
|
readonly cf: CloudflareCollaborators
|
|
@@ -102,16 +102,16 @@ interface StepEnv {
|
|
|
102
102
|
generatedConfigs: readonly GeneratedConfig[]
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
-
const runStep = async (spec:
|
|
106
|
-
const { config, run, worker, dir, cf } = env
|
|
107
|
-
const {
|
|
105
|
+
const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
|
|
106
|
+
const { config, run, credentials, worker, dir, cf } = env
|
|
107
|
+
const { signal, dryRun } = run
|
|
108
108
|
|
|
109
109
|
switch (spec.kind) {
|
|
110
110
|
case 'build': {
|
|
111
111
|
const build = config.pipeline?.build
|
|
112
112
|
if (build === undefined) return
|
|
113
113
|
if (dryRun) {
|
|
114
|
-
run.
|
|
114
|
+
run.log(` [dry-run] would run build: \`${build}\` in ${dir}`)
|
|
115
115
|
return
|
|
116
116
|
}
|
|
117
117
|
assertRunning(signal)
|
|
@@ -123,16 +123,16 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
|
|
|
123
123
|
assertRunning(signal)
|
|
124
124
|
const result = await cf.provision({
|
|
125
125
|
definition: worker,
|
|
126
|
-
accountId:
|
|
127
|
-
apiToken:
|
|
126
|
+
accountId: credentials.accountId,
|
|
127
|
+
apiToken: credentials.apiToken,
|
|
128
128
|
env: run.env,
|
|
129
129
|
cwd: dir,
|
|
130
|
-
stateNamespace: stateNamespace(config,
|
|
130
|
+
stateNamespace: stateNamespace(config, run),
|
|
131
131
|
dryRun,
|
|
132
132
|
})
|
|
133
133
|
env.generatedConfigs = result.wranglerConfigs
|
|
134
134
|
const names = result.wranglerConfigs.map((item) => item.config.name ?? '(unnamed)').join(', ')
|
|
135
|
-
run.
|
|
135
|
+
run.log(dryRun ? ` [dry-run] provisioned (plan-only): ${names}` : ` provisioned: ${names}`)
|
|
136
136
|
return
|
|
137
137
|
}
|
|
138
138
|
case 'migrate': {
|
|
@@ -142,7 +142,7 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
|
|
|
142
142
|
const commandBinding = migrationBinding(database.binding)
|
|
143
143
|
const migrationDir = databaseOwnerDir(worker, database.binding, dir)
|
|
144
144
|
if (dryRun) {
|
|
145
|
-
run.
|
|
145
|
+
run.log(` [dry-run] would run: wrangler d1 migrations apply ${commandBinding} --remote in ${migrationDir}`)
|
|
146
146
|
return
|
|
147
147
|
}
|
|
148
148
|
assertRunning(signal)
|
|
@@ -150,7 +150,7 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
|
|
|
150
150
|
command: 'wrangler',
|
|
151
151
|
args: ['d1', 'migrations', 'apply', commandBinding, '--remote'],
|
|
152
152
|
cwd: migrationDir,
|
|
153
|
-
env: wranglerEnv(
|
|
153
|
+
env: wranglerEnv(credentials),
|
|
154
154
|
signal,
|
|
155
155
|
})
|
|
156
156
|
if (result.exitCode !== 0) throw commandError(`wrangler d1 migrations apply ${commandBinding}`, result)
|
|
@@ -165,11 +165,11 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
|
|
|
165
165
|
if (configs.length === 0) {
|
|
166
166
|
await assertAssets(dir)
|
|
167
167
|
if (dryRun) {
|
|
168
|
-
run.
|
|
168
|
+
run.log(` [dry-run] would run: wrangler deploy in ${dir}`)
|
|
169
169
|
return
|
|
170
170
|
}
|
|
171
171
|
assertRunning(signal)
|
|
172
|
-
const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: dir, env: wranglerEnv(
|
|
172
|
+
const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: dir, env: wranglerEnv(credentials), signal })
|
|
173
173
|
if (result.exitCode !== 0) throw commandError('wrangler deploy', result)
|
|
174
174
|
return
|
|
175
175
|
}
|
|
@@ -177,11 +177,11 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
|
|
|
177
177
|
const generatedDir = dirname(resolve(dir, generated.path))
|
|
178
178
|
await assertAssets(generatedDir)
|
|
179
179
|
if (dryRun) {
|
|
180
|
-
run.
|
|
180
|
+
run.log(` [dry-run] would run: wrangler deploy in ${generatedDir}`)
|
|
181
181
|
continue
|
|
182
182
|
}
|
|
183
183
|
assertRunning(signal)
|
|
184
|
-
const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: generatedDir, env: wranglerEnv(
|
|
184
|
+
const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: generatedDir, env: wranglerEnv(credentials), signal })
|
|
185
185
|
if (result.exitCode !== 0) throw commandError('wrangler deploy', result)
|
|
186
186
|
}
|
|
187
187
|
return
|
|
@@ -190,9 +190,9 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
|
|
|
190
190
|
if (config.schema === undefined) return
|
|
191
191
|
const returnOrigins = run.returnOrigins !== undefined && run.returnOrigins.length > 0 ? run.returnOrigins : undefined
|
|
192
192
|
if (dryRun) {
|
|
193
|
-
run.
|
|
193
|
+
run.log(` [dry-run] would report the authz schema for \`${config.id}\` to the control plane`)
|
|
194
194
|
if (returnOrigins !== undefined) {
|
|
195
|
-
run.
|
|
195
|
+
run.log(` [dry-run] would register return origins for \`${config.id}\`: ${returnOrigins.join(', ')}`)
|
|
196
196
|
}
|
|
197
197
|
return
|
|
198
198
|
}
|
|
@@ -208,7 +208,7 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
|
|
|
208
208
|
const value = run.secrets[name]
|
|
209
209
|
if (value === undefined) throw new Error(`sync-secrets: missing value for secret \`${name}\` (not in run.secrets)`)
|
|
210
210
|
if (dryRun) {
|
|
211
|
-
run.
|
|
211
|
+
run.log(` [dry-run] would run: wrangler secret put ${name} (value piped from run.secrets)`)
|
|
212
212
|
continue
|
|
213
213
|
}
|
|
214
214
|
assertRunning(signal)
|
|
@@ -216,7 +216,7 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
|
|
|
216
216
|
command: 'wrangler',
|
|
217
217
|
args: ['secret', 'put', name],
|
|
218
218
|
cwd: secretsDir,
|
|
219
|
-
env: wranglerEnv(
|
|
219
|
+
env: wranglerEnv(credentials),
|
|
220
220
|
stdin: value,
|
|
221
221
|
signal,
|
|
222
222
|
})
|
|
@@ -227,7 +227,12 @@ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> =>
|
|
|
227
227
|
}
|
|
228
228
|
}
|
|
229
229
|
|
|
230
|
-
|
|
230
|
+
type CloudflareCredentials = Pick<CloudflareDeployerOptions, 'accountId' | 'apiToken'>
|
|
231
|
+
|
|
232
|
+
export interface CloudflareDeployerOptions {
|
|
233
|
+
readonly accountId: string
|
|
234
|
+
readonly apiToken: string
|
|
235
|
+
readonly collaborators?: CloudflareCollaborators
|
|
231
236
|
/**
|
|
232
237
|
* `refuse` (the default) rejects a config that names one of fabrika's own resources. Only the
|
|
233
238
|
* operator deploying fabrika itself passes `allow`; a checkout is never trusted with it.
|
|
@@ -235,44 +240,59 @@ export interface CloudflareProviderOptions {
|
|
|
235
240
|
readonly platformResources?: 'refuse' | 'allow'
|
|
236
241
|
}
|
|
237
242
|
|
|
238
|
-
export
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
})
|
|
263
|
-
const dir = workerDir(loaded.config, loaded.cwd)
|
|
264
|
-
const plan = buildPlan(loaded.config, { appId: run.appId, env: run.env }, worker)
|
|
265
|
-
const byId = new Map(plan.steps.map((step): [string, CloudflareJobSpec] => [step.id, step]))
|
|
266
|
-
const env: StepEnv = { config: loaded.config, run, worker, dir, cf, platformResources, generatedConfigs: [] }
|
|
267
|
-
return {
|
|
268
|
-
plan,
|
|
269
|
-
execute: async (stepId): Promise<void> => {
|
|
270
|
-
const spec = byId.get(stepId)
|
|
271
|
-
if (spec === undefined) throw new Error(`cloudflare: no step \`${stepId}\` in this plan`)
|
|
272
|
-
await runStep(spec, env)
|
|
273
|
-
},
|
|
274
|
-
}
|
|
275
|
-
},
|
|
276
|
-
})
|
|
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
|
+
}
|
|
277
267
|
|
|
278
|
-
export const
|
|
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
|
+
}
|
package/src/proxy-worker.ts
CHANGED
|
@@ -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-
|
|
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,7 +1,7 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import { reconcileSchema } from '@fabrika/auth'
|
|
3
|
-
import { isActionAllowed } from '@fabrika/auth-core'
|
|
1
|
+
import type { AppSchema } from '@fabrika/auth'
|
|
2
|
+
import { appSchemaSchema, reconcileSchema } from '@fabrika/auth'
|
|
4
3
|
import type { SchemaReconciler } from '@fabrika/provider-contract'
|
|
4
|
+
import type { z } from 'zod'
|
|
5
5
|
|
|
6
6
|
/** Default IAM schema reconciler shared by production Cloudflare sessions. */
|
|
7
7
|
export const defaultReconcileSchema: SchemaReconciler = (input) =>
|
|
@@ -14,95 +14,33 @@ export const defaultReconcileSchema: SchemaReconciler = (input) =>
|
|
|
14
14
|
signal: input.signal,
|
|
15
15
|
})
|
|
16
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
17
|
/** Quote an untrusted fragment for an error message the run log will carry. */
|
|
33
18
|
const token = (value: string): string => `\`${value.slice(0, 80)}\``
|
|
34
19
|
|
|
35
|
-
|
|
36
|
-
|
|
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
|
-
}
|
|
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 }
|
|
48
22
|
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
const
|
|
52
|
-
const
|
|
53
|
-
if (
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
if (
|
|
57
|
-
|
|
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`
|
|
58
32
|
}
|
|
59
|
-
|
|
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`'
|
|
60
37
|
}
|
|
61
38
|
|
|
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
39
|
/**
|
|
66
40
|
* Narrow an untrusted authz vocabulary — it arrives as JSON text compiled inside the deploy container —
|
|
67
|
-
* to the `AppSchema` the reconcile sends IAM
|
|
68
|
-
* name an action the same body declares. IAM validates it again on the way in.
|
|
41
|
+
* to the `AppSchema` the reconcile sends IAM. IAM validates it again on the way in.
|
|
69
42
|
*/
|
|
70
43
|
export const parseAppSchema = (value: unknown): AppSchemaParse => {
|
|
71
|
-
const
|
|
72
|
-
|
|
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 } }
|
|
44
|
+
const parsed = appSchemaSchema.safeParse(value)
|
|
45
|
+
return parsed.success ? { ok: true, schema: parsed.data } : { ok: false, message: refusalMessage(parsed.error.issues) }
|
|
108
46
|
}
|