Skip to content

Complete Cloudflare geo and add pinned Spin KV lookup - #514

Open
prk-Jr wants to merge 26 commits into
feature/kv-geoipfrom
feature/480-cloudflare-spin-geo
Open

prk-Jr wants to merge 26 commits into
feature/kv-geoipfrom
feature/480-cloudflare-spin-geo

Conversation

@prk-Jr

@prk-Jr prk-Jr commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Complete managed Cloudflare ctx.geo() metadata coverage and add opt-in Spin lookup against an explicitly pinned KV dataset, authenticated visitor-IP assertion, and one aggregate deadline.
  • Strip the private Spin geo headers before managed admission callbacks and handlers, and expose an immutable request-owned geography outcome.
  • Provide a separate authenticated operator loader with immutable artifact validation, manifest-last publication, remote verification, OS-selected loopback listener identity, and owned process-group/staging cleanup.

Stacked on #454 (feature/kv-geoip), which includes #502. The parent supplies the portable KV reader and Axum foundation. #517 splits Spin authentication and lookup; integration must carry the per-read deadline guard, single secret deadline owner, early-wake handling and private test seam through that split. No dependent branch is changed here.

Changes

Crate / File Change
edgezero-adapter-spin Typed manifest/environment selection, shared field restrictions, authenticated IP admission, fixed-size credential comparison, per-backend-read deadline admission, request-local resources and managed header stripping
edgezero-core Spin geo placement, value-free malformed configuration-key inspection, shared Spin restrictions and authenticated-IP provenance
Axum / Cloudflare Reject Spin-only credential settings on Axum; positive Cloudflare metadata coverage across managed entrypoints
examples/geo-kv-prototype Read-only validated artifact API, verified generation/digest identity, optional publisher feature implied by native backends
examples/geo-spin-loader One manifest template, preserved executable shim/caller cwd, actual Spin bound-address discovery, no redirects, exact report validation, group shutdown/escalation and owned Spin staging/state/logs
Tests / docs / CI Inline unit tests, private configurable store/timer test seam, loader lifecycle regressions, scoped managed-dispatch guarantees, provider outcome matrix and narrow standalone Python unittest policy exception

Spin defaults to off. KV selection requires a declared store, generation/hash pin, authenticated-header reader mode and a Spin credential-variable name. A trusted proxy must replace and authenticate the original visitor IP. Both roots and the selected path are verified per request. Invalid deployment configuration produces a redacted 500; ordinary geography outcomes do not themselves select HTTP status or grant permission. No automatic fallback or lazy-resolution feature is added.

Closes

Closes #480
Closes #486

This PR targets feature/kv-geoip, so merging it there does not automatically close the issues on the default branch.

Current CI follow-up

Current revision: b9829802b4e43db1a0eb02ecf4f43b0c9fbbe481, using Rust 1.98.1, Node 24.20.0, Spin 4.1.0 / SDK 8 and Wasmtime 48.0.2.

pin-project-lite 0.2.17 was yanked, so newly generated offline consumers could no longer resolve it from the locked cache. Six active lockfiles now select non-yanked 0.2.19; no other package nodes changed. Generated consumers still resolve their own dependencies without network access or seeded fixture locks.

