From afb462f336ffc4d01b9885e8e4fbf01ed34224b7 Mon Sep 17 00:00:00 2001 From: Adel Zaalouk Date: Mon, 27 Jul 2026 16:37:33 +0200 Subject: [PATCH 1/6] fix(router): strip unsupported Anthropic beta fields from Vertex rawPredict body (#2465) Claude Code v2.1.156+ sends `context_management` on every request. The direct Anthropic API accepts it, but Vertex AI rawPredict rejects it with HTTP 400 "Extra inputs are not permitted". The inference proxy was only stripping the `model` field for Vertex routes; extend it to also strip Anthropic-SDK-only beta fields listed in VERTEX_UNSUPPORTED_BODY_FIELDS. Fixes #2444 Signed-off-by: Adel Zaalouk --- crates/openshell-router/src/backend.rs | 141 +++++++++++++++++- .../tests/backend_integration.rs | 115 +++++++++++++- 2 files changed, 251 insertions(+), 5 deletions(-) diff --git a/crates/openshell-router/src/backend.rs b/crates/openshell-router/src/backend.rs index 9fbd538c06..19c2ae5272 100644 --- a/crates/openshell-router/src/backend.rs +++ b/crates/openshell-router/src/backend.rs @@ -82,6 +82,16 @@ const VERTEX_ANTHROPIC_VERSION: &str = "vertex-2023-10-16"; const COMMON_INFERENCE_REQUEST_HEADERS: [&str; 4] = ["content-type", "accept", "accept-encoding", "user-agent"]; +/// Anthropic-SDK-only body fields that Vertex AI rawPredict does not accept. +/// Vertex AI's rawPredict endpoint uses strict pydantic validation and rejects +/// any extra inputs not in its schema. The Anthropic SDKs' native Vertex +/// transport (`AnthropicVertex`) strips these automatically; we must do the same +/// when proxying through `inference.local`. +/// +/// `model` is handled separately (rewritten or stripped depending on route type) +/// and is intentionally omitted here. +const VERTEX_UNSUPPORTED_BODY_FIELDS: &[&str] = &["context_management"]; + impl StreamingProxyResponse { /// Create from a fully-buffered [`ProxyResponse`] (for mock routes). pub fn from_buffered(resp: ProxyResponse) -> Self { @@ -281,11 +291,12 @@ fn prepare_backend_request( let needs_vertex_anthropic_version = is_vertex_anthropic_rawpredict_route(route); if needs_vertex_anthropic_version { // Vertex AI rawPredict encodes the model in the URL path, not - // the request body. Clients using the standard Anthropic API - // (e.g. Claude Code via inference.local) always send "model" - // in the body; strip it so Vertex AI does not reject the - // request with "Extra inputs are not permitted". + // the request body. Strip "model" and any Anthropic-SDK-only + // beta fields that Vertex's strict pydantic validation rejects. obj.remove("model"); + for field in VERTEX_UNSUPPORTED_BODY_FIELDS { + obj.remove(*field); + } } else if route_is_bedrock(route) { // AWS Bedrock InvokeModel encodes the model in the URL // path; the request body is the raw provider-specific @@ -1970,6 +1981,128 @@ mod tests { ); } + #[tokio::test] + async fn vertex_ai_body_strips_unsupported_beta_fields() { + let mock_server = MockServer::start().await; + + let base_path = "/v1/projects/my-project/locations/us-east5/publishers/anthropic/models"; + let route = ResolvedRoute { + name: "vertex-anthropic".to_string(), + endpoint: format!("{}{base_path}", mock_server.uri()), + model: "claude-sonnet-4-6@20250514".to_string(), + api_key: "ya29.token".to_string(), + protocols: vec!["anthropic_messages".to_string()], + auth: AuthHeader::Bearer, + default_headers: Vec::new(), + passthrough_headers: Vec::new(), + timeout: DEFAULT_ROUTE_TIMEOUT, + model_in_path: true, + request_path_override: Some(":rawPredict".to_string()), + }; + + Mock::given(method("POST")) + .and(path(format!( + "{base_path}/claude-sonnet-4-6@20250514:rawPredict" + ))) + .respond_with( + ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "msg_1"})), + ) + .mount(&mock_server) + .await; + + let client = reqwest::Client::builder().build().unwrap(); + let body = bytes::Bytes::from( + serde_json::to_vec(&serde_json::json!({ + "model": "claude-sonnet-4-6-20250514", + "messages": [{"role": "user", "content": "ping"}], + "max_tokens": 32, + "context_management": {"enabled": true}, + })) + .unwrap(), + ); + let headers = vec![("content-type".to_string(), "application/json".to_string())]; + + let (builder, _url) = prepare_backend_request( + &client, + &route, + "POST", + "/v1/messages", + &headers, + body, + false, + ) + .unwrap(); + + let response = builder.send().await.unwrap(); + assert_eq!(response.status().as_u16(), 200); + let received = mock_server.received_requests().await.unwrap(); + let received_body: serde_json::Value = serde_json::from_slice(&received[0].body).unwrap(); + let obj = received_body.as_object().unwrap(); + assert!( + !obj.contains_key("context_management"), + "context_management must be stripped for Vertex AI rawPredict, got: {received_body}" + ); + assert!( + !obj.contains_key("model"), + "model must also be stripped for Vertex AI rawPredict, got: {received_body}" + ); + assert!( + obj.contains_key("messages"), + "standard fields must be preserved, got: {received_body}" + ); + } + + #[tokio::test] + async fn direct_anthropic_preserves_beta_fields() { + let route = ResolvedRoute { + name: "direct-anthropic".to_string(), + endpoint: "https://api.anthropic.com/v1".to_string(), + model: "claude-sonnet-4-6-20250514".to_string(), + api_key: "sk-test".to_string(), + protocols: vec!["anthropic_messages".to_string()], + auth: AuthHeader::Custom("x-api-key"), + default_headers: Vec::new(), + passthrough_headers: Vec::new(), + timeout: DEFAULT_ROUTE_TIMEOUT, + model_in_path: false, + request_path_override: None, + }; + + let client = reqwest::Client::builder().build().unwrap(); + let body = bytes::Bytes::from( + serde_json::to_vec(&serde_json::json!({ + "model": "claude-sonnet-4-6-20250514", + "messages": [{"role": "user", "content": "ping"}], + "max_tokens": 32, + "context_management": {"enabled": true}, + })) + .unwrap(), + ); + let headers = vec![("content-type".to_string(), "application/json".to_string())]; + + let (builder, _url) = prepare_backend_request( + &client, + &route, + "POST", + "/v1/messages", + &headers, + body, + false, + ) + .unwrap(); + + let request = builder.build().unwrap(); + let sent_body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert!( + sent_body + .as_object() + .unwrap() + .contains_key("context_management"), + "context_management must be preserved for direct Anthropic API routes" + ); + } + #[tokio::test] async fn vertex_ai_body_preserves_client_anthropic_version() { // When the client already sends anthropic_version, the router must NOT overwrite it. diff --git a/crates/openshell-router/tests/backend_integration.rs b/crates/openshell-router/tests/backend_integration.rs index 02f94b868c..fe5c2dd0bc 100644 --- a/crates/openshell-router/tests/backend_integration.rs +++ b/crates/openshell-router/tests/backend_integration.rs @@ -4,7 +4,7 @@ use openshell_router::Router; use openshell_router::config::{AuthHeader, ResolvedRoute, RouteConfig, RouterConfig}; use wiremock::matchers::{bearer_token, body_partial_json, header, method, path}; -use wiremock::{Mock, MockServer, ResponseTemplate}; +use wiremock::{Match, Mock, MockServer, Request, ResponseTemplate}; fn mock_candidates(base_url: &str) -> Vec { vec![ResolvedRoute { @@ -668,6 +668,119 @@ async fn proxy_vertex_anthropic_route_uses_model_path_suffix() { ); } +/// Fields that Vertex AI rawPredict actually accepts for Anthropic models. +const VERTEX_ACCEPTED_FIELDS: &[&str] = &[ + "anthropic_version", + "messages", + "max_tokens", + "stop_sequences", + "stream", + "system", + "temperature", + "thinking", + "tool_choice", + "tools", + "top_k", + "top_p", + "metadata", +]; + +/// Simulates Vertex AI's strict pydantic validation: rejects any body field not +/// in the known Anthropic Messages API schema. This is what causes the real 400 +/// error described in #2444. +struct VertexStrictBodyValidator; + +impl Match for VertexStrictBodyValidator { + fn matches(&self, request: &Request) -> bool { + let Ok(body) = serde_json::from_slice::(&request.body) else { + return false; + }; + let Some(obj) = body.as_object() else { + return false; + }; + obj.keys() + .all(|k| VERTEX_ACCEPTED_FIELDS.contains(&k.as_str())) + } +} + +/// End-to-end reproduction of #2444: Claude Code sends `context_management` in +/// the body, the router must strip it before it reaches Vertex. The mock uses +/// strict body validation (like Vertex's pydantic) so the request only succeeds +/// if the field was actually removed. +#[tokio::test] +async fn proxy_vertex_strips_beta_fields_e2e() { + let mock_server = MockServer::start().await; + + let model_path = "/v1/projects/my-project/locations/us-east5/publishers/anthropic/models"; + let model = "claude-sonnet-4-6@20250514"; + + // This mock only matches if the body passes strict validation — + // context_management would cause a mismatch (simulating a real 400). + Mock::given(method("POST")) + .and(path(format!("{model_path}/{model}:rawPredict"))) + .and(VertexStrictBodyValidator) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "id": "msg_1", + "type": "message", + "role": "assistant", + "model": model, + "content": [{"type": "text", "text": "Pong"}] + }))) + .mount(&mock_server) + .await; + + let router = Router::new().unwrap(); + let candidates = vec![ResolvedRoute { + name: "vertex-test".to_string(), + endpoint: format!("{}{model_path}", mock_server.uri()), + model: model.to_string(), + api_key: "ya29.token".to_string(), + protocols: vec!["anthropic_messages".to_string()], + auth: AuthHeader::Bearer, + default_headers: Vec::new(), + passthrough_headers: vec!["anthropic-beta".to_string()], + timeout: openshell_router::config::DEFAULT_ROUTE_TIMEOUT, + model_in_path: true, + request_path_override: Some(":rawPredict".to_string()), + }]; + + // Exact payload Claude Code v2.1.156+ sends: includes model, + // context_management, and anthropic-beta header. + let body = serde_json::to_vec(&serde_json::json!({ + "model": "claude-sonnet-4-6-20250514", + "messages": [{"role": "user", "content": "say pong"}], + "max_tokens": 128, + "context_management": {"enabled": true}, + })) + .unwrap(); + + let response = router + .proxy_with_candidates( + "anthropic_messages", + "POST", + "/v1/messages", + vec![ + ("content-type".to_string(), "application/json".to_string()), + ( + "anthropic-beta".to_string(), + "context-management-2025-06-27".to_string(), + ), + ], + bytes::Bytes::from(body), + &candidates, + ) + .await + .unwrap(); + + // If context_management leaked through, the strict mock wouldn't match + // and wiremock would return 404. + assert_eq!( + response.status, 200, + "request must succeed — context_management should have been stripped. \ + A 404 here means the strict body validator rejected an unsupported field." + ); +} + #[tokio::test] async fn proxy_vertex_anthropic_streaming_route_uses_stream_rawpredict() { let mock_server = MockServer::start().await; From 516be602d89ddef440be44c9b906d0ef1c3c8198 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Mon, 27 Jul 2026 09:38:09 -0500 Subject: [PATCH 2/6] fix: assorted byte-index slicing safety fixes (#2452) * fix(supervisor-process): use slice patterns when rewriting passwd/group lines rewrite_passwd_at and rewrite_group_at indexed into a Vec of fields with fields[N] after checking fields.len(). Use slice patterns so a malformed line falls through to the no-op branch instead of risking a panic if the guard is ever changed. Add regression tests for malformed sandbox entries. Signed-off-by: Andrew White * fix(bootstrap): avoid byte-index slice after @ in SSH destination extract_host_from_ssh_destination sliced dest[at_pos + 1..] after finding '@'. '@' is ASCII so this is currently safe, but it is a latent panic surface if the split logic changes. Use get() instead and add a multi-byte hostname test. Signed-off-by: Andrew White * fix(bootstrap): avoid byte-index slice in .dockerignore glob matcher glob_match sliced path[idx + 1..] after matching '/'. '/' is ASCII so this is currently safe, but it is a latent UTF-8 panic surface. Use get() instead. Signed-off-by: Andrew White * fix(router): avoid literal byte offset when stripping /v1 prefix build_backend_url sliced &path[3..] after verifying the /v1 prefix. Use strip_prefix() so the code stays correct if the prefix length ever changes. Signed-off-by: Andrew White * fix(supervisor-network): avoid byte-index slice in inference path matching The Bedrock-style /*/ path matcher sliced rest[slash_at + 1..] after finding '/'. '/' is ASCII so this is currently safe, but it is a latent UTF-8 panic surface. Use get() instead. Signed-off-by: Andrew White --------- Signed-off-by: Andrew White --- crates/openshell-bootstrap/src/build.rs | 5 ++- crates/openshell-bootstrap/src/metadata.rs | 8 ++++- crates/openshell-router/src/backend.rs | 8 +++-- .../src/l7/inference.rs | 5 ++- .../src/process.rs | 35 +++++++++++++++---- 5 files changed, 49 insertions(+), 12 deletions(-) diff --git a/crates/openshell-bootstrap/src/build.rs b/crates/openshell-bootstrap/src/build.rs index efa040c34a..f0e03fcd89 100644 --- a/crates/openshell-bootstrap/src/build.rs +++ b/crates/openshell-bootstrap/src/build.rs @@ -398,7 +398,9 @@ fn glob_match(pattern: &str, path: &str, is_dir: bool) -> bool { return true; } for (idx, _) in path.match_indices('/') { - if glob_match(rest, &path[idx + 1..], is_dir) { + if let Some(suffix) = path.get(idx + 1..) + && glob_match(rest, suffix, is_dir) + { return true; } } @@ -592,6 +594,7 @@ mod tests { assert!(glob_match("**/*.log", "a/b/c.log", false)); assert!(glob_match("**/*.log", "c.log", false)); assert!(!glob_match("**/*.log", "c.txt", false)); + assert!(glob_match("**/föö.log", "a/b/föö.log", false)); } #[test] diff --git a/crates/openshell-bootstrap/src/metadata.rs b/crates/openshell-bootstrap/src/metadata.rs index fe4c277bd2..8190fac829 100644 --- a/crates/openshell-bootstrap/src/metadata.rs +++ b/crates/openshell-bootstrap/src/metadata.rs @@ -142,7 +142,8 @@ pub fn extract_host_from_ssh_destination(destination: &str) -> String { // Handle user@host format dest.find('@') - .map_or_else(|| dest.to_string(), |at_pos| dest[at_pos + 1..].to_string()) + .and_then(|at_pos| dest.get(at_pos + 1..)) + .map_or_else(|| dest.to_string(), ToString::to_string) } /// Resolve an SSH host alias to the actual hostname or IP address. @@ -457,6 +458,11 @@ mod tests { ); } + #[test] + fn extract_host_user_at_multi_byte_hostname() { + assert_eq!(extract_host_from_ssh_destination("user@mülti"), "mülti"); + } + #[test] fn metadata_roundtrip() { let meta = GatewayMetadata { diff --git a/crates/openshell-router/src/backend.rs b/crates/openshell-router/src/backend.rs index 19c2ae5272..df8830ae39 100644 --- a/crates/openshell-router/src/backend.rs +++ b/crates/openshell-router/src/backend.rs @@ -835,8 +835,12 @@ fn build_backend_url(endpoint: &str, path: &str) -> String { let base_path = &base[path_start..]; base_path.starts_with("/v1/") || base_path.ends_with("/v1") }); - if base_path_has_v1_edge_segment && (path == "/v1" || path.starts_with("/v1/")) { - return format!("{base}{}", &path[3..]); + if base_path_has_v1_edge_segment + && let Some(rest) = path + .strip_prefix("/v1") + .filter(|rest| rest.is_empty() || rest.starts_with('/')) + { + return format!("{base}{rest}"); } format!("{base}{path}") diff --git a/crates/openshell-supervisor-network/src/l7/inference.rs b/crates/openshell-supervisor-network/src/l7/inference.rs index e06dffd324..5aefab9e93 100644 --- a/crates/openshell-supervisor-network/src/l7/inference.rs +++ b/crates/openshell-supervisor-network/src/l7/inference.rs @@ -179,7 +179,10 @@ pub fn detect_inference_pattern<'a>( let Some(slash_at) = rest.find('/') else { return false; }; - return slash_at > 0 && rest[slash_at + 1..] == *after; + let Some(after_segment) = rest.get(slash_at + 1..) else { + return false; + }; + return slash_at > 0 && after_segment == after; } path_only == p.path_glob diff --git a/crates/openshell-supervisor-process/src/process.rs b/crates/openshell-supervisor-process/src/process.rs index 322dcadd86..3733c7c7e3 100644 --- a/crates/openshell-supervisor-process/src/process.rs +++ b/crates/openshell-supervisor-process/src/process.rs @@ -1101,11 +1101,8 @@ fn rewrite_passwd_at(path: &Path, uid: &str, gid: &str) -> Result<()> { if line.starts_with("sandbox:") { found = true; let fields: Vec<&str> = line.split(':').collect(); - if fields.len() >= 7 { - format!( - "{}:{}:{}:{}:{}:{}:{}", - fields[0], fields[1], uid, gid, fields[4], fields[5], fields[6] - ) + if let [name, pass, _, _, gecos, home, shell, ..] = fields.as_slice() { + format!("{name}:{pass}:{uid}:{gid}:{gecos}:{home}:{shell}") } else { line.to_string() } @@ -1139,8 +1136,8 @@ fn rewrite_group_at(path: &Path, gid: &str) -> Result<()> { if line.starts_with("sandbox:") { found = true; let fields: Vec<&str> = line.split(':').collect(); - if fields.len() >= 4 { - format!("{}:{}:{}:{}", fields[0], fields[1], gid, fields[3]) + if let [name, pass, _, members, ..] = fields.as_slice() { + format!("{name}:{pass}:{gid}:{members}") } else { line.to_string() } @@ -2302,6 +2299,30 @@ mod tests { assert!(content.contains("sandbox:x:6000:")); } + #[cfg(unix)] + #[test] + fn rewrite_passwd_leaves_malformed_entry_unchanged() { + let dir = tempfile::tempdir().unwrap(); + let passwd = dir.path().join("passwd"); + // Only 3 fields — slice pattern should fall through instead of panic. + std::fs::write(&passwd, "sandbox:x:1000\n").unwrap(); + rewrite_passwd_at(&passwd, "5000", "6000").unwrap(); + let content = std::fs::read_to_string(&passwd).unwrap(); + assert!(content.contains("sandbox:x:1000")); + } + + #[cfg(unix)] + #[test] + fn rewrite_group_leaves_malformed_entry_unchanged() { + let dir = tempfile::tempdir().unwrap(); + let group = dir.path().join("group"); + // Only 2 fields — slice pattern should fall through instead of panic. + std::fs::write(&group, "sandbox:x\n").unwrap(); + rewrite_group_at(&group, "6000").unwrap(); + let content = std::fs::read_to_string(&group).unwrap(); + assert!(content.contains("sandbox:x")); + } + #[cfg(unix)] #[test] fn rewrite_passwd_preserves_other_entries() { From 76a5397e6fcf10386f5d8533f72e32808833b226 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Mon, 27 Jul 2026 09:39:40 -0500 Subject: [PATCH 3/6] fix: assorted arithmetic and indexing robustness fixes (#2451) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(core): avoid i64 underflow on expired GCP token When a cached GCP access token was already expired (expires_at_ms < now), the remaining lifetime calculation used plain subtraction: (expires_at_ms - now) / 1000. This underflows in debug builds and wraps in release builds. Use saturating_sub so an expired token simply yields a non-positive remaining lifetime and is skipped. Add a regression test. Signed-off-by: Andrew White * fix(server): avoid i64 underflow in lease age calculation The lease steal path computed age as now_ms() - record.updated_at_ms. If the stored updated_at timestamp is in the future (e.g. clock skew), the subtraction underflows. Use saturating_sub to treat a future timestamp as age 0, keeping the lease considered fresh. Signed-off-by: Andrew White * fix(server): avoid i64 overflow on large credential max lifetime max_lifetime_seconds is only validated as >= 0. The code multiplied the raw i64 value by 1000 to compute max_expires, which overflows for values above i64::MAX / 1000. The capped i32 value used for the STS request was already computed but not reused. Compute max_lifetime_ms from the capped value with saturating_mul and use it for both expires_at fallback and max_expires. Signed-off-by: Andrew White * fix(server): avoid hardcoded indexing into base_url_config_keys resolve_vertex_ai_route assumed every inference provider profile has at least two base URL config keys by indexing [0] and [1]. Only the Vertex profile satisfies that today; other profiles would panic here. Iterate base_url_config_keys with find_map instead, and add a test with an empty key list to ensure no panic. Signed-off-by: Andrew White * fix(server): clamp lease age at zero for future timestamps Address review feedback: add regression coverage for future-timestamp lease clock skew. Extract lease_is_expired() and clamp the age at zero — i64::saturating_sub saturates at i64::MIN, not zero, so a future updated_at_ms must be clamped explicitly to be treated as age zero and remain unstealable with a positive TTL. Signed-off-by: Andrew White * fix(server): fall back past blank preferred Vertex base URL Address review feedback: find_map stopped at the first present key even when its value was blank, and the outer filter discarded it without considering lower-priority aliases. Filter blank values inside the closure so a blank preferred key falls back to a valid alias, matching the documented priority order. Add a regression test with a blank preferred key and a valid fallback. Signed-off-by: Andrew White * fix(server): saturate AWS STS expiry cap on saturated clock Address review feedback: now_ms + max_lifetime_ms could still overflow when current_time_ms() saturates near i64::MAX. Compute max_expires = now_ms.saturating_add(max_lifetime_ms) once and use it for both the conversion fallback and the expiry cap. Add a boundary unit test covering a saturated clock. Signed-off-by: Andrew White --------- Signed-off-by: Andrew White --- .../src/provider_credentials.rs | 23 ++++++- crates/openshell-server/src/compute/lease.rs | 37 +++++++++- crates/openshell-server/src/inference.rs | 67 +++++++++++++++++-- .../openshell-server/src/provider_refresh.rs | 18 +++-- 4 files changed, 133 insertions(+), 12 deletions(-) diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index 65310b3a43..d0b7b38ad5 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -243,7 +243,7 @@ impl ProviderCredentialState { DEFAULT_EXPIRES_IN } else { let now = crate::time::now_ms(); - (expires_at_ms - now) / 1000 + expires_at_ms.saturating_sub(now) / 1000 } }, ); @@ -587,6 +587,27 @@ mod tests { ); } + #[test] + fn gcp_token_response_handles_already_expired_token_without_panic() { + let now_ms = i64::try_from( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis(), + ) + .unwrap(); + let state = ProviderCredentialState::from_environment( + 1, + HashMap::from([("GCP_ADC_ACCESS_TOKEN".to_string(), "adc-tok".to_string())]), + HashMap::from([("GCP_ADC_ACCESS_TOKEN".to_string(), now_ms - 1_000)]), + HashMap::new(), + ); + assert!( + state.gcp_token_response().is_none(), + "expired token should be skipped rather than panic" + ); + } + #[test] fn child_env_with_gcp_resolved_resolves_vertex_vars_without_metadata_host() { let state = ProviderCredentialState::from_environment( diff --git a/crates/openshell-server/src/compute/lease.rs b/crates/openshell-server/src/compute/lease.rs index 1de4de4734..bf58fae48b 100644 --- a/crates/openshell-server/src/compute/lease.rs +++ b/crates/openshell-server/src/compute/lease.rs @@ -121,9 +121,9 @@ impl ReconcilerLease { pub async fn try_steal_expired(&self) -> Result { let record = self.read().await?.ok_or(LeaseError::NotFound)?; - let age_ms = now_ms() - record.updated_at_ms; + let current_ms = now_ms(); let ttl_ms = i64::try_from(self.ttl.as_millis()).unwrap_or(i64::MAX); - if age_ms < ttl_ms { + if !lease_is_expired(current_ms, record.updated_at_ms, ttl_ms) { return Err(LeaseError::AlreadyHeld); } @@ -252,6 +252,17 @@ pub fn replica_id() -> String { .unwrap_or_else(|_| uuid::Uuid::new_v4().to_string()) } +/// True if a lease record's age exceeds its TTL. +/// +/// Clamps at zero so a stored `updated_at_ms` in the future (clock skew) +/// is treated as age zero and the lease is considered fresh. Note that +/// `i64::saturating_sub` alone is not sufficient here: it saturates at +/// `i64::MIN`, not zero. +fn lease_is_expired(now_ms: i64, updated_at_ms: i64, ttl_ms: i64) -> bool { + let age_ms = now_ms.saturating_sub(updated_at_ms).max(0); + age_ms >= ttl_ms +} + #[cfg(test)] mod tests { use super::*; @@ -351,6 +362,28 @@ mod tests { assert_eq!(record.resource_version, guard.resource_version); } + #[test] + fn future_updated_at_is_treated_as_age_zero() { + let now = 1_000_000; + let future_updated = now + 86_400_000; // 1 day in the future + assert!( + !lease_is_expired(now, future_updated, 1_000), + "future updated_at_ms should not be stealable with positive TTL" + ); + assert!( + lease_is_expired(now, future_updated, 0), + "TTL zero always expires regardless of timestamp" + ); + assert!( + !lease_is_expired(now, now, 1_000), + "fresh lease with positive TTL should not be expired" + ); + assert!( + lease_is_expired(now, now, 0), + "present timestamp with TTL zero should be expired" + ); + } + #[tokio::test] async fn release_allows_immediate_reacquire() { let store = test_store().await; diff --git a/crates/openshell-server/src/inference.rs b/crates/openshell-server/src/inference.rs index 97217c2565..39d6afe2fd 100644 --- a/crates/openshell-server/src/inference.rs +++ b/crates/openshell-server/src/inference.rs @@ -627,11 +627,11 @@ fn resolve_vertex_ai_route( // protocol and path contract, but only for the OpenAI-compatible Vertex surface. // Anthropic-on-Vertex needs model-path shaping and body adaptation that a fully // caller-controlled URL cannot safely preserve. - if let Some(base_url) = config - .get(profile.base_url_config_keys[0]) - .or_else(|| config.get(profile.base_url_config_keys[1])) + if let Some(base_url) = profile + .base_url_config_keys + .iter() + .find_map(|key| config.get(*key).filter(|v| !v.trim().is_empty())) .map(String::as_str) - .filter(|v| !v.trim().is_empty()) { if is_anthropic { return Err(Status::invalid_argument( @@ -1133,6 +1133,65 @@ mod tests { } } + #[test] + fn resolve_vertex_ai_route_handles_empty_base_url_keys() { + let config = HashMap::new(); + let profile = openshell_core::inference::InferenceProviderProfile { + provider_type: "google_vertex_ai", + default_base_url: "https://example.com", + protocols: &[], + credential_key_names: &[], + base_url_config_keys: &[], + auth: openshell_core::inference::AuthHeader::Bearer, + default_headers: &[], + passthrough_headers: &[], + }; + let result = resolve_vertex_ai_route(&config, "model-id", "route", "api-key", &profile); + // Empty base_url_config_keys must not panic. The route still errors because + // the minimal Vertex config is missing, so we only assert reachability. + assert!( + result.is_err(), + "expected missing config to error, got {result:?}" + ); + } + + #[test] + fn resolve_vertex_ai_route_skips_blank_preferred_for_fallback() { + let mut config = HashMap::new(); + config.insert("GOOGLE_VERTEX_AI_BASE_URL".to_string(), " ".to_string()); + config.insert( + "VERTEX_AI_BASE_URL".to_string(), + "https://us-central1-aiplatform.googleapis.com".to_string(), + ); + config.insert( + VERTEX_AI_PROJECT_ID_KEY.to_string(), + "my-project".to_string(), + ); + config.insert(VERTEX_AI_REGION_KEY.to_string(), "us-central1".to_string()); + + let profile = openshell_core::inference::InferenceProviderProfile { + provider_type: "google-vertex-ai", + default_base_url: "", + protocols: &[], + credential_key_names: &[], + base_url_config_keys: &["GOOGLE_VERTEX_AI_BASE_URL", "VERTEX_AI_BASE_URL"], + auth: openshell_core::inference::AuthHeader::Bearer, + default_headers: &[], + passthrough_headers: &[], + }; + + let result = resolve_vertex_ai_route(&config, "model-id", "route", "api-key", &profile); + assert!( + result.is_ok(), + "blank preferred key should fall back to valid alias: {result:?}" + ); + let route = result.unwrap(); + assert_eq!( + route.endpoint, + "https://us-central1-aiplatform.googleapis.com" + ); + } + #[test] fn inference_bundle_requires_sandbox_principal() { let sandbox = test_sandbox_principal(); diff --git a/crates/openshell-server/src/provider_refresh.rs b/crates/openshell-server/src/provider_refresh.rs index f8fa867c1b..a51ec53373 100644 --- a/crates/openshell-server/src/provider_refresh.rs +++ b/crates/openshell-server/src/provider_refresh.rs @@ -769,6 +769,7 @@ async fn mint_aws_sts_assume_role( DEFAULT_MAX_LIFETIME_SECONDS }; let max_lifetime = i32::try_from(max_lifetime_i64.min(i64::from(i32::MAX))).unwrap_or(i32::MAX); + let max_lifetime_ms = i64::from(max_lifetime).saturating_mul(1000); let mut req = client .assume_role() @@ -794,11 +795,8 @@ async fn mint_aws_sts_assume_role( let session_token = creds.session_token().to_string(); let now_ms = current_time_ms(); - let expires_at_ms = creds - .expiration() - .to_millis() - .unwrap_or_else(|_| now_ms + max_lifetime_i64 * 1000); - let max_expires = now_ms + max_lifetime_i64 * 1000; + let max_expires = now_ms.saturating_add(max_lifetime_ms); + let expires_at_ms = creds.expiration().to_millis().unwrap_or(max_expires); let expires_at_ms = expires_at_ms.min(max_expires); // Map STS response fields to the env keys the profile bound to each semantic @@ -1519,6 +1517,16 @@ mod tests { ); } + #[test] + fn aws_sts_max_expires_saturates_on_saturated_clock() { + assert_eq!(i64::MAX.saturating_add(3_600_000), i64::MAX); + let now_ms = i64::MAX - 1_000; + let max_lifetime_ms = 3_600_000; + let max_expires = now_ms.saturating_add(max_lifetime_ms); + assert_eq!(max_expires, i64::MAX); + assert!(max_expires >= now_ms); + } + #[tokio::test] async fn aws_sts_assume_role_mints_three_credentials_from_mock_endpoint() { let mock_server = MockServer::start().await; From 2d108818f84be568e63232d5d0aba53775cea4f7 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Mon, 27 Jul 2026 09:40:26 -0500 Subject: [PATCH 4/6] fix(policy): avoid panic truncating multi-byte UTF-8 paths for display (#2448) truncate_for_display sliced at a fixed byte index (&s[..77]), which panics when the index is not a char boundary. A policy with an over-long filesystem path containing multi-byte characters crashed the sandbox supervisor / OPA policy loader instead of producing the intended FieldTooLong violation. Back off to the nearest char boundary before slicing, and add regression tests. Signed-off-by: Andrew White --- crates/openshell-policy/src/lib.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/openshell-policy/src/lib.rs b/crates/openshell-policy/src/lib.rs index ea838b3b74..6c92b1b567 100644 --- a/crates/openshell-policy/src/lib.rs +++ b/crates/openshell-policy/src/lib.rs @@ -1440,7 +1440,13 @@ fn truncate_for_display(s: &str) -> String { if s.len() <= 80 { s.to_string() } else { - format!("{}...", &s[..77]) + // Back off to a char boundary: slicing at a fixed byte index panics + // on multi-byte UTF-8 (e.g. non-ASCII characters in policy paths). + let mut end = 77; + while !s.is_char_boundary(end) { + end -= 1; + } + format!("{}...", &s[..end]) } } @@ -1462,6 +1468,21 @@ pub use openshell_core::paths::normalize_path; mod tests { use super::*; + #[test] + fn truncate_for_display_handles_multi_byte_utf8_without_panicking() { + // Byte index 77 falls inside the multi-byte 'é'. + let s = format!("/{}{}", "a".repeat(75), "é".repeat(100)); + let truncated = truncate_for_display(&s); + assert!(truncated.ends_with("...")); + assert!(truncated.len() <= 80); + } + + #[test] + fn truncate_for_display_leaves_short_strings_untouched() { + let s = "short path"; + assert_eq!(truncate_for_display(s), s); + } + /// Verify that the serialized YAML uses `filesystem_policy` (not /// `filesystem`) so it can be fed back to `parse_sandbox_policy`. #[test] From 39bf94e528a58da6e9112b5b2278c2a1957b29e3 Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Mon, 27 Jul 2026 17:02:04 +0200 Subject: [PATCH 5/6] fix(server): bind gateway listeners before sandbox resume (#2495) * refactor(server): extract gateway listener binding Signed-off-by: Evan Lezar * fix(server): bind gateway listeners before sandbox resume Signed-off-by: Evan Lezar --------- Signed-off-by: Evan Lezar --- crates/openshell-server/src/lib.rs | 65 +++++++++++++++++++++++------- 1 file changed, 50 insertions(+), 15 deletions(-) diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index a75534d397..e832b468cc 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -431,6 +431,9 @@ pub(crate) async fn run_server( // snapshot on its first poll. ensure_default_workspace(&store).await?; + let gateway_listeners = + bind_gateway_listeners(config.bind_address, state.compute.gateway_bind_addresses()).await?; + if let Err(err) = state.compute.resume_persisted_sandboxes().await { warn!(error = %err, "Failed to resume persisted sandboxes during startup"); } @@ -443,18 +446,6 @@ pub(crate) async fn run_server( // Create the multiplexed service let service = MultiplexService::new(state.clone()); - let gateway_listener_addresses = - gateway_listener_addresses(config.bind_address, state.compute.gateway_bind_addresses()); - let mut gateway_listeners = Vec::with_capacity(gateway_listener_addresses.len()); - for address in gateway_listener_addresses { - let listener = TcpListener::bind(address) - .await - .map_err(|e| Error::transport(format!("failed to bind to {address}: {e}")))?; - let local_addr = listener.local_addr().unwrap_or(address); - info!(address = %local_addr, "Server listening"); - gateway_listeners.push((listener, local_addr)); - } - // Bind the unauthenticated health endpoint on a separate port when configured. if let Some(health_bind_address) = config.health_bind_address { let health_listener = TcpListener::bind(health_bind_address).await.map_err(|e| { @@ -569,6 +560,23 @@ fn gateway_listener_addresses( addresses } +async fn bind_gateway_listeners( + bind_address: SocketAddr, + extra_addresses: &[SocketAddr], +) -> Result> { + let addresses = gateway_listener_addresses(bind_address, extra_addresses); + let mut listeners = Vec::with_capacity(addresses.len()); + for address in addresses { + let listener = TcpListener::bind(address) + .await + .map_err(|e| Error::transport(format!("failed to bind to {address}: {e}")))?; + let local_addr = listener.local_addr().unwrap_or(address); + info!(address = %local_addr, "Server listening"); + listeners.push((listener, local_addr)); + } + Ok(listeners) +} + fn listener_covers(existing: SocketAddr, requested: SocketAddr) -> bool { if existing == requested { return true; @@ -1020,8 +1028,8 @@ pub(crate) async fn ensure_default_workspace(store: &Store) -> Result<()> { mod tests { use super::{ ConfiguredComputeDriver, ConnectionProtocol, MultiplexService, ServerState, TlsAcceptor, - allow_plaintext_service_http, classify_initial_bytes, configured_compute_driver, - gateway_listener_addresses, is_benign_tls_handshake_failure, + allow_plaintext_service_http, bind_gateway_listeners, classify_initial_bytes, + configured_compute_driver, gateway_listener_addresses, is_benign_tls_handshake_failure, kubernetes_sandbox_jwt_expiry_disabled, serve_gateway_listener, }; use openshell_core::{ @@ -1030,7 +1038,10 @@ mod tests { }; use std::io::{Error, ErrorKind}; use std::net::SocketAddr; - use std::sync::Arc; + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; use std::time::Duration; use tempfile::{TempDir, tempdir}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -1513,4 +1524,28 @@ mod tests { vec![primary, docker] ); } + + #[tokio::test] + async fn failed_gateway_listener_bind_does_not_attempt_persisted_sandbox_resume() { + let occupied_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let occupied_address = occupied_listener.local_addr().unwrap(); + let resume_attempted = AtomicBool::new(false); + let primary_address: SocketAddr = "127.0.0.1:0".parse().unwrap(); + + let result: openshell_core::Result<()> = async { + let _listeners = bind_gateway_listeners(primary_address, &[occupied_address]).await?; + resume_attempted.store(true, Ordering::SeqCst); + Ok(()) + } + .await; + + assert!( + result.is_err(), + "binding the occupied extra gateway address should fail" + ); + assert!( + !resume_attempted.load(Ordering::SeqCst), + "persisted sandbox resume must not run before every gateway listener is bound" + ); + } } From 79bcf296cd7c7254ad63641dade0b2d6e9fe2f0f Mon Sep 17 00:00:00 2001 From: Polite_realism <119441270+politerealism@users.noreply.github.com> Date: Mon, 27 Jul 2026 14:15:10 -0400 Subject: [PATCH 6/6] fix(proxy): retry with backoff on transient accept errors instead of exiting (#2369) * fix(proxy): retry with backoff on transient accept errors instead of exiting The proxy accept loop unconditionally broke on any accept() error, permanently killing the proxy while the sandbox continued to report Ready. Replace the break with a sleep-and-continue pattern: EMFILE/ENFILE errors get exponential backoff (100ms to 3.2s) to let file descriptors drain, and all other accept errors get a fixed 100ms backoff matching the existing metadata_server and edge_tunnel patterns. Closes #2337 Signed-off-by: Sean Burdine Signed-off-by: politerealism * fix(proxy): address review feedback on accept retry backoff - Use libc::EMFILE / libc::ENFILE instead of raw errno values; promote libc from dev-dependency to regular dependency - Extract accept_backoff() and is_fd_exhaustion_error() into testable helpers - Fix unreachable 5s cap: bump exponent limit from min(6) to min(7) so the 5_000ms ceiling is reachable (100 * 2^6 = 6400, capped to 5000) - Add 6 unit tests covering exponential progression, counter reset, saturation at cap, EMFILE/ENFILE detection, and non-FD error rejection Signed-off-by: Sean Burdine Signed-off-by: politerealism * fix(proxy): classify accept errors and exit on terminal failures Three-way error classification for the accept loop: transient errors (EMFILE, ECONNABORTED) retry with backoff, terminal errors (EBADF, EINVAL, ENOTSOCK) exit immediately, and unknown errors exit after 5 consecutive failures. Adds unit tests for the classifier and error handler, plus a subprocess-isolated integration test that validates EMFILE recovery by lowering RLIMIT_NOFILE. Signed-off-by: Quinn Burdine Signed-off-by: politerealism * fix(proxy): use nested or-patterns to satisfy clippy lint Signed-off-by: Quinn Burdine Signed-off-by: politerealism * fix(proxy): expand transient error allowlist and fix clippy/test issues Widen the accept-error classification to cover all Linux accept(2) transient errnos (ENETDOWN, EPROTO, ENOPROTOOPT, EHOSTDOWN, EHOSTUNREACH, EOPNOTSUPP, ENETUNREACH, ENONET behind cfg gate). Rename fd-exhaustion helpers to resource-pressure to reflect ENOBUFS and ENOMEM coverage. Fix clippy lints in the integration test (borrow_as_ptr, collection_is_never_read, while_let_loop) and make post-EMFILE recovery verification cross-platform by handling Linux's stale backlog behavior. Signed-off-by: Quinn Burdine Signed-off-by: politerealism * fix(proxy): add remaining Linux accept(2) transient errnos and make test skip explicit Classify ENOSR, ESOCKTNOSUPPORT, EPROTONOSUPPORT, and ETIMEDOUT as transient accept errors per Linux accept(2) documentation. Treat ENOSR as resource pressure (exponential backoff). Make the EMFILE integration test skip path emit a diagnostic instead of silently returning success. Signed-off-by: Quinn Burdine Signed-off-by: politerealism * fix(proxy): panic instead of silent skip when EMFILE is not triggered The integration test child runs inside Command::output() which captures stderr. A silent return on the Ok path meant CI would report a passing test without any diagnostic. Panic instead so the parent test fails visibly if the platform cannot induce EMFILE. Signed-off-by: Quinn Burdine Signed-off-by: politerealism --------- Signed-off-by: Sean Burdine Signed-off-by: politerealism Signed-off-by: Quinn Burdine --- .../openshell-supervisor-network/Cargo.toml | 4 +- .../openshell-supervisor-network/src/proxy.rs | 483 +++++++++++++++++- .../tests/accept_fd_exhaustion.rs | 113 ++++ 3 files changed, 596 insertions(+), 4 deletions(-) create mode 100644 crates/openshell-supervisor-network/tests/accept_fd_exhaustion.rs diff --git a/crates/openshell-supervisor-network/Cargo.toml b/crates/openshell-supervisor-network/Cargo.toml index 008bf1104b..3dead2b8be 100644 --- a/crates/openshell-supervisor-network/Cargo.toml +++ b/crates/openshell-supervisor-network/Cargo.toml @@ -58,8 +58,10 @@ tokio-tungstenite = { workspace = true } futures = { workspace = true } tracing-subscriber = { workspace = true } -[target.'cfg(unix)'.dev-dependencies] +[target.'cfg(unix)'.dependencies] libc = "0.2" +[target.'cfg(unix)'.dev-dependencies] + [lints] workspace = true diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 69245e11e1..6e9c48220b 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -309,9 +309,13 @@ impl ProxyHandle { } } + let mut consecutive_resource_errors: u32 = 0; + let mut consecutive_unknown_errors: u32 = 0; loop { match listener.accept().await { Ok((stream, _addr)) => { + consecutive_resource_errors = 0; + consecutive_unknown_errors = 0; let opa = opa_engine.clone(); let cache = identity_cache.clone(); let spid = entrypoint_pid.clone(); @@ -362,14 +366,24 @@ impl ProxyHandle { }); } Err(err) => { + let outcome = handle_accept_error( + &err, + &mut consecutive_resource_errors, + &mut consecutive_unknown_errors, + ); + let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Fail) - .severity(SeverityId::Low) + .severity(outcome.severity) .status(StatusId::Failure) - .message(format!("Proxy accept error: {err}")) + .message(outcome.message) .build(); ocsf_emit!(event); - break; + + match outcome.backoff { + Some(backoff) => tokio::time::sleep(backoff).await, + None => break, + } } } } @@ -399,6 +413,139 @@ fn emit_activity(tx: &Option, denied: bool, deny_group: &'static } } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum AcceptErrorClass { + Transient, + Terminal, + Unknown, +} + +#[cfg(unix)] +fn classify_accept_error(err: &std::io::Error) -> AcceptErrorClass { + match err.raw_os_error() { + Some( + libc::EMFILE + | libc::ENFILE + | libc::ENOBUFS + | libc::ENOMEM + | libc::ECONNABORTED + | libc::ECONNRESET + | libc::EINTR + | libc::ENETDOWN + | libc::EPROTO + | libc::ENOPROTOOPT + | libc::EHOSTDOWN + | libc::EHOSTUNREACH + | libc::EOPNOTSUPP + | libc::ENETUNREACH + | libc::ENOSR + | libc::ESOCKTNOSUPPORT + | libc::EPROTONOSUPPORT + | libc::ETIMEDOUT, + ) => AcceptErrorClass::Transient, + #[cfg(target_os = "linux")] + Some(libc::ENONET) => AcceptErrorClass::Transient, + Some(libc::EBADF | libc::EINVAL | libc::ENOTSOCK) => AcceptErrorClass::Terminal, + _ => AcceptErrorClass::Unknown, + } +} + +#[cfg(not(unix))] +fn classify_accept_error(_err: &std::io::Error) -> AcceptErrorClass { + AcceptErrorClass::Unknown +} + +#[cfg(unix)] +fn is_resource_pressure_error(err: &std::io::Error) -> bool { + matches!( + err.raw_os_error(), + Some(libc::EMFILE | libc::ENFILE | libc::ENOBUFS | libc::ENOMEM | libc::ENOSR) + ) +} + +#[cfg(not(unix))] +fn is_resource_pressure_error(_err: &std::io::Error) -> bool { + false +} + +const ACCEPT_BACKOFF_BASE_MS: u64 = 100; +const ACCEPT_BACKOFF_MAX_MS: u64 = 5_000; +const MAX_CONSECUTIVE_UNKNOWN_ERRORS: u32 = 5; + +fn accept_backoff(consecutive_errors: u32) -> std::time::Duration { + let exponent = consecutive_errors.saturating_sub(1).min(7); + let ms = ACCEPT_BACKOFF_BASE_MS + .saturating_mul(1u64 << exponent) + .min(ACCEPT_BACKOFF_MAX_MS); + std::time::Duration::from_millis(ms) +} + +struct AcceptErrorOutcome { + severity: SeverityId, + message: String, + backoff: Option, +} + +fn handle_accept_error( + err: &std::io::Error, + consecutive_resource_errors: &mut u32, + consecutive_unknown_errors: &mut u32, +) -> AcceptErrorOutcome { + let class = classify_accept_error(err); + + match class { + AcceptErrorClass::Terminal => AcceptErrorOutcome { + severity: SeverityId::High, + message: format!("Proxy accept error (terminal, exiting): {err}"), + backoff: None, + }, + AcceptErrorClass::Unknown => { + *consecutive_unknown_errors = consecutive_unknown_errors.saturating_add(1); + if *consecutive_unknown_errors > MAX_CONSECUTIVE_UNKNOWN_ERRORS { + AcceptErrorOutcome { + severity: SeverityId::High, + message: format!( + "Proxy accept error (exceeded {MAX_CONSECUTIVE_UNKNOWN_ERRORS} retries, exiting): {err}" + ), + backoff: None, + } + } else { + let backoff = accept_backoff(*consecutive_unknown_errors); + AcceptErrorOutcome { + severity: SeverityId::Medium, + message: format!( + "Proxy accept error (retry {}/{MAX_CONSECUTIVE_UNKNOWN_ERRORS} in {}ms): {err}", + *consecutive_unknown_errors, + backoff.as_millis(), + ), + backoff: Some(backoff), + } + } + } + AcceptErrorClass::Transient => { + *consecutive_unknown_errors = 0; + if is_resource_pressure_error(err) { + *consecutive_resource_errors = consecutive_resource_errors.saturating_add(1); + let backoff = accept_backoff(*consecutive_resource_errors); + AcceptErrorOutcome { + severity: SeverityId::Medium, + message: format!( + "Proxy accept error (retrying in {}ms): {err}", + backoff.as_millis(), + ), + backoff: Some(backoff), + } + } else { + AcceptErrorOutcome { + severity: SeverityId::Low, + message: format!("Proxy accept error (retrying in 100ms): {err}"), + backoff: Some(std::time::Duration::from_millis(100)), + } + } + } + } +} + fn l7_inspection_active(l7_route: Option<&L7RouteSnapshot>) -> bool { l7_route.is_some_and(|route| !route.configs.is_empty()) } @@ -10059,4 +10206,334 @@ network_policies: } } } + + #[test] + fn accept_backoff_exponential_progression() { + let ms = |n| accept_backoff(n).as_millis(); + assert_eq!(ms(1), 100); + assert_eq!(ms(2), 200); + assert_eq!(ms(3), 400); + assert_eq!(ms(4), 800); + assert_eq!(ms(5), 1_600); + assert_eq!(ms(6), 3_200); + assert_eq!(ms(7), 5_000); // 6400 capped to 5000 + assert_eq!(ms(8), 5_000); // stays at cap + } + + #[test] + fn accept_backoff_zero_consecutive_errors() { + assert_eq!(accept_backoff(0).as_millis(), 100); + } + + #[test] + fn accept_backoff_saturates_at_cap() { + assert_eq!(accept_backoff(100).as_millis(), 5_000); + assert_eq!(accept_backoff(u32::MAX).as_millis(), 5_000); + } + + #[cfg(unix)] + #[test] + fn is_resource_pressure_detects_emfile() { + let err = std::io::Error::from_raw_os_error(libc::EMFILE); + assert!(is_resource_pressure_error(&err)); + } + + #[cfg(unix)] + #[test] + fn is_resource_pressure_detects_enfile() { + let err = std::io::Error::from_raw_os_error(libc::ENFILE); + assert!(is_resource_pressure_error(&err)); + } + + #[cfg(unix)] + #[test] + fn is_resource_pressure_detects_memory_pressure() { + assert!(is_resource_pressure_error( + &std::io::Error::from_raw_os_error(libc::ENOBUFS) + )); + assert!(is_resource_pressure_error( + &std::io::Error::from_raw_os_error(libc::ENOMEM) + )); + assert!(is_resource_pressure_error( + &std::io::Error::from_raw_os_error(libc::ENOSR) + )); + } + + #[cfg(unix)] + #[test] + fn is_resource_pressure_rejects_other_errors() { + let err = std::io::Error::from_raw_os_error(libc::ECONNABORTED); + assert!(!is_resource_pressure_error(&err)); + } + + #[cfg(unix)] + #[test] + fn classify_accept_error_fd_exhaustion_is_transient() { + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::EMFILE)), + AcceptErrorClass::Transient, + ); + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::ENFILE)), + AcceptErrorClass::Transient, + ); + } + + #[cfg(unix)] + #[test] + fn classify_accept_error_connection_errors_are_transient() { + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::ECONNABORTED)), + AcceptErrorClass::Transient, + ); + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::ECONNRESET)), + AcceptErrorClass::Transient, + ); + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::EINTR)), + AcceptErrorClass::Transient, + ); + } + + #[cfg(unix)] + #[test] + fn classify_accept_error_broken_listener_is_terminal() { + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::EBADF)), + AcceptErrorClass::Terminal, + ); + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::EINVAL)), + AcceptErrorClass::Terminal, + ); + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::ENOTSOCK)), + AcceptErrorClass::Terminal, + ); + } + + #[cfg(unix)] + #[test] + fn classify_accept_error_unrecognized_errno_is_unknown() { + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::EPERM)), + AcceptErrorClass::Unknown, + ); + } + + #[cfg(unix)] + #[test] + fn handle_accept_error_terminal_exits_immediately() { + let mut res = 0; + let mut unk = 0; + let err = std::io::Error::from_raw_os_error(libc::EBADF); + let outcome = handle_accept_error(&err, &mut res, &mut unk); + assert!(outcome.backoff.is_none()); + assert_eq!(outcome.severity, SeverityId::High); + } + + #[cfg(unix)] + #[test] + fn handle_accept_error_transient_retries_indefinitely() { + let mut res = 0; + let mut unk = 0; + let err = std::io::Error::from_raw_os_error(libc::EMFILE); + for i in 1..=20 { + let outcome = handle_accept_error(&err, &mut res, &mut unk); + assert!(outcome.backoff.is_some(), "should retry on attempt {i}"); + assert_eq!(outcome.severity, SeverityId::Medium); + } + assert_eq!(res, 20); + } + + #[cfg(unix)] + #[test] + fn handle_accept_error_unknown_exits_after_limit() { + let mut res = 0; + let mut unk = 0; + let err = std::io::Error::from_raw_os_error(libc::EPERM); + for i in 1..=MAX_CONSECUTIVE_UNKNOWN_ERRORS { + let outcome = handle_accept_error(&err, &mut res, &mut unk); + assert!( + outcome.backoff.is_some(), + "should retry on attempt {i}/{MAX_CONSECUTIVE_UNKNOWN_ERRORS}", + ); + assert_eq!(outcome.severity, SeverityId::Medium); + } + let outcome = handle_accept_error(&err, &mut res, &mut unk); + assert!( + outcome.backoff.is_none(), + "should exit after limit exceeded" + ); + assert_eq!(outcome.severity, SeverityId::High); + } + + #[cfg(unix)] + #[test] + fn handle_accept_error_transient_resets_unknown_counter() { + let mut res = 0; + let mut unk = 0; + let unknown_err = std::io::Error::from_raw_os_error(libc::EPERM); + let transient_err = std::io::Error::from_raw_os_error(libc::ECONNABORTED); + + // Accumulate unknowns up to the limit. + for _ in 1..=MAX_CONSECUTIVE_UNKNOWN_ERRORS { + handle_accept_error(&unknown_err, &mut res, &mut unk); + } + assert_eq!(unk, MAX_CONSECUTIVE_UNKNOWN_ERRORS); + + // A transient error resets the unknown counter. + let outcome = handle_accept_error(&transient_err, &mut res, &mut unk); + assert!(outcome.backoff.is_some()); + assert_eq!(unk, 0); + + // Unknown errors can retry again from zero. + let outcome = handle_accept_error(&unknown_err, &mut res, &mut unk); + assert!(outcome.backoff.is_some()); + assert_eq!(unk, 1); + } + + #[cfg(unix)] + #[test] + fn handle_accept_error_fd_exhaustion_uses_exponential_backoff() { + let mut res = 0; + let mut unk = 0; + let err = std::io::Error::from_raw_os_error(libc::EMFILE); + + let b1 = handle_accept_error(&err, &mut res, &mut unk) + .backoff + .unwrap(); + let b2 = handle_accept_error(&err, &mut res, &mut unk) + .backoff + .unwrap(); + let b3 = handle_accept_error(&err, &mut res, &mut unk) + .backoff + .unwrap(); + + assert_eq!(b1.as_millis(), 100); + assert_eq!(b2.as_millis(), 200); + assert_eq!(b3.as_millis(), 400); + } + + #[cfg(unix)] + #[test] + fn classify_accept_error_network_errors_are_transient() { + for errno in [ + libc::ENETDOWN, + libc::EPROTO, + libc::ENOPROTOOPT, + libc::EHOSTDOWN, + libc::EHOSTUNREACH, + libc::EOPNOTSUPP, + libc::ENETUNREACH, + libc::ESOCKTNOSUPPORT, + libc::EPROTONOSUPPORT, + libc::ETIMEDOUT, + ] { + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(errno)), + AcceptErrorClass::Transient, + "errno {errno} should be transient", + ); + } + } + + #[cfg(target_os = "linux")] + #[test] + fn classify_accept_error_enonet_is_transient() { + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::ENONET)), + AcceptErrorClass::Transient, + ); + } + + #[cfg(unix)] + #[test] + fn classify_accept_error_resource_pressure_is_transient() { + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::ENOBUFS)), + AcceptErrorClass::Transient, + ); + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::ENOMEM)), + AcceptErrorClass::Transient, + ); + assert_eq!( + classify_accept_error(&std::io::Error::from_raw_os_error(libc::ENOSR)), + AcceptErrorClass::Transient, + ); + } + + #[cfg(unix)] + #[test] + fn handle_accept_error_non_resource_transient_uses_fixed_backoff() { + let mut res = 0; + let mut unk = 0; + let err = std::io::Error::from_raw_os_error(libc::ECONNABORTED); + + let o1 = handle_accept_error(&err, &mut res, &mut unk); + let o2 = handle_accept_error(&err, &mut res, &mut unk); + + assert_eq!(o1.severity, SeverityId::Low); + assert_eq!(o1.backoff.unwrap().as_millis(), 100); + assert_eq!(o2.backoff.unwrap().as_millis(), 100); + assert_eq!(res, 0); + } + + #[cfg(unix)] + #[test] + fn handle_accept_error_unknown_uses_exponential_backoff() { + let mut res = 0; + let mut unk = 0; + let err = std::io::Error::from_raw_os_error(libc::EPERM); + + let b1 = handle_accept_error(&err, &mut res, &mut unk) + .backoff + .unwrap(); + let b2 = handle_accept_error(&err, &mut res, &mut unk) + .backoff + .unwrap(); + let b3 = handle_accept_error(&err, &mut res, &mut unk) + .backoff + .unwrap(); + + assert_eq!(b1.as_millis(), 100); + assert_eq!(b2.as_millis(), 200); + assert_eq!(b3.as_millis(), 400); + } + + #[cfg(unix)] + #[test] + fn handle_accept_error_resource_counter_persists_across_mixed_transient() { + let mut res = 0; + let mut unk = 0; + let resource_err = std::io::Error::from_raw_os_error(libc::EMFILE); + let transient_err = std::io::Error::from_raw_os_error(libc::ECONNABORTED); + + let o1 = handle_accept_error(&resource_err, &mut res, &mut unk); + assert_eq!(res, 1); + assert_eq!(o1.backoff.unwrap().as_millis(), 100); + + let o2 = handle_accept_error(&transient_err, &mut res, &mut unk); + assert_eq!(res, 1); + assert_eq!(o2.backoff.unwrap().as_millis(), 100); + + let o3 = handle_accept_error(&resource_err, &mut res, &mut unk); + assert_eq!(res, 2); + assert_eq!(o3.backoff.unwrap().as_millis(), 200); + } + + #[cfg(unix)] + #[test] + fn handle_accept_error_terminal_leaves_counters_unchanged() { + let mut res = 3; + let mut unk = 2; + let err = std::io::Error::from_raw_os_error(libc::EBADF); + + let outcome = handle_accept_error(&err, &mut res, &mut unk); + assert!(outcome.backoff.is_none()); + assert_eq!(res, 3); + assert_eq!(unk, 2); + } } diff --git a/crates/openshell-supervisor-network/tests/accept_fd_exhaustion.rs b/crates/openshell-supervisor-network/tests/accept_fd_exhaustion.rs new file mode 100644 index 0000000000..3fd09f9c89 --- /dev/null +++ b/crates/openshell-supervisor-network/tests/accept_fd_exhaustion.rs @@ -0,0 +1,113 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Subprocess-isolated integration test: lowers `RLIMIT_NOFILE`, induces +//! EMFILE on `accept()`, releases file descriptors, and verifies the +//! listener recovers and accepts a subsequent connection. +//! +//! Uses blocking I/O in the child to surface EMFILE reliably across +//! platforms (tokio's async accept may swallow EMFILE on kqueue-based +//! systems). The proxy's retry logic is validated by the unit tests for +//! `handle_accept_error`; this test validates the OS-level precondition +//! that recovery is possible after FD exhaustion clears. +//! +//! Runs in a child process so the test runner's process-wide resource +//! limits are not affected. + +#![cfg(unix)] +#![allow(unsafe_code, reason = "setrlimit requires unsafe")] + +use std::env; +use std::io::Read; +use std::io::Write; +use std::process::Command; + +const CHILD_SENTINEL: &str = "__ACCEPT_FD_EXHAUSTION_CHILD"; + +#[test] +fn accept_recovers_after_fd_exhaustion() { + let exe = env::current_exe().expect("current_exe"); + let output = Command::new(exe) + .env(CHILD_SENTINEL, "1") + .arg("--test-threads=1") + .arg("accept_fd_exhaustion_child") + .output() + .expect("spawn child"); + + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success(), + "child failed (exit {}):\nstdout: {stdout}\nstderr: {stderr}", + output.status, + ); +} + +#[test] +fn accept_fd_exhaustion_child() { + if env::var(CHILD_SENTINEL).is_err() { + return; + } + + let limit = libc::rlimit { + rlim_cur: 32, + rlim_max: 32, + }; + assert_eq!( + unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, std::ptr::from_ref(&limit)) }, + 0, + ); + + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); + let addr = listener.local_addr().unwrap(); + + // Place a connection in the kernel backlog before exhausting FDs. + let backlog_conn = std::net::TcpStream::connect(addr).expect("backlog connect"); + + // Exhaust remaining FDs. + #[allow(clippy::collection_is_never_read)] + let mut held_fds = Vec::new(); + while let Ok(f) = std::fs::File::open("/dev/null") { + held_fds.push(f); + } + + // accept() should fail with EMFILE: there's a connection in the + // backlog but no FD available for the accepted socket. + let first = listener.accept(); + match first { + Err(ref e) if e.raw_os_error() == Some(libc::EMFILE) => {} + Err(ref e) => panic!("expected EMFILE, got: {e}"), + Ok(_) => { + panic!("EMFILE not triggered: OS found a spare FD slot despite RLIMIT_NOFILE=32"); + } + } + + // Release FDs and close the backlog connection. + drop(held_fds); + drop(backlog_conn); + + // Make a fresh connection now that FDs are available. + let client = std::net::TcpStream::connect(addr).expect("connect after FD release"); + + // Accept should succeed, proving that an accept loop retrying on + // EMFILE (like the proxy does) will recover once FDs are available. + // On Linux the closed backlog connection may still be queued ahead + // of the fresh client (EMFILE fires before dequeue), so use a read + // timeout to detect and drain it. + let (accepted, _peer) = listener + .accept() + .expect("accept should succeed after FD release"); + + // Verify the connection is functional. + (&client).write_all(b"ping").expect("write"); + accepted + .set_read_timeout(Some(std::time::Duration::from_secs(1))) + .expect("set timeout"); + let mut buf = [0u8; 4]; + if (&accepted).read_exact(&mut buf).is_err() { + // Got the stale backlog socket; accept the fresh connection. + let (fresh, _) = listener.accept().expect("accept fresh connection"); + (&fresh).read_exact(&mut buf).expect("read"); + } + assert_eq!(&buf, b"ping"); +}