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-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-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] diff --git a/crates/openshell-router/src/backend.rs b/crates/openshell-router/src/backend.rs index 9fbd538c06..df8830ae39 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 @@ -824,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}") @@ -1970,6 +1985,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; 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/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" + ); + } } 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; 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/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-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"); +} 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() {