Three fake-Cargo cancellation tests performed real source/compiler fingerprinting twice before their five-second readiness check. Their dedicated test helper now supplies a scoped fixture identity and fake compiler. Nested-unwind restoration is covered; production identity capture and every readiness, cancellation, listener and reaping assertion remain unchanged. This does not repair the separate macOS zombie-group signal race.

  • Mandatory five local gates: workspace format, strict all-feature Clippy, workspace tests (3,095 passed; seven ignored), feature compilation and Spin Wasm compilation.
  • Isolated harness: 680 passed; four ignored. Standalone formatting, strict all-target Clippy, default non-test compilation, all three Cargo cancellation paths and identity restoration passed.
  • Actual Fastly, Cloudflare and Spin Wasm target compilation; Spin strict Wasm lint, 39 contracts and 25 SDK tests.
  • Publisher default/all-feature tests (14 each) and strict lint; loader Rust/Python tests (one / 12), strict lint and fresh release Wasm build.
  • Fresh loader and managed serving consumer both compiled actual 0.2.19 sources. Actual Spin passed fresh three-object publication, identical replay, paused-trigger publication timeout, readiness timeout and unauthorized 401; the serving consumer delivered US/CA through real secret/SQLite metadata with private-header removal. Wrong credential and dataset-gap controls failed the expected-location assertion. Launcher exit, live-group absence, bound-listener closure and temporary-directory removal were checked.

All 30 hosted checks now pass on b982980, including the current native and Wasm suites. The processed Rust CodeQL analysis has no errors, warnings or findings across 27 rules; the other configured language analyses are also clean. The local synthetic/runtime limitations below remain applicable; earlier verification and controls are recorded separately.

Historical verification for the original review correction

Historical correction: 0434ec0c23cd0760501e1d3eeda6136e9bdcc2d0, using Rust 1.98.1, Node 24.20.0, Spin 4.1.0 / SDK 8 and Wasmtime 48.0.2.

  • Mandatory workspace format, strict all-feature Clippy, workspace tests (3,095 passed; seven ignored), all-target feature compilation and Spin Wasm compilation.

  • Isolated harness: 679 passed; four ignored. Spin Wasm strict lint and all 39 contracts / 25 SDK tests passed.

  • Publisher default/all-feature tests (14 each), strict lint and formatting; loader Rust/Python tests (one / 12), strict lint, formatting and final release Wasm build.

  • All 32 native adapter feature combinations; isolated CLI-only graph does not enable core geo-kv.

  • Docs lint, formatting and VitePress build.

  • The broader scripts/run_tests.sh invocation completed tooling/workspace/harness/dependency/native-feature checks and Axum executor-ownership/native/fixture checks, then was interrupted during optional Axum wire qualification. Its owned process groups were stopped and checked. This is not a complete prescribed-suite pass; remaining runtime qualification is separate. Stock Viceroy 0.22.0 does not include the repository's tracked local-runtime repairs.

  • Actual Spin loader: fresh three-object publication, identical replay, paused real HTTP-trigger publication timeout, readiness timeout, unauthorized 401 and corrupt-artifact 500; launcher/trigger exit, listener closure and temporary root/staging removal checked.

  • Actual Spin async managed serving consumer: declared KV metadata, real credential-variable provider, populated SQLite and component environment produced Located(US, CA) with KV/authenticated-header provenance. Admission and handler saw neither private header. Wrong credential and dataset gap failed the fixture's expected-location assertion.

  • Meaningful isolated controls rejected launcher-only cleanup, redirect forwarding, unchecked report identity and timer-first-only deadline handling. Ready reads advancing 100ms under a 250ms aggregate budget stop at three reads; late pending resume, admitted deadline cap, preexpired zero reads, early wake and pending cancellation are covered.

  • Synchronous guest tests explicitly inject their timer. SDK timer cancellation is separately exercised through Spin's actual async HTTP export; a synchronous CLI test export cannot certify that host contract.

No GitHub Actions runs were observed for the original correction head 0434ec0c23cd0760501e1d3eeda6136e9bdcc2d0. The new CI follow-up triggered Actions naturally; all 30 checks have now succeeded. Earlier green checks and historical runtime counts are not current-head qualification.

Local synthetic evidence does not qualify deployed proxy protection, live external-backend credentials/permissions/propagation, licensed-data accuracy or production capacity. Guest deadline cancellation does not certify host/backend cancellation. Request-local lookup repeats secret/manifest/root reads. Publication requires one operator per generation; read-before-write is not a distributed lock, and failed publication may leave validated resumable partial objects.

