From fb985656c47880264bbf5cda5d5e2821c97e94b4 Mon Sep 17 00:00:00 2001 From: Michel Blaauw Date: Wed, 25 Nov 2026 16:01:04 +0100 Subject: [PATCH] fix(tests): inject the outbound policy and licence instead of setting env vars (#445) Integration tests set ORBIT_OUTBOUND_ALLOWED_HOSTS=127.0.0.1 (the outcome-writer test and, through a Once, the output-delivery tests) and ORBIT_LICENSE_PUBLIC_KEYS process-wide and never unset them. Every outbound check read the environment on each call, so whether the Kubernetes guard test saw loopback refused depended on which test ran first. The S3 delivery tests only passed because of that leak. - AppState gains `outbound: OutboundPolicy`, read once from ORBIT_OUTBOUND_* at startup. Work sources (dispatcher, team outcomes), output delivery and credential checks, provider and connection probes, connection URL validation and portable import use it instead of `OutboundPolicy::from_env()` / `guarded_client`. - `S3Client::with_policy` lets the API pass its policy; `S3Client::new` (the worker) still reads the environment. The orbit-s3 unit tests use the injected policy too. - Tests: `test_app_allowing_loopback` exempts 127.0.0.1 in one app's state only; `licensed_test_app` installs a verified licence status instead of signing a token against an env-supplied key. New `outbound_policy_is_per_app_state` shows a loopback-allowing app and a default app side by side. No `std::env::set_var` is left in crates/*/tests. - AGENTS.md: connector probes use the API's policy. Finding 2 was fixed in #472, so this completes #445. The Kubernetes connector crate still reads the policy from the environment (only the worker and the API's Kubernetes test path use it; #497 moves it onto the client config). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +- changelog.d/445.changed.md | 4 + crates/orbit-api/src/dispatcher.rs | 7 +- crates/orbit-api/src/handlers/catalog.rs | 48 ++++--- .../orbit-api/src/handlers/import_portable.rs | 7 +- crates/orbit-api/src/handlers/outputs.rs | 48 ++++--- crates/orbit-api/src/state.rs | 4 + crates/orbit-api/src/team_outcomes.rs | 7 +- crates/orbit-api/tests/api_integration.rs | 122 ++++++++++-------- .../orbit-api/tests/portable_export_import.rs | 1 + crates/orbit-s3/src/lib.rs | 54 +++++--- services/api/src/main.rs | 1 + 12 files changed, 195 insertions(+), 112 deletions(-) create mode 100644 changelog.d/445.changed.md diff --git a/AGENTS.md b/AGENTS.md index e460a02e..5936db6c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -146,7 +146,9 @@ third-party connectors; the built-in connectors are not trait objects. `services/worker/src/.rs` using the connection config and leased credential. 3. Check URL-typed config fields in `validate_connection_urls` and, when a probe exists, `probe_connection` (`crates/orbit-api/src/handlers/catalog.rs`); use - `orbit_security::guarded_client` for every HTTP call. + `orbit_security::guarded_client_with_policy` with `state.outbound` (the API's outbound + policy) for every HTTP call, so tests can inject a policy instead of setting environment + variables. 4. Store credentials only as encrypted `secret_ref` handles. 5. Enforce capability allowlists and autonomy in the platform (the broker), not in the client. 6. Add mock/webhook tests in `crates/orbit-api/tests`; never commit real credentials. diff --git a/changelog.d/445.changed.md b/changelog.d/445.changed.md new file mode 100644 index 00000000..a0a9c06b --- /dev/null +++ b/changelog.d/445.changed.md @@ -0,0 +1,4 @@ +- The API reads the outbound network policy (`ORBIT_OUTBOUND_*`) once at startup and keeps + it in its state, and the integration tests inject a policy and a licence instead of + changing process environment variables, so a test that allows loopback can no longer + loosen the outbound guard for other tests (#445). diff --git a/crates/orbit-api/src/dispatcher.rs b/crates/orbit-api/src/dispatcher.rs index 249f38f4..6fa99610 100644 --- a/crates/orbit-api/src/dispatcher.rs +++ b/crates/orbit-api/src/dispatcher.rs @@ -358,14 +358,17 @@ impl WorkSourceConnection { .to_string(), other => anyhow::bail!("unsupported work source provider '{other}'"), }; - orbit_security::check_outbound_url(&base_url, &orbit_security::OutboundPolicy::from_env()) + orbit_security::check_outbound_url(&base_url, &state.outbound) .await .map_err(|error| anyhow::anyhow!("work source baseUrl refused: {error}"))?; Ok(Self { config: connection.config.clone(), base_url, token, - client: orbit_security::guarded_client(std::time::Duration::from_secs(20)), + client: orbit_security::guarded_client_with_policy( + std::time::Duration::from_secs(20), + state.outbound.clone(), + ), }) } } diff --git a/crates/orbit-api/src/handlers/catalog.rs b/crates/orbit-api/src/handlers/catalog.rs index 5b39a8da..1e4aff31 100644 --- a/crates/orbit-api/src/handlers/catalog.rs +++ b/crates/orbit-api/src/handlers/catalog.rs @@ -342,7 +342,13 @@ pub async fn probe_provider( .map(|value| value.expose().to_string()), None => None, }; - let result = probe_endpoint(kind, &provider.config, credential.as_deref()).await; + let result = probe_endpoint( + kind, + &provider.config, + credential.as_deref(), + &state.outbound, + ) + .await; state.metrics.provider_probe(kind.as_str(), result.ok); // Persist discovered models so agent/worker selectors can use them without a manual @@ -392,7 +398,7 @@ pub async fn probe_unsaved( return Err(ApiError::validation(report.issues)); } // Never persist or log the credential used for this probe. - let result = probe_endpoint(kind, &config, body.credential.as_deref()).await; + let result = probe_endpoint(kind, &config, body.credential.as_deref(), &state.outbound).await; state.metrics.provider_probe(kind.as_str(), result.ok); Ok(Json(result)) } @@ -401,6 +407,7 @@ async fn probe_endpoint( kind: ProviderKind, config: &serde_json::Value, credential: Option<&str>, + policy: &orbit_security::OutboundPolicy, ) -> ProviderProbeResponse { let base_url = match config.get("baseUrl").and_then(|v| v.as_str()) { Some(value) if !value.is_empty() => value, @@ -428,9 +435,7 @@ async fn probe_endpoint( }; } let url = format!("{}/models", base_url.trim_end_matches('/')); - if let Err(error) = - orbit_security::check_outbound_url(&url, &orbit_security::OutboundPolicy::from_env()).await - { + if let Err(error) = orbit_security::check_outbound_url(&url, policy).await { return ProviderProbeResponse { ok: false, latency_ms: 0, @@ -438,7 +443,10 @@ async fn probe_endpoint( error: Some(format!("endpoint refused ({})", error.category())), }; } - let client = orbit_security::guarded_client(std::time::Duration::from_secs(10)); + let client = orbit_security::guarded_client_with_policy( + std::time::Duration::from_secs(10), + policy.clone(), + ); let mut request = client.get(&url); if let Some(credential) = credential { request = if kind == ProviderKind::Anthropic { @@ -535,8 +543,10 @@ const CONNECTION_URL_FIELDS: [&str; 4] = ["baseUrl", "cloneBaseUrl", "url", "api /// (`ORBIT_OUTBOUND_ALLOW_PRIVATE` / `ORBIT_OUTBOUND_ALLOWED_HOSTS`); errors are 422s on /// the offending field name. A kubeconfig credential's own `server` is checked when the /// Kubernetes client connects. -pub(crate) async fn validate_connection_urls(config: &serde_json::Value) -> Result<(), ApiError> { - let policy = orbit_security::OutboundPolicy::from_env(); +pub(crate) async fn validate_connection_urls( + config: &serde_json::Value, + policy: &orbit_security::OutboundPolicy, +) -> Result<(), ApiError> { let mut issues = Vec::new(); for field in CONNECTION_URL_FIELDS { let Some(value) = config.get(field).and_then(|v| v.as_str()) else { @@ -546,7 +556,7 @@ pub(crate) async fn validate_connection_urls(config: &serde_json::Value) -> Resu if value.is_empty() { continue; } - if let Err(error) = orbit_security::check_outbound_url(value, &policy).await { + if let Err(error) = orbit_security::check_outbound_url(value, policy).await { issues.push(orbit_domain::ValidationIssue::new(field, error.to_string())); } } @@ -605,7 +615,7 @@ pub async fn create_connection( .get_connector_by_slug(auth.org_id, &body.connector_slug) .await? .ok_or_else(|| ApiError::not_found(format!("connector '{}'", body.connector_slug)))?; - validate_connection_urls(&body.config).await?; + validate_connection_urls(&body.config, &state.outbound).await?; let secret_ref = if let Some(credential) = &body.credential { if credential.trim().is_empty() { @@ -693,7 +703,7 @@ pub async fn update_connection( &existing.visibility, )?; if let Some(config) = &body.config { - validate_connection_urls(config).await?; + validate_connection_urls(config, &state.outbound).await?; // A stored credential must never follow an edited endpoint (#321), the same rule // providers follow: changing a URL field requires the credential for it. if existing.credential_ref.is_some() && body.credential.is_none() { @@ -879,6 +889,7 @@ pub async fn test_connection( &row.connector_slug, &row.connection.config, credential.as_deref(), + &state.outbound, ) .await else { @@ -916,6 +927,7 @@ async fn probe_connection( slug: &str, config: &serde_json::Value, credential: Option<&str>, + policy: &orbit_security::OutboundPolicy, ) -> Option<(bool, Option, String)> { Some(match slug { // The mock connector talks to nothing; a stored connection is always usable. @@ -925,13 +937,13 @@ async fn probe_connection( "Mock connector needs no external service".into(), ), "gitlab" | "github" | "webhook" | "kubernetes" => { - probe_supported_connection(slug, config, credential).await + probe_supported_connection(slug, config, credential, policy).await } "s3" => { let result = async { let (config, credentials) = orbit_s3::S3Config::from_connection(config, credential)?; - let client = orbit_s3::S3Client::new(config, credentials)?; + let client = orbit_s3::S3Client::with_policy(config, credentials, policy.clone())?; match client.list_buckets().await { Ok(buckets) => Ok(format!( "S3 reachable; {} allowed bucket(s) visible", @@ -978,8 +990,12 @@ async fn probe_supported_connection( slug: &str, config: &serde_json::Value, credential: Option<&str>, + policy: &orbit_security::OutboundPolicy, ) -> (bool, Option, String) { - let client = orbit_security::guarded_client(std::time::Duration::from_secs(10)); + let client = orbit_security::guarded_client_with_policy( + std::time::Duration::from_secs(10), + policy.clone(), + ); let (url, request) = match slug { "gitlab" | "github" => { let base = config @@ -1041,9 +1057,7 @@ async fn probe_supported_connection( ); } }; - if let Err(error) = - orbit_security::check_outbound_url(&url, &orbit_security::OutboundPolicy::from_env()).await - { + if let Err(error) = orbit_security::check_outbound_url(&url, policy).await { return ( false, None, diff --git a/crates/orbit-api/src/handlers/import_portable.rs b/crates/orbit-api/src/handlers/import_portable.rs index 697c2ee5..ff73ce45 100644 --- a/crates/orbit-api/src/handlers/import_portable.rs +++ b/crates/orbit-api/src/handlers/import_portable.rs @@ -415,7 +415,12 @@ async fn translate( if config.is_null() { config = json!({}); } - if let Err(error) = crate::handlers::catalog::validate_connection_urls(&config).await { + if let Err(error) = crate::handlers::catalog::validate_connection_urls( + &config, + &resolver.state.outbound, + ) + .await + { for issue in &error.details { found.issue(issue.path.clone(), issue.message.clone()); } diff --git a/crates/orbit-api/src/handlers/outputs.rs b/crates/orbit-api/src/handlers/outputs.rs index 8c36b0ce..7e9b7887 100644 --- a/crates/orbit-api/src/handlers/outputs.rs +++ b/crates/orbit-api/src/handlers/outputs.rs @@ -202,7 +202,11 @@ fn credential(body: &OutputRequest, kind: OutputKind) -> Option<&str> { .filter(|value| !value.is_empty()) } -async fn guard_credential(kind: OutputKind, value: &str) -> Result<(), ApiError> { +async fn guard_credential( + kind: OutputKind, + value: &str, + policy: &OutboundPolicy, +) -> Result<(), ApiError> { match kind { OutputKind::Telegram => { // Telegram tokens are `:`; rejecting URL metacharacters here @@ -231,7 +235,7 @@ async fn guard_credential(kind: OutputKind, value: &str) -> Result<(), ApiError> })?; Ok(()) } - _ => guard_webhook_url(value).await, + _ => guard_webhook_url(value, policy).await, } } @@ -514,7 +518,7 @@ pub async fn create( format!("{} is required", credential_field(kind)), )]) })?; - guard_credential(kind, value).await?; + guard_credential(kind, value, &state.outbound).await?; let config = request_config(&body)?.unwrap_or_else(|| serde_json::json!({})); if kind == OutputKind::S3 { orbit_s3::S3Config::for_output(&config, Some(value)).map_err(|message| { @@ -597,7 +601,7 @@ pub async fn update( })?; } let secret_ref = if let Some(value) = credential(&body, kind) { - guard_credential(kind, value).await?; + guard_credential(kind, value, &state.outbound).await?; if kind == OutputKind::S3 { orbit_s3::S3Config::for_output(&config, Some(value)).map_err(|message| { ApiError::validation(vec![ValidationIssue::new("config", message)]) @@ -774,7 +778,8 @@ pub async fn send( message, retryable: false, })?; - let client = orbit_s3::S3Client::new(config, credentials).map_err(|message| SendError { + let client = orbit_s3::S3Client::with_policy(config, credentials, state.outbound.clone()) + .map_err(|message| SendError { status: None, message, retryable: false, @@ -805,7 +810,7 @@ pub async fn send( retryable: false, })?; return send_telegram_with_progress( - &TelegramEndpoint::from_env(), + &TelegramEndpoint::from_env(state.outbound.clone()), &secret, &target, text, @@ -814,14 +819,17 @@ pub async fn send( ) .await; } - guard_webhook_url(&secret) + guard_webhook_url(&secret, &state.outbound) .await .map_err(|error| SendError { status: None, message: error.message, retryable: false, })?; - let client = orbit_security::guarded_client(std::time::Duration::from_secs(15)); + let client = orbit_security::guarded_client_with_policy( + std::time::Duration::from_secs(15), + state.outbound.clone(), + ); let payload = if kind == OutputKind::Webhook { serde_json::json!({ "event": execution @@ -875,13 +883,15 @@ pub struct TelegramEndpoint { } impl TelegramEndpoint { - pub fn from_env() -> Self { + /// The Bot API base URL from `ORBIT_TELEGRAM_API_BASE_URL` (tests point it at a mock), + /// guarded by the given outbound policy. + pub fn from_env(policy: OutboundPolicy) -> Self { let base_url = std::env::var("ORBIT_TELEGRAM_API_BASE_URL") .ok() .map(|value| value.trim().to_string()) .filter(|value| !value.is_empty()) .unwrap_or_else(|| TELEGRAM_API_BASE_URL.to_string()); - Self::new(base_url, OutboundPolicy::from_env()) + Self::new(base_url, policy) } pub fn new(base_url: impl Into, policy: OutboundPolicy) -> Self { @@ -1195,8 +1205,8 @@ fn summary(execution: &ExecutionRecord) -> String { /// Refuse webhook targets in loopback, link-local/metadata or other blocked ranges /// (see `ORBIT_OUTBOUND_*`). Private ranges are allowed by default. -async fn guard_webhook_url(url: &str) -> Result<(), ApiError> { - orbit_security::check_outbound_url(url, &orbit_security::OutboundPolicy::from_env()) +async fn guard_webhook_url(url: &str, policy: &OutboundPolicy) -> Result<(), ApiError> { + orbit_security::check_outbound_url(url, policy) .await .map_err(|error| { ApiError::validation(vec![ValidationIssue::new("webhookUrl", error.to_string())]) @@ -1250,9 +1260,13 @@ mod tests { #[tokio::test] async fn telegram_tokens_cannot_alter_the_request_path() { - assert!(guard_credential(OutputKind::Telegram, "123456:ABC_def-1") - .await - .is_ok()); + assert!(guard_credential( + OutputKind::Telegram, + "123456:ABC_def-1", + &OutboundPolicy::default() + ) + .await + .is_ok()); for token in [ "123:abc/../../evil", "123:abc?x=1", @@ -1261,7 +1275,9 @@ mod tests { ":secret", ] { assert!( - guard_credential(OutputKind::Telegram, token).await.is_err(), + guard_credential(OutputKind::Telegram, token, &OutboundPolicy::default()) + .await + .is_err(), "{token} must be rejected" ); } diff --git a/crates/orbit-api/src/state.rs b/crates/orbit-api/src/state.rs index ac93f927..ef07825c 100644 --- a/crates/orbit-api/src/state.rs +++ b/crates/orbit-api/src/state.rs @@ -74,6 +74,10 @@ pub struct AppState { pub license: LicenseHandle, /// Cancelled on SIGTERM/SIGINT: stops background loops and ends SSE streams. pub shutdown: tokio_util::sync::CancellationToken, + /// Outbound network policy for every request the API sends (work sources, outputs, + /// provider and connection probes). Read once from `ORBIT_OUTBOUND_*` at startup so + /// tests can inject a policy instead of changing the process environment (#445). + pub outbound: orbit_security::OutboundPolicy, } /// Guard held while an execution is counted and inserted. `Unrestricted` is returned when diff --git a/crates/orbit-api/src/team_outcomes.rs b/crates/orbit-api/src/team_outcomes.rs index c9d8a0f9..490ff831 100644 --- a/crates/orbit-api/src/team_outcomes.rs +++ b/crates/orbit-api/src/team_outcomes.rs @@ -215,7 +215,7 @@ async fn connector_for_work_source( .to_string(), other => anyhow::bail!("unsupported work source provider '{other}'"), }; - orbit_security::check_outbound_url(&base_url, &orbit_security::OutboundPolicy::from_env()) + orbit_security::check_outbound_url(&base_url, &state.outbound) .await .map_err(|error| anyhow::anyhow!("work source baseUrl refused: {error}"))?; Ok(Some(WorkSourceConnector { @@ -223,7 +223,10 @@ async fn connector_for_work_source( connection_config: connection.config.clone(), base_url, token, - client: orbit_security::guarded_client(std::time::Duration::from_secs(20)), + client: orbit_security::guarded_client_with_policy( + std::time::Duration::from_secs(20), + state.outbound.clone(), + ), })) } diff --git a/crates/orbit-api/tests/api_integration.rs b/crates/orbit-api/tests/api_integration.rs index e465ec4a..aea42432 100644 --- a/crates/orbit-api/tests/api_integration.rs +++ b/crates/orbit-api/tests/api_integration.rs @@ -64,6 +64,17 @@ async fn test_app(allow_anonymous: bool) -> Option { test_app_with_license(allow_anonymous, None).await } +/// A test app whose outbound policy exempts 127.0.0.1, for tests that talk to a mock server +/// on loopback. The policy lives in this app's state only, so other tests keep the +/// default policy that refuses loopback (#445). +async fn test_app_allowing_loopback() -> Option { + let mut app = test_app(true).await?; + app.state.outbound = orbit_security::OutboundPolicy::new(true, "127.0.0.1"); + // The router keeps its own clone of the state, so rebuild it. + app.router = build_router(app.state.clone()); + Some(app) +} + async fn test_app_with_license( allow_anonymous: bool, license: Option, @@ -153,6 +164,9 @@ async fn test_app_with_license( archive_after_days: None, output_delivery_retention_days: None, shutdown: shutdown.clone(), + // The default policy: loopback is refused. Tests that talk to a local mock opt in + // with `test_app_allowing_loopback` instead of changing the process environment (#445). + outbound: orbit_security::OutboundPolicy::default(), license: license.map(LicenseHandle::from_status).unwrap_or_else(|| { orbit_security::LicenseHandle::load(orbit_security::LicenseSource { token: None, @@ -5333,16 +5347,43 @@ async fn stored_queue_item_with_a_foreign_repository_is_refused_on_start() { assert_eq!(runs, 0); } +/// #445: the outbound policy comes from each app's state, not from the process +/// environment, so a test that exempts loopback cannot loosen the guard for another test +/// running in the same process. +#[tokio::test] +async fn outbound_policy_is_per_app_state() { + let Some(strict) = test_app(true).await else { + return; + }; + let Some(loopback) = test_app_allowing_loopback().await else { + return; + }; + let body = |name: &str| { + json!({ + "name": format!("{name}-{}", Uuid::now_v7()), + "kind": "webhook", + "webhookUrl": "http://127.0.0.1:9/hook", + "enabled": false + }) + }; + let (status, created) = send(&loopback.router, post("/api/v1/outputs", body("loopback"))).await; + assert_eq!(status, StatusCode::CREATED, "{created}"); + let (status, refused) = send(&strict.router, post("/api/v1/outputs", body("strict"))).await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{refused}"); + assert!(refused["error"]["details"] + .as_array() + .is_some_and(|details| details.iter().any(|detail| detail["path"] == "webhookUrl"))); +} + /// #384: the outcome writer only touches the work source's repository, whatever /// repository the queue item carries. #[tokio::test] async fn outcome_writer_never_contacts_a_foreign_repository() { - let Some(app) = test_app(true).await else { - return; - }; // The mock GitHub listens on loopback, which the outbound guard (#142) blocks unless // explicitly allowed. - std::env::set_var("ORBIT_OUTBOUND_ALLOWED_HOSTS", "127.0.0.1"); + let Some(app) = test_app_allowing_loopback().await else { + return; + }; let hits: Arc>> = Arc::default(); let recorded = hits.clone(); let mock = axum::Router::new().fallback(move |request: axum::extract::Request| { @@ -5521,13 +5562,15 @@ mod output_delivery { /// deliver_pending is global across orgs; serialize these tests so counts are exact. fn guard() -> &'static tokio::sync::Mutex<()> { static GUARD: std::sync::OnceLock> = std::sync::OnceLock::new(); - // The test hooks listen on 127.0.0.1; the outbound guard (#142) blocks loopback - // unless explicitly allowlisted. - static ALLOW: std::sync::Once = std::sync::Once::new(); - ALLOW.call_once(|| std::env::set_var("ORBIT_OUTBOUND_ALLOWED_HOSTS", "127.0.0.1")); GUARD.get_or_init(|| tokio::sync::Mutex::new(())) } + /// The test hooks listen on 127.0.0.1, which the outbound guard (#142) refuses unless + /// the app's policy exempts it. + async fn delivery_app() -> Option { + test_app_allowing_loopback().await + } + #[derive(Clone)] struct Hook { url: String, @@ -5622,7 +5665,7 @@ mod output_delivery { #[tokio::test] async fn s3_output_uploads_one_signed_object() { - let Some(app) = test_app(true).await else { + let Some(app) = delivery_app().await else { return; }; let _guard = guard().lock().await; @@ -5739,7 +5782,7 @@ mod output_delivery { #[tokio::test] async fn s3_output_created_like_the_web_form_delivers() { - let Some(app) = test_app(true).await else { + let Some(app) = delivery_app().await else { return; }; let _guard = guard().lock().await; @@ -5762,7 +5805,7 @@ mod output_delivery { #[tokio::test] async fn s3_output_config_that_cannot_deliver_is_refused() { - let Some(app) = test_app(true).await else { + let Some(app) = delivery_app().await else { return; }; let _guard = guard().lock().await; @@ -5807,7 +5850,7 @@ mod output_delivery { #[tokio::test] async fn turning_an_s3_output_off_and_on_keeps_its_settings() { - let Some(app) = test_app(true).await else { + let Some(app) = delivery_app().await else { return; }; let _guard = guard().lock().await; @@ -5850,7 +5893,7 @@ mod output_delivery { #[tokio::test] async fn s3_access_denied_is_permanent_and_server_errors_retry() { - let Some(app) = test_app(true).await else { + let Some(app) = delivery_app().await else { return; }; let _guard = guard().lock().await; @@ -5970,7 +6013,7 @@ mod output_delivery { #[tokio::test] async fn concurrent_deliver_pending_sends_each_delivery_once() { - let Some(app) = test_app(true).await else { + let Some(app) = delivery_app().await else { return; }; let _guard = guard().lock().await; @@ -6014,7 +6057,7 @@ mod output_delivery { #[tokio::test] async fn interrupted_send_is_retried_after_lease_expiry() { - let Some(app) = test_app(true).await else { + let Some(app) = delivery_app().await else { return; }; let _guard = guard().lock().await; @@ -6062,7 +6105,7 @@ mod output_delivery { #[tokio::test] async fn runs_finished_during_long_outage_are_delivered_once() { - let Some(app) = test_app(true).await else { + let Some(app) = delivery_app().await else { return; }; let _guard = guard().lock().await; @@ -6082,7 +6125,7 @@ mod output_delivery { #[tokio::test] async fn new_output_does_not_backfill_old_runs() { - let Some(app) = test_app(true).await else { + let Some(app) = delivery_app().await else { return; }; let _guard = guard().lock().await; @@ -6102,7 +6145,7 @@ mod output_delivery { #[tokio::test] async fn client_errors_are_permanent_and_server_errors_retry() { - let Some(app) = test_app(true).await else { + let Some(app) = delivery_app().await else { return; }; let _guard = guard().lock().await; @@ -6158,7 +6201,7 @@ mod output_delivery { #[tokio::test] async fn deleted_or_disabled_output_leaves_no_pending_rows() { - let Some(app) = test_app(true).await else { + let Some(app) = delivery_app().await else { return; }; let _guard = guard().lock().await; @@ -6194,7 +6237,7 @@ mod output_delivery { #[tokio::test] async fn delivery_history_shows_results_and_hides_runs_from_members() { - let Some(app) = test_app(true).await else { + let Some(app) = delivery_app().await else { return; }; let _guard = guard().lock().await; @@ -11676,42 +11719,9 @@ async fn settings_write_has_a_ceiling_for_toggles_and_access_teams() { } async fn licensed_test_app() -> Option { - let mut app = test_app(true).await?; - use ed25519_dalek::{Signer, SigningKey}; - - let signing = SigningKey::from_bytes(&[202u8; 32]); - let kid = "orbit-test-role-grants"; - let public_key = - base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()); - std::env::set_var( - "ORBIT_LICENSE_PUBLIC_KEYS", - json!({ kid: public_key }).to_string(), - ); - let encode = |value: Value| { - base64::engine::general_purpose::URL_SAFE_NO_PAD - .encode(serde_json::to_vec(&value).expect("license JSON")) - }; - let header = encode(json!({ "alg": "EdDSA", "kid": kid })); - let claims = encode(json!({ - "v": 1, - "id": "orbit-test-role-grants", - "customer": "Test", - "plan": "enterprise", - "features": ["custom_roles", "teams"], - "issued_at": "2020-01-01T00:00:00Z", - "expires_at": "2099-01-01T00:00:00Z", - "grace_days": 0, - })); - let signed = format!("{header}.{claims}"); - let signature = base64::engine::general_purpose::URL_SAFE_NO_PAD - .encode(signing.sign(signed.as_bytes()).to_bytes()); - app.state.license = orbit_security::LicenseHandle::load(orbit_security::LicenseSource { - token: Some(format!("{signed}.{signature}")), - file: None, - }); - // The router keeps its own clone of the state, so rebuild it with the licensed one. - app.router = orbit_api::build_router(app.state.clone()); - Some(app) + // The licence is installed as a verified status: signing a token here would need a + // test key in ORBIT_LICENSE_PUBLIC_KEYS, which is process-wide state (#445). + test_app_with_license(true, Some(licensed(&["custom_roles", "teams"], json!({})))).await } #[tokio::test] diff --git a/crates/orbit-api/tests/portable_export_import.rs b/crates/orbit-api/tests/portable_export_import.rs index f95559e4..43e94021 100644 --- a/crates/orbit-api/tests/portable_export_import.rs +++ b/crates/orbit-api/tests/portable_export_import.rs @@ -128,6 +128,7 @@ async fn env() -> Option { file: None, }), shutdown: tokio_util::sync::CancellationToken::new(), + outbound: orbit_security::OutboundPolicy::default(), }; Some(Env { router: build_router(state), diff --git a/crates/orbit-s3/src/lib.rs b/crates/orbit-s3/src/lib.rs index 4567c201..922ee362 100644 --- a/crates/orbit-s3/src/lib.rs +++ b/crates/orbit-s3/src/lib.rs @@ -395,18 +395,34 @@ pub struct S3Client { config: S3Config, credentials: S3Credentials, http: reqwest::Client, + policy: orbit_security::OutboundPolicy, } impl S3Client { + /// A client guarded by the outbound policy from `ORBIT_OUTBOUND_*` (the worker). pub fn new(config: S3Config, credentials: S3Credentials) -> Result { + Self::with_policy( + config, + credentials, + orbit_security::OutboundPolicy::from_env(), + ) + } + + /// A client guarded by the given outbound policy (the API passes its own, #445). + pub fn with_policy( + config: S3Config, + credentials: S3Credentials, + policy: orbit_security::OutboundPolicy, + ) -> Result { let http = orbit_security::guarded_client_with_policy( std::time::Duration::from_secs(60), - orbit_security::OutboundPolicy::from_env(), + policy.clone(), ); Ok(Self { config, credentials, http, + policy, }) } @@ -599,12 +615,9 @@ impl S3Client { extra_header: Option<(&str, String)>, ) -> Result { let url = build_url(&self.config, bucket, key, query).map_err(S3Error::permanent)?; - orbit_security::check_outbound_url( - url.as_str(), - &orbit_security::OutboundPolicy::from_env(), - ) - .await - .map_err(|error| S3Error::outbound(&error))?; + orbit_security::check_outbound_url(url.as_str(), &self.policy) + .await + .map_err(|error| S3Error::outbound(&error))?; let payload_hash = hex::encode(Sha256::digest(body.unwrap_or_default())); let now = Utc::now(); let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string(); @@ -890,6 +903,16 @@ async fn read_limited( mod tests { use super::*; + /// The mock servers listen on 127.0.0.1, which the outbound guard refuses unless the + /// policy exempts it; the policy is passed in rather than set in the environment. + fn test_client(config: S3Config, credentials: S3Credentials) -> Result { + S3Client::with_policy( + config, + credentials, + orbit_security::OutboundPolicy::new(true, "127.0.0.1"), + ) + } + fn connection() -> (S3Config, S3Credentials) { S3Config::from_connection( &serde_json::json!({ @@ -909,7 +932,7 @@ mod tests { #[test] fn keys_cannot_escape_the_prefix() { let (config, credentials) = connection(); - let client = S3Client::new(config, credentials).unwrap(); + let client = test_client(config, credentials).unwrap(); assert!(client.config.object_key("orbit/runs/a.txt").is_ok()); assert!(client.config.object_key("other/a.txt").is_err()); assert!(client.config.object_key("orbit/../a.txt").is_err()); @@ -976,7 +999,7 @@ mod tests { #[test] fn bucket_allowlist_is_required() { let (config, credentials) = connection(); - let client = S3Client::new(config, credentials).unwrap(); + let client = test_client(config, credentials).unwrap(); assert!(client.config.bucket(Some("orbit")).is_ok()); assert!(client.config.bucket(Some("other")).is_err()); } @@ -984,7 +1007,7 @@ mod tests { #[test] fn path_style_urls_include_the_bucket() { let (config, credentials) = connection(); - let client = S3Client::new(config, credentials).unwrap(); + let client = test_client(config, credentials).unwrap(); let url = build_url( &client.config, Some("orbit"), @@ -1001,7 +1024,6 @@ mod tests { #[tokio::test] async fn put_object_signs_a_path_style_request() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; - std::env::set_var("ORBIT_OUTBOUND_ALLOWED_HOSTS", "127.0.0.1"); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let (tx, rx) = tokio::sync::oneshot::channel(); @@ -1035,7 +1057,7 @@ mod tests { Some(r#"{ "accessKeyId": "AK", "secretAccessKey": "SK" }"#), ) .unwrap(); - let client = S3Client::new(config, credentials).unwrap(); + let client = test_client(config, credentials).unwrap(); client .put_object(None, "orbit/runs/one.txt", b"hello", "text/plain") .await @@ -1137,7 +1159,6 @@ mod tests { async fn answer_with(status_line: &'static str, body: String) -> std::net::SocketAddr { use tokio::io::{AsyncReadExt, AsyncWriteExt}; - std::env::set_var("ORBIT_OUTBOUND_ALLOWED_HOSTS", "127.0.0.1"); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); tokio::spawn(async move { @@ -1165,7 +1186,7 @@ mod tests { Some(SECRET), ) .unwrap(); - S3Client::new(config, credentials).unwrap() + test_client(config, credentials).unwrap() } #[tokio::test] @@ -1214,7 +1235,7 @@ mod tests { async fn put(endpoint: String) -> Result<(), S3Error> { let (config, credentials) = S3Config::for_output(&form_config(&endpoint), Some(SECRET)).unwrap(); - S3Client::new(config, credentials) + test_client(config, credentials) .unwrap() .put_object(None, "runs/one.txt", b"hello", "text/plain") .await @@ -1239,7 +1260,6 @@ mod tests { #[tokio::test] async fn connection_errors_are_transient() { - std::env::set_var("ORBIT_OUTBOUND_ALLOWED_HOSTS", "127.0.0.1"); let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); drop(listener); @@ -1254,7 +1274,7 @@ mod tests { assert!(!error.retryable, "{error}"); let (config, credentials) = S3Config::for_output(&form_config("https://s3.example"), Some(SECRET)).unwrap(); - let error = S3Client::new(config, credentials) + let error = test_client(config, credentials) .unwrap() .put_object(Some("other"), "runs/one.txt", b"hello", "text/plain") .await diff --git a/services/api/src/main.rs b/services/api/src/main.rs index 27c95234..1e0e330c 100644 --- a/services/api/src/main.rs +++ b/services/api/src/main.rs @@ -99,6 +99,7 @@ async fn main() -> anyhow::Result<()> { output_delivery_retention_days: config.output_delivery_retention_days, license: LicenseHandle::load(LicenseSource::from_env()), shutdown: shutdown.clone(), + outbound: orbit_security::OutboundPolicy::from_env(), }; // End work left behind by a previous API process before any background loop starts.