diff --git a/doc/2026-11-01_jurisdiction_aware_user_store_design.md b/doc/2026-11-01_jurisdiction_aware_user_store_design.md new file mode 100644 index 0000000000..32adb9c201 --- /dev/null +++ b/doc/2026-11-01_jurisdiction_aware_user_store_design.md @@ -0,0 +1,68 @@ +# Design: jurisdiction-aware hosted user stores + +**Status:** proposed, not implemented. Source: [#2283](https://github.com/developing-today/code/issues/2283), [investigation #2061](2026-10-29T11-43-02Z_investigation_do_jurisdiction_pinning/2026-10-29T11-43-02Z_investigation_do_jurisdiction_pinning.md) and [hosted Workers investigation #2044](2026-10-28T23-34-14Z_investigation_cloudflare_workers_fit/2026-10-28T23-34-14Z_investigation_cloudflare_workers_fit.md). The hosted store is a proposed architecture, not an existing UserDO implementation: a repository search found the `google:` ID derivation only in those investigations. Names and schema below are implementation contracts, not existing APIs. + +## Scope and prerequisite + +The signup policy constant is `us`; it is **not** a silent runtime fallback. The [Cloudflare DO data-location page](https://developers.cloudflare.com/durable-objects/reference/data-location/) (read 2026-11-01) lists `us`, `eu`, and `fedramp`, but documentation is not proof that this account, deployed runtime, generated types, or R2 binding supports `us`. Before creating any account or persistent store, deploy an isolated canary and verify restricted `us` ID creation, `ctx.id.jurisdiction`, mismatch rejection, and `us` R2 creation/binding/read/write on the actual account and compatibility date. Gate production signup and migration on this and on configured destination resources; fail closed, never fall back to unrestricted, `eu`, or a location hint. If unavailable, stop deployment and resolve support/types/configuration; don't represent the store as US-resident. PoC and vendor guarantees are separately tracked by #2285. + +This design does not expose region selection or decide cross-jurisdiction shared-world participation (#2284). It does not promise country-level, request-processing, metadata, backup, or end-to-end residency. The investigation identifies unconfirmed placement of DO SQLite followers, WAL/snapshots and PITR; obtain vendor confirmation before contractual claims. DO IDs may be logged outside the jurisdiction; Worker requests can be processed elsewhere; public KV caches can be global. No personal graph data goes into KV. A location hint is not a jurisdiction. + +## 1–4. Authoritative record, routing and object guard + +The shared directory is the authoritative control plane. A user row has a unique pseudonymous `subject_key`, immutable subject-to-account binding, `jurisdiction` (active), `jurisdiction_pending` (nullable target), `migration_id`, `phase`, and monotonically increasing `routing_epoch`. A transaction creates this row with the policy value `us` **before** any DO ID is derived or request is sent. Duplicate signup reads the existing row; it never overwrites it or resets the policy. Thereafter only the migration state machine may change `jurisdiction`, with a compare-and-swap on migration ID, old jurisdiction, phase and epoch. Normal profile updates cannot change it, even before first DO creation. Invalid, absent, unsupported, or unprovisioned values fail closed. Legacy unrestricted objects must be inventoried and migrated by a separately reviewed procedure, not relabelled `us` or silently backfilled. + +One routing module owns the raw binding and exports a function conceptually `userObjectId(sub: Subject, jurisdiction: Jurisdiction)` with **two required arguments and no default**, plus a `userStub(sub, jurisdiction)` that obtains both ID and stub from the *same* `env.USERS.jurisdiction(jurisdiction)` restricted namespace. `idFromName("google:" + sub)` is called only on that namespace. The module validates both values at runtime as well as statically; no subject-only overload, raw namespace access, unrestricted `get`, or fallback exists in application paths. Expose the raw binding only to this module and enforce this boundary by lint/static tests and code review. Each authenticated request resolves the authoritative row first and routes using its active jurisdiction and epoch; caches cannot authorize writes without the fencing protocol below. A missing jurisdiction must not silently produce a second, empty user store: unrestricted `idFromName` and restricted ID derivation produce different objects for the same name. A restricted namespace also rejects an ID from a different jurisdiction, unlike unrestricted `get`. + +Every identity-touching entry point—fetch, RPC, WebSocket connect/message/close handlers, alarms, initialization, import/export and administrative operations—runs a common guard **before reads, writes, external effects or alarm rescheduling**. It checks `ctx.id.jurisdiction` is defined, supported, and equals the expected jurisdiction from the authenticated, trusted routing context and, once initialized, the object's persisted immutable identity/jurisdiction. The route context includes account ID and epoch and is internal/authenticated, never client-controlled. Initialization is an explicit authorized operation, not automatic empty-store creation on arbitrary reads. Any mismatch or missing trusted context fails closed with a safe error and metric, without revealing identity. + +`undefined` covers both unrestricted objects and alarms scheduled before 2026-03-15. Alarm handlers lack a fresh request context: they compare against persisted identity/jurisdiction and a fresh authoritative migration fence, otherwise stop without side effects. Never infer `us` from undefined. A separately authorized, known restricted object's fetch/RPC may reschedule a legacy alarm so the platform backfills jurisdiction; if it cannot be proven restricted, quarantine and investigate rather than process it. Identity-free health checks must not touch user state. Tests must exercise all paths, including unexpected `undefined`. + +## 5–6. Blob and directory boundaries + +Provision one immutable R2 bucket per supported jurisdiction. Bind each separately and repeat the jurisdiction, e.g. `r2_buckets: [{ binding: "BLOBS_US", bucket_name: "user-blobs-us", jurisdiction: "us" }]`; validate the exact syntax and account support during the canary. Pick the binding strictly from the authoritative jurisdiction; unknown or missing binding is an error. Content hash keys are stable, but deduplication and garbage collection are **within each bucket**, never across jurisdictions. Only the active object may authorize writes; migration copying has narrowly scoped credentials and explicit source/target. Do not assume a hash key itself proves the stored bytes are correct. + +The single D1 directory has one fixed, explicitly configured and documented jurisdiction for all users; provisioning must verify its actual setting rather than infer it from a hint or deployment name. It stores only hashed/pseudonymous subject keys, public keys, public server records, and minimal routing/migration metadata, not graph, journal, blob bytes, or private profile content. A hashed subject remains potentially personal data, not anonymous. Document this shared directory as the **single shared durable-directory residency exception** when a user's jurisdiction differs, including access, retention and deletion policy. This is not a claim that the entire system has only one exception: KV caches, logs, request processing, shared worlds and vendor backup uncertainty also need disclosure. Store migration manifests and exports in jurisdiction-appropriate storage, not D1; D1 stores only opaque operation IDs and progress metadata. + +## 7. Migration protocol and single-account runbook + +Migration is an authenticated, auditable product state machine, not a script that edits the row. The sequence is `jurisdiction_pending` → export → create target → import → verify → switch directory → delete; intermediate phases and checkpoints persist under a unique migration ID. A per-account lease with fencing token prevents concurrent migrations; all steps are idempotent and resumable after crashes. Restrict control APIs to a service identity, protect exports in transit and at rest, and use explicit retention/cleanup for copies, logs and backups. Check policy/authorization permits transfer to target before copying. Capacity, credentials, bindings, vendor support, schema compatibility and recovery access are prerequisites. No user choice UI is implied. + +**Write fence:** CAS the directory from stable `(source, epoch E)` to pending `(source, target, migration M, epoch E+1)`; source remains the only active routing target, but enter maintenance mode and reject new mutations, WS messages, bridge writes, alarms and background jobs. Source must atomically persist the new fence, drain/serialize in-flight mutations and confirm a durable freeze watermark before export. Every mutation, including existing WebSockets and direct RPCs, checks the object's durable fence and request epoch at the point of commit; stale stubs cannot bypass it. The directory pending state alone is not a fence: the coordinator must wait for the source acknowledgement and never export if it cannot establish it. Target stays non-serving/import-only until switch and activation; only the migration principal can import. If a direct path cannot be fenced, migration is blocked. Reads may be served from frozen source only where consistency policy permits; otherwise return retryable maintenance. + +**Example: one account, `us` → `eu` (only after both jurisdictions pass provisioning and policy gates):** + +1. Authenticate operator and account; record M, source, target, epoch and preflight evidence. Confirm target account object does not already contain unrelated data; if it does, stop, never overwrite. Create the pending row via CAS and acquire the fence/maintenance acknowledgement above; disconnect or fence live sessions and bridge workers. +2. Export a consistent snapshot at the source watermark, including graph, complete journal, public-key and signature material, metadata, schema version and a manifest of every reachable blob hash/size. Preserve signed bytes exactly; validate signatures without re-signing. Keep snapshot in approved source storage; capture manifest digest and counts in the migration checkpoint. +3. Enumerate manifest blobs, copy into target jurisdiction bucket using approved transfer path, and verify each destination's bytes/hash and size even if a key already existed. Abort on missing or corrupt source or destination data. Create target via the target restricted namespace and authorized migration initialization, then idempotently import the snapshot under M. Avoid partial import becoming visible; persist progress and reject a different manifest for the same M. +4. Read back the target independently: compare manifest digest, complete graph/journal counts and canonical contents, all referenced blob bytes/hashes and sizes, schema version, and signature verification against the same public keys. Confirm target object's identity and jurisdiction, and that no writes occurred after source watermark. Any discrepancy leaves source frozen and authoritative; fix/retry or explicitly abort. +5. Atomically CAS directory `(source, pending target, M, verified, E+1)` to `(target, M, switched, E+2)`. The source remains permanently fenced for M. Activate target with E+2 after confirming that authoritative row; if the process crashes after CAS, resume activation from durable state. Requests during the gap return retryable maintenance. Invalidate routing caches and reconnect sessions/bridge using account identity, not a permanently cached DO ID. Verify authenticated reads and writes on target; signature bytes remain unchanged. This CAS is the linearization point, not the first copy. +6. Retain the frozen source for a defined recovery period and audit successful target read-back. Then delete source DO state via a fenced, idempotent cleanup operation, confirm its completion, and retire the migration record only after required retention. **Do not delete source R2 blobs as part of migration:** other users may reference the same content. A separate jurisdiction-local GC may delete only after a concurrency-safe reachability proof covering all accounts, in-flight writes, migrations and retention roots; if such a proof is unavailable, retain the blobs. Clean target orphan copies through the same safe GC. Track backup/PITR retention separately: logical deletion is not verified physical erasure. + +Before switch, abort means discard/quarantine target, CAS back to source with a *new* epoch, and explicitly unfreeze source after confirming the directory; orphan blobs remain for safe GC. After switch, **never simply switch back or unfreeze source**, because target may have accepted new writes: recover forward, or perform a new fenced reverse migration including all target writes. On ambiguous CAS/timeout, reread authoritative state and resume from the recorded phase; never guess which side is active. A failed deletion is retried and alerted, not treated as a failed switch. + +## Failure modes and verification + +| Failure | Required behavior | +| --- | --- | +| Missing jurisdiction / subject-only ID / unrestricted namespace | Reject before ID derivation; static boundary checks and deployed mismatch tests prevent silent second store. | +| Wrong jurisdiction or undefined `ctx.id.jurisdiction`, including old alarms | Reject before side effects; alarm quarantine/reschedule only through proven restricted object. | +| US unavailable, missing bucket, bad credentials or vendor claim unverified | Block signup/migration or claims; no fallback or relabelling. | +| Concurrent writes, stale route, alarm, bridge or WebSocket during freeze | Durable per-object fencing and epoch at commit; refuse switch without freeze acknowledgement. | +| Partial export/copy/import, mismatch, crash, retry or duplicate worker | Checkpoint by M, verify and resume idempotently; source stays authoritative until CAS. | +| Switch succeeds but response/activation fails | Reread directory; source stays fenced, resume target activation. No unsafe rollback. | +| Shared blob deletion or post-switch rollback loses data | Separate concurrency-safe GC; reverse migrate after new writes. | +| Directory or public caches leak sensitive content | Schema allowlist, authorization and tests; disclose pseudonymous directory and global caches. | + +Test with unit/type tests for required arguments, runtime validation, restricted namespace selection and no raw-binding access; table-driven guards on all entry points and both undefined cases; directory uniqueness/CAS/state transition and epoch tests; property tests for cross-jurisdiction ID separation and forbidden transitions; and concurrency/fault-injection tests pausing every checkpoint, racing WS/RPC/alarm/bridge writes, duplicate migrations, stale routes and ambiguous CAS. Integration tests must verify exact snapshot/journal/signature preservation, shared-blob survival, corrupted/missing blob rejection, abort, crash recovery, forward activation, and reverse migration after target writes. A deployed canary on the actual Cloudflare account verifies real DO `us`/`eu` behavior, alarm jurisdiction and matching R2 bindings; emulators and mock-only tests cannot establish residency. A pre-2026 alarm may require a fixture or documented platform limitation rather than pretending a new alarm reproduces it. + +## Buildable implementation follow-ons + +1. **Provisioning gate ([#3403](https://github.com/developing-today/code/issues/3403)):** consume the deployed account-level DO/R2 PoC evidence from #2285; implement deployment config validation and explicit production enablement. Do not duplicate #2285's PoC or vendor-confirmation scope; no residency contract is inferred from a probe. +2. **Directory and signup ([#3399](https://github.com/developing-today/code/issues/3399)):** schema, policy constant, atomic creation, immutability, validated routing metadata and legacy inventory; tests for duplicate signup and invalid records. Depends on slice 1 for deployment. +3. **Restricted routing and guards ([#3400](https://github.com/developing-today/code/issues/3400)):** single ID/stub module, encapsulated binding, initialized identity guard for every entry point, alarm quarantine and boundary tests. Depends on slice 2 and the hosted DO interface. +4. **Jurisdiction-local blobs and directory policy ([#3401](https://github.com/developing-today/code/issues/3401)):** provision/bind buckets, strict bucket selection, local dedupe, directory allowlist and disclosures; tests for cross-bucket isolation. Depends on slices 1–3. +5. **Migration control plane and fencing ([#3404](https://github.com/developing-today/code/issues/3404)):** persisted phases, CAS/lease/epochs, maintenance, source freeze and target activation; fault and concurrency tests. Depends on slices 2–4 and actual bridge/WS contracts. +6. **Export/import, verification and cleanup ([#3402](https://github.com/developing-today/code/issues/3402)):** versioned signed-byte snapshot, manifest/blob copy, read-back verification, resumable orchestration, source cleanup and separate safe GC. Depends on slice 5 and defined graph/journal storage. Exercise full runbook in staging before enabling production migration. + +Vendor guarantees and cross-jurisdiction worlds remain in #2285 and #2284 respectively.