Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 63 additions & 6 deletions .github/actions/deploy-core/tests/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -897,6 +897,66 @@ test_workspace_isolation() {
assert_succeeds "cleanup refuses a workspace outside RUNNER_TEMP" test -d "$outside"
}

# The standalone Spin operator's lifecycle suite uses Python, outside deployment
# action tooling. Admit only its exact file-backed unittest command in test.yml;
# inline programs, other workflows, installers and appended commands stay banned.
filter_loader_unit_tests() {
local allowed_workflow="$1" embedded_language=py"thon"
local approved_command="${embedded_language}3 -m unittest discover -s examples/geo-spin-loader -p test_load.py"
local entry remainder candidate_command
while IFS= read -r entry; do
if [[ "$entry" == "$allowed_workflow":* ]]; then
remainder=${entry#"$allowed_workflow":}
candidate_command=${remainder#*:}
candidate_command=${candidate_command#"${candidate_command%%[![:space:]]*}"}
if [[ "$candidate_command" == "$approved_command" ]]; then
continue
fi
fi
printf '%s\n' "$entry"
done
}

unapproved_ci_commands() {
local allowed_workflow="$1" embedded_language=py"thon"
shift
local command_pattern="(^|[[:space:]|;&])(${embedded_language}3?|pip3?|pipx)([[:space:]]|$)"
grep -REn --include='*.sh' --include='*.yml' -E "$command_pattern" "$@" |
grep -vE ':[0-9]+:[[:space:]]*#' |
filter_loader_unit_tests "$allowed_workflow" || true
}

test_standalone_loader_ci_tool_exception() {
section "standalone loader unittest command exception"
local fixture="$WORK_DIR/ci-tool-policy" embedded_language=py"thon" installer=pi"p3" heredoc_marker=P"Y"
local approved_command="${embedded_language}3 -m unittest discover -s examples/geo-spin-loader -p test_load.py"
local variant actual
mkdir -p "$fixture"
printf ' %s\n' "$approved_command" > "$fixture/test.yml"
actual=$(unapproved_ci_commands "$fixture/test.yml" "$fixture")
assert_equals "exact standalone lifecycle command is admitted" "" "$actual"
for variant in \
"$approved_command --failfast" \
"$approved_command; true" \
"$approved_command && true" \
"$approved_command # appended comment" \
"${embedded_language}3 -c pass" \
"${embedded_language}3 - <<'${heredoc_marker}'" \
"$installer install package"; do
printf ' %s\n' "$variant" > "$fixture/test.yml"
actual=$(unapproved_ci_commands "$fixture/test.yml" "$fixture")
assert_equals "non-approved command remains rejected: $variant" "$fixture/test.yml:1: $variant" "$actual"
done
printf ' %s\n' "$approved_command" > "$fixture/test.yml"
printf ' %s\n' "$approved_command" > "$fixture/other.yml"
actual=$(unapproved_ci_commands "$fixture/test.yml" "$fixture")
assert_equals "another workflow cannot use the exception" "$fixture/other.yml:1: $approved_command" "$actual"
rm "$fixture/other.yml"
printf ' %s\n' "$approved_command" > "$fixture/action.sh"
actual=$(unapproved_ci_commands "$fixture/test.yml" "$fixture")
assert_equals "action scripts cannot use the exception" "$fixture/action.sh:1: $approved_command" "$actual"
}

test_no_inline_action_scripts() {
section "actions use script files, never inline run:"
# Every composite `run:` must invoke a `.sh` file — no inline shell in YAML, which
Expand All @@ -913,12 +973,8 @@ test_no_inline_action_scripts() {
bad=$(grep -REn --include='*.sh' -E "$embedded_python_pattern" "$ACTIONS_DIR" || true)
assert_equals "action shell scripts contain no embedded Python programs" "" "$bad"

local command_pattern="(^|[[:space:]|;&])(${embedded_language}3?|pip3?|pipx)([[:space:]]|$)"
bad=$(
grep -REn --include='*.sh' --include='*.yml' -E "$command_pattern" \
"$ACTIONS_DIR" "$REPO_ROOT/.github/workflows" "$REPO_ROOT/scripts/run_coverage.sh" |
grep -vE ':[0-9]+:[[:space:]]*#' || true
)
bad=$(unapproved_ci_commands "$REPO_ROOT/.github/workflows/test.yml" \
"$ACTIONS_DIR" "$REPO_ROOT/.github/workflows" "$REPO_ROOT/scripts/run_coverage.sh")
assert_equals "action and CI tooling use only approved shell tools" "" "$bad"
}

Expand Down Expand Up @@ -3802,6 +3858,7 @@ main() {
test_workspace_isolation
test_workspace_step_scrub
test_no_inline_action_scripts
test_standalone_loader_ci_tool_exception
test_deploy_args_prepend
test_lifecycle_helpers
test_capture_previous
Expand Down
10 changes: 10 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ jobs:
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 examples/geo-spin-loader/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
Expand Down Expand Up @@ -228,6 +229,15 @@ jobs:
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: Spin KV operator loader
if: matrix.suite == 'workspace'
run: |
cargo fmt --manifest-path examples/geo-spin-loader/Cargo.toml -- --check
cargo clippy --offline --locked --manifest-path examples/geo-spin-loader/Cargo.toml --all-targets -- -D warnings
cargo test --offline --locked --manifest-path examples/geo-spin-loader/Cargo.toml
cargo check --offline --locked --manifest-path examples/geo-spin-loader/Cargo.toml --target wasm32-wasip2
python3 -m unittest discover -s examples/geo-spin-loader -p test_load.py

- name: Native Geo public examples
run: cargo test --offline --locked -p edgezero-adapter-axum --features geo-cloudfront --doc

Expand Down
29 changes: 29 additions & 0 deletions crates/edgezero-adapter-axum/src/geo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,12 @@ fn configured_selection(
env: &EnvConfig,
defaults: Option<&ManifestAdapterGeo>,
) -> Result<NativeGeoSelection, NativeGeoConfigError> {
if env
.get(&["adapter", "geo", "credential_variable"])
.is_some()
{
return Err(NativeGeoConfigError::InvalidSelection);
}
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"]);
Expand Down Expand Up @@ -791,6 +797,29 @@ mod tests {
}
}

#[test]
fn axum_rejects_spin_credential_override() {
struct NoGeo;
#[expect(
clippy::missing_trait_methods,
reason = "fixture retains unused Hooks defaults"
)]
impl Hooks for NoGeo {
fn routes() -> Result<RouterService, EdgeError> {
Ok(RouterService::builder().build())
}
}
let options = AxumRunOptions::from_vars([(
"EDGEZERO__ADAPTER__GEO__CREDENTIAL_VARIABLE",
"geo_token",
)])
.unwrap();
assert_eq!(
options.geo_capability_for::<NoGeo>(),
Err(NativeGeoConfigError::InvalidSelection)
);
}

#[test]
fn geo_capability_for_applies_the_app_manifest() {
struct GeoApp;
Expand Down
166 changes: 132 additions & 34 deletions crates/edgezero-adapter-cloudflare/tests/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ mod tests {
};
use edgezero_core::context::RequestContext;
use edgezero_core::error::EdgeError;
use edgezero_core::geo::{GeoError, GeoOutcome, GeoProviderId, GeoSource, GeoStatus};
use edgezero_core::geo::{
GeoError, GeoOutcome, GeoProviderId, GeoSource, GeoStatus, GeoTrustBasis,
GeoUnavailableReason, SubdivisionCode,
};
use edgezero_core::http::{Method, Response, StatusCode, response_builder};
use edgezero_core::outbound::{
HttpClient, OutboundCollectedSlot, OutboundRequest, OutboundSlotResult, OutboundTime,
Expand Down Expand Up @@ -415,43 +418,138 @@ mod tests {
}

#[wasm_bindgen_test]
async fn dispatch_exposes_cf_metadata_through_ctx_geo() {
async fn geo(ctx: RequestContext) -> Result<Response, EdgeError> {
let body = Body::text(format!("{:?}", ctx.geo()));
response_builder()
.status(StatusCode::OK)
.body(body)
.map_err(EdgeError::internal)
}
let app = App::new(RouterService::builder().get("/geo", geo).build());
let inner = Clone::clone(cf_request(CfMethod::Get, "/geo", None).inner());
let cf = Object::new();
for (key, value) in [("country", "US"), ("regionCode", "CA")] {
Reflect::set(&cf, &JsValue::from_str(key), &JsValue::from_str(value))
.expect("cf field");
#[expect(
clippy::too_many_lines,
reason = "one matrix compares all three managed entrypoints across the same ordered requests"
)]
async fn managed_entrypoints_keep_platform_geo_per_request() {
struct GeoApp;

#[expect(
clippy::missing_trait_methods,
reason = "store-free fixture deliberately uses default application configuration"
)]
impl Hooks for GeoApp {
fn owns_logging() -> bool {
true
}

fn routes() -> Result<RouterService, EdgeError> {
Ok(RouterService::builder().get("/geo", geo).build())
}
}
Reflect::set(&inner, &JsValue::from_str("cf"), &cf).expect("cf");
let (env, ctx, _timers) = test_env_ctx();

let mut response = CloudflareService::new(&app)
.dispatch(CfRequest::from(inner), env, ctx)
.await
.expect("cf response");
#[edgezero_core::action]
async fn geo(ctx: RequestContext) -> String {
let GeoOutcome::Selected { provider, status } = ctx.geo() else {
return serde_json::json!({"status": "no-selection"}).to_string();
};
assert_eq!(provider.as_str(), "cloudflare");
match status {
GeoStatus::Located {
location,
source,
trust_basis,
} => {
assert_eq!(*source, GeoSource::Cloudflare);
assert_eq!(*trust_basis, GeoTrustBasis::PlatformMetadata);
serde_json::json!({
"status": "located",
"country": location.country().as_str(),
"subdivision": location.subdivision().map(SubdivisionCode::as_str),
})
.to_string()
}
GeoStatus::Unavailable(reason) => {
assert_eq!(*reason, GeoUnavailableReason::MissingMetadata);
serde_json::json!({"status": "missing"}).to_string()
}
GeoStatus::Error(error) => {
serde_json::json!({"unexpected_error": error.to_string()}).to_string()
}
}
}

assert_eq!(response.status_code(), StatusCode::OK.as_u16());
let expected = GeoOutcome::platform(GeoSource::Cloudflare, Some("US"), Some("CA"));
assert!(matches!(
&expected,
GeoOutcome::Selected {
status: GeoStatus::Located { .. },
..
let app = App::build::<GeoApp>(edgezero_adapter_cloudflare::CLOUDFLARE_PLATFORM)
.expect("store-free application");
let cases: &[(&[(&str, &str)], serde_json::Value)] = &[
(
&[
("country", "US"),
("region", "California"),
("regionCode", "CA"),
],
serde_json::json!({"status": "located", "country": "US", "subdivision": "CA"}),
),
(&[], serde_json::json!({"status": "missing"})),
(
&[("country", "gb")],
serde_json::json!({"status": "located", "country": "GB", "subdivision": null}),
),
(
&[("country", "us"), ("regionCode", "01")],
serde_json::json!({"status": "located", "country": "US", "subdivision": "01"}),
),
(
&[("country", "US"), ("regionCode", "US-CA")],
serde_json::json!({"status": "located", "country": "US", "subdivision": null}),
),
(
&[("country", "XX")],
serde_json::json!({"status": "missing"}),
),
(
&[("country", "T1")],
serde_json::json!({"status": "missing"}),
),
(
&[("regionCode", "CA")],
serde_json::json!({"status": "missing"}),
),
];

for entrypoint in ["service", "run_app", "dispatch_app"] {
for (fields, expected) in cases {
let inner = Clone::clone(cf_request(CfMethod::Get, "/geo", None).inner());
if !fields.is_empty() {
let cf = Object::new();
for (key, value) in *fields {
Reflect::set(&cf, &JsValue::from_str(key), &JsValue::from_str(value))
.expect("platform metadata field");
}
Reflect::set(&inner, &JsValue::from_str("cf"), &cf).expect("cf metadata");
}
for (name, value) in [
("cf-ipcountry", "DE"),
("cloudfront-viewer-country", "DE"),
("cloudfront-viewer-country-region", "BE"),
] {
inner.headers().set(name, value).expect("spoofed header");
}
let request = CfRequest::from(inner);
let (env, ctx, _timers) = test_env_ctx();
let mut response = match entrypoint {
"service" => {
CloudflareService::new(&app)
.dispatch(request, env, ctx)
.await
}
"run_app" => {
edgezero_adapter_cloudflare::run_app::<GeoApp>(request, env, ctx).await
}
_ => {
edgezero_adapter_cloudflare::dispatch_app::<GeoApp>(&app, request, env, ctx)
.await
}
}
.expect("managed geo response");
assert_eq!(response.status_code(), StatusCode::OK.as_u16());
let actual: serde_json::Value =
serde_json::from_str(&response.text().await.expect("geo response body"))
.expect("geo response JSON");
assert_eq!(&actual, expected, "{entrypoint}, metadata {fields:?}");
}
));
assert_eq!(
response.text().await.expect("text"),
format!("{expected:?}"),
"cf metadata wins over the request's CloudFront headers"
);
}
}

#[wasm_bindgen_test]
Expand Down
4 changes: 2 additions & 2 deletions crates/edgezero-adapter-spin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ test-utils = ["edgezero-core/test-utils"]
cli = ["dep:edgezero-adapter", "edgezero-adapter/cli", "dep:ctor", "dep:rusqlite", "dep:toml", "dep:toml_edit", "dep:walkdir"]

[dependencies]
edgezero-core = { path = "../edgezero-core" }
edgezero-core = { path = "../edgezero-core", features = ["geo-kv"] }
edgezero-adapter = { path = "../edgezero-adapter", optional = true, features = ["cli"] }
anyhow = { workspace = true }
async-stream = { workspace = true }
Expand Down Expand Up @@ -45,6 +45,6 @@ walkdir = { workspace = true, optional = true }
rusqlite = { workspace = true, optional = true }

[dev-dependencies]
edgezero-core = { path = "../edgezero-core", features = ["test-utils"] }
edgezero-core = { path = "../edgezero-core", features = ["test-utils", "geo-kv-build"] }
http-body-util = { workspace = true }
tempfile = { workspace = true }
Loading
Loading