Checklist

  • Changes follow CLAUDE.md conventions
  • No Tokio dependencies added to core or adapter crates
  • Route parameters use {id} syntax
  • Application HTTP types come from edgezero_core
  • Serving stores use the declared KvRegistry
  • New behavior has meaningful tests
  • No secrets, licensed datasets or credentials committed

@prk-Jr prk-Jr self-assigned this Nov 18, 2026
@prk-Jr prk-Jr changed the title Add authenticated Spin geo and verify Cloudflare context Complete Cloudflare geo and add pinned Spin KV lookup Nov 18, 2026
@prk-Jr
prk-Jr changed the base branch from spec/482-axum-geo-manifest-binding to feature/kv-geoip November 18, 2026 14:25
@prk-Jr
prk-Jr marked this pull request as ready for review November 18, 2026 15:50
aram356 added a commit that referenced this pull request Nov 19, 2026
#517 (10ed380) tops ChristianPavilonis's line on #439:
- #510, the KvStore record contract with DynamoDB and celld providers on
  Axum (#472, #473);
- #454, portable KV-backed geo;
- #514, country and region through ctx.geo() on Cloudflare and Spin (#480,
  #486);
- #517, the portable ClientInfo contract with its Fastly, Axum, Cloudflare and
  Spin mappings (#475, #90, #91, #92, #485).

#517 also merged #469 and #502 itself, so its tree contains everything this
branch had. The only conflicts were JA4 lines that #517 refactors on top of
#469; this merge takes #517's version, and its tree is identical to #517's.
Bring in main's Fastly SDK 0.13.3 upgrade (#529) with Viceroy 0.22.0
and the Fastly CLI 17.2.0 upgrade (#531), with PR #275's exact pins at
0.13.3 and url 2.5.9, its Viceroy readiness repair on 0.22.0 and its
typed Image Optimizer unavailability check for SDK 0.13.3.
The workspace now pins url =2.5.9 for main's Fastly SDK 0.13.3 upgrade
(#529), and this loader resolves edgezero-core from the workspace, so
its lockfile no longer satisfied the manifests after the merge. A
targeted `cargo update -p url --precise 2.5.9` moves url to 2.5.9 and
form_urlencoded to 1.2.3, matching the v0.0.12 lockfiles.
Bring in PR #275's installation of the wasm32-unknown-unknown target
before the Viceroy 0.22.0 readiness repair builds, which the fastly
wasm tests and Portable record contracts (Fastly) jobs need.
@aram356

aram356 commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

For the identity integration branch (#495), I pushed 521ad02f, f53d4508 and 49d16cd4.

Bring in PR #275's atomic conditional KV insert in the Viceroy readiness
repair, and the production hosting tests' held port reservations and
spawn-token respawn from PR #406 up, with each later PR's tests reading
the live host's address.
@aram356

aram356 commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

For the identity integration branch (#495), I pushed 251074eb, a merge of #454's new head that brings #275's 41cdf035, which makes conditional KV inserts atomic in the Viceroy readiness repair, as the Fastly record contract's native race needs, and the production hosting tests' held port reservations and spawn-token respawn from #406 up, with each later PR's tests reading the live host's address. It had no conflicts.

Bring in PR #275's batch cutoff test fix, which advances the test clock
when the request arms its own deadline instead of after dispatch, and
the AWS emulator proofs' readiness markers from PRs #414 and #510, now
published by rename.

@dhruv8sh dhruv8sh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Review

Summary

This PR does four things: it finishes Cloudflare managed geo coverage across all three entrypoints, adds an opt-in Spin KV geo provider gated on a pinned dataset and an authenticated visitor-IP header, adds a separate operator loader (Rust component plus Python runner), and allows the runner's unit tests through the CI tool policy. The trust model and deadline handling are careful and well tested. I found no blocking issues. The findings below are small hardening and documentation-accuracy points.

😃 Praise

  • In dispatch_ingress_stream_with_timer_and, head limits are checked against the original header bytes before the private x-edgezero-geo-* headers are captured and stripped. Admission callbacks therefore never see the credential, and the private headers still count toward the limits. Tests cover both properties (private_geo_headers_count_toward_original_head_limits, configured_geo_does_not_read_secrets_before_admission).
  • SpinKvGeo::resolve takes one absolute KV deadline, capped by the admitted read deadline, and doesn't reset it between stages. The AdvancingKv test (four reads of 80 ms against a 250 ms budget) and the pending-read drop test show this precisely.
  • from_config rejects unknown EDGEZERO__ADAPTER__GEO__* keys through the new value-free EnvConfig::keys_below, so a typo fails loudly and nothing leaks into diagnostics.
  • The Cloudflare contract matrix runs the same metadata and spoofed-header cases through CloudflareService, run_app and dispatch_app.

Findings

Blocking

None.

Non-blocking

  • 🤔 Token comparison short-circuits on length: subtle's slice ct_eq returns early when lengths differ, which leaks the secret's length (crates/edgezero-adapter-spin/src/geo.rs:280).
  • 🤔 The runner may send its token to a local process that grabbed the port first: the port is reserved and then released before spin up binds it, and the readiness probe accepts any listener (examples/geo-spin-loader/load.py:36).
  • 🤔 The stripping claim in the docs is broader than the code: the public unmanaged into_core_request converter does not remove the private geo headers (docs/guide/adapters/spin.md:425).
  • 🌱 Geo is resolved eagerly on every authenticated request: every admitted request with a token pays for one secret read and about four KV reads, whether or not the route uses ctx.geo() (crates/edgezero-adapter-spin/src/request.rs:444).
  • ⛏ urllib.error is used but never imported: it only works because urllib.request happens to import it (examples/geo-spin-loader/load.py:148).

📌 Out of Scope

  • The new run.sh exception narrowly admits one exact python3 -m unittest command in test.yml, and tests show variants are still rejected. Maintainers may still want to confirm they accept a Python runtime in the CI tool policy.

CI Status

  • Not run: this review was static.

Comment thread crates/edgezero-adapter-spin/src/geo.rs Resolved
Comment thread examples/geo-spin-loader/load.py Resolved
Comment thread docs/guide/adapters/spin.md Resolved
Comment thread examples/geo-spin-loader/load.py Resolved

@ChristianPavilonis ChristianPavilonis left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed this PR's delta against feature/kv-geoip at 7580806a, excluding the inherited #502 work. Please address R1 and R2 before shipping the operator loader: its timeout does not own the real Spin process tree, and TCP readiness does not establish that the authenticated POST reaches its own listener. The other inline findings are follow-ups.

The focused native geo tests, Spin and Cloudflare guest contracts, loader and publisher tests, and all ten new deploy-action assertions passed. The deploy-action suite's remaining Fastly failure also reproduced on the base. The Spin guest and fake-runtime tests do not qualify real loader cleanup or a deployed proxy.

Comment thread examples/geo-spin-loader/load.py Resolved
Comment thread examples/geo-spin-loader/load.py Resolved
Comment thread crates/edgezero-adapter-spin/src/geo.rs Resolved
Comment thread examples/geo-spin-loader/load.py Resolved
Comment thread crates/edgezero-adapter-spin/src/geo.rs Resolved
Comment thread crates/edgezero-core/src/manifest.rs Resolved
Comment thread crates/edgezero-adapter-spin/src/geo.rs Resolved
Comment thread examples/geo-spin-loader/src/lib.rs Resolved

@aram356 aram356 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Review

Summary

Found while reviewing the rc/identity integration branch (#495) and traced to this PR. Each finding was re-checked at this head (c12fd631); line numbers refer to it.

Requesting changes for two blocking findings.

Findings

Blocking

  • 🔧 Spin geo misconfiguration answers every request with 422. See spin/src/geo.rs:37.
  • 🔧 CHANGELOG: ## Unreleased has no entry for the completed Cloudflare geo or the pinned Spin KV geo lookup.

Non-blocking

  • 🤔 An early timer wake ends the Spin geo lookup. See spin/src/geo.rs.
  • 🤔 An unusable country code gets a different status per provider. Platform geo (core/src/geo.rs:399-400, outside this diff) gives Unavailable(MissingMetadata) for a well-formed code outside the snapshot, such as XK. KV geo gives Unavailable(UnsupportedGeography), and Axum CloudFront rejects the whole result as InvalidAssertion (that part is already open on #439). A portable handler that serves a "region unsupported" page on UnsupportedGeography misses those visitors on Fastly and Cloudflare. Use UnsupportedGeography here too, or document the matrix in native-geo.md.

CI Status

  • GitHub checks at c12fd631: 29 of 29 pass.

Comment thread crates/edgezero-adapter-spin/src/geo.rs Resolved
Comment thread crates/edgezero-adapter-spin/src/geo.rs Resolved
A bad geo selection is a deployment error. As a validation error, assembly answered
every visitor with 422 and the message; as an internal error it is a redacted 500.
The credential read and KV lookup treated any timer completion as the deadline. Like the
Spin config and secret reads, re-check the deadline and keep polling the same in-flight work.
@aram356

aram356 commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

CHANGELOG finding from the review: fixed in b576456. ## Unreleased has a new "Spin KV Geo and Cloudflare platform Geo" entry. It covers the settings and their defaults, the trust requirements for the geo IP and token headers, the outcome reasons, the redacted 500 on an invalid selection, and the loader. Migration notes: Spin always strips the two geo headers, and Axum rejects credential_variable.

Bring in PR #454's KV Geo review fixes and the review fixes below it,
from PR #510 down to PR #275, including PR #439's Geo sanitization,
which strips the CloudFront viewer fields for every selected Geo,
RunMode hosting, the KvOpenFailure categories and main's lockfile
versions.

CHANGELOG.md: both sides added Unreleased sections at the top. The
resolution keeps the base's sections first, then this PR's "Spin KV Geo
and Cloudflare platform Geo".

docs/guide/native-geo.md: the resolution keeps PR #439's paragraph on
what cannot admit protected CloudFront assertions. It then uses this
PR's NoSelection paragraph (unconfigured Spin, Fastly and Cloudflare
platform geography) in place of the base's older Spin wording.
Bring in PR #275's Fastly contract test fix, which expects the terminal
error body in the production key order (serde_json without
preserve_order sorts keys alphabetically). The merge is clean.
Bring in PR #275's Viceroy repair, which fails an if-generation-match
insert when the key has no live entry, so a stale generation cannot
recreate a deleted key. The merge is clean.
@aram356

aram356 commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

Round 12 identity realignment: rc/identity (#495) is now at 38cb74fe. This branch fast-forwarded from b5764560 to 51554a60:

Each merge message says what it carries and how any conflict was resolved.

@prk-Jr

prk-Jr commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator Author

Review-summary follow-ups in 0434ec0c: the existing Unreleased entry for Spin KV / Cloudflare geo is retained, with its header-stripping statement scoped to managed dispatch. The native geo guide now records the provider distinction for unsupported countries such as XK: platform geo reports MissingMetadata, KV reports UnsupportedGeography, and Axum CloudFront reports InvalidAssertion. The existing internal-500 and early-wake corrections were reverified, including a real Spin component-environment misconfiguration returning a redacted 500. No hosted checks were observed for that original correction head.

CI follow-up in b9829802: refreshed the six active pin-project-lite lock nodes from yanked 0.2.17 to non-yanked 0.2.19, preserving fresh offline scaffold resolution. The Cargo cancellation fixtures now use a scoped test-only build identity and fake compiler so unrelated source fingerprinting does not consume their five-second readiness window; production hashing and all deadline/reaping assertions remain unchanged. Mandatory five local gates, 680 harness tests (four ignored), strict standalone lint/non-test compilation, all three Wasm targets, 39 Spin contracts / 25 SDK tests, publisher and loader checks passed. Fresh 0.2.19 loader/consumer components passed actual Spin publication, replay, timeout/authentication controls, managed US/CA delivery and owned process/listener/staging cleanup. This does not qualify hosted deployment or repair the separate macOS zombie-group race. All 30 hosted checks now pass on b982980, including the current native and Wasm suites. The processed Rust CodeQL analysis has no errors, warnings or findings across 27 rules; the other configured language analyses are also clean. Both existing re-review requests are retained.

prk-Jr and others added 2 commits December 3, 2026 07:42
Bring in PR #275's lockfile update, which moves the yanked
pin-project-lite, chacha20 and yoke-derive versions to their
replacements, and PR #454's matching pin-project-lite update in the
geo-kv-prototype lockfile. Both match this PR's own updates, so the
merge is clean.
aram356 added a commit that referenced this pull request Dec 3, 2026
Take PR #515's new head, which brings the yanked-crate lockfile updates
from PR #275 and PR #454, the owner updates on PR #509, #512, #515 and
#519, and PR #514's Spin geo hardening through PR #517.
aram356 added a commit that referenced this pull request Dec 3, 2026
Take PR #464's new head, which carries the lockfile updates and PR
#514's Spin geo hardening through PR #517.
@aram356

aram356 commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator

Round 15 identity realignment: rc/identity is now at ef5cbf308. This branch fast-forwarded from b9829802b to 1b6c80d49:

Each merge message says what it carries and how any conflict was resolved.

The setting now drops the manifest's geo fields, as on Axum, instead of rejecting them and answering every request with a 500.
Credential, binding, timeout and store failures were indistinguishable ProviderFailure outcomes; a fixed-reason warning names them without request values.
@aram356

aram356 commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator

Review follow-up: fixes committed to this branch

A full review of this PR turned up the problems below; each would otherwise have needed a follow-up ticket, so it is fixed on this branch instead. Every item names its commit.

  • EDGEZERO__ADAPTER__GEO__PROVIDER=off could not turn off a baked Spin KV selection. Setting off over a baked provider = "kv" rejected the manifest's own store_id, pin, reader_ip and credential_variable, so every route (health checks included) answered a redacted 500: the documented kill switch caused an outage. e48037d applies Axum's rule: a setting that switches providers carries over none of the manifest's geo fields. Settings off now yields no selection; other EDGEZERO__ADAPTER__GEO__* settings beside off still fail assembly, and a manifest off with source keys is still rejected. Guide and CHANGELOG updated; kv_selection_uses_manifest_and_validated_overrides covers the three cases.
  • Spin KV geo deployment failures left no signal. A missing or malformed credential variable, a missing pinned manifest, a failed KV read and a timeout all became the same ProviderFailure with nothing logged, and the guide claimed configuration errors fail assembly. da8a13d logs event=geo_lookup_failed reason=credential|binding|timeout|store on edgezero::boot (the same event vocabulary as the Axum KV provider), once per reason per component instance, never including the visitor IP, token, store key or error text; untrusted or incomplete visitor input still logs nothing. Spin keeps no state between instances, so there is no recovery event; the guide states the dedupe operators can expect and corrects the assembly sentence. deployment_failures_log_a_fixed_reason_once asserts exactly one fixed line per failure class across two identical failures and none for a wrong token or missing IP.

Fixes made on the PRs below this one in the stack were merged into this branch with merge commits. 5ba992f adapts the merged #510 Spin record-requirement test to this branch's dispatch signature (GeoSecret::missing()).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Geo with country and region through ctx.geo() on Spin Geo with country and region through ctx.geo() on Cloudflare

4 participants