diff --git a/CHANGELOG.md b/CHANGELOG.md
index fb177bad0..dba069e80 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -43,17 +43,19 @@ settings, and request records.
`NoSelection`, or `Selected` with the provider ID and a `GeoStatus`: `Located`,
`Unavailable` (`MissingMetadata` or `UntrustedIngress`), or `Error` (`InvalidAssertion` or
`ProviderFailure`). An outcome never sets an HTTP status or grants access, and request
- extensions cannot replace it. Fastly, Cloudflare, Spin and unmanaged Axum dispatch report
- `NoSelection`.
+ extensions cannot replace it. Spin and unmanaged Axum dispatch report `NoSelection`; Fastly
+ and Cloudflare managed dispatch report platform geography (see Platform Geo and Axum Geo
+ settings below).
- Add `edgezero_core::geo` with validated `CountryCode`, `SubdivisionCode`, `GeoLocation` and
`GeoProviderId` values, and the `GeoProvider` trait for synchronous, local-only providers.
-- Managed Axum hosting selects one provider with `AxumRunOptions::with_geo`. Geo is `Off` by
- default, including for `from_env` and `from_vars`; there is no environment, CLI or manifest
- selector. `NativeGeoSelection::CloudFront` reads `CloudFront-Viewer-Country` and
+- Managed Axum hosting selects one provider with `AxumRunOptions::with_geo`,
+ `EDGEZERO__ADAPTER__GEO__*` settings or `[adapters.axum.geo]`. Geo is `Off` by default, and
+ there is no CLI selector. `NativeGeoSelection::CloudFront` reads `CloudFront-Viewer-Country` and
`CloudFront-Viewer-Country-Region` and needs the default-off `geo-cloudfront` feature;
selecting it without the feature fails at startup. `NativeGeoSelection::Supplied` plugs in an
application `GeoProvider` under its own ID, and `cloudfront` is reserved.
- `AxumRunOptions::geo_capability()` validates the selection before the server listens.
+ `AxumRunOptions::geo_capability_for::()` validates the selection the runner will use
+ before the server listens; `geo_capability()` validates only an explicit `with_geo` selection.
- Both selections require a `ProtectedCloudFrontAlb` policy: the ALB peer networks and the name
of a dedicated origin-credential header. Geo headers are read only when the socket peer
matches those networks; trusted-proxy settings do not admit them. EdgeZero stores only the
@@ -82,6 +84,31 @@ settings, and request records.
even after header or extension edits. Raw payload handoff drops the policy and preserves
exact egress ownership.
+### Platform Geo and Axum Geo settings
+
+- Fastly and Cloudflare managed dispatch now report the platform's own geography through
+ `ctx.geo()`, with no setting or store. Fastly looks up the client address; Cloudflare reads
+ `cf.country` and `cf.regionCode`. Results use provider `fastly` or `cloudflare`,
+ `GeoSource::Fastly` or `GeoSource::Cloudflare`, and `GeoTrustBasis::PlatformMetadata`.
+ A missing or unusable country, including Cloudflare's `XX` and `T1`, is `MissingMetadata`;
+ an unusable subdivision leaves a country-only location. For countries with several levels
+ of subdivision, Fastly reports the more specific one. Spin still reports `NoSelection`.
+- Add `GeoOutcome::platform` for adapters that build an outcome from platform metadata.
+- Axum can select Geo from `[adapters.axum.geo]` in `edgezero.toml`, with `provider`
+ (`cloudfront` or `off`), `alb_peer_cidrs` and `origin_credential_header_name`. Each key is a
+ default that the matching `EDGEZERO__ADAPTER__GEO__*` setting overrides at startup, so ALB
+ networks can stay out of the compiled manifest. `AxumRunOptions::with_geo` still takes
+ precedence over both. The development runner, `run_app` and the scaffold's `run_generated_app`
+ without `EDGEZERO__STORE_BINDINGS_FILE`, reads only the settings, warns that a baked table is
+ ignored and names it in geo startup errors; `run_production_app` applies it. Misconfiguration
+ fails startup instead of turning Geo off. See the
+ [native Geo guide](docs/guide/native-geo.md#select-from-the-manifest-and-settings).
+- `AxumRunOptions::geo_capability()` now reports only an explicit `with_geo` selection. Use
+ `geo_capability_for::()` for the selection the runner will use.
+- `GeoSource` and `GeoTrustBasis` are now non-exhaustive; add wildcard arms to exhaustive
+ matches. `fastly` and `cloudflare` are reserved provider IDs, so rename a supplied provider
+ that uses either. A `geo` table under any adapter other than Axum now fails to load.
+
### Native celld KV on Axum
- Opt into live KV backed by celld with the default-off `celld-kv` feature. There is no celld
diff --git a/crates/edgezero-adapter-axum/src/dev_server.rs b/crates/edgezero-adapter-axum/src/dev_server.rs
index 03720a44d..6e9f364aa 100644
--- a/crates/edgezero-adapter-axum/src/dev_server.rs
+++ b/crates/edgezero-adapter-axum/src/dev_server.rs
@@ -24,7 +24,7 @@ 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_request_setting,
+ JsonBodyLimit, config_path, failure, geo_setting, native_limit_setting, native_request_setting,
native_settings,
};
use crate::trusted_proxy::TrustedProxyPolicy;
@@ -48,6 +48,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;
@@ -62,7 +63,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::{KvOpenFailure, PersistentKvStore};
use crate::native_stores::{self, NativeSourcePlan, NativeStoreOverrides, NativeStoreSource};
@@ -1159,12 +1160,29 @@ where
A: Hooks,
F: FnOnce() -> anyhow::Result<()>,
{
- let (env, json_body_limit, native) = capture_dev_environment(vars_os())?;
+ /// Startup error context and warning when this runner skips a baked geo table.
+ const IGNORED_MANIFEST_GEO: &str = "the development runner (run_app, and run_generated_app \
+ without EDGEZERO__STORE_BINDINGS_FILE) ignores [adapters.axum.geo]; only \
+ EDGEZERO__ADAPTER__GEO__* settings select geo here, and run_production_app applies \
+ the table";
+ 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 ignores_manifest_geo = geo::has_manifest_geo(&A::manifest());
+ let resolved = geo::resolve(None, &env, &BakedManifest::Absent);
+ native.geo = if ignores_manifest_geo {
+ resolved.context(IGNORED_MANIFEST_GEO)?
+ } else {
+ resolved?
+ };
if !A::owns_logging() {
app_logger(&env)
.init()
.context("failed to initialize application logger")?;
}
+ if ignores_manifest_geo {
+ log::warn!(target: BOOT_LOG_TARGET, "{IGNORED_MANIFEST_GEO}");
+ }
let ingress = AxumIngressConfig::from_env(&env)?;
let config_limits = ConfigStoreLimits::from_env(&env)?;
log::info!("[edgezero] axum HTTP/1 ingress limits: {ingress:?}");
@@ -1208,8 +1226,11 @@ where
"not supported by the development runner; use run_generated_app or run_production_app",
));
}
- let setting = config_path(key, cfg!(windows))
- .and_then(|path| native_limit_setting(&path).or_else(|| native_request_setting(&path)));
+ let setting = config_path(key, cfg!(windows)).and_then(|path| {
+ native_limit_setting(&path)
+ .or_else(|| native_request_setting(&path))
+ .or_else(|| geo_setting(&path))
+ });
match (os_value.to_str(), setting) {
(Some(value), _) => pairs.push((key.to_owned(), value.to_owned())),
(None, Some(category)) => {
@@ -1404,7 +1425,7 @@ where
&'startup PreparedStores,
) -> LocalStartupFuture<'startup>,
{
- let geo = options.native_geo()?;
+ let geo = options.native_geo(&A::manifest())?;
let native = NativeHosting {
diagnostics: options.diagnostics(),
policy: options.trusted_proxy_policy(),
diff --git a/crates/edgezero-adapter-axum/src/geo.rs b/crates/edgezero-adapter-axum/src/geo.rs
index 1dbab6ba2..22511bcbe 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};
@@ -106,11 +108,13 @@ 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,
+ GeoStatus, GeoTrustBasis, GeoUnavailableReason, GeoValueError,
};
use edgezero_core::http::{HeaderMap, HeaderName};
+use edgezero_core::manifest::{BakedManifest, ManifestAdapterGeo, ManifestGeoProvider};
use crate::peer_networks::PeerNetworks;
@@ -125,6 +129,8 @@ pub enum NativeGeoConfigError {
UnavailableCloudFront,
#[error("native_geo: reserved supplied provider identity")]
ReservedProviderId,
+ #[error("native_geo: invalid provider selection")]
+ InvalidSelection,
}
/// An operator declaration of a credential-gated, isolated CloudFront/ALB path.
@@ -244,6 +250,81 @@ 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 {
+ match explicit {
+ Some(selection) => NativeGeo::validate(selection),
+ None => NativeGeo::validate(&configured_selection(env, manifest_geo(manifest))?),
+ }
+}
+
+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()
+}
+
+/// Whether the app bakes an `[adapters.axum.geo]` table; the development runner ignores it.
+pub(crate) fn has_manifest_geo(manifest: &BakedManifest) -> bool {
+ manifest_geo(manifest).is_some()
+}
+
+fn configured_selection(
+ env: &EnvConfig,
+ manifest: 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("off") => Some(ManifestGeoProvider::Off),
+ Some(_) => return Err(NativeGeoConfigError::InvalidSelection),
+ None => manifest.and_then(|geo| geo.provider),
+ };
+ match provider {
+ Some(ManifestGeoProvider::CloudFront) => {
+ let header = env_header
+ .or_else(|| manifest?.origin_credential_header_name.as_deref())
+ .ok_or(NativeGeoConfigError::InvalidCredentialHeader)?;
+ // Raw entries: the policy validator owns trimming and the byte and entry bounds.
+ let policy = match env_networks {
+ Some(raw) => ProtectedCloudFrontAlb::new(raw.split(','), header),
+ None => ProtectedCloudFrontAlb::new(
+ manifest
+ .and_then(|geo| geo.alb_peer_cidrs.as_deref())
+ .unwrap_or_default(),
+ 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()
+ })) =>
+ {
+ Err(NativeGeoConfigError::InvalidSelection)
+ }
+ _ => Ok(NativeGeoSelection::Off),
+ }
+}
+
/// Validated runner-owned composition, never installed in public extensions.
#[derive(Clone, Default)]
pub(crate) enum NativeGeo {
@@ -275,7 +356,9 @@ impl NativeGeo {
id,
provider,
} => {
- if id == &GeoProviderId::cloudfront() {
+ // Every built-in or platform identity, even one taken from a platform
+ // outcome, fails the label check that owns the reserved list.
+ if GeoProviderId::new(id.as_str()) == Err(GeoValueError::ReservedProviderId) {
return Err(NativeGeoConfigError::ReservedProviderId);
}
Ok(Self::Selected {
@@ -364,8 +447,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};
@@ -373,6 +460,202 @@ 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_manifest_table_detection_needs_a_baked_axum_geo_table() {
+ assert!(has_manifest_geo(&baked(
+ r#"{"provider":"cloudfront","alb_peer_cidrs":["10.0.0.0/24"],"origin_credential_header_name":"x-origin-verify"}"#
+ )));
+ assert!(has_manifest_geo(&baked(r#"{"provider":"off"}"#)));
+ assert!(!has_manifest_geo(&BakedManifest::Absent));
+ let without_geo = Manifest::from_baked_json(r#"{"adapters":{"axum":{}}}"#);
+ assert!(matches!(without_geo, BakedManifest::Present(_)));
+ assert!(!has_manifest_geo(&without_geo));
+ }
+
+ #[test]
+ fn geo_settings_networks_keep_the_policy_input_bounds() {
+ // The setting reaches the policy validator unmodified, so its control-character
+ // and 16,384-byte input checks apply exactly as they do to direct construction.
+ let oversized = format!("127.0.0.1/32{}", " ".repeat(0x4000));
+ for networks in ["127.0.0.1/32\n", oversized.as_str()] {
+ assert_eq!(
+ ProtectedCloudFrontAlb::new([networks], "x-origin-verify").err(),
+ Some(NativeGeoConfigError::InvalidProtectedPolicy)
+ );
+ assert_eq!(
+ resolved(
+ None,
+ &[
+ ("EDGEZERO__ADAPTER__GEO__PROVIDER", "cloudfront"),
+ ("EDGEZERO__ADAPTER__GEO__ALB_PEER_CIDRS", networks),
+ (
+ "EDGEZERO__ADAPTER__GEO__ORIGIN_CREDENTIAL_HEADER_NAME",
+ "x-origin-verify"
+ ),
+ ],
+ &BakedManifest::Absent
+ ),
+ Err(NativeGeoConfigError::InvalidProtectedPolicy),
+ "{} input bytes",
+ networks.len()
+ );
+ }
+ }
+
+ #[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!(
@@ -595,20 +878,37 @@ mod tests {
{
}
assert_bounds::();
- let error = NativeGeo::validate(&NativeGeoSelection::Supplied {
- policy: policy(),
- id: GeoProviderId::cloudfront(),
- provider: Arc::new(CountingProvider {
- calls: Arc::default(),
- result: GeoResolution::Located(GeoLocation::new(
- CountryCode::new("US").unwrap(),
- None,
- )),
- }),
- })
- .err()
- .unwrap();
- assert_eq!(error, NativeGeoConfigError::ReservedProviderId);
+ // Platform outcomes hand out the other reserved identities.
+ let platform_id = |source| {
+ match GeoOutcome::platform(source, None, None) {
+ GeoOutcome::Selected { provider, .. } => Some(provider),
+ GeoOutcome::NoSelection => None,
+ }
+ .unwrap()
+ };
+ for id in [
+ GeoProviderId::cloudfront(),
+ platform_id(GeoSource::Fastly),
+ platform_id(GeoSource::Cloudflare),
+ ] {
+ let error = NativeGeo::validate(&NativeGeoSelection::Supplied {
+ policy: policy(),
+ id: id.clone(),
+ provider: Arc::new(CountingProvider {
+ calls: Arc::default(),
+ result: GeoResolution::Located(GeoLocation::new(
+ CountryCode::new("US").unwrap(),
+ None,
+ )),
+ }),
+ })
+ .err();
+ assert_eq!(
+ error,
+ Some(NativeGeoConfigError::ReservedProviderId),
+ "{id:?}"
+ );
+ }
let options = AxumRunOptions::new("127.0.0.1:8080".parse().unwrap()).unwrap();
assert_eq!(options.geo_capability().unwrap(), NativeGeoCapability::Off);
let supplied = NativeGeoSelection::Supplied {
diff --git a/crates/edgezero-adapter-axum/src/run_options.rs b/crates/edgezero-adapter-axum/src/run_options.rs
index 8bd342d75..87fb14b67 100644
--- a/crates/edgezero-adapter-axum/src/run_options.rs
+++ b/crates/edgezero-adapter-axum/src/run_options.rs
@@ -8,14 +8,15 @@ 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, NativeGeo, NativeGeoCapability, NativeGeoConfigError, NativeGeoSelection};
use crate::native_bindings::{
NativeBindingsLimits, NativeConfigBinding, NativeKvBinding, NativePreparationPolicySources,
NativeStoreBindings, NativeStoreBindingsInput,
@@ -77,7 +78,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,
@@ -385,7 +387,7 @@ impl AxumRunOptions {
data_dir: None,
diagnostics: NativeDiagnosticsHandle::new(),
env: EnvConfig::default(),
- geo: NativeGeoSelection::Off,
+ geo: None,
grace: DEFAULT_SHUTDOWN_GRACE,
json_body_limit: JsonBodyLimit::DEFAULT,
level: LevelFilter::Info,
@@ -399,21 +401,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())
+ }
+
+ /// 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) -> Result {
- NativeGeo::validate(&self.geo)
+ 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 {
@@ -773,10 +800,26 @@ fn fixed_setting(path: &[String]) -> Option<&'static str> {
["adapter", "shutdown_grace_seconds"] => Some("SHUTDOWN_GRACE_SECONDS"),
["logging", "level"] => Some("LOGGING__LEVEL"),
["store_bindings_file"] => Some("STORE_BINDINGS_FILE"),
- _ => native_limit_setting(path).or_else(|| native_request_setting(path)),
+ _ => geo_setting(path)
+ .or_else(|| native_limit_setting(path))
+ .or_else(|| native_request_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"
+ ]
+ )
+ .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/tests/fixtures/production_host.rs b/crates/edgezero-adapter-axum/tests/fixtures/production_host.rs
index eabe4fcb3..b817d61ba 100644
--- a/crates/edgezero-adapter-axum/tests/fixtures/production_host.rs
+++ b/crates/edgezero-adapter-axum/tests/fixtures/production_host.rs
@@ -44,6 +44,7 @@ use edgezero_core::ingress::{
AdmissionDecision, CheckedEffectiveHost, CheckedHostSource, IngressGrant,
};
use edgezero_core::key_value_store::KvHandle;
+use edgezero_core::manifest::{BakedManifest, Manifest};
use edgezero_core::middleware::{Middleware, Next};
use edgezero_core::params::PathParams;
use edgezero_core::probe::{self, LifecyclePhase, LifecycleReader};
@@ -325,6 +326,17 @@ impl Hooks for FixtureApp {
Ok(())
}
+ /// `geo-manifest` bakes `CloudFront` geo with the credential header; the ALB
+ /// networks come from `EDGEZERO__ADAPTER__GEO__ALB_PEER_CIDRS`.
+ fn manifest() -> BakedManifest {
+ if mode().starts_with("geo-manifest") {
+ return Manifest::from_baked_json(
+ r#"{"adapters":{"axum":{"geo":{"provider":"cloudfront","origin_credential_header_name":"x-origin-verify-fixture"}}}}"#,
+ );
+ }
+ BakedManifest::Absent
+ }
+
fn owns_logging() -> bool {
!matches!(
mode().as_str(),
@@ -1079,6 +1091,10 @@ async fn geo_observation(mut ctx: RequestContext) -> Result
reason = "test-only initializer asserts root-free startup, capability capture and known-valid forged state"
)]
fn run_geo_fixture(selected: &str) -> anyhow::Result<()> {
+ if selected == "geo-manifest-dev" {
+ // The dev runner ignores the manifest table; only settings select geo.
+ return run_app::();
+ }
let address: SocketAddr = env::var("FIXTURE_BIND")?.parse()?;
let peer_network = if selected.ends_with("untrusted") {
"192.0.2.1/32"
@@ -1102,15 +1118,23 @@ fn run_geo_fixture(selected: &str) -> anyhow::Result<()> {
} else {
NativeGeoSelection::CloudFront { policy }
};
- let mut options = AxumRunOptions::new(address)?.with_geo(selection);
- if selected == "geo-supplied-untrusted" {
- options = options.with_trusted_proxy_policy(TrustedProxyPolicy::new(
- ForwardingHeaderFamily::XForwarded,
- ["127.0.0.1/32"],
- )?);
- }
- // Capture from the same finalized options, without bypassing the runner's validation.
- let capability = options.geo_capability();
+ let (options, capability) = if selected == "geo-manifest" {
+ // No `with_geo`: the baked manifest and EDGEZERO__ settings select geo.
+ let options = AxumRunOptions::from_env()?;
+ let capability = options.geo_capability_for::();
+ (options, capability)
+ } else {
+ let mut options = AxumRunOptions::new(address)?.with_geo(selection);
+ if selected == "geo-supplied-untrusted" {
+ options = options.with_trusted_proxy_policy(TrustedProxyPolicy::new(
+ ForwardingHeaderFamily::XForwarded,
+ ["127.0.0.1/32"],
+ )?);
+ }
+ // Capture from the same finalized options, without bypassing the runner's validation.
+ let capability = options.geo_capability();
+ (options, capability)
+ };
let is_off = selected == "geo-off";
let (sender, receiver) = oneshot::channel();
run_app_with_options_and_initializer::(
diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs
index 88038d6cc..0d7133b28 100644
--- a/crates/edgezero-adapter-axum/tests/production_hosting.rs
+++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs
@@ -2686,6 +2686,97 @@ mod tests {
);
}
+ #[test]
+ #[cfg(feature = "geo-cloudfront")]
+ fn geo_hosting_binds_cloudfront_from_manifest_and_settings() {
+ let cwd = tempfile::tempdir().expect("unrelated cwd");
+ let addr = address();
+ let mut command = geo_command("geo-manifest", &cwd, addr);
+ command
+ .env("EDGEZERO__ADAPTER__HOST", addr.ip().to_string())
+ .env("EDGEZERO__ADAPTER__PORT", addr.port().to_string())
+ .env("EDGEZERO__ADAPTER__GEO__ALB_PEER_CIDRS", "127.0.0.1/32");
+ let mut server = Server::spawn(command, addr);
+ server.ready();
+ let value = geo_response(
+ &server,
+ "CloudFront-Viewer-Country: us\r\nCloudFront-Viewer-Country-Region: ca\r\nx-origin-verify-fixture: ORIGIN_CREDENTIAL_SENTINEL\r\n",
+ );
+ assert_eq!(value["geo"]["status"], "located");
+ assert_eq!(value["geo"]["provider"], "cloudfront");
+ assert_eq!(value["geo"]["country"], "US");
+ assert_eq!(value["geo"]["subdivision"], "CA");
+ assert_eq!(value["geo"]["trust_basis"], "DeclaredProtectedAlb");
+ finish_geo(&mut server, &cwd);
+ }
+
+ #[test]
+ fn geo_dev_runner_ignores_manifest_and_reads_settings() {
+ let cwd = tempfile::tempdir().expect("unrelated cwd");
+ let dev = |settings: &[(&str, &str)]| {
+ let addr = address();
+ let mut command = geo_command("geo-manifest-dev", &cwd, addr);
+ command
+ .env("EDGEZERO__ADAPTER__HOST", addr.ip().to_string())
+ .env("EDGEZERO__ADAPTER__PORT", addr.port().to_string());
+ for (key, value) in settings {
+ command.env(key, value);
+ }
+ let mut server = Server::spawn(command, addr);
+ server.ready();
+ server
+ };
+ let request = "CloudFront-Viewer-Country: US\r\nCloudFront-Viewer-Country-Region: CA\r\n";
+
+ // The baked table lacks networks; the dev server still starts, with geo off.
+ let unselected = dev(&[]);
+ let value = geo_response(&unselected, request);
+ assert_eq!(value["geo"]["status"], "no_selection");
+ drop(unselected);
+
+ // Settings alone opt a dev run in. Without the built-in this fails startup instead.
+ #[cfg(feature = "geo-cloudfront")]
+ {
+ let selected = dev(&[
+ ("EDGEZERO__ADAPTER__GEO__PROVIDER", "cloudfront"),
+ ("EDGEZERO__ADAPTER__GEO__ALB_PEER_CIDRS", "127.0.0.1/32"),
+ (
+ "EDGEZERO__ADAPTER__GEO__ORIGIN_CREDENTIAL_HEADER_NAME",
+ "x-origin-verify-fixture",
+ ),
+ ]);
+ let located = geo_response(&selected, request);
+ assert_eq!(located["geo"]["status"], "located");
+ assert_eq!(located["geo"]["provider"], "cloudfront");
+ assert_eq!(located["geo"]["country"], "US");
+ assert_eq!(located["geo"]["subdivision"], "CA");
+ }
+ }
+
+ #[test]
+ fn geo_hosting_dev_runner_names_ignored_manifest_table() {
+ // The documented split bakes the provider and header and supplies only the networks
+ // at deploy time. The dev runner ignores the table, so the error must say so.
+ let cwd = tempfile::tempdir().expect("unrelated cwd");
+ let (addr, _addr_held) = reserved_address();
+ let mut command = geo_command("geo-manifest-dev", &cwd, addr);
+ command
+ .env("EDGEZERO__ADAPTER__HOST", addr.ip().to_string())
+ .env("EDGEZERO__ADAPTER__PORT", addr.port().to_string())
+ .env("EDGEZERO__ADAPTER__GEO__ALB_PEER_CIDRS", "127.0.0.1/32");
+ let mut server = Server::spawn(command, addr);
+ assert!(!server.wait().success());
+ let log = server.log();
+ assert!(
+ log.contains("native_geo: invalid provider selection"),
+ "{log}"
+ );
+ assert!(log.contains("ignores [adapters.axum.geo]"), "{log}");
+ assert!(!log.contains("127.0.0.1/32"), "{log}");
+ assert!(!log.contains("INITIALIZED"), "{log}");
+ assert_eq!(fs::read_dir(cwd.path()).expect("unrelated cwd").count(), 0);
+ }
+
#[test]
#[cfg(not(feature = "geo-cloudfront"))]
fn geo_hosting_rejects_unavailable_cloudfront() {
diff --git a/crates/edgezero-adapter-cloudflare/src/request.rs b/crates/edgezero-adapter-cloudflare/src/request.rs
index 17e1f9b66..ff3a00338 100644
--- a/crates/edgezero-adapter-cloudflare/src/request.rs
+++ b/crates/edgezero-adapter-cloudflare/src/request.rs
@@ -11,12 +11,13 @@ use std::{io, task::Poll};
#[cfg(feature = "test-utils")]
use bytes::Bytes;
use edgezero_core::OutboundScopeOwner;
-use edgezero_core::app::{App, StoreMetadata};
+use edgezero_core::app::{App, FrameworkErrorDetail, StoreMetadata};
use edgezero_core::body::Body;
use edgezero_core::config_store::{ConfigStoreHandle, ConfigStoreOpenFailure};
use edgezero_core::context::RuntimeVariables;
use edgezero_core::env_config::EnvConfig;
use edgezero_core::error::EdgeError;
+use edgezero_core::geo::{GeoOutcome, GeoSource};
use edgezero_core::http::{HeaderValue, Method as CoreMethod, Request, Uri, request_builder};
use edgezero_core::ingress::{
CapturedTarget, HeaderFidelity, InboundOrigin, IngressBeginOutcome, IngressDispatchOutcome,
@@ -41,7 +42,8 @@ use futures_util::stream::poll_fn;
use futures_util::stream::{LocalBoxStream, unfold};
use futures_util::{StreamExt as _, TryStreamExt as _};
use worker::{
- Context, Delay, Env, Error as WorkerError, Method, Request as CfRequest, Response as CfResponse,
+ Cf, Context, Delay, Env, Error as WorkerError, Method, Request as CfRequest,
+ Response as CfResponse,
};
use crate::config_store::CloudflareConfigStore;
@@ -506,6 +508,7 @@ where
core_request,
Stores::default(),
request_start,
+ GeoOutcome::NoSelection,
move || Ok(Some(source)),
Ok,
))
@@ -540,6 +543,7 @@ where
core_request,
Stores::default(),
request_start,
+ GeoOutcome::NoSelection,
move || make_source().map(Some),
deliver,
))
@@ -566,6 +570,7 @@ pub async fn dispatch_ingress_source_error_for_test(
core_request,
Stores::default(),
request_start,
+ GeoOutcome::NoSelection,
|| -> Result