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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions crates/openshell-credential-issuer/src/refresh/github_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand Down
4 changes: 1 addition & 3 deletions crates/openshell-driver-vault/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand Down
4 changes: 1 addition & 3 deletions crates/openshell-sandbox/src/perf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
Expand Down
7 changes: 4 additions & 3 deletions crates/openshell-server/src/compute/mutation_guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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));
Expand Down
3 changes: 2 additions & 1 deletion crates/openshell-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<()>();
Expand Down
102 changes: 60 additions & 42 deletions crates/openshell-server/src/persistence/postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand All @@ -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(_)),
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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);
Expand All @@ -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();
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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);
}
Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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(),
Expand Down
11 changes: 2 additions & 9 deletions crates/openshell-server/src/supervisor_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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(),
)
Expand Down
7 changes: 2 additions & 5 deletions crates/openshell-supervisor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
20 changes: 8 additions & 12 deletions crates/openshell-supervisor/src/otlp_relay/exporter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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);
}
Expand Down Expand Up @@ -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);
}
Expand Down
4 changes: 1 addition & 3 deletions tests/testkit/testkit/tests/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading