diff --git a/TESTING.md b/TESTING.md index ec22cdba3a..3cfa928a89 100644 --- a/TESTING.md +++ b/TESTING.md @@ -52,6 +52,18 @@ mise run test:rust # cargo test --workspace Rust validation checks tracked Cargo lockfiles; run `mise run rust:lockfiles:check` to check them directly. If one is stale, refresh it with Cargo using its adjacent manifest, review the diff, and commit the update. +### TCP ports in tests + +Let test servers bind port `0` and keep the resulting listener alive. Binding a +temporary listener, reading its port, and dropping it lets a parallel test claim +the port before the test uses it. + +For a generic connection failure, use destination `127.0.0.1:0`: port zero cannot +host a TCP listener. The error kind differs by OS, so do not assert a specific +refusal error. For handshake or acquisition timeouts, keep a listener bound and +never serve its connections. When a separate process must bind a selected port, +retry only bind collisions with a fresh port and a bounded attempt count. + ### PostgreSQL-backed tests Tests that need a real PostgreSQL server, such as advisory-lock concurrency diff --git a/crates/openshell-credential-issuer/src/refresh/github_app.rs b/crates/openshell-credential-issuer/src/refresh/github_app.rs index c790c24004..6b3e90e138 100644 --- a/crates/openshell-credential-issuer/src/refresh/github_app.rs +++ b/crates/openshell-credential-issuer/src/refresh/github_app.rs @@ -697,13 +697,13 @@ mod tests { assert!(failure.status.message().contains("timed out")); assert!(!failure.status.message().contains("secret")); - drop(listener); + let url = "http://127.0.0.1:0/secret-path?secret-query=value"; let client = reqwest::Client::builder() .no_proxy() .timeout(Duration::from_secs(5)) .build() .unwrap(); - let failure = transport_failure(client.get(&url).send().await.unwrap_err()); + let failure = transport_failure(client.get(url).send().await.unwrap_err()); assert_eq!(failure.failure_code, "github_token_endpoint_unavailable"); assert_eq!(failure.recovery_action, Recovery::Retry); assert!(failure.status.message().contains("connection failed")); diff --git a/crates/openshell-driver-vault/src/lib.rs b/crates/openshell-driver-vault/src/lib.rs index cdfafc3ce1..d42bc068df 100644 --- a/crates/openshell-driver-vault/src/lib.rs +++ b/crates/openshell-driver-vault/src/lib.rs @@ -1374,9 +1374,7 @@ mod tests { #[test] fn loopback_http_bypasses_system_proxy() { - let proxy_listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let proxy_address = proxy_listener.local_addr().unwrap(); - drop(proxy_listener); + let proxy_address = "127.0.0.1:0"; let output = std::process::Command::new(std::env::current_exe().unwrap()) .args([ diff --git a/crates/openshell-sandbox/src/perf.rs b/crates/openshell-sandbox/src/perf.rs index 408d6d69a1..762204585d 100644 --- a/crates/openshell-sandbox/src/perf.rs +++ b/crates/openshell-sandbox/src/perf.rs @@ -435,9 +435,7 @@ mod tests { #[test] fn preparation_failure_does_not_wait_for_other_workers() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind test listener"); - let address = listener.local_addr().expect("test listener address"); - drop(listener); + let address = "127.0.0.1:0".parse().unwrap(); assert!(run_worker(Protocol::TcpStream, address, 1, 1, 2, 8).is_err()); } diff --git a/crates/openshell-server/src/compute/mutation_guard.rs b/crates/openshell-server/src/compute/mutation_guard.rs index 7481fbc3b4..40197ee568 100644 --- a/crates/openshell-server/src/compute/mutation_guard.rs +++ b/crates/openshell-server/src/compute/mutation_guard.rs @@ -896,12 +896,13 @@ mod tests { const TIMEOUTS: &str = "openshell_server_mutation_lock_timeouts_total{scope=\"sandbox\"}"; const ERRORS: &str = "openshell_server_mutation_lock_errors_total{scope=\"sandbox\"}"; let metrics = MetricsCapture::install(); - let url = crate::persistence::PostgresStore::refusing_url_for_tests().await; + let (_listener, url) = + crate::persistence::PostgresStore::unresponsive_url_for_tests().await; let store = crate::persistence::PostgresStore::connect_lazy_for_tests(&url, 1); let runtime = super::super::new_test_runtime_for_driver(Arc::new(Store::Postgres(store)), "test") .await; - // Leave enough time to open a lock connection, so the refusal is a + // Leave enough time to open a lock connection, so the acquisition failure is a // database error. runtime.set_mutation_lock_timeout_for_tests( crate::persistence::mutation_lock::LOCK_CONNECTION_MIN_BUDGET @@ -917,7 +918,7 @@ mod tests { "{detail}" ), Err(error) => panic!("expected a database error, got {error:?}"), - Ok(_) => panic!("nothing listens, yet the guard was acquired"), + Ok(_) => panic!("the database never answers, yet the guard was acquired"), } assert_eq!(metrics.value(TIMEOUTS), None); assert_eq!(metrics.value(ERRORS), Some(1)); diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 799c46e397..00d84dc081 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -4225,7 +4225,8 @@ mod tests { #[tokio::test] async fn connect_store_serves_probes_while_the_database_is_unreachable() { - let url = crate::persistence::PostgresStore::refusing_url_for_tests().await; + let (_listener, url) = + crate::persistence::PostgresStore::unresponsive_url_for_tests().await; let health_address = reserved_loopback_address().await; let mut health = super::HealthListener::new(Some(health_address)); let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); diff --git a/crates/openshell-server/src/persistence/postgres.rs b/crates/openshell-server/src/persistence/postgres.rs index b62144ae0d..d212d85ba9 100644 --- a/crates/openshell-server/src/persistence/postgres.rs +++ b/crates/openshell-server/src/persistence/postgres.rs @@ -2759,15 +2759,16 @@ impl PostgresStore { } } - /// Test support only: a `PostgreSQL` URL on a loopback port where nothing - /// listens, so every connection attempt is refused. - pub(crate) async fn refusing_url_for_tests() -> String { + /// Hold a listener that never answers the `PostgreSQL` handshake. + pub(crate) async fn unresponsive_url_for_tests() -> (tokio::net::TcpListener, String) { let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await - .expect("reserve a loopback port"); - let port = listener.local_addr().expect("loopback address").port(); - drop(listener); - format!("postgres://openshell@127.0.0.1:{port}/openshell") + .expect("bind a silent database endpoint"); + let url = format!( + "postgres://openshell@{}/openshell", + listener.local_addr().unwrap() + ); + (listener, url) } } @@ -2776,14 +2777,43 @@ mod tests { use super::super::mutation_lock::SSH_IDENTITY_LOCK_KEY; use super::*; + #[cfg(target_os = "linux")] #[tokio::test] async fn connect_to_a_refusing_server_fails_unavailable_within_the_acquire_timeout() { - let url = PostgresStore::refusing_url_for_tests().await; + // Linux refuses connections to a bound, non-listening socket. Keeping + // it bound also excludes listeners with SO_REUSEADDR enabled. + let socket = + socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None).unwrap(); + socket + .bind(&std::net::SocketAddr::from(([127, 0, 0, 1], 0)).into()) + .unwrap(); + let address = socket.local_addr().unwrap().as_socket().unwrap(); + assert!(tokio::net::TcpListener::bind(address).await.is_err()); + assert_eq!( + openshell_core::net::connect_tcp_nodelay_best_effort(address) + .await + .unwrap_err() + .kind(), + std::io::ErrorKind::ConnectionRefused + ); + let url = format!("postgres://openshell@{address}/openshell"); + let started = std::time::Instant::now(); + let error = PostgresStore::connect(&url, None, None).await.unwrap_err(); + assert!( + matches!(error, PersistenceError::Unavailable(_)), + "{error:?}" + ); + assert!(started.elapsed() < DATA_POOL_ACQUIRE_TIMEOUT + Duration::from_secs(3)); + } + + #[tokio::test] + async fn connect_to_an_unresponsive_server_fails_unavailable_within_the_acquire_timeout() { + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; let started = std::time::Instant::now(); let error = PostgresStore::connect(&url, None, None) .await - .expect_err("nothing listens on the port"); + .expect_err("the database never answers"); assert!( matches!(error, PersistenceError::Unavailable(_)), @@ -2827,10 +2857,8 @@ mod tests { #[tokio::test] async fn lock_connection_timeout_is_contention_only_if_the_pool_filled_during_the_wait() { - let store = PostgresStore::connect_lazy_for_tests( - &PostgresStore::refusing_url_for_tests().await, - 2, - ); + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; + let store = PostgresStore::connect_lazy_for_tests(&url, 2); let usage = &store.lock_usage; let is_contention = |error: PersistenceError| match error { PersistenceError::LockTimeout(detail) => { @@ -2873,10 +2901,8 @@ mod tests { async fn lock_connection_checkout_tracks_the_in_use_gauge() { const IN_USE: &str = "openshell_server_mutation_lock_connections_in_use"; let metrics = crate::gateway_metrics::MetricsCapture::install(); - let store = PostgresStore::connect_lazy_for_tests( - &PostgresStore::refusing_url_for_tests().await, - 2, - ); + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; + let store = PostgresStore::connect_lazy_for_tests(&url, 2); let usage = &store.lock_usage; let first = LockConnectionCheckout::new(usage); @@ -2900,10 +2926,8 @@ mod tests { #[tokio::test] async fn lock_connection_timeout_without_time_to_connect_is_a_lock_timeout() { - let store = PostgresStore::connect_lazy_for_tests( - &PostgresStore::refusing_url_for_tests().await, - 1, - ); + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; + let store = PostgresStore::connect_lazy_for_tests(&url, 1); // The pool never fills, but an earlier wait left too little time to // open a connection. let start = store.lock_usage.snapshot(); @@ -2913,7 +2937,7 @@ mod tests { PersistenceError::LockTimeout(_) )); - // SQLx retries the refused connection until the deadline. + // The handshake stays pending until the acquisition deadline. let deadline = tokio::time::Instant::now() + LOCK_CONNECTION_MIN_BUDGET / 4; match store .acquire_mutation_locks(&MutationLockSet::default(), deadline) @@ -2923,19 +2947,17 @@ mod tests { assert_eq!(detail, "waiting for a mutation lock connection"); } Err(error) => panic!("expected a lock timeout, got {error:?}"), - Ok(_) => panic!("nothing listens, yet a lock connection opened"), + Ok(_) => panic!("the database never answers, yet a lock connection opened"), } assert_eq!(store.lock_usage.in_use.load(Ordering::Acquire), 0); } #[tokio::test] - async fn refused_lock_connection_is_a_database_error_not_a_lock_timeout() { - let store = PostgresStore::connect_lazy_for_tests( - &PostgresStore::refusing_url_for_tests().await, - 1, - ); - // SQLx retries a refused connection until the deadline, which leaves - // ample time to open one. + async fn unresponsive_lock_connection_is_a_database_error_not_a_lock_timeout() { + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; + let store = PostgresStore::connect_lazy_for_tests(&url, 1); + // Give acquisition enough budget to classify an unanswered handshake + // as a database error rather than lock contention. let deadline = tokio::time::Instant::now() + LOCK_CONNECTION_MIN_BUDGET + Duration::from_millis(300); match store @@ -2947,7 +2969,7 @@ mod tests { "{detail}" ), Err(error) => panic!("expected a database error, got {error:?}"), - Ok(_) => panic!("nothing listens, yet a lock connection opened"), + Ok(_) => panic!("the database never answers, yet a lock connection opened"), } assert_eq!(store.lock_usage.in_use.load(Ordering::Acquire), 0); } @@ -2983,10 +3005,8 @@ mod tests { .with_writer(move || LogWriter(writer.clone())) .finish(), ); - let store = PostgresStore::connect_lazy_for_tests( - &PostgresStore::refusing_url_for_tests().await, - 1, - ); + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; + let store = PostgresStore::connect_lazy_for_tests(&url, 1); let available = u32::try_from(store.data_lock_slots.available_permits()) .expect("the slot count fits in u32"); let _held = Arc::clone(&store.data_lock_slots) @@ -2995,7 +3015,7 @@ mod tests { // The outer timeout turns a missing bound into a failure instead of a // hang. It also fails a data connection acquired before the slot: - // SQLx retries the refused connection until its 30-second acquire + // The handshake waits for the 30-second acquire // timeout, past this one. match tokio::time::timeout( MUTATION_LOCK_TIMEOUT * 2, @@ -3022,12 +3042,10 @@ mod tests { #[tokio::test(start_paused = true)] async fn failed_data_pool_lock_acquisition_returns_its_slot() { - let store = PostgresStore::connect_lazy_for_tests( - &PostgresStore::refusing_url_for_tests().await, - 1, - ); + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; + let store = PostgresStore::connect_lazy_for_tests(&url, 1); let slots = store.data_lock_slots.available_permits(); - // SQLx retries the refused connection until its 30-second acquire + // The handshake waits for the 30-second acquire // timeout, so the acquisition's own deadline ends the wait first. match tokio::time::timeout( MUTATION_LOCK_TIMEOUT * 2, @@ -3040,7 +3058,7 @@ mod tests { assert_eq!(detail, "waiting for a data-pool lock connection"); } Err(error) => panic!("expected a lock timeout, got {error:?}"), - Ok(_) => panic!("nothing listens, yet a data-pool lock was acquired"), + Ok(_) => panic!("the database never answers, yet a data-pool lock was acquired"), } assert_eq!( store.data_lock_slots.available_permits(), diff --git a/crates/openshell-server/src/supervisor_session.rs b/crates/openshell-server/src/supervisor_session.rs index 0c39fdbf9f..f9f46b153b 100644 --- a/crates/openshell-server/src/supervisor_session.rs +++ b/crates/openshell-server/src/supervisor_session.rs @@ -5140,13 +5140,6 @@ mod tests { owner } - fn closed_local_endpoint() -> String { - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - drop(listener); - format!("http://{addr}") - } - fn peer_relay_open(channel_id: &str) -> RelayOpen { RelayOpen { channel_id: channel_id.to_string(), @@ -5613,11 +5606,11 @@ mod tests { let metrics = MetricsCapture::install(); let state = crate::grpc::test_support::test_server_state().await; seed_peer_token(&state); - let endpoint = closed_local_endpoint(); + let endpoint = "http://127.0.0.1:0"; let err = forward_provider_status_query_to_owner( &state, - &owner_at(&endpoint), + &owner_at(endpoint), "sbx-peer", GetSandboxProviderStatusRequest::default(), ) diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 3ec4035113..6278307846 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -4982,11 +4982,8 @@ mod tests { #[test] fn tcp_readiness_listener_accepts_ipv4_regardless_of_bindv6only() { - let port = std::net::TcpListener::bind("127.0.0.1:0") - .and_then(|reserved| reserved.local_addr()) - .expect("reserve loopback port") - .port(); - let listener = bind_readiness_tcp(port).expect("bind readiness listener"); + let listener = bind_readiness_tcp(0).expect("bind readiness listener"); + let port = listener.local_addr().expect("readiness address").port(); if listener.local_addr().expect("local address").is_ipv6() { assert!( !socket2::SockRef::from(&listener) diff --git a/crates/openshell-supervisor/src/otlp_relay/exporter.rs b/crates/openshell-supervisor/src/otlp_relay/exporter.rs index ec29acdfb3..3643914a29 100644 --- a/crates/openshell-supervisor/src/otlp_relay/exporter.rs +++ b/crates/openshell-supervisor/src/otlp_relay/exporter.rs @@ -418,12 +418,10 @@ mod tests { } #[tokio::test] - async fn http_export_to_a_closed_port_fails_promptly() { - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let endpoint = format!("http://{}", listener.local_addr().unwrap()); - drop(listener); + async fn http_export_to_port_zero_fails_promptly() { + let endpoint = "http://127.0.0.1:0"; let exporter = Exporter::new( - &endpoint, + endpoint, OtlpProtocol::HttpProtobuf, http::HeaderMap::new(), None, @@ -434,7 +432,7 @@ mod tests { let error = exporter .export(Bytes::from(encoded_request("s", &[]))) .await - .expect_err("closed port fails"); + .expect_err("port zero fails"); assert!(matches!(error, ExportError::Http(_)), "{error}"); assert!(started.elapsed() < EXPORT_TIMEOUT); } @@ -613,18 +611,16 @@ mod tests { } #[tokio::test] - async fn export_to_a_closed_port_returns_status_promptly() { - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let endpoint = format!("http://{}", listener.local_addr().unwrap()); - drop(listener); + async fn export_to_port_zero_returns_status_promptly() { + let endpoint = "http://127.0.0.1:0"; let exporter = - Exporter::new(&endpoint, OtlpProtocol::Grpc, http::HeaderMap::new(), None).unwrap(); + Exporter::new(endpoint, OtlpProtocol::Grpc, http::HeaderMap::new(), None).unwrap(); let started = Instant::now(); let error = exporter .export(Bytes::from(encoded_request("s", &[]))) .await - .expect_err("closed port fails"); + .expect_err("port zero fails"); assert!(matches!(error, ExportError::Status(_)), "{error}"); assert!(started.elapsed() < EXPORT_TIMEOUT); } diff --git a/tests/testkit/testkit/tests/program.rs b/tests/testkit/testkit/tests/program.rs index 6f03ffbec7..2ee1903c4e 100644 --- a/tests/testkit/testkit/tests/program.rs +++ b/tests/testkit/testkit/tests/program.rs @@ -606,9 +606,7 @@ mod unix { /// Point the gateway lookup at a closed port, away from any registered /// gateways. fn without_gateway(mut command: Command, config: &Path) -> Command { - let closed = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); - let endpoint = format!("http://{}", closed.local_addr().expect("address")); - drop(closed); + let endpoint = "http://127.0.0.1:0"; command .env("XDG_CONFIG_HOME", config) .env("OPENSHELL_GATEWAY_ENDPOINT", endpoint)