diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index be1e649b1..8ac815209 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -70,6 +70,7 @@ jobs:
run: |
cargo fetch --locked
cargo fetch --locked --manifest-path examples/app-demo/Cargo.toml
+ cargo fetch --locked --manifest-path examples/geo-kv-prototype/Cargo.toml
cargo fetch --locked --manifest-path crates/edgezero-test-harness/fixtures/reusable-app/Cargo.toml
cargo fetch --locked --manifest-path crates/edgezero-test-harness/Cargo.toml
cargo fetch --locked --manifest-path crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.toml
@@ -215,6 +216,18 @@ jobs:
- name: Native Geo real-peer hosting (loopback only)
run: scripts/run_test_nonzero.sh geo_hosting_proves_real_peer_and_shared_outcome cargo test --offline --locked -p edgezero-adapter-axum --no-default-features --features geo-cloudfront,test-utils --test production_hosting geo_hosting_proves_real_peer_and_shared_outcome
+ - name: Portable KV Geo and managed listener (loopback only)
+ if: matrix.suite == 'workspace'
+ run: |
+ cargo fmt --manifest-path examples/geo-kv-prototype/Cargo.toml -- --check
+ cargo clippy --offline --locked --manifest-path examples/geo-kv-prototype/Cargo.toml --all-targets --all-features -- -D warnings
+ cargo test --offline --locked --manifest-path examples/geo-kv-prototype/Cargo.toml
+ cargo test --offline --locked --manifest-path examples/geo-kv-prototype/Cargo.toml --all-features
+ node --test scripts/run_geo_kv_integration.test.mjs
+ cargo test --offline --locked -p edgezero-core --features geo-kv-build --lib geo::kv
+ cargo check --offline --locked -p edgezero-core --no-default-features --features geo-kv --target wasm32-unknown-unknown
+ scripts/run_test_nonzero.sh kv_geo_listener_checks_reader_provenance_and_pinned_objects cargo test --offline --locked -p edgezero-adapter-axum --features geo-kv,geo-cloudfront,test-utils --test production_hosting kv_geo
+
- name: Native Geo public examples
run: cargo test --offline --locked -p edgezero-adapter-axum --features geo-cloudfront --doc
diff --git a/crates/edgezero-adapter-axum/Cargo.toml b/crates/edgezero-adapter-axum/Cargo.toml
index fd8a2c15f..27626db40 100644
--- a/crates/edgezero-adapter-axum/Cargo.toml
+++ b/crates/edgezero-adapter-axum/Cargo.toml
@@ -39,6 +39,7 @@ aws-dynamodb-records = ["aws-dynamodb", "edgezero-store-aws/dynamodb-records"]
celld-kv = ["axum", "edgezero-store-celld/kv"]
celld-records = ["celld-kv", "edgezero-store-celld/records"]
geo-cloudfront = ["axum"]
+geo-kv = ["axum", "edgezero-core/geo-kv"]
cli = [
"native-bindings",
"dep:edgezero-adapter",
@@ -121,7 +122,7 @@ required-features = ["celld-kv", "test-utils"]
async-trait = { workspace = true }
axum = { workspace = true, features = ["macros"] }
edgezero-adapter-cloudflare = { path = "../edgezero-adapter-cloudflare", default-features = false }
-edgezero-core = { path = "../edgezero-core", features = ["test-utils"] }
+edgezero-core = { path = "../edgezero-core", features = ["test-utils", "geo-kv-build"] }
flate2 = { workspace = true }
http-body = { workspace = true }
httparse = { workspace = true }
diff --git a/crates/edgezero-adapter-axum/src/dev_server.rs b/crates/edgezero-adapter-axum/src/dev_server.rs
index 426982332..26271a760 100644
--- a/crates/edgezero-adapter-axum/src/dev_server.rs
+++ b/crates/edgezero-adapter-axum/src/dev_server.rs
@@ -28,7 +28,8 @@ use crate::diagnostics::{NativeDiagnosticsHandle, NativeSession};
use crate::outbound_executor::{AxumOutboundExecutor, AxumOutboundExecutorHandle};
pub use crate::run_options::AxumRunOptions;
use crate::run_options::{
- JsonBodyLimit, config_path, failure, native_limit_setting, native_settings, shutdown_grace,
+ JsonBodyLimit, config_path, failure, geo_setting, native_limit_setting, native_settings,
+ shutdown_grace,
};
use crate::trusted_proxy::TrustedProxyPolicy;
use anyhow::Context as _;
@@ -51,6 +52,7 @@ use edgezero_core::config_store::{ConfigStoreError, ConfigStoreHandle, ConfigSto
use edgezero_core::env_config::EnvConfig;
use edgezero_core::key_value_store::KvHandle;
use edgezero_core::logging::{BOOT_LOG_LEVEL, BOOT_LOG_TARGET, resolve_logging_level};
+use edgezero_core::manifest::BakedManifest;
#[cfg(test)]
use edgezero_core::router::RouterService;
use edgezero_core::secret_store::SecretHandle;
@@ -66,7 +68,7 @@ use tokio::time::{Instant as NativeInstant, sleep_until};
use crate::config_store::AxumConfigStore;
use crate::config_store_limits::ConfigStoreLimits;
use crate::connection::{ConnectionExit, serve_http1_with_shutdown};
-use crate::geo::NativeGeo;
+use crate::geo::{self, NativeGeo};
use crate::ingress_config::AxumIngressConfig;
use crate::key_value_store::PersistentKvStore;
use crate::native_stores::{self, NativeSourcePlan, NativeStoreOverrides, NativeStoreSource};
@@ -1059,7 +1061,10 @@ where
A: Hooks,
F: FnOnce() -> anyhow::Result<()>,
{
- let (env, json_body_limit, native) = capture_dev_environment(vars_os())?;
+ let (env, json_body_limit, mut native) = capture_dev_environment(vars_os())?;
+ // The dev server ignores the manifest table: its deployment-only values are
+ // usually absent locally. Settings alone opt a dev run into geo.
+ let geo = geo::resolve(None, &env, &BakedManifest::Absent)?;
if !A::owns_logging() {
app_logger(&env)
.init()
@@ -1094,6 +1099,8 @@ where
config: build_config_registry(metadata.config, &env, config_limits)?,
secrets: build_secret_registry(metadata.secrets, &env),
};
+ let max_object_bytes = geo.max_object_bytes(None)?;
+ native.geo = geo.prepare(stores.kv(), max_object_bytes).await?;
prepare_transport(app, stores, json_body_limit, native)
},
)
@@ -1120,7 +1127,7 @@ where
["adapter", "trusted_proxy_cidrs"] => Some("TRUSTED_PROXY_CIDRS"),
["adapter", "forwarding_header_family"] => Some("FORWARDING_HEADER_FAMILY"),
["logging", "request_records"] => Some("LOGGING__REQUEST_RECORDS"),
- _ => None,
+ _ => geo_setting(&path),
}
})
});
@@ -1319,12 +1326,12 @@ where
&'startup PreparedStores,
) -> LocalStartupFuture<'startup>,
{
- let geo = options.native_geo()?;
- let native = NativeHosting {
+ let geo = options.native_geo(&A::manifest())?;
+ let mut native = NativeHosting {
diagnostics: options.diagnostics(),
policy: options.trusted_proxy_policy(),
request_records: options.request_records(),
- geo,
+ geo: NativeGeo::default(),
};
run_local(
ListenerSource::Bind(options.addr()),
@@ -1335,6 +1342,7 @@ where
async move {
let metadata = A::stores();
let sources = NativeSourcePlan::validate(metadata, &options, overrides)?;
+ let max_object_bytes = geo.max_object_bytes(Some(&sources))?;
init_logging::(options.logging_level())?;
let mut app = App::build::(crate::AXUM_PLATFORM)
.map_err(|_error| anyhow::anyhow!("application configuration failed"))?;
@@ -1345,6 +1353,7 @@ where
app.record_store_requirements(),
)
.await?;
+ native.geo = geo.prepare(stores.kv(), max_object_bytes).await?;
let transport = AxumOutboundClient::try_transport()
.map_err(|_error| failure("transport", "HTTP client", "initialization failed"))?;
initialize(&mut app, &stores).await.map_err(|error| {
diff --git a/crates/edgezero-adapter-axum/src/geo.rs b/crates/edgezero-adapter-axum/src/geo.rs
index 4d3f86557..4731373bf 100644
--- a/crates/edgezero-adapter-axum/src/geo.rs
+++ b/crates/edgezero-adapter-axum/src/geo.rs
@@ -4,7 +4,9 @@
//! is not proof of an ALB credential rule or a particular `CloudFront` distribution.
//! See the native Geo guide for the required network, header and cache controls.
//!
-//! Off is valid and is the default, with no ambient Geo selector:
+//! Off is valid and is the default. Without an explicit selection the runner reads
+//! `EDGEZERO__ADAPTER__GEO__*` settings, then the app's `[adapters.axum.geo]` manifest table.
+//! An explicit selection overrides both:
//! ```
//! use edgezero_adapter_axum::dev_server::AxumRunOptions;
//! use edgezero_adapter_axum::geo::{NativeGeoCapability, NativeGeoSelection};
@@ -78,6 +80,9 @@
//! GeoOutcome::Selected { status, .. } => match status {
//! GeoStatus::Unavailable(GeoUnavailableReason::UntrustedIngress) => "source not admitted",
//! GeoStatus::Unavailable(GeoUnavailableReason::MissingMetadata) => "metadata missing",
+//! GeoStatus::Unavailable(GeoUnavailableReason::MissingReaderIp) => "no checked reader",
+//! GeoStatus::Unavailable(GeoUnavailableReason::NoMatch) => "no geographic coverage",
+//! GeoStatus::Unavailable(GeoUnavailableReason::UnsupportedGeography) => "unknown country code",
//! GeoStatus::Error(GeoError::InvalidAssertion) => "assertion rejected",
//! GeoStatus::Error(GeoError::ProviderFailure) => "provider failed",
//! GeoStatus::Located { location, .. } if location.subdivision().is_none() => "country only",
@@ -92,7 +97,7 @@
reason = "public composition types precede private request-bound resolution and tests"
)]
#![cfg_attr(
- feature = "geo-cloudfront",
+ any(feature = "geo-cloudfront", feature = "geo-kv"),
expect(
clippy::self_named_module_files,
reason = "repo convention uses geo.rs with submodules under geo/, not mod.rs"
@@ -106,14 +111,26 @@ use std::fmt;
use std::net::SocketAddr;
use std::sync::Arc;
+use edgezero_core::env_config::EnvConfig;
use edgezero_core::geo::{
GeoAssertion, GeoInput, GeoOutcome, GeoProvider, GeoProviderId, GeoResolution, GeoSource,
GeoStatus, GeoTrustBasis, GeoUnavailableReason,
};
use edgezero_core::http::{HeaderMap, HeaderName};
+use edgezero_core::manifest::{BakedManifest, ManifestAdapterGeo, ManifestGeoProvider};
+use edgezero_core::store_registry::KvRegistry;
+
+use crate::diagnostics::NativeIngressMetadata;
+use crate::native_stores::NativeSourcePlan;
use crate::peer_networks::PeerNetworks;
+/// Native KV Geo selection and checked reader-IP policy.
+#[cfg(feature = "geo-kv")]
+pub mod kv;
+#[cfg(feature = "geo-kv")]
+use kv::{KvGeoReaderIp, KvGeoSelection};
+
/// Bounded startup configuration categories. No policy inputs are retained.
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum NativeGeoConfigError {
@@ -125,6 +142,16 @@ pub enum NativeGeoConfigError {
UnavailableCloudFront,
#[error("native_geo: reserved supplied provider identity")]
ReservedProviderId,
+ #[error("native_geo: invalid provider selection")]
+ InvalidSelection,
+ #[error("native_geo: KV implementation unavailable")]
+ UnavailableKv,
+ #[error("native_geo: selected KV binding is undeclared or unavailable")]
+ MissingKvBinding,
+ #[error("native_geo: KV preparation deadline")]
+ KvPreparationDeadline,
+ #[error("native_geo: pinned KV data could not be prepared")]
+ KvPreparationFailed,
}
/// An operator declaration of a credential-gated, isolated CloudFront/ALB path.
@@ -201,6 +228,8 @@ impl fmt::Debug for ProtectedCloudFrontAlb {
pub enum NativeGeoSelection {
#[default]
Off,
+ #[cfg(feature = "geo-kv")]
+ Kv(KvGeoSelection),
CloudFront {
policy: ProtectedCloudFrontAlb,
},
@@ -216,6 +245,8 @@ impl fmt::Debug for NativeGeoSelection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Off => f.write_str("Off"),
+ #[cfg(feature = "geo-kv")]
+ Self::Kv(selection) => fmt::Debug::fmt(selection, f),
Self::CloudFront { policy } => f
.debug_struct("CloudFront")
.field("policy", policy)
@@ -240,11 +271,254 @@ pub enum NativeGeoCapability {
},
}
+/// Resolves the startup selection: an explicit [`AxumRunOptions::with_geo`] wins,
+/// then `EDGEZERO__ADAPTER__GEO__*` settings, then the baked `[adapters.axum.geo]`
+/// table. With none of them geo stays off.
+///
+/// [`AxumRunOptions::with_geo`]: crate::run_options::AxumRunOptions::with_geo
+pub(crate) fn resolve(
+ explicit: Option<&NativeGeoSelection>,
+ env: &EnvConfig,
+ manifest: &BakedManifest,
+) -> Result {
+ let configured = match explicit {
+ Some(selection) => selection.clone(),
+ None => configured_selection(env, manifest_geo(manifest))?,
+ };
+ #[cfg(feature = "geo-kv")]
+ if let NativeGeoSelection::Kv(selection) = configured {
+ return Ok(NativeGeoPlan::Kv(selection));
+ }
+ NativeGeo::validate(&configured).map(NativeGeoPlan::Ready)
+}
+
+fn manifest_geo(baked: &BakedManifest) -> Option<&ManifestAdapterGeo> {
+ // An absent or malformed manifest selects nothing; app building rejects malformed.
+ let BakedManifest::Present(manifest) = baked else {
+ return None;
+ };
+ let (_name, adapter) = manifest.adapter_entry("axum")?;
+ adapter.geo.as_ref()
+}
+
+fn configured_selection(
+ env: &EnvConfig,
+ defaults: Option<&ManifestAdapterGeo>,
+) -> Result {
+ let env_provider = env.get(&["adapter", "geo", "provider"]);
+ let env_networks = env.get(&["adapter", "geo", "alb_peer_cidrs"]);
+ let env_header = env.get(&["adapter", "geo", "origin_credential_header_name"]);
+ let provider = match env_provider {
+ Some("cloudfront") => Some(ManifestGeoProvider::CloudFront),
+ Some("kv") => Some(ManifestGeoProvider::Kv),
+ Some("off") => Some(ManifestGeoProvider::Off),
+ Some(_) => return Err(NativeGeoConfigError::InvalidSelection),
+ None => defaults.and_then(|geo| geo.provider),
+ };
+ let kv_keys = [
+ "store_id",
+ "pin",
+ "reader_ip",
+ "lookup_timeout_ms",
+ "max_in_flight",
+ ];
+ let has_env_kv = kv_keys
+ .into_iter()
+ .any(|key| env.get(&["adapter", "geo", key]).is_some());
+ if (provider != Some(ManifestGeoProvider::Kv) && has_env_kv)
+ || (provider == Some(ManifestGeoProvider::Kv)
+ && (env_networks.is_some() || env_header.is_some()))
+ {
+ return Err(NativeGeoConfigError::InvalidSelection);
+ }
+ // When settings switch providers, only their own fields may carry over.
+ let manifest = defaults.filter(|geo| geo.provider.is_none() || geo.provider == provider);
+ match provider {
+ Some(ManifestGeoProvider::Kv) => configured_kv(env, manifest),
+ Some(ManifestGeoProvider::CloudFront) => {
+ if manifest.is_some_and(ManifestAdapterGeo::has_kv_fields) {
+ return Err(NativeGeoConfigError::InvalidSelection);
+ }
+ let networks: Vec<&str> = match env_networks {
+ Some(raw) => raw.split(',').map(str::trim).collect(),
+ None => manifest
+ .and_then(|geo| geo.alb_peer_cidrs.as_deref())
+ .unwrap_or_default()
+ .iter()
+ .map(String::as_str)
+ .collect(),
+ };
+ let header = env_header
+ .or_else(|| manifest?.origin_credential_header_name.as_deref())
+ .ok_or(NativeGeoConfigError::InvalidCredentialHeader)?;
+ let policy = ProtectedCloudFrontAlb::new(networks, header)?;
+ Ok(NativeGeoSelection::CloudFront { policy })
+ }
+ // Policy without a selected provider is a misconfiguration, not a silent
+ // off. A manifest CloudFront default may still be overridden to off.
+ _ if env_networks.is_some()
+ || env_header.is_some()
+ || (provider.is_none()
+ && manifest.is_some_and(|geo| {
+ geo.alb_peer_cidrs.is_some()
+ || geo.origin_credential_header_name.is_some()
+ || geo.has_kv_fields()
+ })) =>
+ {
+ Err(NativeGeoConfigError::InvalidSelection)
+ }
+ _ => Ok(NativeGeoSelection::Off),
+ }
+}
+
+fn configured_kv(
+ env: &EnvConfig,
+ manifest: Option<&ManifestAdapterGeo>,
+) -> Result {
+ #[cfg(not(feature = "geo-kv"))]
+ {
+ let _: (&EnvConfig, Option<&ManifestAdapterGeo>) = (env, manifest);
+ Err(NativeGeoConfigError::UnavailableKv)
+ }
+ #[cfg(feature = "geo-kv")]
+ {
+ use NativeGeoConfigError::InvalidSelection;
+ if manifest.is_some_and(|geo| {
+ geo.alb_peer_cidrs.is_some() || geo.origin_credential_header_name.is_some()
+ }) {
+ return Err(InvalidSelection);
+ }
+ let get = |key| env.get(&["adapter", "geo", key]);
+ let reader_ip = match get("reader_ip").or_else(|| manifest?.reader_ip.as_deref()) {
+ Some("direct-peer") => KvGeoReaderIp::DirectPeer,
+ Some("forwarded-required") => KvGeoReaderIp::ForwardedRequired,
+ _ => return Err(InvalidSelection),
+ };
+ let timeout = match get("lookup_timeout_ms") {
+ Some(raw) => raw.parse().ok(),
+ None => manifest.and_then(|geo| geo.lookup_timeout_ms),
+ }
+ .ok_or(InvalidSelection)?;
+ let max_in_flight = match get("max_in_flight") {
+ Some(raw) => raw.parse().ok(),
+ None => manifest.and_then(|geo| geo.max_in_flight),
+ }
+ .ok_or(InvalidSelection)?;
+ let selection = KvGeoSelection::new(
+ get("store_id")
+ .or_else(|| manifest?.store_id.as_deref())
+ .ok_or(InvalidSelection)?,
+ get("pin")
+ .or_else(|| manifest?.pin.as_deref())
+ .ok_or(InvalidSelection)?,
+ reader_ip,
+ timeout,
+ max_in_flight,
+ )?;
+ Ok(NativeGeoSelection::Kv(selection))
+ }
+}
+
+/// A syntactically valid selection that still needs its serving binding.
+pub(crate) enum NativeGeoPlan {
+ Ready(NativeGeo),
+ #[cfg(feature = "geo-kv")]
+ Kv(KvGeoSelection),
+}
+
+impl NativeGeoPlan {
+ pub(crate) fn capability(&self) -> NativeGeoCapability {
+ match self {
+ Self::Ready(geo) => geo.capability(),
+ #[cfg(feature = "geo-kv")]
+ Self::Kv(selection) => NativeGeoCapability::Selected {
+ provider: GeoProviderId::kv(),
+ source: GeoSource::Kv,
+ trust_basis: selection.trust_basis(),
+ },
+ }
+ }
+
+ #[cfg_attr(
+ not(feature = "geo-kv"),
+ expect(
+ clippy::unnecessary_wraps,
+ clippy::unused_self,
+ reason = "share the runner's preparation path while compiled-out Geo needs no KV limit"
+ )
+ )]
+ pub(crate) fn max_object_bytes(
+ &self,
+ sources: Option<&NativeSourcePlan>,
+ ) -> Result {
+ #[cfg(feature = "geo-kv")]
+ if let Self::Kv(selection) = self {
+ return match sources {
+ Some(plan) => {
+ use crate::native_stores::{NativeKvSource, NativeStoreSource};
+ let provider_cap = match plan.kv.get(selection.store_id()) {
+ Some(NativeStoreSource::BuiltIn(NativeKvSource::DynamoDb(settings))) => {
+ settings.limits.max_value_bytes
+ }
+ Some(NativeStoreSource::BuiltIn(NativeKvSource::Celld { .. })) => {
+ usize::try_from(plan.policies.celld.max_value_bytes)
+ .map_err(|_error| NativeGeoConfigError::InvalidSelection)?
+ }
+ Some(NativeStoreSource::BuiltIn(
+ NativeKvSource::DynamoDbRecords(_)
+ | NativeKvSource::CelldRecords { .. },
+ )) => return Err(NativeGeoConfigError::InvalidSelection),
+ Some(
+ NativeStoreSource::Local
+ | NativeStoreSource::Ready(_)
+ | NativeStoreSource::Prepare(_),
+ ) => kv::MAX_OBJECT_BYTES,
+ None => return Err(NativeGeoConfigError::MissingKvBinding),
+ };
+ Ok(provider_cap.min(kv::MAX_OBJECT_BYTES))
+ }
+ // Dev mode uses the declared local KV. It still validates the selected pin.
+ None => Ok(kv::MAX_OBJECT_BYTES),
+ };
+ }
+ let _: Option<&NativeSourcePlan> = sources;
+ Ok(0)
+ }
+
+ #[cfg_attr(
+ not(feature = "geo-kv"),
+ expect(
+ clippy::unused_async,
+ clippy::unused_async_trait_impl,
+ reason = "only the optional KV provider awaits preparation"
+ )
+ )]
+ pub(crate) async fn prepare(
+ self,
+ stores: Option<&KvRegistry>,
+ max_object_bytes: usize,
+ ) -> Result {
+ match self {
+ Self::Ready(geo) => {
+ let _: (Option<&KvRegistry>, usize) = (stores, max_object_bytes);
+ Ok(geo)
+ }
+ #[cfg(feature = "geo-kv")]
+ Self::Kv(selection) => selection
+ .prepare(stores, max_object_bytes)
+ .await
+ .map(|prepared| NativeGeo::Kv(Arc::new(prepared))),
+ }
+ }
+}
+
/// Validated runner-owned composition, never installed in public extensions.
#[derive(Clone, Default)]
pub(crate) enum NativeGeo {
#[default]
Off,
+ #[cfg(feature = "geo-kv")]
+ Kv(Arc),
Selected {
policy: ProtectedCloudFrontAlb,
id: GeoProviderId,
@@ -256,6 +530,8 @@ impl NativeGeo {
pub(crate) fn validate(selection: &NativeGeoSelection) -> Result {
match selection {
NativeGeoSelection::Off => Ok(Self::Off),
+ #[cfg(feature = "geo-kv")]
+ NativeGeoSelection::Kv(_) => Err(NativeGeoConfigError::InvalidSelection),
#[cfg(feature = "geo-cloudfront")]
NativeGeoSelection::CloudFront { policy } => Ok(Self::Selected {
policy: policy.clone(),
@@ -271,7 +547,7 @@ impl NativeGeo {
id,
provider,
} => {
- if id == &GeoProviderId::cloudfront() {
+ if id == &GeoProviderId::cloudfront() || id == &GeoProviderId::kv() {
return Err(NativeGeoConfigError::ReservedProviderId);
}
Ok(Self::Selected {
@@ -286,6 +562,12 @@ impl NativeGeo {
pub(crate) fn capability(&self) -> NativeGeoCapability {
match self {
Self::Off => NativeGeoCapability::Off,
+ #[cfg(feature = "geo-kv")]
+ Self::Kv(prepared) => NativeGeoCapability::Selected {
+ provider: GeoProviderId::kv(),
+ source: GeoSource::Kv,
+ trust_basis: prepared.trust_basis(),
+ },
Self::Selected { id, .. } => NativeGeoCapability::Selected {
provider: id.clone(),
source: GeoSource::CloudFront,
@@ -300,6 +582,31 @@ impl NativeGeo {
}
}
+ #[cfg_attr(
+ not(feature = "geo-kv"),
+ expect(
+ clippy::unused_async,
+ clippy::unused_async_trait_impl,
+ reason = "only the optional KV provider awaits request I/O"
+ )
+ )]
+ pub(crate) async fn resolve_request(
+ &self,
+ peer: Option,
+ headers: &HeaderMap,
+ checked: Option<&NativeIngressMetadata>,
+ ) -> GeoOutcome {
+ #[cfg(feature = "geo-kv")]
+ if let Self::Kv(provider) = self {
+ return GeoOutcome::Selected {
+ provider: GeoProviderId::kv(),
+ status: provider.resolve(peer, checked).await,
+ };
+ }
+ let _: Option<&NativeIngressMetadata> = checked;
+ self.resolve(peer, headers)
+ }
+
pub(crate) fn resolve(&self, peer: Option, headers: &HeaderMap) -> GeoOutcome {
let Self::Selected {
policy,
@@ -359,8 +666,12 @@ fn assertion(headers: &HeaderMap, name: &'static str) -> GeoAsse
mod tests {
use super::*;
use crate::run_options::AxumRunOptions;
+ use edgezero_core::app::Hooks;
+ use edgezero_core::error::EdgeError;
use edgezero_core::geo::{CountryCode, GeoError, GeoLocation};
use edgezero_core::http::HeaderValue;
+ use edgezero_core::manifest::Manifest;
+ use edgezero_core::router::RouterService;
use std::iter::empty;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -368,6 +679,160 @@ mod tests {
ProtectedCloudFrontAlb::new(["127.0.0.1/32"], "x-origin-verify-fixture").unwrap()
}
+ fn resolved(
+ explicit: Option<&NativeGeoSelection>,
+ vars: &[(&str, &str)],
+ manifest: &BakedManifest,
+ ) -> Result {
+ let env = EnvConfig::from_vars(vars.iter().copied());
+ resolve(explicit, &env, manifest).map(|geo| geo.capability())
+ }
+
+ fn baked(geo: &'static str) -> BakedManifest {
+ let json: &'static str =
+ Box::leak(format!(r#"{{"adapters":{{"axum":{{"geo":{geo}}}}}}}"#).into_boxed_str());
+ let baked = Manifest::from_baked_json(json);
+ assert!(matches!(baked, BakedManifest::Present(_)), "{json}");
+ baked
+ }
+
+ #[test]
+ fn geo_settings_resolve_explicit_then_env_then_manifest() {
+ const CIDRS: &str = "EDGEZERO__ADAPTER__GEO__ALB_PEER_CIDRS";
+ const HEADER: &str = "EDGEZERO__ADAPTER__GEO__ORIGIN_CREDENTIAL_HEADER_NAME";
+ const PROVIDER: &str = "EDGEZERO__ADAPTER__GEO__PROVIDER";
+ let none = BakedManifest::Absent;
+ let cloudfront = baked(
+ r#"{"provider":"cloudfront","alb_peer_cidrs":["10.0.0.0/24"],"origin_credential_header_name":"x-origin-verify"}"#,
+ );
+ let header_only =
+ baked(r#"{"provider":"cloudfront","origin_credential_header_name":"x-origin-verify"}"#);
+ let off = Ok(NativeGeoCapability::Off);
+
+ // Nothing selected stays off; an explicit selection beats settings and manifest.
+ assert_eq!(resolved(None, &[], &none), off);
+ assert_eq!(
+ resolved(
+ Some(&NativeGeoSelection::Off),
+ &[(PROVIDER, "cloudfront")],
+ &cloudfront
+ ),
+ off
+ );
+ // Settings override the manifest provider and fill deployment-only values.
+ assert_eq!(resolved(None, &[(PROVIDER, "off")], &cloudfront), off);
+ assert_eq!(
+ resolved(None, &[], &header_only),
+ Err(NativeGeoConfigError::InvalidProtectedPolicy),
+ "manifest without networks needs the setting"
+ );
+ assert_eq!(
+ resolved(
+ None,
+ &[(PROVIDER, "cloudfront"), (CIDRS, "10.0.0.0/24")],
+ &none
+ ),
+ Err(NativeGeoConfigError::InvalidCredentialHeader)
+ );
+ assert_eq!(
+ resolved(
+ None,
+ &[
+ (CIDRS, "10.0.0.0/24, 10.0.1.0/24"),
+ (HEADER, "x-forwarded-for")
+ ],
+ &header_only
+ ),
+ Err(NativeGeoConfigError::InvalidCredentialHeader),
+ "setting header replaces the manifest header and is validated"
+ );
+ // Misconfiguration never falls back to off.
+ for (vars, manifest) in [
+ (vec![(PROVIDER, "maxmind")], &none),
+ (vec![(CIDRS, "10.0.0.0/24")], &none),
+ (
+ vec![(PROVIDER, "off"), (HEADER, "x-origin-verify")],
+ &cloudfront,
+ ),
+ ] {
+ assert_eq!(
+ resolved(None, &vars, manifest),
+ Err(NativeGeoConfigError::InvalidSelection),
+ "{vars:?}"
+ );
+ }
+ assert_eq!(
+ resolved(None, &[], &baked(r#"{"alb_peer_cidrs":["10.0.0.0/24"]}"#)),
+ Err(NativeGeoConfigError::InvalidSelection)
+ );
+ assert_eq!(resolved(None, &[], &baked(r#"{"provider":"off"}"#)), off);
+
+ let selected = [
+ resolved(None, &[], &cloudfront),
+ resolved(None, &[(CIDRS, "10.0.0.0/24, 10.0.1.0/24")], &header_only),
+ resolved(
+ None,
+ &[
+ (PROVIDER, "cloudfront"),
+ (CIDRS, "10.0.0.0/24"),
+ (HEADER, "x-origin-verify"),
+ ],
+ &none,
+ ),
+ ];
+ for result in selected {
+ #[cfg(feature = "geo-cloudfront")]
+ assert!(
+ matches!(&result, Ok(NativeGeoCapability::Selected { provider, .. }) if provider == &GeoProviderId::cloudfront()),
+ "{result:?}"
+ );
+ #[cfg(not(feature = "geo-cloudfront"))]
+ assert_eq!(result, Err(NativeGeoConfigError::UnavailableCloudFront));
+ }
+ }
+
+ #[test]
+ fn geo_capability_for_applies_the_app_manifest() {
+ struct GeoApp;
+ #[expect(
+ clippy::missing_trait_methods,
+ reason = "fixture retains unused Hooks defaults"
+ )]
+ impl Hooks for GeoApp {
+ fn routes() -> Result {
+ Ok(RouterService::builder().build())
+ }
+ fn manifest() -> BakedManifest {
+ Manifest::from_baked_json(
+ r#"{"adapters":{"axum":{"geo":{"provider":"cloudfront","alb_peer_cidrs":["10.0.0.0/24"],"origin_credential_header_name":"x-origin-verify"}}}}"#,
+ )
+ }
+ }
+ let options = AxumRunOptions::new("127.0.0.1:8080".parse().unwrap()).unwrap();
+ assert_eq!(options.geo_capability(), Ok(NativeGeoCapability::Off));
+ #[cfg(feature = "geo-cloudfront")]
+ assert!(matches!(
+ options.geo_capability_for::(),
+ Ok(NativeGeoCapability::Selected { .. })
+ ));
+ #[cfg(not(feature = "geo-cloudfront"))]
+ assert_eq!(
+ options.geo_capability_for::(),
+ Err(NativeGeoConfigError::UnavailableCloudFront)
+ );
+ // Settings feed only the runner view; the explicit-only view never errors on them.
+ let partial =
+ AxumRunOptions::from_vars([("EDGEZERO__ADAPTER__GEO__ALB_PEER_CIDRS", "10.0.1.0/24")])
+ .unwrap();
+ assert_eq!(partial.geo_capability(), Ok(NativeGeoCapability::Off));
+ let disabled =
+ AxumRunOptions::from_vars([("EDGEZERO__ADAPTER__GEO__PROVIDER", "off")]).unwrap();
+ assert_eq!(
+ disabled.geo_capability_for::(),
+ Ok(NativeGeoCapability::Off)
+ );
+ }
+
#[test]
fn geo_protected_policy_reuses_network_bounds() {
assert_eq!(
diff --git a/crates/edgezero-adapter-axum/src/geo/kv.rs b/crates/edgezero-adapter-axum/src/geo/kv.rs
new file mode 100644
index 000000000..0601a4b17
--- /dev/null
+++ b/crates/edgezero-adapter-axum/src/geo/kv.rs
@@ -0,0 +1,192 @@
+//! Axum-owned preparation and execution budgets for a portable KV resolver.
+
+use std::fmt;
+use std::net::{IpAddr, SocketAddr};
+use std::time::Duration;
+
+use edgezero_core::geo::kv::{IndexLimits, Receipt, Resolver};
+use edgezero_core::geo::{GeoError, GeoSource, GeoStatus, GeoTrustBasis, GeoUnavailableReason};
+use edgezero_core::ingress::CheckedHostSource;
+use edgezero_core::store_registry::KvRegistry;
+use tokio::sync::Semaphore;
+use tokio::time::timeout;
+
+use super::NativeGeoConfigError;
+use crate::diagnostics::NativeIngressMetadata;
+
+// The 16 KiB production-size prototype needed up to three nodes; the 64 KiB
+// index needed two. The cache payload budget is the measured prototype budget.
+const MAX_PATH_OBJECTS: usize = 3;
+const CACHE_BYTES: usize = 4 * 1024 * 1024;
+// 4 MiB holds 256 objects at the smaller measured object budget (16 KiB).
+const CACHE_ENTRIES: usize = 256;
+// Do not exceed the smaller qualified backend ceiling (ordinary DynamoDB).
+pub(crate) const MAX_OBJECT_BYTES: usize = 384 * 1024;
+// Use the native celld preparation window for the bounded manifest/root probe.
+const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
+
+/// How this listener acquires a reader IP for KV geography.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum KvGeoReaderIp {
+ /// This listener receives reader connections directly.
+ DirectPeer,
+ /// Only the client approved by the trusted proxy policy is usable.
+ ForwardedRequired,
+}
+
+impl KvGeoReaderIp {
+ pub(crate) const fn trust_basis(self) -> GeoTrustBasis {
+ match self {
+ Self::DirectPeer => GeoTrustBasis::CheckedDirectPeer,
+ Self::ForwardedRequired => GeoTrustBasis::CheckedForwardedClient,
+ }
+ }
+
+ fn address(
+ self,
+ peer: Option,
+ checked: Option<&NativeIngressMetadata>,
+ ) -> Option {
+ match self {
+ Self::DirectPeer => peer.map(|address| address.ip().to_canonical()),
+ Self::ForwardedRequired => checked
+ .filter(|metadata| {
+ matches!(
+ metadata.client_source(),
+ CheckedHostSource::TrustedForwarded | CheckedHostSource::TrustedXForwarded
+ )
+ })
+ .and_then(NativeIngressMetadata::effective_client),
+ }
+ }
+}
+
+/// Validated KV Geo selection. The serving credential comes from the named KV binding.
+#[derive(Clone)]
+pub struct KvGeoSelection {
+ store_id: String,
+ receipt: Receipt,
+ reader_ip: KvGeoReaderIp,
+ lookup_timeout: Duration,
+ max_in_flight: usize,
+}
+
+impl fmt::Debug for KvGeoSelection {
+ #[inline]
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("KvGeoSelection")
+ .field("reader_ip", &self.reader_ip)
+ .finish_non_exhaustive()
+ }
+}
+
+impl KvGeoSelection {
+ /// Capture an explicit `@` pin and request budgets.
+ ///
+ /// # Errors
+ /// Rejects missing/invalid configuration and a malformed pin.
+ #[inline]
+ pub fn new(
+ store_id: &str,
+ pin: &str,
+ reader_ip: KvGeoReaderIp,
+ lookup_timeout_ms: u32,
+ max_in_flight: usize,
+ ) -> Result {
+ if store_id.is_empty()
+ || lookup_timeout_ms == 0
+ || !(1..=Semaphore::MAX_PERMITS).contains(&max_in_flight)
+ {
+ return Err(NativeGeoConfigError::InvalidSelection);
+ }
+ let receipt =
+ Receipt::from_pin(pin).map_err(|_error| NativeGeoConfigError::InvalidSelection)?;
+ Ok(Self {
+ store_id: store_id.into(),
+ receipt,
+ reader_ip,
+ lookup_timeout: Duration::from_millis(lookup_timeout_ms.into()),
+ max_in_flight,
+ })
+ }
+
+ pub(super) const fn trust_basis(&self) -> GeoTrustBasis {
+ self.reader_ip.trust_basis()
+ }
+
+ pub(super) fn store_id(&self) -> &str {
+ &self.store_id
+ }
+
+ pub(super) async fn prepare(
+ self,
+ stores: Option<&KvRegistry>,
+ max_object_bytes: usize,
+ ) -> Result {
+ let handle = stores
+ .and_then(|registry| registry.named(&self.store_id))
+ .ok_or(NativeGeoConfigError::MissingKvBinding)?;
+ let index = timeout(STARTUP_TIMEOUT, async {
+ let index = Resolver::open(
+ handle,
+ &self.receipt,
+ IndexLimits {
+ max_object_bytes,
+ max_path_objects: MAX_PATH_OBJECTS,
+ cache_bytes: CACHE_BYTES,
+ cache_entries: CACHE_ENTRIES,
+ },
+ )
+ .await?;
+ index.verify_roots().await?;
+ Ok::<_, anyhow::Error>(index)
+ })
+ .await
+ .map_err(|_error| NativeGeoConfigError::KvPreparationDeadline)?
+ .map_err(|_error| NativeGeoConfigError::KvPreparationFailed)?;
+ log::info!(target: "edgezero::native", "event=geo_ready schema={} generation={}", index.manifest().schema, index.manifest().generation);
+ Ok(PreparedKvGeo {
+ index,
+ reader_ip: self.reader_ip,
+ lookup_timeout: self.lookup_timeout,
+ slots: Semaphore::new(self.max_in_flight),
+ })
+ }
+}
+
+pub(crate) struct PreparedKvGeo {
+ index: Resolver,
+ reader_ip: KvGeoReaderIp,
+ lookup_timeout: Duration,
+ slots: Semaphore,
+}
+
+impl PreparedKvGeo {
+ pub(super) const fn trust_basis(&self) -> GeoTrustBasis {
+ self.reader_ip.trust_basis()
+ }
+ pub(super) async fn resolve(
+ &self,
+ peer: Option,
+ checked: Option<&NativeIngressMetadata>,
+ ) -> GeoStatus {
+ let Some(ip) = self.reader_ip.address(peer, checked) else {
+ return GeoStatus::Unavailable(GeoUnavailableReason::MissingReaderIp);
+ };
+ let Ok(_slot) = self.slots.try_acquire() else {
+ return GeoStatus::Error(GeoError::ProviderFailure);
+ };
+ match timeout(self.lookup_timeout, self.index.lookup(ip)).await {
+ Ok(Ok(Some(source))) => match source.geo_location() {
+ Some(location) => GeoStatus::Located {
+ location,
+ source: GeoSource::Kv,
+ trust_basis: self.reader_ip.trust_basis(),
+ },
+ None => GeoStatus::Unavailable(GeoUnavailableReason::UnsupportedGeography),
+ },
+ Ok(Ok(None)) => GeoStatus::Unavailable(GeoUnavailableReason::NoMatch),
+ _ => GeoStatus::Error(GeoError::ProviderFailure),
+ }
+ }
+}
diff --git a/crates/edgezero-adapter-axum/src/run_options.rs b/crates/edgezero-adapter-axum/src/run_options.rs
index b2384b1de..6b30c605a 100644
--- a/crates/edgezero-adapter-axum/src/run_options.rs
+++ b/crates/edgezero-adapter-axum/src/run_options.rs
@@ -8,14 +8,17 @@ use std::str::FromStr as _;
use std::time::{Duration, Instant};
use edgezero_core::addr;
-use edgezero_core::app::StoresMetadata;
+use edgezero_core::app::{Hooks, StoresMetadata};
use edgezero_core::env_config::EnvConfig;
+use edgezero_core::manifest::BakedManifest;
use edgezero_store_aws::settings::{AgentAccessToken, AwsPreparationLimits};
use edgezero_store_celld::settings::{CelldAccessToken, CelldPreparationLimits};
use log::LevelFilter;
use crate::diagnostics::NativeDiagnosticsHandle;
-use crate::geo::{NativeGeo, NativeGeoCapability, NativeGeoConfigError, NativeGeoSelection};
+use crate::geo::{
+ self, NativeGeoCapability, NativeGeoConfigError, NativeGeoPlan, NativeGeoSelection,
+};
use crate::native_bindings::{
NativeBindingsLimits, NativeConfigBinding, NativeKvBinding, NativePreparationPolicySources,
NativeStoreBindings, NativeStoreBindingsInput,
@@ -74,7 +77,8 @@ pub struct AxumRunOptions {
data_dir: Option,
diagnostics: NativeDiagnosticsHandle,
env: EnvConfig,
- geo: NativeGeoSelection,
+ /// `None` until [`Self::with_geo`]; the manifest and settings then decide.
+ geo: Option,
grace: Duration,
json_body_limit: JsonBodyLimit,
level: LevelFilter,
@@ -357,7 +361,7 @@ impl AxumRunOptions {
data_dir: None,
diagnostics: NativeDiagnosticsHandle::new(),
env: EnvConfig::default(),
- geo: NativeGeoSelection::Off,
+ geo: None,
grace: Duration::from_secs(10),
json_body_limit: JsonBodyLimit::DEFAULT,
level: LevelFilter::Info,
@@ -371,21 +375,46 @@ impl AxumRunOptions {
#[must_use]
#[inline]
pub fn with_geo(mut self, selection: NativeGeoSelection) -> Self {
- self.geo = selection;
+ self.geo = Some(selection);
self
}
- /// Validate the finalized selection and capture its startup capability.
+ /// Validate an explicit [`Self::with_geo`] selection and capture its capability.
+ ///
+ /// Without one this reports `Off`; it does not read `EDGEZERO__ADAPTER__GEO__*`
+ /// settings or a manifest. Use [`Self::geo_capability_for`] for the selection the
+ /// runner will actually use.
///
/// # Errors
/// Rejects unavailable implementations and invalid protected-source policies.
#[inline]
pub fn geo_capability(&self) -> Result {
- self.native_geo().map(|geo| geo.capability())
+ geo::resolve(
+ self.geo.as_ref(),
+ &EnvConfig::default(),
+ &BakedManifest::Absent,
+ )
+ .map(|geo| geo.capability())
}
- pub(crate) fn native_geo(&self) -> Result {
- NativeGeo::validate(&self.geo)
+ /// Capture the capability the runner will use for `A`: an explicit selection,
+ /// then `EDGEZERO__ADAPTER__GEO__*` settings, then its baked `[adapters.axum.geo]`.
+ ///
+ /// # Errors
+ /// Rejects unavailable implementations and invalid protected-source policies.
+ #[inline]
+ pub fn geo_capability_for(&self) -> Result
+ where
+ A: Hooks,
+ {
+ self.native_geo(&A::manifest()).map(|geo| geo.capability())
+ }
+
+ pub(crate) fn native_geo(
+ &self,
+ manifest: &BakedManifest,
+ ) -> Result {
+ geo::resolve(self.geo.as_ref(), &self.env, manifest)
}
pub(crate) fn request_records(&self) -> bool {
@@ -747,10 +776,31 @@ fn fixed_setting(path: &[String]) -> Option<&'static str> {
["adapter", "json_body_limit_bytes"] => Some("JSON_BODY_LIMIT_BYTES"),
["logging", "level"] => Some("LOGGING__LEVEL"),
["store_bindings_file"] => Some("STORE_BINDINGS_FILE"),
- _ => native_limit_setting(path),
+ _ => geo_setting(path).or_else(|| native_limit_setting(path)),
}
}
+/// `EDGEZERO__ADAPTER__GEO__*` names, shared by the dev and production input checks.
+pub(crate) fn geo_setting(path: &[String]) -> Option<&'static str> {
+ let segments: Vec<&str> = path.iter().map(String::as_str).collect();
+ matches!(
+ segments.as_slice(),
+ [
+ "adapter",
+ "geo",
+ "provider"
+ | "alb_peer_cidrs"
+ | "origin_credential_header_name"
+ | "store_id"
+ | "pin"
+ | "reader_ip"
+ | "lookup_timeout_ms"
+ | "max_in_flight"
+ ]
+ )
+ .then_some("GEO")
+}
+
pub(crate) fn native_limit_setting(path: &[String]) -> Option<&'static str> {
let segments: Vec<&str> = path.iter().map(String::as_str).collect();
match segments.as_slice() {
diff --git a/crates/edgezero-adapter-axum/src/service.rs b/crates/edgezero-adapter-axum/src/service.rs
index c2e32737a..340c6da4b 100644
--- a/crates/edgezero-adapter-axum/src/service.rs
+++ b/crates/edgezero-adapter-axum/src/service.rs
@@ -493,7 +493,14 @@ impl AxumServiceState {
.await;
}
};
- let geo = self.geo.resolve(remote_addr, &parts.headers);
+ let geo = self
+ .geo
+ .resolve_request(
+ remote_addr,
+ &parts.headers,
+ parts.extensions.get::(),
+ )
+ .await;
Ok(self
.dispatch_prepared(prepared, parts, native_body, connection, guard, geo)
.await)
diff --git a/crates/edgezero-adapter-axum/tests/fixtures/geo_artifact.rs b/crates/edgezero-adapter-axum/tests/fixtures/geo_artifact.rs
new file mode 100644
index 000000000..ac7b825e5
--- /dev/null
+++ b/crates/edgezero-adapter-axum/tests/fixtures/geo_artifact.rs
@@ -0,0 +1,54 @@
+//! Files as exact-key KV fixtures for the managed listener test, not a backend.
+
+use std::fs;
+use std::io::ErrorKind;
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::time::Duration;
+
+use async_trait::async_trait;
+use bytes::Bytes;
+use edgezero_core::geo::kv::{digest, hex};
+use edgezero_core::key_value_store::{KvError, KvPage, KvStore};
+
+pub static READS: AtomicUsize = AtomicUsize::new(0);
+
+pub struct Artifact(pub PathBuf);
+
+impl Artifact {
+ pub fn path(&self, key: &str) -> PathBuf {
+ self.0.join(hex(&digest(key.as_bytes())))
+ }
+}
+
+#[expect(
+ clippy::missing_trait_methods,
+ reason = "Geo fixture needs no record operations"
+)]
+#[async_trait(?Send)]
+impl KvStore for Artifact {
+ async fn delete(&self, _: &str) -> Result<(), KvError> {
+ Err(KvError::Unavailable)
+ }
+
+ async fn get_bytes(&self, key: &str) -> Result