@fabrika/provider-cloudflare 0.3.3 → 0.4.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/package.json +8 -6
- package/src/assets.ts +16 -38
- package/src/authoring.ts +1 -0
- package/src/bounds.ts +434 -0
- package/src/checkout.ts +48 -0
- package/src/collaborators.ts +29 -2
- package/src/command.ts +54 -0
- package/src/config-schema.ts +26 -0
- package/src/control.ts +91 -51
- package/src/index.ts +6 -3
- package/src/installation/installation.ts +1 -1
- package/src/plan.ts +1 -192
- package/src/provider.ts +195 -22
- package/src/proxy-worker.ts +99 -18
- package/src/proxy.ts +63 -19
- package/src/runner-protocol.ts +28 -0
package/src/command.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
|
+
import { type AppEnvironment, type ContractArtifact, parseAppEnvironmentId } from '@fabrika/auth-core'
|
|
2
|
+
import { readFile } from 'node:fs/promises'
|
|
3
|
+
import { z } from 'zod'
|
|
1
4
|
import type { CloudflareAppConfig } from './authoring'
|
|
2
5
|
import { loadCloudflareConfig } from './collaborators'
|
|
3
6
|
import { type CloudflareDeployResult, createCloudflareDeployer } from './provider'
|
|
7
|
+
import { APPROVED_ACCESS_FILE_ENV, INSTALLATION_APPS_ENV, type RunnerApprovedAccess, runnerApprovedAccessSchema } from './runner-protocol'
|
|
4
8
|
|
|
5
9
|
const requiredEnvironmentValue = (name: string): string => {
|
|
6
10
|
const value = environmentValue(name)
|
|
@@ -42,6 +46,51 @@ export const parseReturnOrigins = (raw: string | undefined): readonly string[] |
|
|
|
42
46
|
return origins.length === 0 ? undefined : origins
|
|
43
47
|
}
|
|
44
48
|
|
|
49
|
+
const installationAppsSchema = z.array(z.string())
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Decode `FABRIKA_INSTALLATION_APPS`, the Cloudflare deployments Control registered, as the runner writes it.
|
|
53
|
+
* Undefined when absent; anything malformed fails the deploy rather than dropping the refusal it feeds.
|
|
54
|
+
*/
|
|
55
|
+
export const parseInstallationApps = (raw: string | undefined): readonly AppEnvironment[] | undefined => {
|
|
56
|
+
if (raw === undefined || raw === '') return undefined
|
|
57
|
+
let decoded: unknown
|
|
58
|
+
try {
|
|
59
|
+
decoded = JSON.parse(raw)
|
|
60
|
+
} catch {
|
|
61
|
+
throw new Error(`${INSTALLATION_APPS_ENV} is not a JSON array`)
|
|
62
|
+
}
|
|
63
|
+
const ids = installationAppsSchema.safeParse(decoded)
|
|
64
|
+
if (!ids.success) throw new Error(`${INSTALLATION_APPS_ENV} is not a JSON array of strings`)
|
|
65
|
+
return ids.data.map((id) => {
|
|
66
|
+
const deployment = parseAppEnvironmentId(id)
|
|
67
|
+
if (deployment === null) throw new Error(`${INSTALLATION_APPS_ENV} holds \`${id.slice(0, 80)}\`, which is not \`<app>@<env>\``)
|
|
68
|
+
return deployment
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Read the access Control approved for this run from the file at `FABRIKA_APPROVED_ACCESS_FILE`, as the runner
|
|
74
|
+
* writes it. Undefined when no runner set it (a local deploy); a file that is unreadable or malformed fails the deploy
|
|
75
|
+
* rather than falling back to the checkout.
|
|
76
|
+
*/
|
|
77
|
+
export const readApprovedAccess = async (path: string | undefined): Promise<RunnerApprovedAccess | undefined> => {
|
|
78
|
+
if (path === undefined || path === '') return undefined
|
|
79
|
+
let decoded: unknown
|
|
80
|
+
try {
|
|
81
|
+
decoded = JSON.parse(await readFile(path, 'utf8'))
|
|
82
|
+
} catch {
|
|
83
|
+
throw new Error(`${APPROVED_ACCESS_FILE_ENV} does not name a readable JSON file`)
|
|
84
|
+
}
|
|
85
|
+
const access = runnerApprovedAccessSchema.safeParse(decoded)
|
|
86
|
+
if (!access.success) throw new Error(`${APPROVED_ACCESS_FILE_ENV} does not hold the access Control approved`)
|
|
87
|
+
return access.data
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The approved access as the deployer takes it: the contract Control read at the commit. */
|
|
91
|
+
const approvedRun = (access: RunnerApprovedAccess | undefined): { readonly contract?: ContractArtifact } =>
|
|
92
|
+
access === undefined ? {} : { contract: access.contract }
|
|
93
|
+
|
|
45
94
|
export interface LoadedCloudflareCommandConfig {
|
|
46
95
|
readonly config: CloudflareAppConfig
|
|
47
96
|
readonly absolutePath: string
|
|
@@ -67,6 +116,8 @@ export interface CloudflareCommandDeployOptions {
|
|
|
67
116
|
/** Deploy one config with the account credentials, declared secrets and vars read from the environment. */
|
|
68
117
|
export const deployCloudflareConfig = async (options: CloudflareCommandDeployOptions): Promise<CloudflareDeployResult> => {
|
|
69
118
|
const cwd = options.cwd ?? process.cwd()
|
|
119
|
+
// Before the config runs: loading it executes the checkout's code.
|
|
120
|
+
const approved = approvedRun(await readApprovedAccess(environmentValue(APPROVED_ACCESS_FILE_ENV)))
|
|
70
121
|
const loaded = await loadCloudflareCommandConfig(options.configPath ?? './fabrika.config.ts', cwd)
|
|
71
122
|
const deploy = createCloudflareDeployer({
|
|
72
123
|
accountId: requiredEnvironmentValue('CLOUDFLARE_ACCOUNT_ID'),
|
|
@@ -75,11 +126,14 @@ export const deployCloudflareConfig = async (options: CloudflareCommandDeployOpt
|
|
|
75
126
|
})
|
|
76
127
|
const domain = environmentValue('FABRIKA_CONTROL_DOMAIN')
|
|
77
128
|
const returnOrigins = parseReturnOrigins(environmentValue('FABRIKA_IAM_RETURN_ORIGINS'))
|
|
129
|
+
const installationApps = parseInstallationApps(environmentValue(INSTALLATION_APPS_ENV))
|
|
78
130
|
return deploy({
|
|
79
131
|
appId: loaded.config.id,
|
|
80
132
|
env: options.env,
|
|
81
133
|
...(domain === undefined ? {} : { domain }),
|
|
82
134
|
...(returnOrigins === undefined ? {} : { returnOrigins }),
|
|
135
|
+
...(installationApps === undefined ? {} : { installationApps }),
|
|
136
|
+
...approved,
|
|
83
137
|
cwd: loaded.cwd,
|
|
84
138
|
configPath: loaded.absolutePath,
|
|
85
139
|
...(options.stateNamespace === undefined ? {} : { stateNamespace: options.stateNamespace }),
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// The IAM schema a Cloudflare config declares, read once before the checkout's `resources()` runs again. Worker-safe.
|
|
2
|
+
|
|
3
|
+
import { appSchemaSchema } from '@fabrika/auth'
|
|
4
|
+
import type { AppSchema } from '@fabrika/auth-core'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A config's IAM schema, parsed and deep-frozen. A config that still declares `gates` is refused: an application is
|
|
8
|
+
* protected by the endpoint table of its `fabrika.contract.ts`, and the platform's own services by theirs.
|
|
9
|
+
*/
|
|
10
|
+
export const configSchema = (config: { readonly gates?: unknown; readonly schema?: unknown }): AppSchema | null => {
|
|
11
|
+
if (config.gates !== undefined) {
|
|
12
|
+
throw new Error('cloudflare: the config declares `gates`, which no deployment reads any more; protect the application with `fabrika.contract.ts`')
|
|
13
|
+
}
|
|
14
|
+
if (config.schema === undefined) return null
|
|
15
|
+
const parsed = appSchemaSchema.safeParse(config.schema)
|
|
16
|
+
if (!parsed.success) throw new Error("cloudflare: the config's IAM `schema` is malformed")
|
|
17
|
+
return deepFreeze(parsed.data)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function deepFreeze<T>(value: T): T {
|
|
21
|
+
if (typeof value === 'object' && value !== null && !Object.isFrozen(value)) {
|
|
22
|
+
Object.freeze(value)
|
|
23
|
+
for (const child of Object.values(value)) deepFreeze(child)
|
|
24
|
+
}
|
|
25
|
+
return value
|
|
26
|
+
}
|
package/src/control.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { ReconcileSchemaError } from '@fabrika/auth'
|
|
2
|
+
import { type AppEnvironment, appEnvironmentId, type AppSchema, isWorkloadKeyVariable, parseAppEnvironmentId } from '@fabrika/auth-core'
|
|
2
3
|
import type {
|
|
3
4
|
ControlProvider,
|
|
4
5
|
JsonValue,
|
|
6
|
+
ProviderApprovedAccess,
|
|
5
7
|
ProviderCodec,
|
|
6
8
|
ProviderDeployInput,
|
|
7
9
|
ProviderEnvelope,
|
|
10
|
+
ProviderEnvironment,
|
|
8
11
|
ProviderRegistration,
|
|
9
12
|
ProviderRegistrationInput,
|
|
10
13
|
ProviderSource,
|
|
@@ -18,10 +21,10 @@ import { abortableWait, decodeEnvelope, isLeaseLoss, ProviderInvocationAbort } f
|
|
|
18
21
|
import { isProxyHost } from '@fabrika/proxy-core/manifest'
|
|
19
22
|
import { z } from 'zod'
|
|
20
23
|
import { cloudflareArtifactCodec } from './codec'
|
|
21
|
-
import { type
|
|
24
|
+
import { type RunnerApprovedAccess, runnerApprovedAccessSchema, type RunnerIamReconcile } from './runner-protocol'
|
|
22
25
|
// `./runner` is this module: keep every import here clear of `oblaka-iac`, which the runner packages
|
|
23
26
|
// cannot typecheck (they do not relax the two strict flags the raw TS needs).
|
|
24
|
-
import { defaultReconcileSchema
|
|
27
|
+
import { defaultReconcileSchema } from './schema'
|
|
25
28
|
|
|
26
29
|
export * from './runner-protocol'
|
|
27
30
|
|
|
@@ -58,6 +61,10 @@ export interface CloudflareRunnerJob {
|
|
|
58
61
|
readonly domain?: string
|
|
59
62
|
/** Every origin IAM may hand this app a session at, projected by the control plane (ADR-0022). */
|
|
60
63
|
readonly returnOrigins?: readonly string[]
|
|
64
|
+
/** `<app>@<env>` of every Cloudflare deployment in Control's registry; the deploy refuses another application's names. */
|
|
65
|
+
readonly installationApps?: readonly string[]
|
|
66
|
+
/** What the deployed proxy enforces and the application starts as; every run but a dry one carries it. */
|
|
67
|
+
readonly approvedAccess?: RunnerApprovedAccess
|
|
61
68
|
readonly dryRun?: boolean
|
|
62
69
|
/**
|
|
63
70
|
* Shared secret the runner verifies before it touches D1 or the container; the binding alone proves
|
|
@@ -103,6 +110,19 @@ const isHttpsUrl = (value: string): boolean => {
|
|
|
103
110
|
}
|
|
104
111
|
}
|
|
105
112
|
|
|
113
|
+
/**
|
|
114
|
+
* The checkout-relative directory a relative `path` names, as the runner resolves it: `''` for the checkout itself
|
|
115
|
+
* (`.`, `./` and no path), empty and `.` segments dropped, or null for an absolute path or one with a `..` segment.
|
|
116
|
+
* The runner executes from this directory and Control reads the run's snapshot there, so both normalize with this.
|
|
117
|
+
*/
|
|
118
|
+
export const checkoutRelativeDirectory = (path: string | undefined): string | null => {
|
|
119
|
+
if (path === undefined) return ''
|
|
120
|
+
if (path.startsWith('/')) return null
|
|
121
|
+
const segments = path.split('/')
|
|
122
|
+
if (segments.includes('..')) return null
|
|
123
|
+
return segments.filter((segment) => segment !== '' && segment !== '.').join('/')
|
|
124
|
+
}
|
|
125
|
+
|
|
106
126
|
/** A path that stays inside the checkout: relative, and with no `..` segment to climb out of it. */
|
|
107
127
|
const isContainedPath = (value: string): boolean =>
|
|
108
128
|
value !== '' && !value.startsWith('/') && !hasUnsafeChars(value) && !value.split('/').includes('..')
|
|
@@ -129,6 +149,8 @@ export const cloudflareRunnerJobSchema = z.object({
|
|
|
129
149
|
stateNamespace: z.string().min(1).optional(),
|
|
130
150
|
domain: z.string().refine((value) => isProxyHost(value.toLowerCase())).optional(),
|
|
131
151
|
returnOrigins: z.array(z.string().min(1)).optional(),
|
|
152
|
+
installationApps: z.array(z.string().refine((id) => !hasUnsafeChars(id) && parseAppEnvironmentId(id) !== null)).optional(),
|
|
153
|
+
approvedAccess: runnerApprovedAccessSchema.optional(),
|
|
132
154
|
dryRun: z.boolean().optional(),
|
|
133
155
|
secrets: stringRecordSchema.optional(),
|
|
134
156
|
vars: stringRecordSchema.optional(),
|
|
@@ -143,13 +165,17 @@ export const cloudflareRunnerJobSchema = z.object({
|
|
|
143
165
|
runId: z.string().min(1),
|
|
144
166
|
}).optional(),
|
|
145
167
|
}).refine((job) => job.dryRun === true || isCanonicalCommit(job.ref))
|
|
168
|
+
.refine((job) => job.dryRun === true || job.approvedAccess !== undefined)
|
|
146
169
|
|
|
147
170
|
export interface CloudflareCloneSource {
|
|
148
171
|
readonly repoUrl: string
|
|
149
172
|
}
|
|
150
173
|
|
|
151
|
-
/** A run's terminal outcome plus
|
|
152
|
-
export type CloudflareRunOutcome = ProviderTerminalOutcome & {
|
|
174
|
+
/** A run's terminal outcome plus what the executor reported: the IAM schema it compiled. */
|
|
175
|
+
export type CloudflareRunOutcome = ProviderTerminalOutcome & {
|
|
176
|
+
readonly iamReconcile?: RunnerIamReconcile
|
|
177
|
+
readonly dryRun?: boolean
|
|
178
|
+
}
|
|
153
179
|
|
|
154
180
|
/** What the runner reports for a run after a control-plane restart: its persisted outcome, or still in flight. */
|
|
155
181
|
export type CloudflareRunRecovery = CloudflareRunOutcome | { readonly state: 'running' }
|
|
@@ -160,6 +186,8 @@ export interface CloudflareControlOptions {
|
|
|
160
186
|
readonly propustkaUrl?: string
|
|
161
187
|
readonly propustkaProvisioningKey?: string
|
|
162
188
|
readonly runnerKey: string
|
|
189
|
+
/** Every Cloudflare deployment in Control's registry, sent with each job so another application's names are refused. */
|
|
190
|
+
installationApps?(signal: AbortSignal): Promise<readonly AppEnvironment[]>
|
|
163
191
|
/** Overridable for tests; production reconciles over HTTPS with the control plane's own admin key. */
|
|
164
192
|
readonly reconcileSchema?: SchemaReconciler
|
|
165
193
|
resolveSource(input: ProviderSourceResolutionInput): Promise<ProviderSourceResolution>
|
|
@@ -228,6 +256,11 @@ const awaitWithSignal = async <T>(signal: AbortSignal, invoke: () => Promise<T>)
|
|
|
228
256
|
}
|
|
229
257
|
}
|
|
230
258
|
|
|
259
|
+
const runnerApprovedAccess = (environment: ProviderEnvironment): RunnerApprovedAccess | undefined =>
|
|
260
|
+
environment.access === undefined
|
|
261
|
+
? undefined
|
|
262
|
+
: { kind: 'contract', contract: environment.access.contract, contractDigest: environment.access.contractDigest }
|
|
263
|
+
|
|
231
264
|
const buildJob = async (options: CloudflareControlOptions, input: ProviderDeployInput): Promise<CloudflareRunnerJob> => {
|
|
232
265
|
input.signal.throwIfAborted()
|
|
233
266
|
assertRegistrationApp(input)
|
|
@@ -237,7 +270,22 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
|
|
|
237
270
|
if (!input.dryRun && !isCanonicalCommit(ref)) {
|
|
238
271
|
throw new Error('Cloudflare deploy requires a canonical 40-character commit SHA')
|
|
239
272
|
}
|
|
273
|
+
const approvedAccess = runnerApprovedAccess(input.environment)
|
|
274
|
+
if (!input.dryRun && approvedAccess === undefined) {
|
|
275
|
+
throw new Error('Cloudflare deploy requires the access Control approved for this environment')
|
|
276
|
+
}
|
|
277
|
+
// A job and a webhook need `@fabrika/db` on Postgres, which a Worker has not; their keys would only sit in a config.
|
|
278
|
+
const workloadKey = Object.keys(input.managedEnvironment).find(isWorkloadKeyVariable)
|
|
279
|
+
if (workloadKey !== undefined) {
|
|
280
|
+
throw new Error(`cloudflare: the contract declares a job or a webhook (${workloadKey}); they run on Zerops only`)
|
|
281
|
+
}
|
|
240
282
|
const source = await awaitWithSignal(input.signal, () => options.prepareClone(input.app.source, input.signal, input.sourceBinding))
|
|
283
|
+
const listInstallationApps = options.installationApps
|
|
284
|
+
const installationApps = listInstallationApps === undefined
|
|
285
|
+
? undefined
|
|
286
|
+
: (await awaitWithSignal(input.signal, () => listInstallationApps(input.signal))).map((deployment) =>
|
|
287
|
+
appEnvironmentId(deployment.app, deployment.env)
|
|
288
|
+
)
|
|
241
289
|
const managedEnvironment: Record<string, string> = {}
|
|
242
290
|
for (const [name, value] of Object.entries(input.managedEnvironment)) {
|
|
243
291
|
if (value !== null) managedEnvironment[name] = value
|
|
@@ -257,6 +305,8 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
|
|
|
257
305
|
...(storedTarget.stateNamespace === undefined ? {} : { stateNamespace: storedTarget.stateNamespace }),
|
|
258
306
|
...(input.environment.domain === undefined ? {} : { domain: input.environment.domain }),
|
|
259
307
|
...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }),
|
|
308
|
+
...(installationApps === undefined ? {} : { installationApps }),
|
|
309
|
+
...(approvedAccess === undefined ? {} : { approvedAccess }),
|
|
260
310
|
...(input.dryRun ? { dryRun: true } : {}),
|
|
261
311
|
...(Object.keys(input.secrets).length === 0 ? {} : { secrets: input.secrets }),
|
|
262
312
|
...(Object.keys(input.vars).length === 0 ? {} : { vars: input.vars }),
|
|
@@ -265,57 +315,29 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
|
|
|
265
315
|
}
|
|
266
316
|
}
|
|
267
317
|
|
|
268
|
-
/** A megabyte of vocabulary is already absurd; beyond it the control plane refuses to parse at all. */
|
|
269
|
-
const MAX_SCHEMA_JSON_CHARS = 1024 * 1024
|
|
270
|
-
|
|
271
318
|
/** The app a terminal outcome belongs to, and where IAM may hand it a session. */
|
|
272
319
|
interface IamReconcileTarget {
|
|
273
320
|
readonly appId: string
|
|
321
|
+
readonly env: string
|
|
274
322
|
readonly returnOrigins?: readonly string[]
|
|
323
|
+
/** Control's approved contract (ADR-0050): a contract application's IAM schema comes from it, never from the runner. */
|
|
324
|
+
readonly access?: ProviderApprovedAccess
|
|
275
325
|
readonly signal: AbortSignal
|
|
276
326
|
}
|
|
277
327
|
|
|
278
328
|
/** The executor's report itself is unusable; retrying cannot make it valid. */
|
|
279
329
|
class InvalidIamReport extends Error {}
|
|
280
330
|
|
|
281
|
-
/**
|
|
282
|
-
|
|
283
|
-
* have implementations other than the runner relay, so validate and bound its report before IAM hears it.
|
|
284
|
-
*/
|
|
285
|
-
const applyIamReconcile = async (
|
|
286
|
-
options: CloudflareControlOptions,
|
|
287
|
-
target: IamReconcileTarget,
|
|
288
|
-
report: RunnerIamReconcile,
|
|
289
|
-
): Promise<void> => {
|
|
290
|
-
const parsedReport = runnerIamReconcileSchema.safeParse(report)
|
|
291
|
-
if (!parsedReport.success) {
|
|
292
|
-
throw new InvalidIamReport('reported an authz schema whose app id or body is not a string')
|
|
293
|
-
}
|
|
294
|
-
const reconcile = parsedReport.data
|
|
295
|
-
if (reconcile.app !== target.appId) {
|
|
296
|
-
throw new InvalidIamReport(`reported an authz schema for app "${reconcile.app}", expected "${target.appId}"`)
|
|
297
|
-
}
|
|
298
|
-
if (reconcile.schemaJson.length > MAX_SCHEMA_JSON_CHARS) {
|
|
299
|
-
throw new InvalidIamReport(`reported an authz schema of ${reconcile.schemaJson.length} characters, over the ${MAX_SCHEMA_JSON_CHARS} limit`)
|
|
300
|
-
}
|
|
301
|
-
let parsed: unknown
|
|
302
|
-
try {
|
|
303
|
-
parsed = JSON.parse(reconcile.schemaJson)
|
|
304
|
-
} catch {
|
|
305
|
-
throw new InvalidIamReport('reported an authz schema that is not valid JSON')
|
|
306
|
-
}
|
|
307
|
-
const schema = parseAppSchema(parsed)
|
|
308
|
-
if (!schema.ok) {
|
|
309
|
-
throw new InvalidIamReport(`reported a malformed authz schema: ${schema.message}`)
|
|
310
|
-
}
|
|
331
|
+
/** Apply a schema with the control plane's own IAM key. */
|
|
332
|
+
const applySchema = async (options: CloudflareControlOptions, target: IamReconcileTarget, schema: AppSchema): Promise<void> => {
|
|
311
333
|
if (options.propustkaUrl === undefined) return
|
|
312
334
|
// Return origins ride this call because `apps.setReturnOrigins` 404s for an app IAM has never heard
|
|
313
335
|
// of, and the schema reconcile is what registers it. Separate call, same moment.
|
|
314
336
|
const returnOrigins = target.returnOrigins !== undefined && target.returnOrigins.length > 0 ? target.returnOrigins : undefined
|
|
315
337
|
await (options.reconcileSchema ?? defaultReconcileSchema)({
|
|
316
338
|
url: options.propustkaUrl,
|
|
317
|
-
app: target.appId,
|
|
318
|
-
schema
|
|
339
|
+
app: appEnvironmentId(target.appId, target.env),
|
|
340
|
+
schema,
|
|
319
341
|
...(returnOrigins === undefined ? {} : { returnOrigins }),
|
|
320
342
|
...(options.propustkaProvisioningKey === undefined ? {} : { adminKey: options.propustkaProvisioningKey }),
|
|
321
343
|
signal: target.signal,
|
|
@@ -323,11 +345,11 @@ const applyIamReconcile = async (
|
|
|
323
345
|
}
|
|
324
346
|
|
|
325
347
|
/**
|
|
326
|
-
* Settle a terminal outcome: apply
|
|
327
|
-
* the awaited deploy and a post-restart reconcile come through here under Control's lease. IAM replaces
|
|
328
|
-
*
|
|
329
|
-
*
|
|
330
|
-
*
|
|
348
|
+
* Settle a terminal outcome: apply the IAM schema Control approved, if any, before Control marks the run terminal. Both
|
|
349
|
+
* the awaited deploy and a post-restart reconcile come through here under Control's lease. IAM replaces the app's whole
|
|
350
|
+
* vocabulary, so applying the same schema again after a lost lease is harmless. `retryUnavailableIam` keeps the run in
|
|
351
|
+
* flight when IAM was unreachable or answered 5xx/408/429, so the next reconcile retries; an invalid report or any
|
|
352
|
+
* other IAM refusal fails the run.
|
|
331
353
|
*/
|
|
332
354
|
const settleOutcome = async (
|
|
333
355
|
options: CloudflareControlOptions,
|
|
@@ -336,22 +358,31 @@ const settleOutcome = async (
|
|
|
336
358
|
log: (line: string) => Promise<void>,
|
|
337
359
|
retryUnavailableIam: boolean,
|
|
338
360
|
): Promise<ProviderTerminalOutcome | { readonly state: 'running' }> => {
|
|
361
|
+
const terminal: ProviderTerminalOutcome = {
|
|
362
|
+
state: outcome.state,
|
|
363
|
+
...(outcome.exitCode === undefined ? {} : { exitCode: outcome.exitCode }),
|
|
364
|
+
...(outcome.artifactState === undefined ? {} : { artifactState: outcome.artifactState }),
|
|
365
|
+
}
|
|
339
366
|
const failed: ProviderTerminalOutcome = { state: 'failed', ...(outcome.artifactState === undefined ? {} : { artifactState: outcome.artifactState }) }
|
|
340
|
-
const
|
|
341
|
-
if (reconcile === undefined) return outcome
|
|
367
|
+
const reported = outcome.iamReconcile !== undefined
|
|
342
368
|
if (outcome.dryRun === true) {
|
|
343
|
-
|
|
369
|
+
if (!reported) return terminal
|
|
370
|
+
await log('reconcile-schema refused: a dry run reported access')
|
|
344
371
|
return failed
|
|
345
372
|
}
|
|
346
373
|
try {
|
|
347
|
-
|
|
374
|
+
if (target.access === undefined && reported) {
|
|
375
|
+
throw new InvalidIamReport('reported access, but Control approved no access for this environment')
|
|
376
|
+
}
|
|
377
|
+
// An approved contract reconciles its own schema once the deploy succeeded, whatever the runner reported.
|
|
378
|
+
if (target.access !== undefined && outcome.state === 'succeeded') await applySchema(options, target, target.access.schema)
|
|
348
379
|
} catch (error) {
|
|
349
380
|
target.signal.throwIfAborted()
|
|
350
381
|
await log(`reconcile-schema failed: ${error instanceof Error ? error.message : 'unknown error'}`)
|
|
351
382
|
if (retryUnavailableIam && isTransientIamFailure(error)) return { state: 'running' }
|
|
352
383
|
return failed
|
|
353
384
|
}
|
|
354
|
-
return
|
|
385
|
+
return terminal
|
|
355
386
|
}
|
|
356
387
|
|
|
357
388
|
const isTransientIamFailure = (error: unknown): boolean => {
|
|
@@ -364,6 +395,7 @@ const isTransientIamFailure = (error: unknown): boolean => {
|
|
|
364
395
|
export const createCloudflareControlProvider = (options: CloudflareControlOptions): ControlProvider => ({
|
|
365
396
|
id: 'cloudflare',
|
|
366
397
|
normalizeRegistration,
|
|
398
|
+
applicationRoot: (source) => checkoutRelativeDirectory(source.workerDir),
|
|
367
399
|
source: { binding: 'connection' },
|
|
368
400
|
resolveSource: async (input) => {
|
|
369
401
|
input.signal.throwIfAborted()
|
|
@@ -400,7 +432,13 @@ export const createCloudflareControlProvider = (options: CloudflareControlOption
|
|
|
400
432
|
}
|
|
401
433
|
input.signal.throwIfAborted()
|
|
402
434
|
if (input.dryRun) return outcome
|
|
403
|
-
const target
|
|
435
|
+
const target: IamReconcileTarget = {
|
|
436
|
+
appId: input.app.id,
|
|
437
|
+
env: input.environment.env,
|
|
438
|
+
signal: input.signal,
|
|
439
|
+
...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }),
|
|
440
|
+
...(input.environment.access === undefined ? {} : { access: input.environment.access }),
|
|
441
|
+
}
|
|
404
442
|
const log = async (line: string): Promise<void> => input.events.log(line)
|
|
405
443
|
return settleOutcome(options, target, outcome, log, false)
|
|
406
444
|
},
|
|
@@ -410,10 +448,12 @@ export const createCloudflareControlProvider = (options: CloudflareControlOption
|
|
|
410
448
|
if (recoverRun === undefined) return { state: 'running' }
|
|
411
449
|
const recovery = await awaitWithSignal(input.signal, () => recoverRun(input.runId))
|
|
412
450
|
if (recovery.state === 'running') return { state: 'running' }
|
|
413
|
-
const target = {
|
|
451
|
+
const target: IamReconcileTarget = {
|
|
414
452
|
appId: input.environment.appId,
|
|
453
|
+
env: input.environment.env,
|
|
415
454
|
signal: input.signal,
|
|
416
455
|
...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }),
|
|
456
|
+
...(input.environment.access === undefined ? {} : { access: input.environment.access }),
|
|
417
457
|
}
|
|
418
458
|
const log = async (line: string): Promise<void> => {
|
|
419
459
|
if (input.log === undefined) console.error(`run ${input.runId}: ${line}`)
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export * from 'oblaka-iac'
|
|
2
2
|
export { type CloudflareAppConfig, type CloudflareAppConfigInput, defineApp, isCloudflareAppConfig, type ResourceContext } from './authoring'
|
|
3
|
+
export { assertGeneratedConfigs, assertGeneration, generateWranglerConfigs } from './bounds'
|
|
4
|
+
export type { ConfigGeneration, DeploymentBounds, GeneratedResource } from './bounds'
|
|
3
5
|
export { parseCloudflareArgs, platformComponents } from './cli-args'
|
|
4
6
|
export type { ParsedCloudflareArgs, PlatformComponent } from './cli-args'
|
|
5
7
|
export { type CloudflareArtifact, cloudflareArtifact, cloudflareArtifactCodec } from './codec'
|
|
@@ -9,6 +11,7 @@ export {
|
|
|
9
11
|
type CommandResult,
|
|
10
12
|
type CommandRunner,
|
|
11
13
|
type CommandSpec,
|
|
14
|
+
type ContractReader,
|
|
12
15
|
defaultCloudflareCollaborators,
|
|
13
16
|
type LoadedCloudflareConfig,
|
|
14
17
|
type OblakaProvisioner,
|
|
@@ -20,9 +23,9 @@ export { deployCloudflareConfig, loadCloudflareCommandConfig } from './command'
|
|
|
20
23
|
export type { CloudflareCommandDeployOptions, LoadedCloudflareCommandConfig } from './command'
|
|
21
24
|
export { cloudflareStoredTargetCodec, createCloudflareControlProvider } from './control'
|
|
22
25
|
export type { CloudflareCloneSource, CloudflareControlOptions, CloudflareRunnerJob, CloudflareStoredTarget } from './control'
|
|
23
|
-
export {
|
|
24
|
-
export type {
|
|
26
|
+
export { buildPlan, findMigratableDatabases, PLATFORM_RESOURCE_NAMES } from './plan'
|
|
27
|
+
export type { CloudflareStep, CloudflareStepKind, MigratableDatabase } from './plan'
|
|
25
28
|
export { type CloudflareDeployerOptions, type CloudflareDeployResult, type CloudflareDeployRun, createCloudflareDeployer } from './provider'
|
|
26
|
-
export { createCloudflareProxyWorker } from './proxy'
|
|
29
|
+
export { createCloudflareProxyWorker, IAM_APPLICATION_ENTRYPOINT, iamServiceReference } from './proxy'
|
|
27
30
|
export type { CloudflareProxyWorkerOptions } from './proxy'
|
|
28
31
|
export { type AppSchemaParse, parseAppSchema } from './schema'
|
|
@@ -80,7 +80,7 @@ const run = async (command: InstallationCommand, argv: readonly string[]): Promi
|
|
|
80
80
|
return
|
|
81
81
|
}
|
|
82
82
|
if (command !== 'plan' && command !== 'deploy') {
|
|
83
|
-
// The router already
|
|
83
|
+
// The router already filters on `commands`, so this is unreachable today — and it is the branch that
|
|
84
84
|
// keeps it unreachable: without it, a command added to the contract later falls through to a deploy.
|
|
85
85
|
throw new Error(`Cloudflare installation does not support \`platform ${command}\``)
|
|
86
86
|
}
|
package/src/plan.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { Container, D1Database, KVNamespace, Queue, R2Bucket, ServiceReference, Worker } from 'oblaka-iac'
|
|
1
|
+
import { Worker } from 'oblaka-iac'
|
|
3
2
|
import type { CloudflareAppConfig } from './authoring'
|
|
4
3
|
|
|
5
4
|
export type CloudflareStepKind = 'build' | 'provision-resources' | 'migrate' | 'deploy-worker' | 'reconcile-schema' | 'sync-secrets'
|
|
@@ -69,196 +68,6 @@ export const PLATFORM_RESOURCE_NAMES: ReadonlySet<string> = new Set([
|
|
|
69
68
|
'operations-ingest-dlq',
|
|
70
69
|
])
|
|
71
70
|
|
|
72
|
-
const namedResource = (value: unknown): { readonly kind: string; readonly name: string } | null => {
|
|
73
|
-
if (value instanceof Worker) return { kind: 'Worker', name: value.options.name }
|
|
74
|
-
if (value instanceof D1Database) return { kind: 'D1 database', name: value.options.name }
|
|
75
|
-
if (value instanceof KVNamespace) return { kind: 'KV namespace', name: value.options.name }
|
|
76
|
-
if (value instanceof R2Bucket) return { kind: 'R2 bucket', name: value.options.name }
|
|
77
|
-
if (value instanceof Queue) return { kind: 'queue', name: value.options.name }
|
|
78
|
-
if (value instanceof Container) return { kind: 'container', name: value.options.name }
|
|
79
|
-
return null
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* A `ServiceReference` binds `${env}-${name}` without declaring it, so it never reaches `namedResource`
|
|
84
|
-
* — it is how an app would call the control plane or the runner directly. IAM is the one exception:
|
|
85
|
-
* every app binds `propustka-worker` (`proxy.ts`), which is the platform's intended front door.
|
|
86
|
-
*/
|
|
87
|
-
const serviceReferenceTarget = (value: unknown): string | null => {
|
|
88
|
-
if (!(value instanceof ServiceReference)) return null
|
|
89
|
-
const target = Reflect.get(value, 'serviceName')
|
|
90
|
-
return typeof target === 'string' && target !== '' ? target : '(unreadable)'
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
const routeHostname = (route: unknown): string | null => {
|
|
94
|
-
const pattern = typeof route === 'string' ? route : typeof route === 'object' && route !== null ? Reflect.get(route, 'pattern') : undefined
|
|
95
|
-
if (typeof pattern !== 'string') return null
|
|
96
|
-
const host = pattern.split('/')[0]
|
|
97
|
-
return host === undefined ? null : host.toLowerCase()
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
const applicationChain = (root: Worker): ReadonlySet<Worker> => {
|
|
101
|
-
const chain = new Set<Worker>()
|
|
102
|
-
let current: unknown = root
|
|
103
|
-
while (current instanceof Worker) {
|
|
104
|
-
chain.add(current)
|
|
105
|
-
current = current.options.bindings?.['APP']
|
|
106
|
-
}
|
|
107
|
-
return chain
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* The only `Worker` options an app may set. oblaka's `ResourceProcessor` spreads everything but
|
|
112
|
-
* `dir`/`bindings`/`deleteDurableObjectsOnRemoval` verbatim into the generated wrangler config, so any
|
|
113
|
-
* other key — `services`, `durable_objects`, `r2_buckets`, `build` — binds or runs something the typed
|
|
114
|
-
* `bindings` walk never sees. Fail closed: a new wrangler key is refused until reviewed.
|
|
115
|
-
*/
|
|
116
|
-
const APP_WORKER_OPTIONS: ReadonlySet<string> = new Set([
|
|
117
|
-
'assets',
|
|
118
|
-
'bindings',
|
|
119
|
-
'compatibility_date',
|
|
120
|
-
'compatibility_flags',
|
|
121
|
-
'deleteDurableObjectsOnRemoval',
|
|
122
|
-
'dir',
|
|
123
|
-
'main',
|
|
124
|
-
'name',
|
|
125
|
-
'observability',
|
|
126
|
-
'preview_urls',
|
|
127
|
-
'routes',
|
|
128
|
-
'triggers',
|
|
129
|
-
'vars',
|
|
130
|
-
'workers_dev',
|
|
131
|
-
// Every other key is deliberately absent: `build` runs a command, the rest bind a resource by raw name.
|
|
132
|
-
])
|
|
133
|
-
|
|
134
|
-
/** Everything wrangler reads out of `assets`. `directory` is the only one that names a path. */
|
|
135
|
-
const APP_ASSETS_OPTIONS: ReadonlySet<string> = new Set(['binding', 'directory', 'html_handling', 'not_found_handling', 'run_worker_first'])
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* `assets.directory` is resolved against the generated `wrangler.jsonc`'s own directory and uploaded
|
|
139
|
-
* PUBLICLY: wrangler walks it recursively and ignores only `.assetsignore`/`_redirects`/`_headers`, so
|
|
140
|
-
* `.` on a root `workerDir` would publish the checkout's `.git/config` and the clone token in it.
|
|
141
|
-
*/
|
|
142
|
-
const isContainedAssetDirectory = (value: unknown): value is string => {
|
|
143
|
-
if (typeof value !== 'string' || value.startsWith('/')) return false
|
|
144
|
-
const segments = value.split('/')
|
|
145
|
-
if (segments.includes('..') || segments.includes('.git')) return false
|
|
146
|
-
return segments.some((segment) => segment !== '' && segment !== '.')
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/** `assets` is the one raw key that names a path, so it is bounded rather than refused outright. */
|
|
150
|
-
const assertBoundedAssets = (worker: Worker): void => {
|
|
151
|
-
const assets: unknown = worker.options.assets
|
|
152
|
-
if (assets === undefined) return
|
|
153
|
-
if (typeof assets !== 'object' || assets === null || Array.isArray(assets)) {
|
|
154
|
-
throw new Error(`cloudflare: Worker \`${worker.options.name}\` sets \`assets\` to something that is not an object`)
|
|
155
|
-
}
|
|
156
|
-
for (const key of Object.keys(assets)) {
|
|
157
|
-
if (!APP_ASSETS_OPTIONS.has(key)) {
|
|
158
|
-
throw new Error(`cloudflare: Worker \`${worker.options.name}\` sets \`assets.${key}\`, which an app may not configure`)
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
const directory: unknown = Reflect.get(assets, 'directory')
|
|
162
|
-
if (!isContainedAssetDirectory(directory)) {
|
|
163
|
-
throw new Error(
|
|
164
|
-
`cloudflare: Worker \`${worker.options.name}\` sets \`assets.directory\` to \`${
|
|
165
|
-
typeof directory === 'string' ? directory : '(not a string)'
|
|
166
|
-
}\`; it must be a relative path strictly inside the worker directory, with no \`..\` or \`.git\` segment`,
|
|
167
|
-
)
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
interface PlatformAdoption {
|
|
172
|
-
readonly adopted: string
|
|
173
|
-
readonly platform: string
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Every oblaka resource kind adopts the remote name `${env}-${name}`, and an env name may contain `-`
|
|
178
|
-
* (`ENV_NAME` in `control.ts`), so an app in env `prod-propustka` naming `worker` lands on IAM's
|
|
179
|
-
* `prod-propustka-worker`. Bound the ADOPTED name, which holds wherever the env/name boundary falls.
|
|
180
|
-
*/
|
|
181
|
-
const platformAdoption = (env: string, name: string): PlatformAdoption | null => {
|
|
182
|
-
const adopted = `${env}-${name}`
|
|
183
|
-
for (const platform of PLATFORM_RESOURCE_NAMES) {
|
|
184
|
-
if (adopted === platform || adopted.endsWith(`-${platform}`)) {
|
|
185
|
-
return { adopted, platform }
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
return null
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
export interface AuthoredGraphLimits {
|
|
192
|
-
/** The environment oblaka provisions into. Every remote name is `${env}-${name}`, so the bound is on that. */
|
|
193
|
-
readonly env: string
|
|
194
|
-
/** The one hostname this environment may route; a route on any other host belongs to another app. */
|
|
195
|
-
readonly domain?: string
|
|
196
|
-
/** The KV namespace oblaka keeps this deploy's state in; naming the platform's own would clobber it. */
|
|
197
|
-
readonly stateNamespace: string
|
|
198
|
-
/** Fabrika deploying its own components is the one caller allowed to name a platform resource. */
|
|
199
|
-
readonly platformResources: 'refuse' | 'allow'
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/**
|
|
203
|
-
* Refuse an authored graph before any Cloudflare call: the config comes from the checkout and the
|
|
204
|
-
* deploy holds an account-wide token, so the names and routes it may claim are bounded here (ADR-0014).
|
|
205
|
-
*/
|
|
206
|
-
export const assertAuthoredGraph = (root: Worker, limits: AuthoredGraphLimits): void => {
|
|
207
|
-
const deployable = applicationChain(root)
|
|
208
|
-
const refuse = limits.platformResources === 'refuse'
|
|
209
|
-
const assertAdoptable = (kind: string, name: string): void => {
|
|
210
|
-
const adoption = refuse ? platformAdoption(limits.env, name) : null
|
|
211
|
-
if (adoption !== null) {
|
|
212
|
-
throw new Error(
|
|
213
|
-
`cloudflare: ${kind} \`${name}\` becomes \`${adoption.adopted}\` on Cloudflare, which would take over the Fabrika platform resource \`${adoption.platform}\``,
|
|
214
|
-
)
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
const visit = (worker: Worker): void => {
|
|
218
|
-
for (const key of refuse ? Object.keys(worker.options) : []) {
|
|
219
|
-
if (!APP_WORKER_OPTIONS.has(key)) {
|
|
220
|
-
throw new Error(
|
|
221
|
-
`cloudflare: Worker \`${worker.options.name}\` sets \`${key}\`, which an app may not configure; declare resources in \`bindings\``,
|
|
222
|
-
)
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
if (refuse) {
|
|
226
|
-
assertBoundedAssets(worker)
|
|
227
|
-
}
|
|
228
|
-
for (const route of worker.options.routes ?? []) {
|
|
229
|
-
const host = routeHostname(route)
|
|
230
|
-
if (host === null || !isProxyHost(host) || host !== limits.domain?.toLowerCase()) {
|
|
231
|
-
throw new Error(`cloudflare: Worker \`${worker.options.name}\` routes \`${host ?? '(unreadable)'}\`, which is not this environment's domain`)
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
for (const value of Object.values(worker.options.bindings ?? {})) {
|
|
235
|
-
const resource = namedResource(value)
|
|
236
|
-
if (resource !== null) {
|
|
237
|
-
assertAdoptable(resource.kind, resource.name)
|
|
238
|
-
}
|
|
239
|
-
const service = serviceReferenceTarget(value)
|
|
240
|
-
if (service !== null && refuse && service !== 'propustka-worker') {
|
|
241
|
-
if (service === '(unreadable)') {
|
|
242
|
-
throw new Error('cloudflare: service binding to `(unreadable)` cannot be checked against the Fabrika platform services')
|
|
243
|
-
}
|
|
244
|
-
assertAdoptable('service binding to', service)
|
|
245
|
-
}
|
|
246
|
-
if (value instanceof Worker) {
|
|
247
|
-
if (!deployable.has(value)) {
|
|
248
|
-
throw new Error(`cloudflare: config declares Worker \`${value.options.name}\`; only the application Worker and its proxy are deployable`)
|
|
249
|
-
}
|
|
250
|
-
visit(value)
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
assertAdoptable('Worker', root.options.name)
|
|
255
|
-
// The state namespace is the ONE name oblaka uses verbatim (`KVStateStorage`), so no env prefix applies.
|
|
256
|
-
if (refuse && PLATFORM_RESOURCE_NAMES.has(limits.stateNamespace)) {
|
|
257
|
-
throw new Error(`cloudflare: state namespace \`${limits.stateNamespace}\` is a Fabrika platform resource and cannot be used by an app`)
|
|
258
|
-
}
|
|
259
|
-
visit(root)
|
|
260
|
-
}
|
|
261
|
-
|
|
262
71
|
export const buildPlan = (config: CloudflareAppConfig, worker: Worker): readonly CloudflareStep[] => {
|
|
263
72
|
const steps: CloudflareStep[] = []
|
|
264
73
|
|