|
| 1 | +// Provisioning surface for hosted production enablement (#3403): the |
| 2 | +// evidence-producing half of the provisioning gate in |
| 3 | +// ./provisioning.ts. The gate is a pure validator — it consumes |
| 4 | +// deployed-account evidence and never probes an account itself. This |
| 5 | +// module is the prober it presupposes: |
| 6 | +// |
| 7 | +// - R2 buckets are provisioned through the Cloudflare API route |
| 8 | +// with the `cf-r2-jurisdiction` request header — never through |
| 9 | +// wrangler, whose `--jurisdiction` flag the #2285 canary showed |
| 10 | +// can be silently ignored (it created a default bucket with no |
| 11 | +// warning), and never without the header. |
| 12 | +// - A bucket's jurisdiction is taken only from the API read-back. |
| 13 | +// A jurisdiction-less read sees only default-jurisdiction |
| 14 | +// buckets (the canary's jurisdiction-less GET of an eu bucket |
| 15 | +// returned "does not exist"), so the read-back probes each |
| 16 | +// supported jurisdiction with its header before concluding a |
| 17 | +// bucket is unverified. |
| 18 | +// - The #2285 canary's results are captured into the gate's |
| 19 | +// evidence shape verbatim: only what the canary actually proved |
| 20 | +// is recorded, and it is the gate — not this surface — that |
| 21 | +// judges it. |
| 22 | +// |
| 23 | +// Nothing here enables production by itself: `provisionAndValidate` |
| 24 | +// returns the gate's validated plan or the gate's refusal, and the |
| 25 | +// gate authorizes no deployment. This surface makes no residency |
| 26 | +// claim; it records what the account's own API reports. |
| 27 | + |
| 28 | +import { SUPPORTED_JURISDICTIONS, type Jurisdiction } from "./routing.ts"; |
| 29 | +import { |
| 30 | + validateEnablement, |
| 31 | + type AccountEvidence, |
| 32 | + type BucketEvidence, |
| 33 | + type EnablementConfig, |
| 34 | + type EnablementPlan, |
| 35 | + type JurisdictionEvidence, |
| 36 | + type SupportState, |
| 37 | +} from "./provisioning.ts"; |
| 38 | + |
| 39 | +/** An operational failure of the provisioning surface itself (the |
| 40 | + * API route refused or could not be reached). Distinct from the |
| 41 | + * gate's FailClosed refusals: no evidence judgement was reached. */ |
| 42 | +export class ProvisioningError extends Error { |
| 43 | + readonly code: string; |
| 44 | + constructor(code: string, message: string) { |
| 45 | + super(message); |
| 46 | + this.code = code; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/** The slice of the Cloudflare API this surface needs. Structural, |
| 51 | + * so tests can model the account's observed behaviour (#2285) |
| 52 | + * without network access. */ |
| 53 | +export interface CloudflareApiClient { |
| 54 | + /** Create a bucket through the API route, scoped by the |
| 55 | + * jurisdiction header. Resolves with the HTTP status: 2xx created, |
| 56 | + * 409 already exists, anything else a failure. */ |
| 57 | + createR2Bucket(bucketName: string, jurisdiction: Jurisdiction): Promise<{ status: number }>; |
| 58 | + /** Read one bucket back. Without a jurisdiction the read sees |
| 59 | + * only default-jurisdiction buckets; with one it sees only that |
| 60 | + * jurisdiction's buckets. `jurisdiction` in the result is the |
| 61 | + * bucket's API-reported jurisdiction, or null when the response |
| 62 | + * carries none. */ |
| 63 | + getR2Bucket( |
| 64 | + bucketName: string, |
| 65 | + jurisdiction?: Jurisdiction, |
| 66 | + ): Promise<{ status: number; jurisdiction: string | null }>; |
| 67 | +} |
| 68 | + |
| 69 | +/** Minimal structural fetch shape (the package carries no |
| 70 | + * workers-types dependency; the global fetch satisfies this). */ |
| 71 | +export type FetchFn = ( |
| 72 | + url: string, |
| 73 | + init?: { method?: string; headers?: Record<string, string>; body?: string }, |
| 74 | +) => Promise<{ status: number; json(): Promise<unknown> }>; |
| 75 | + |
| 76 | +export function createCloudflareApiClient(options: { |
| 77 | + accountId: string; |
| 78 | + apiToken: string; |
| 79 | + fetchFn?: FetchFn; |
| 80 | +}): CloudflareApiClient { |
| 81 | + const fetchFn: FetchFn = options.fetchFn ?? ((url, init) => fetch(url, init)); |
| 82 | + const base = `https://api.cloudflare.com/client/v4/accounts/${options.accountId}/r2/buckets`; |
| 83 | + const auth = { authorization: `Bearer ${options.apiToken}` }; |
| 84 | + return { |
| 85 | + async createR2Bucket(bucketName, jurisdiction) { |
| 86 | + const res = await fetchFn(base, { |
| 87 | + method: "POST", |
| 88 | + headers: { |
| 89 | + ...auth, |
| 90 | + "content-type": "application/json", |
| 91 | + // The verified API route (#2285 mechanic 5): the header is |
| 92 | + // what places the bucket; there is no other creation path. |
| 93 | + "cf-r2-jurisdiction": jurisdiction, |
| 94 | + }, |
| 95 | + body: JSON.stringify({ name: bucketName }), |
| 96 | + }); |
| 97 | + return { status: res.status }; |
| 98 | + }, |
| 99 | + async getR2Bucket(bucketName, jurisdiction) { |
| 100 | + const headers = jurisdiction ? { ...auth, "cf-r2-jurisdiction": jurisdiction } : { ...auth }; |
| 101 | + const res = await fetchFn(`${base}/${encodeURIComponent(bucketName)}`, { method: "GET", headers }); |
| 102 | + if (res.status !== 200) return { status: res.status, jurisdiction: null }; |
| 103 | + const body = (await res.json()) as { result?: { jurisdiction?: unknown } } | null; |
| 104 | + const reported = body?.result?.jurisdiction; |
| 105 | + return { status: 200, jurisdiction: typeof reported === "string" ? reported : null }; |
| 106 | + }, |
| 107 | + }; |
| 108 | +} |
| 109 | + |
| 110 | +async function tryGet( |
| 111 | + client: CloudflareApiClient, |
| 112 | + bucketName: string, |
| 113 | + jurisdiction?: Jurisdiction, |
| 114 | +): Promise<{ status: number; jurisdiction: string | null } | null> { |
| 115 | + try { |
| 116 | + return await client.getR2Bucket(bucketName, jurisdiction); |
| 117 | + } catch { |
| 118 | + // A failed read is not evidence either way; the caller records |
| 119 | + // the bucket as unverified and the gate fails closed on it. |
| 120 | + return null; |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +/** Read one bucket's actual jurisdiction back from the R2 API. |
| 125 | + * Returns the gate's BucketEvidence: `actualJurisdiction` is what |
| 126 | + * the API reports ("default" for a bucket outside every supported |
| 127 | + * jurisdiction), or null when no read could verify the bucket. */ |
| 128 | +export async function readBucketEvidence( |
| 129 | + client: CloudflareApiClient, |
| 130 | + bucketName: string, |
| 131 | +): Promise<BucketEvidence> { |
| 132 | + // A jurisdiction-less read sees default-jurisdiction buckets only. |
| 133 | + const plain = await tryGet(client, bucketName); |
| 134 | + if (plain?.status === 200) { |
| 135 | + return { bucketName, actualJurisdiction: plain.jurisdiction ?? "default" }; |
| 136 | + } |
| 137 | + // Jurisdiction-scoped reads: the header is what makes a bucket in |
| 138 | + // that jurisdiction visible at all (#2285), so a 200 here is the |
| 139 | + // API attesting the bucket resides in the probed jurisdiction even |
| 140 | + // when the response omits the field. |
| 141 | + for (const jurisdiction of SUPPORTED_JURISDICTIONS) { |
| 142 | + const scoped = await tryGet(client, bucketName, jurisdiction); |
| 143 | + if (scoped?.status === 200) { |
| 144 | + return { bucketName, actualJurisdiction: scoped.jurisdiction ?? jurisdiction }; |
| 145 | + } |
| 146 | + } |
| 147 | + return { bucketName, actualJurisdiction: null }; |
| 148 | +} |
| 149 | + |
| 150 | +/** Provision one bucket through the verified API route, then read |
| 151 | + * it back. Idempotent: a bucket that already exists (409) is read |
| 152 | + * back like any other — where it actually resides is the read-back's |
| 153 | + * to say, and the gate refuses a mismatch. */ |
| 154 | +export async function provisionBucket( |
| 155 | + client: CloudflareApiClient, |
| 156 | + bucketName: string, |
| 157 | + jurisdiction: Jurisdiction, |
| 158 | +): Promise<BucketEvidence> { |
| 159 | + let status: number; |
| 160 | + try { |
| 161 | + status = (await client.createR2Bucket(bucketName, jurisdiction)).status; |
| 162 | + } catch (e) { |
| 163 | + throw new ProvisioningError( |
| 164 | + "bucket_provision_failed", |
| 165 | + `creating bucket "${bucketName}" through the R2 API route failed: ${e instanceof Error ? e.message : String(e)}`, |
| 166 | + ); |
| 167 | + } |
| 168 | + if ((status < 200 || status >= 300) && status !== 409) { |
| 169 | + throw new ProvisioningError( |
| 170 | + "bucket_provision_failed", |
| 171 | + `creating bucket "${bucketName}" through the R2 API route returned HTTP ${status}; not proceeding`, |
| 172 | + ); |
| 173 | + } |
| 174 | + return readBucketEvidence(client, bucketName); |
| 175 | +} |
| 176 | + |
| 177 | +/** One jurisdiction's outcome from the deployed-account canary |
| 178 | + * (#2285 mechanics 1–4 for Durable Objects, plus the deployed |
| 179 | + * runtime/generated-types support check). Fields the canary did not |
| 180 | + * determine stay absent here and are captured as "unverified". */ |
| 181 | +export interface CanaryJurisdictionResult { |
| 182 | + jurisdiction: string; |
| 183 | + durableObjects?: SupportState; |
| 184 | + runtimeTypes?: SupportState; |
| 185 | +} |
| 186 | + |
| 187 | +/** Capture canary results into the gate's evidence shape, verbatim: |
| 188 | + * only supported jurisdictions are recorded, and only the states |
| 189 | + * the canary actually reported — this surface never upgrades a |
| 190 | + * result. */ |
| 191 | +export function captureCanaryEvidence( |
| 192 | + results: readonly CanaryJurisdictionResult[], |
| 193 | +): Partial<Record<Jurisdiction, JurisdictionEvidence>> { |
| 194 | + const captured: Partial<Record<Jurisdiction, JurisdictionEvidence>> = {}; |
| 195 | + for (const result of results) { |
| 196 | + if (!(SUPPORTED_JURISDICTIONS as readonly string[]).includes(result.jurisdiction)) continue; |
| 197 | + const jurisdiction = result.jurisdiction as Jurisdiction; |
| 198 | + captured[jurisdiction] = { |
| 199 | + durableObjects: result.durableObjects ?? "unverified", |
| 200 | + runtimeTypes: result.runtimeTypes ?? "unverified", |
| 201 | + }; |
| 202 | + } |
| 203 | + return captured; |
| 204 | +} |
| 205 | + |
| 206 | +/** Gather the full deployed-account evidence the gate consumes: |
| 207 | + * canary results for the jurisdictions, API read-backs for the |
| 208 | + * buckets. */ |
| 209 | +export async function gatherAccountEvidence( |
| 210 | + client: CloudflareApiClient, |
| 211 | + input: { buckets: readonly string[]; canary: readonly CanaryJurisdictionResult[] }, |
| 212 | +): Promise<AccountEvidence> { |
| 213 | + const buckets: BucketEvidence[] = []; |
| 214 | + for (const bucketName of input.buckets) { |
| 215 | + buckets.push(await readBucketEvidence(client, bucketName)); |
| 216 | + } |
| 217 | + return { jurisdictions: captureCanaryEvidence(input.canary), buckets }; |
| 218 | +} |
| 219 | + |
| 220 | +/** The surface end to end: provision the configured bucket through |
| 221 | + * the API route, gather the evidence, and invoke the gate before |
| 222 | + * any production signup/migration enablement. Returns the gate's |
| 223 | + * validated plan; the gate's FailClosed refusal propagates |
| 224 | + * unchanged. When the configured jurisdiction is not a supported |
| 225 | + * one, no bucket is created — the gate refuses that configuration |
| 226 | + * on its own, and provisioning under an invalid jurisdiction would |
| 227 | + * be exactly the silent misplacement this gate exists to prevent. */ |
| 228 | +export async function provisionAndValidate( |
| 229 | + client: CloudflareApiClient, |
| 230 | + config: EnablementConfig, |
| 231 | + canary: readonly CanaryJurisdictionResult[], |
| 232 | +): Promise<EnablementPlan> { |
| 233 | + const buckets: BucketEvidence[] = []; |
| 234 | + if (config.bucket) { |
| 235 | + const configured = config.jurisdiction; |
| 236 | + if (configured !== undefined && (SUPPORTED_JURISDICTIONS as readonly string[]).includes(configured)) { |
| 237 | + buckets.push(await provisionBucket(client, config.bucket.bucketName, configured as Jurisdiction)); |
| 238 | + } else { |
| 239 | + buckets.push(await readBucketEvidence(client, config.bucket.bucketName)); |
| 240 | + } |
| 241 | + } |
| 242 | + return validateEnablement(config, { jurisdictions: captureCanaryEvidence(canary), buckets }); |
| 243 | +} |