Repository navigation
Conversation
#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.
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.
|
For the identity integration branch (#495), I pushed
|
|
For the identity integration branch (#495), I pushed |
|
For the identity integration branch (#495), I pushed |
PR #524 (outbound mTLS client identities, #523) belongs to no identity epic, and PR #522 (portable DynamoDB and celld record providers on Fastly, #474) is still a draft. #524 is stacked on #522, so both leave together. This commit reverts their net changes. Its tree is rc/identity as it was before #522 (654f546) merged with the current tips of #519, #515, #502, #469 and #536, the branch's remaining lines. #514 and #517 are already inside them. The rebuild merges without conflicts, and the change touches only the 113 paths that #522 and #524 changed against #517. Three files differed from a plain reverse of the two PRs because of the conflict resolutions in 7616c85 and b3a45df. Each keeps the other lines' code and drops only #522's or #524's: - crates/edgezero-adapter-axum/src/cli.rs keeps the capability matrix test's lint expectation and drops #524's client identity test. - crates/edgezero-adapter-fastly/src/request.rs keeps the after-response handle and wrapper and drops #522's deferred portable KV registry. - crates/edgezero-store-aws/src/dynamodb_records_tests.rs drops imports used only by #522's tests. Merging a later tip of #522 or #524 will not restore this code, because git treats their earlier commits as already merged. Bringing them back needs a revert of this commit first.
dhruv8sh
left a comment
There was a problem hiding this comment.
This PR does two things:
- Cloudflare: managed dispatch now exposes
cfmetadata throughctx.geo(). A per-request test covers all three entrypoints, including theXX/T1placeholder values, spoofed headers and country-only cases. - Spin: adds a pinned KV geo lookup, gated on an authenticated visitor-IP header. The private headers are stripped after their original bytes are counted toward head limits, so admission callbacks and handlers never see them. The credential is read only after admission, with a 128-byte bound, and compared in constant time. The KV lookup shares one aggregate deadline with the admitted request deadline and drops pending futures when it times out.
Configuration is validated in several places:
- Unknown override keys are rejected.
- Axum rejects
credential_variable. - Spin rejects Axum-only fields.
provider = "off"cannot carry leftover source settings.
dispatch_app and run_app both resolve the selection through SpinKvGeo::from_config. The tests cover:
- token and IP parsing edge cases, including duplicates, ports, zone identifiers and IPv4-mapped IPv6 addresses
- that serving never writes to KV
- the aggregate budget
- dropping pending work on timeout
- no secret read before admission
Non-blocking points:
- Per-request config check:
from_configruns on everydispatch_appcall, so a bad configuration shows up as a per-request assembly error rather than failing at startup. - Per-request cost: each authenticated request re-reads the manifest, both roots and the secret. The docs say this, but it is worth load-testing before production.
- CI exception: the
deploy-coretest that admits one Python command in CI is narrowly scoped and has negative tests.
I found nothing that blocks merging. I could not run the CI gates because this review has read-only access. I only skimmed the loader example and the plan/spec docs.
dhruv8sh
left a comment
There was a problem hiding this comment.
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 privatex-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::resolvetakes one absolute KV deadline, capped by the admitted read deadline, and doesn't reset it between stages. TheAdvancingKvtest (four reads of 80 ms against a 250 ms budget) and the pending-read drop test show this precisely.from_configrejects unknownEDGEZERO__ADAPTER__GEO__*keys through the new value-freeEnvConfig::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_appanddispatch_app.
Findings
Blocking
None.
Non-blocking
- 🤔 Token comparison short-circuits on length:
subtle's slicect_eqreturns 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 upbinds 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_requestconverter 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.erroris used but never imported: it only works becauseurllib.requesthappens to import it (examples/geo-spin-loader/load.py:148).
📌 Out of Scope
- The new
run.shexception narrowly admits one exactpython3 -m unittestcommand intest.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.
| let Some(expected) = read_value.filter(|value| ingress::valid_token(value)) else { | ||
| return failure(); | ||
| }; | ||
| if !bool::from(token.as_ref().ct_eq(expected.as_ref())) { |
There was a problem hiding this comment.
🤔 Length leak in constant-time compare: <[u8] as ConstantTimeEq>::ct_eq returns 0 immediately when the lengths differ. Timing can therefore reveal the expected credential's length (a value from 32 to 128) even though the content comparison is constant-time. The impact is small, but you can remove it cheaply by comparing fixed-size digests, or by padding both sides to 128 bytes and checking the lengths with ct_eq too:
let mut a = [0u8; 128];
let mut b = [0u8; 128];
a[..token.len()].copy_from_slice(&token);
b[..expected.len()].copy_from_slice(&expected);
let same = a.ct_eq(&b) & (token.len() as u64).ct_eq(&(expected.len() as u64));
if !bool::from(same) { return untrusted(); }The same pattern appears in examples/geo-spin-loader/src/lib.rs (authenticated).
| raise ValueError("runtime configuration must explicitly define the selected store") | ||
| if binding.get("type") == "spin" and not Path(binding.get("path", "")).is_absolute(): | ||
| raise ValueError("local Spin storage requires an absolute database path") | ||
| with socket.socket() as listener: |
There was a problem hiding this comment.
🤔 Port-reservation race can send the token to another local listener: the socket is bound and then closed before spin up starts. In that window, any local process can bind the same port. The readiness loop accepts any TCP accept, and the POST then sends x-edgezero-loader-token to whoever is listening. The token is ephemeral, but in that case the publication goes to the wrong process.
One way to narrow this: after readiness, check that process.poll() is None and require the loader to identify itself, for example a GET /ready that returns a nonce passed through a second Spin variable. Alternatively, retry with a fresh port if spin up exits early with an address-in-use error. At minimum, document the assumption that the host is single-tenant.
| - A valid dataset gap: `NoMatch`; a source country unsupported by core: `UnsupportedGeography`. | ||
| - A country without subdivision remains country-only. | ||
|
|
||
| The adapter strips both private headers before admission, middleware and handlers, |
There was a problem hiding this comment.
🤔 The stripping guarantee is broader than the code: only the managed path (dispatch_ingress_stream_with_timer_and) calls capture_inputs. The public unmanaged request::into_core_request converter still passes x-edgezero-geo-token and x-edgezero-geo-ip through to handler code. Please either scope this sentence to managed dispatch (run_app / run_app_with_platform / dispatch_app), or also strip the headers in into_core_request so a handler using the low-level converter can't accidentally log the credential.
| return Ok(deliver(egress)?); | ||
| } | ||
| }; | ||
| let geo = match stores.geo.as_ref() { |
There was a problem hiding this comment.
🌱 Eager resolution on every authenticated request: when geo is configured, every admitted request that carries a valid-syntax token performs one secret read plus a manifest read, two root checks and the lookup. This happens before routing, whether or not the handler ever calls ctx.geo(). It also spends part of the admitted body-read budget. The docs cover this, so it doesn't block the PR. A later improvement could resolve lazily on first ctx.geo() access, or let routes opt in, so health checks and static routes don't pay for the KV reads.
| raise SystemExit(130) from None | ||
| except TimeoutError: | ||
| parser.exit(1, "loader readiness or publication deadline exceeded\n") | ||
| except urllib.error.HTTPError as error: |
There was a problem hiding this comment.
⛏ Implicit urllib.error import: urllib.error.HTTPError resolves only because urllib.request imports urllib.error internally. Please add import urllib.error at the top so the dependency is explicit.
ChristianPavilonis
left a comment
There was a problem hiding this comment.
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.
| expired.set() | ||
| if process.poll() is None: | ||
| try: | ||
| process.kill() |
There was a problem hiding this comment.
R1 · P1: Publication timeout can leave Spin running. This kills only the spin up PID. Spin 4.1 spawns the HTTP trigger separately, so a hard kill can leave the trigger listening or publishing after the runner returns a timeout. Spin also stages its own copy of the mounted files outside the runner's cleanup directory. The single-process fake only proves the launcher exits. Please supervise an owned process group through shutdown and escalation, put the Spin working directory under the runner's temp root, and check listener and artifact cleanup.
| headers={"x-edgezero-loader-token": token}, | ||
| ) | ||
| # The secret stays in process memory/environment, never argv or a log. | ||
| opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) |
There was a problem hiding this comment.
R2 · P1: The loader does not verify that it owns the listener. The runner gives up the reserved port before Spin binds. A successful TCP connection then counts as readiness, so a different local listener can receive the credential and its JSON response can be mistaken for a publication report. The default opener also follows redirects with the custom header. Please use port zero and read Spin's actual bound address from the child, reject redirects, and validate the report's count and pin fields.
| resolver.lookup(ip).await | ||
| }; | ||
| let lookup_remaining = deadline.instant().saturating_duration_since(clock.now()); | ||
| match select(Box::pin(lookup), Box::pin(make_timer(lookup_remaining))).await { |
There was a problem hiding this comment.
R3 · P2: The KV lookup can start another read after its deadline. select polls lookup first. A pending read that becomes ready after expiry can resume the resolver and start another root or path read before the final clock check. The aggregate test checks that late results are rejected, not that no new read starts. Arm the timer before polling lookup and check the same absolute deadline before each new backend read. This does not require host-side cancellation.
| executable = shutil.which(spin) | ||
| if executable is None: | ||
| raise ValueError("Spin executable not found") | ||
| spin = str(Path(executable).resolve()) |
There was a problem hiding this comment.
R4 · P2: Resolving the executable breaks PATH shims. Following a symlink-based shim here can replace the Spin entry point with a dispatcher that relies on the invoked name. The temporary cwd in Popen can also lose project-local version selection. The relative executable test exercises a regular file. Make the selected path absolute without dereferencing it, and keep the caller's cwd when launching with the already absolute manifest and config paths.
| pub receipt: Receipt, | ||
| pub inventory: Vec<InventoryEntry>, | ||
| #[cfg(any(test, feature = "celld", feature = "dynamodb"))] | ||
| #[cfg(any(test, feature = "publisher", feature = "celld", feature = "dynamodb"))] |
There was a problem hiding this comment.
R5 · Architecture: Keep the validated artifact immutable. The new library exports a mutable receipt and inventory, while Artifact::open validates a separate private snapshot. A consumer can remove entries after validation and publish can write the manifest without all its descendants. The current loader does not mutate it. Please make the fields private with read-only accessors, and format the loader's pin from the verified generation and digest rather than splitting the storage key. This preserves both on-disk formats.
| .map(|provider| match provider { | ||
| ManifestGeoProvider::Kv => "kv", | ||
| ManifestGeoProvider::Off => "off", | ||
| ManifestGeoProvider::CloudFront | _ => "unsupported", |
There was a problem hiding this comment.
R12 · Maintenance: Keep the typed provider through config merge. Parse the environment override once, keep the manifest enum as the fallback, and match the merged enum. This removes string round-tripping and the "unsupported" sentinel without changing precedence.
| secret: Option<Bytes>, | ||
| reads: Option<Arc<AtomicUsize>>, | ||
| ) -> anyhow::Result<ResponseEgressEnvelope> { | ||
| dispatch_request_with_geo_stores(app, req, secret, reads, None).await |
There was a problem hiding this comment.
R13 · Maintenance: Remove the forwarding test helper. This only calls dispatch_request_with_geo_stores with a final None. The two callers can use the store-aware helper directly without losing any injection coverage.
| fn validate_manifest_adapter_geo(geo: &ManifestAdapterGeo) -> Result<(), ValidationError> { | ||
| let assertion = geo.alb_peer_cidrs.is_some() || geo.origin_credential_header_name.is_some(); | ||
| let kv = geo.has_kv_fields(); | ||
| let kv = geo.has_kv_fields() || geo.credential_variable.is_some(); |
There was a problem hiding this comment.
R14 · Style: The Spin off-policy diagnostic points to Axum. The message immediately below names [adapters.axum.geo] even when Spin's table is the one rejected. Make it adapter-neutral and retain the current error code and rejection.
| } | ||
|
|
||
| #[cfg(test)] | ||
| #[path = "geo/kv_tests.rs"] |
There was a problem hiding this comment.
R15 · Style: The Spin geo unit tests depart from the same-file convention. CLAUDE.md:159 calls for inline unit tests. Inline these tests or document a deliberate exception for the large fixture. The public contract tests are unaffected.
| Ok(report) => response(StatusCode::OK, report.to_string()), | ||
| Err(_) => response( | ||
| StatusCode::INTERNAL_SERVER_ERROR, | ||
| "{\"error\":\"publication failed\"}".into(), |
There was a problem hiding this comment.
R16 · Style: Use structured JSON for the loader errors. The 401 and 500 bodies are ordinary JSON, not serialization fallbacks. Use the same serde_json::json! convention as the success response, keeping the fixed messages and status codes.
| "{\"error\":\"publication failed\"}".into(), | |
| serde_json::json!({"error": "publication failed"}).to_string(), |
aram356
left a comment
There was a problem hiding this comment.
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:
## Unreleasedhas 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) givesUnavailable(MissingMetadata)for a well-formed code outside the snapshot, such asXK. KV geo givesUnavailable(UnsupportedGeography), and Axum CloudFront rejects the whole result asInvalidAssertion(that part is already open on #439). A portable handler that serves a "region unsupported" page onUnsupportedGeographymisses those visitors on Fastly and Cloudflare. UseUnsupportedGeographyhere too, or document the matrix innative-geo.md.
CI Status
- GitHub checks at
c12fd631: 29 of 29 pass.
| } | ||
|
|
||
| fn invalid_selection() -> EdgeError { | ||
| EdgeError::validation("invalid Spin KV geo selection") |
There was a problem hiding this comment.
🔧 Operator configuration errors reach every visitor as 422
A bad KV geo setting or pin becomes EdgeError::validation. lib.rs:268-277 passes it to send_assembly_error, which renders it with error.status() through App::assembly_error_egress, so every request returns 422 with the message. The same misconfiguration is a 500 on Cloudflare and a refusal to start on Axum. Return EdgeError::internal for deployment and configuration failures, and keep 4xx for request-derived ones. #517's client-source check has the same problem.
There was a problem hiding this comment.
Fixed in 7fa6e65. Every error on the SpinKvGeo::from_config path goes through invalid_selection(), which now returns EdgeError::internal. A misconfigured selection therefore answers a redacted 500 instead of a 422 carrying the message. kv_selection_uses_manifest_and_validated_overrides asserts 500 for every rejection case. #517 still has its own copy of the old function until this merges forward.
| .instant() | ||
| .saturating_duration_since(clock.now()); | ||
| let read_value = match select(Box::pin(secret), Box::pin(make_timer(remaining))).await { | ||
| Either::Left((Ok(read), _)) if !admitted_deadline.is_expired_at(clock.now()) => { |
There was a problem hiding this comment.
🤔 An early timer wake ends the lookup as if the deadline passed
The credential read (:268-276) and the KV lookup (:316-332) each race a timer and treat any timer completion as the deadline. The Spin config and secret reads (config_store.rs:208-219) re-check is_expired_at when the timer fires and loop if time remains. If the wasi timer fires early, this reports a provider failure with budget left. Use the same re-check loop.
There was a problem hiding this comment.
Fixed in dff35ad. A private before_deadline helper pins the in-flight future once, and when a timer fires early it re-checks the remaining time and re-arms, as config_store.rs does. Both the credential read and the KV lookup use it. early_timer_wakes_rearm_and_keep_in_flight_reads covers it with timers that fire immediately on their first arm. Merging this forward into #517 needs care: #517 splits resolve into authenticate and lookup, and both races there need the helper.
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.
|
CHANGELOG finding from the review: fixed in b576456. |
Summary
ctx.geo()coverage with Cloudflare request metadata and Spin lookup against an explicitly pinned KV dataset.Stacked on #454 (
feature/kv-geoip), which already includes #502. The portable KV reader and Axum foundation are supplied by those parents.Integration note: a current
git merge-treecomparison with #496 reports conflicts in Axum response conversion, Cloudflare/Spin contracts, and core error/extractor code. These siblings need reconciliation when integrated.Changes
edgezero-adapter-spinedgezero-coreedgezero-adapter-axumexamples/geo-kv-prototypeexamples/geo-spin-loaderSpin 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; it does not need to supply geography. Both roots and the selected path are verified on each request. Geo errors remain application policy inputs and do not independently grant permission or select HTTP status. No automatic fallback is added.
Closes
closes #480
closes #486
This PR targets
feature/kv-geoip, so merging it into that branch does not automatically close the linked issue(s); close them manually or upon default-branch integration.Test plan
Historical author-reported local verification below (original head unrecorded unless an explicit SHA is given). These results, counts, timings and negative controls were not rerun in this audit, and their underlying local logs were unavailable; checked boxes retain the original report. At the current head
ec0b912b, all 29 reported hosted checks are passing.cargo test --workspace --all-targets(3,058 passed; nine ignored)cargo clippy --workspace --all-targets --all-features -- -D warningscargo fmt --all -- --checkcargo check --workspace --all-targets --features "fastly cloudflare spin"examples/app-demo(68 tests + three WASM checks), 32 native feature combinations, 199 tooling tests, generated consumer, and isolated serial harness (679 passed; four ignored)Additional diagnostic: native
cargo build --workspace --all-targets --all-featurescannot link Fastly SDK host imports on ARM64. The same failure is reproduced on unchanged base925fe019; the supported Fastly WASM suite passes all 362 tests using the prescribed CI runner.Checklist
CLAUDE.mdconventions{id}syntaxedgezero_coreKvRegistryLocal synthetic runtime evidence does not qualify hosted proxy protection, external backend permissions/propagation, geography accuracy or production capacity. Spin SDK reads materialize values before core validates size; guest deadlines do not certify host-side cancellation. The request-local cache repeats manifest/root reads, so operators must qualify backend latency and capacity. Publication assumes one operator per generation; ordinary read-before-write is not a distributed lock.