diff --git a/apps/piqueld/src/api/service/views.rs b/apps/piqueld/src/api/service/views/mod.rs similarity index 72% rename from apps/piqueld/src/api/service/views.rs rename to apps/piqueld/src/api/service/views/mod.rs index bcb1a22f9..9327c6680 100644 --- a/apps/piqueld/src/api/service/views.rs +++ b/apps/piqueld/src/api/service/views/mod.rs @@ -166,79 +166,4 @@ pub(super) fn detail_diagnostics( } #[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use piqueld_core::resource::{ObservedTask, TaskDiagnostic}; - - use super::*; - - /// A one-replica `web` service running `tasks`. - fn service(tasks: Vec, healthcheck_configured: bool) -> ObservedService { - ObservedService { - secrets: Vec::new(), - files: Vec::new(), - name: "web".into(), - image: "example/web@sha256:digest".into(), - replicas: 1, - environment: BTreeMap::new(), - command: Vec::new(), - arguments: Vec::new(), - mounts: Vec::new(), - healthcheck: None, - healthcheck_configured, - resources: None, - networks: Vec::new(), - labels: BTreeMap::new(), - rollout: None, - telemetry: None, - runtime_configuration_matches: true, - tasks, - convergence: Convergence::Converged, - } - } - - #[test] - fn service_diagnostics_ignore_historical_tasks() { - let service = service( - vec![ - ObservedTask { - state: TaskState::Failed, - healthy: None, - desired_running: false, - diagnostic: Some(TaskDiagnostic::Failed { exit_code: Some(1) }), - ..ObservedTask::default() - }, - ObservedTask { - state: TaskState::Rejected, - healthy: None, - desired_running: true, - diagnostic: Some(TaskDiagnostic::Rejected), - ..ObservedTask::default() - }, - ], - false, - ); - - let diagnostics = service_diagnostics(&service); - - assert_eq!(diagnostics.len(), 1); - assert_eq!(diagnostics[0].code, ApiErrorCode::TaskRejected); - } - - #[test] - fn pending_runtime_health_is_not_reported_as_healthy() { - let task = ObservedTask { - state: TaskState::Running, - healthy: None, - desired_running: true, - diagnostic: None, - ..ObservedTask::default() - }; - let mut service = service(vec![task], true); - - assert_eq!(healthy_replicas(&service), 0); - service.healthcheck_configured = false; - assert_eq!(healthy_replicas(&service), 1); - } -} +mod tests; diff --git a/apps/piqueld/src/api/service/views/tests.rs b/apps/piqueld/src/api/service/views/tests.rs new file mode 100644 index 000000000..0271a4cae --- /dev/null +++ b/apps/piqueld/src/api/service/views/tests.rs @@ -0,0 +1,74 @@ +use std::collections::BTreeMap; + +use piqueld_core::resource::{ObservedTask, TaskDiagnostic}; + +use super::*; + +/// A one-replica `web` service running `tasks`. +fn service(tasks: Vec, healthcheck_configured: bool) -> ObservedService { + ObservedService { + secrets: Vec::new(), + files: Vec::new(), + name: "web".into(), + image: "example/web@sha256:digest".into(), + replicas: 1, + environment: BTreeMap::new(), + command: Vec::new(), + arguments: Vec::new(), + mounts: Vec::new(), + healthcheck: None, + healthcheck_configured, + resources: None, + networks: Vec::new(), + labels: BTreeMap::new(), + rollout: None, + telemetry: None, + runtime_configuration_matches: true, + tasks, + convergence: Convergence::Converged, + } +} + +#[test] +fn service_diagnostics_ignore_historical_tasks() { + let service = service( + vec![ + ObservedTask { + state: TaskState::Failed, + healthy: None, + desired_running: false, + diagnostic: Some(TaskDiagnostic::Failed { exit_code: Some(1) }), + ..ObservedTask::default() + }, + ObservedTask { + state: TaskState::Rejected, + healthy: None, + desired_running: true, + diagnostic: Some(TaskDiagnostic::Rejected), + ..ObservedTask::default() + }, + ], + false, + ); + + let diagnostics = service_diagnostics(&service); + + assert_eq!(diagnostics.len(), 1); + assert_eq!(diagnostics[0].code, ApiErrorCode::TaskRejected); +} + +#[test] +fn pending_runtime_health_is_not_reported_as_healthy() { + let task = ObservedTask { + state: TaskState::Running, + healthy: None, + desired_running: true, + diagnostic: None, + ..ObservedTask::default() + }; + let mut service = service(vec![task], true); + + assert_eq!(healthy_replicas(&service), 0); + service.healthcheck_configured = false; + assert_eq!(healthy_replicas(&service), 1); +} diff --git a/apps/piqueld/src/api/service/webhooks.rs b/apps/piqueld/src/api/service/webhooks/mod.rs similarity index 58% rename from apps/piqueld/src/api/service/webhooks.rs rename to apps/piqueld/src/api/service/webhooks/mod.rs index cf18d78d7..d0b87a249 100644 --- a/apps/piqueld/src/api/service/webhooks.rs +++ b/apps/piqueld/src/api/service/webhooks/mod.rs @@ -189,128 +189,4 @@ pub const WEBHOOK_PATH: &str = "/hooks/github/"; pub const WEBHOOK_BODY_LIMIT: usize = 1024 * 1024; #[cfg(test)] -mod tests { - use super::super::sync::tests::{Fake, Fixture, NEW, OLD, Schedule}; - use super::*; - use tower::ServiceExt; - - /// GitHub's documented example: secret "It's a Secret to Everybody", - /// payload "Hello, World!". - const EXAMPLE: &str = "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17"; - - /// GitHub's `X-Hub-Signature-256` for `body` under `secret`. - fn sign(secret: &[u8], body: &[u8]) -> String { - Signature::of(secret, body).unwrap().to_string() - } - - /// Posts a push delivery to `router`. - async fn deliver( - router: &axum::Router, - path: &str, - signature: Option<&str>, - body: Vec, - ) -> axum::http::StatusCode { - let mut request = axum::http::Request::post(path).header("x-github-event", "push"); - if let Some(signature) = signature { - request = request.header("x-hub-signature-256", signature); - } - router - .clone() - .oneshot(request.body(axum::body::Body::from(body)).unwrap()) - .await - .unwrap() - .status() - } - - #[tokio::test] - async fn only_signed_deliveries_hint_sync_which_deploys_the_head_it_lists() { - let fixture = Fixture::new("{mode='webhook'}").await; - let production = fixture.production().await; - let secret = fixture - .service - .generate_webhook_secret(piqueld_store::Actor::Daemon, &fixture.application) - .await - .unwrap() - .secret; - let router = crate::api::http::webhook_router(fixture.service.clone()); - let path = format!("{WEBHOOK_PATH}{}", fixture.application); - // The payload names a commit the branch does not have. - let forged = "dddddddddddddddddddddddddddddddddddddddd"; - let body = format!(r#"{{"ref":"refs/heads/main","after":"{forged}"}}"#).into_bytes(); - let valid = sign(secret.as_bytes(), &body); - - let wrong = sign(b"another secret", &body); - assert_eq!( - deliver(&router, &path, Some(&wrong), body.clone()).await, - axum::http::StatusCode::UNAUTHORIZED - ); - assert_eq!( - deliver(&router, &path, None, body.clone()).await, - axum::http::StatusCode::UNAUTHORIZED - ); - let unknown = format!("{WEBHOOK_PATH}app-unknown-01"); - assert_eq!( - deliver(&router, &unknown, Some(&valid), body.clone()).await, - axum::http::StatusCode::UNAUTHORIZED - ); - let oversized = vec![b' '; WEBHOOK_BODY_LIMIT + 1]; - let signed = sign(secret.as_bytes(), &oversized); - assert_eq!( - deliver(&router, &path, Some(&signed), oversized).await, - axum::http::StatusCode::PAYLOAD_TOO_LARGE - ); - assert_eq!( - deliver(&router, "/api/v1/applications", Some(&valid), body.clone()).await, - axum::http::StatusCode::NOT_FOUND - ); - // Webhook repositories are listed once at startup, then never polled: - // refused deliveries list nothing. - let lister = Fake::with(vec![("main", OLD)]); - let mut schedule = Schedule::default(); - let start = tokio::time::Instant::now(); - fixture - .service - .sync_due(&lister, &mut schedule, start) - .await; - assert_eq!(lister.listings(), 1); - let later = start + std::time::Duration::from_secs(3600); - fixture - .service - .sync_due(&lister, &mut schedule, later) - .await; - assert_eq!(lister.listings(), 1); - - *lister.heads.lock() = Some(vec![("main", NEW)]); - assert_eq!( - deliver(&router, &path, Some(&valid), body).await, - axum::http::StatusCode::NO_CONTENT - ); - fixture - .service - .sync_due(&lister, &mut schedule, later) - .await; - assert_eq!(lister.listings(), 2); - assert_eq!( - fixture.synced(&production).await, - vec![(NEW.to_owned(), "sync:webhook".to_owned())] - ); - } - - #[test] - fn signatures_verify_only_their_secret_and_body() { - let secret = b"It's a Secret to Everybody"; - let signature = Signature::parse(EXAMPLE).unwrap(); - assert!(signature.verifies(secret, b"Hello, World!")); - assert!(!signature.verifies(secret, b"Hello, World?")); - assert!(!signature.verifies(b"another secret", b"Hello, World!")); - for malformed in [ - "", - "sha1=757107ea0eb2509fc211221cce984b8a37570b6d", - &EXAMPLE[..EXAMPLE.len() - 2], - &EXAMPLE.replace('7', "g"), - &EXAMPLE.replacen('7', "+", 1), - ] { - assert!(Signature::parse(malformed).is_none(), "{malformed}"); - } - } -} +mod tests; diff --git a/apps/piqueld/src/api/service/webhooks/tests.rs b/apps/piqueld/src/api/service/webhooks/tests.rs new file mode 100644 index 000000000..6f39b8a70 --- /dev/null +++ b/apps/piqueld/src/api/service/webhooks/tests.rs @@ -0,0 +1,123 @@ +use super::super::sync::tests::{Fake, Fixture, NEW, OLD, Schedule}; +use super::*; +use tower::ServiceExt; + +/// GitHub's documented example: secret "It's a Secret to Everybody", +/// payload "Hello, World!". +const EXAMPLE: &str = "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17"; + +/// GitHub's `X-Hub-Signature-256` for `body` under `secret`. +fn sign(secret: &[u8], body: &[u8]) -> String { + Signature::of(secret, body).unwrap().to_string() +} + +/// Posts a push delivery to `router`. +async fn deliver( + router: &axum::Router, + path: &str, + signature: Option<&str>, + body: Vec, +) -> axum::http::StatusCode { + let mut request = axum::http::Request::post(path).header("x-github-event", "push"); + if let Some(signature) = signature { + request = request.header("x-hub-signature-256", signature); + } + router + .clone() + .oneshot(request.body(axum::body::Body::from(body)).unwrap()) + .await + .unwrap() + .status() +} + +#[tokio::test] +async fn only_signed_deliveries_hint_sync_which_deploys_the_head_it_lists() { + let fixture = Fixture::new("{mode='webhook'}").await; + let production = fixture.production().await; + let secret = fixture + .service + .generate_webhook_secret(piqueld_store::Actor::Daemon, &fixture.application) + .await + .unwrap() + .secret; + let router = crate::api::http::webhook_router(fixture.service.clone()); + let path = format!("{WEBHOOK_PATH}{}", fixture.application); + // The payload names a commit the branch does not have. + let forged = "dddddddddddddddddddddddddddddddddddddddd"; + let body = format!(r#"{{"ref":"refs/heads/main","after":"{forged}"}}"#).into_bytes(); + let valid = sign(secret.as_bytes(), &body); + + let wrong = sign(b"another secret", &body); + assert_eq!( + deliver(&router, &path, Some(&wrong), body.clone()).await, + axum::http::StatusCode::UNAUTHORIZED + ); + assert_eq!( + deliver(&router, &path, None, body.clone()).await, + axum::http::StatusCode::UNAUTHORIZED + ); + let unknown = format!("{WEBHOOK_PATH}app-unknown-01"); + assert_eq!( + deliver(&router, &unknown, Some(&valid), body.clone()).await, + axum::http::StatusCode::UNAUTHORIZED + ); + let oversized = vec![b' '; WEBHOOK_BODY_LIMIT + 1]; + let signed = sign(secret.as_bytes(), &oversized); + assert_eq!( + deliver(&router, &path, Some(&signed), oversized).await, + axum::http::StatusCode::PAYLOAD_TOO_LARGE + ); + assert_eq!( + deliver(&router, "/api/v1/applications", Some(&valid), body.clone()).await, + axum::http::StatusCode::NOT_FOUND + ); + // Webhook repositories are listed once at startup, then never polled: + // refused deliveries list nothing. + let lister = Fake::with(vec![("main", OLD)]); + let mut schedule = Schedule::default(); + let start = tokio::time::Instant::now(); + fixture + .service + .sync_due(&lister, &mut schedule, start) + .await; + assert_eq!(lister.listings(), 1); + let later = start + std::time::Duration::from_secs(3600); + fixture + .service + .sync_due(&lister, &mut schedule, later) + .await; + assert_eq!(lister.listings(), 1); + + *lister.heads.lock() = Some(vec![("main", NEW)]); + assert_eq!( + deliver(&router, &path, Some(&valid), body).await, + axum::http::StatusCode::NO_CONTENT + ); + fixture + .service + .sync_due(&lister, &mut schedule, later) + .await; + assert_eq!(lister.listings(), 2); + assert_eq!( + fixture.synced(&production).await, + vec![(NEW.to_owned(), "sync:webhook".to_owned())] + ); +} + +#[test] +fn signatures_verify_only_their_secret_and_body() { + let secret = b"It's a Secret to Everybody"; + let signature = Signature::parse(EXAMPLE).unwrap(); + assert!(signature.verifies(secret, b"Hello, World!")); + assert!(!signature.verifies(secret, b"Hello, World?")); + assert!(!signature.verifies(b"another secret", b"Hello, World!")); + for malformed in [ + "", + "sha1=757107ea0eb2509fc211221cce984b8a37570b6d", + &EXAMPLE[..EXAMPLE.len() - 2], + &EXAMPLE.replace('7', "g"), + &EXAMPLE.replacen('7', "+", 1), + ] { + assert!(Signature::parse(malformed).is_none(), "{malformed}"); + } +} diff --git a/apps/piqueld/src/auth/throttle.rs b/apps/piqueld/src/auth/throttle/mod.rs similarity index 59% rename from apps/piqueld/src/auth/throttle.rs rename to apps/piqueld/src/auth/throttle/mod.rs index 0f4f65f94..c2ef232dd 100644 --- a/apps/piqueld/src/auth/throttle.rs +++ b/apps/piqueld/src/auth/throttle/mod.rs @@ -68,43 +68,4 @@ pub(crate) fn bucket(peer: IpAddr) -> IpAddr { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn isolates_peers_without_a_shared_cap_and_recovers_after_window() { - let mut throttle = Throttle::default(); - let now = Instant::now(); - let a = Some("192.0.2.1".parse().unwrap()); - for _ in 0..PER_PEER { - throttle.admit(a, now).unwrap(); - } - assert!(throttle.admit(a, now).is_err()); - // Exhausted peers never consume anyone else's allowance. - for host in 2..10 { - let peer = Some(format!("192.0.2.{host}").parse().unwrap()); - for _ in 0..PER_PEER { - throttle.admit(peer, now).unwrap(); - } - } - throttle.admit(None, now).unwrap(); - throttle.admit(a, now + WINDOW).unwrap(); - assert_eq!(throttle.peers.len(), 1); - } - - #[test] - fn groups_ipv6_peers_by_prefix() { - let mut throttle = Throttle::default(); - let now = Instant::now(); - for host in 0..PER_PEER { - let peer = format!("2001:db8:0:1::{host:x}").parse().unwrap(); - throttle.admit(Some(peer), now).unwrap(); - } - let same_prefix = "2001:db8:0:1:ffff::1".parse().unwrap(); - assert!(throttle.admit(Some(same_prefix), now).is_err()); - let other_prefix = "2001:db8:0:2::1".parse().unwrap(); - throttle.admit(Some(other_prefix), now).unwrap(); - let mapped: IpAddr = "::ffff:192.0.2.1".parse().unwrap(); - assert_eq!(bucket(mapped), "192.0.2.1".parse::().unwrap()); - } -} +mod tests; diff --git a/apps/piqueld/src/auth/throttle/tests.rs b/apps/piqueld/src/auth/throttle/tests.rs new file mode 100644 index 000000000..5f7068467 --- /dev/null +++ b/apps/piqueld/src/auth/throttle/tests.rs @@ -0,0 +1,38 @@ +use super::*; + +#[test] +fn isolates_peers_without_a_shared_cap_and_recovers_after_window() { + let mut throttle = Throttle::default(); + let now = Instant::now(); + let a = Some("192.0.2.1".parse().unwrap()); + for _ in 0..PER_PEER { + throttle.admit(a, now).unwrap(); + } + assert!(throttle.admit(a, now).is_err()); + // Exhausted peers never consume anyone else's allowance. + for host in 2..10 { + let peer = Some(format!("192.0.2.{host}").parse().unwrap()); + for _ in 0..PER_PEER { + throttle.admit(peer, now).unwrap(); + } + } + throttle.admit(None, now).unwrap(); + throttle.admit(a, now + WINDOW).unwrap(); + assert_eq!(throttle.peers.len(), 1); +} + +#[test] +fn groups_ipv6_peers_by_prefix() { + let mut throttle = Throttle::default(); + let now = Instant::now(); + for host in 0..PER_PEER { + let peer = format!("2001:db8:0:1::{host:x}").parse().unwrap(); + throttle.admit(Some(peer), now).unwrap(); + } + let same_prefix = "2001:db8:0:1:ffff::1".parse().unwrap(); + assert!(throttle.admit(Some(same_prefix), now).is_err()); + let other_prefix = "2001:db8:0:2::1".parse().unwrap(); + throttle.admit(Some(other_prefix), now).unwrap(); + let mapped: IpAddr = "::ffff:192.0.2.1".parse().unwrap(); + assert_eq!(bucket(mapped), "192.0.2.1".parse::().unwrap()); +} diff --git a/apps/piqueld/src/git/snapshot.rs b/apps/piqueld/src/git/snapshot/mod.rs similarity index 63% rename from apps/piqueld/src/git/snapshot.rs rename to apps/piqueld/src/git/snapshot/mod.rs index ae6e7c00b..095b11663 100644 --- a/apps/piqueld/src/git/snapshot.rs +++ b/apps/piqueld/src/git/snapshot/mod.rs @@ -596,329 +596,4 @@ impl BundleHeader { } #[cfg(test)] -mod tests { - use super::*; - - /// Runs `script` in `directory` with a fixed Git identity, returning its - /// trimmed output. - fn sh(directory: &Path, script: &str) -> String { - let output = std::process::Command::new("sh") - .args(["-ec", script]) - .current_dir(directory) - .env("GIT_AUTHOR_NAME", "Test") - .env("GIT_AUTHOR_EMAIL", "test@example.com") - .env("GIT_COMMITTER_NAME", "Test") - .env("GIT_COMMITTER_EMAIL", "test@example.com") - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - String::from_utf8(output.stdout).unwrap().trim().to_owned() - } - - /// A repository `remote` with two commits, and a clone whose snapshot - /// commit on top of them adds `local.txt`. Returns the base and the - /// snapshot commits. - fn fixture(root: &Path) -> (String, String) { - sh( - root, - "git init -q -b main remote - cd remote && echo one > app.toml && git add . && git commit -qm one - echo two > app.toml && git commit -qam two && cd .. - git clone -q remote work && cd work && echo local > local.txt && git add . - git commit -qm snapshot && git update-ref refs/heads/snapshot HEAD", - ); - ( - sh(&root.join("remote"), "git rev-parse HEAD"), - sh(&root.join("work"), "git rev-parse HEAD"), - ) - } - - /// The bytes of a bundle of `work`'s snapshot ref, with `arguments`. - fn bundle(root: &Path, arguments: &str) -> Vec { - sh( - &root.join("work"), - &format!("git bundle create -q ../x.bundle refs/heads/snapshot {arguments}"), - ); - std::fs::read(root.join("x.bundle")).unwrap() - } - - fn body(bytes: &[u8]) -> impl Stream> { - futures_util::stream::iter( - bytes - .chunks(1000) - .map(|chunk| Ok(Bytes::copy_from_slice(chunk))) - .collect::>(), - ) - } - - /// Checkouts within `max_bytes`; only their limit is used. - fn checkouts(max_bytes: u64) -> Checkouts { - Checkouts::new( - PathBuf::from("unused"), - std::num::NonZeroU64::new(max_bytes).unwrap(), - ) - } - - /// Snapshots kept in `root/snapshots`. - async fn snapshots(root: &Path) -> Snapshots { - Snapshots::open(root.join("snapshots")).await.unwrap() - } - - async fn receive<'a>( - snapshots: &'a Snapshots, - bytes: Vec, - limit: u64, - url: &Path, - ) -> Result, SnapshotError> { - let url = url.display().to_string(); - snapshots - .receive(body(&bytes), (None, limit), &url, &checkouts(1 << 30)) - .await - } - - /// A thin bundle needs its base, which is fetched from the repository; - /// a complete one needs nothing. Either is checked out from its own - /// repository once kept, and holds its upload permit until then, so - /// uploads waiting to be accepted never pile up on disk. - #[tokio::test] - async fn receives_thin_and_complete_bundles() { - let root = tempfile::tempdir().unwrap(); - let (base, commit) = fixture(root.path()); - let remote = root.path().join("remote"); - let snapshots = snapshots(root.path()).await; - let thin = bundle(root.path(), &format!("^{base}")); - let complete = bundle(root.path(), ""); - assert!(thin.len() < complete.len()); - for (bytes, expected) in [(thin, Some(base)), (complete, None)] { - let received = receive(&snapshots, bytes, 1 << 20, &remote).await.unwrap(); - assert_eq!((&received.commit, &received.base), (&commit, &expected)); - let permits = || snapshots.receiving.available_permits(); - assert_eq!(permits(), Snapshots::RECEIVING - 1); - let commit = received.commit.clone(); - let kept = snapshots - .keep(received, async { Ok::<_, SnapshotError>(()) }) - .await; - assert!(kept.is_ok()); - assert_eq!(permits(), Snapshots::RECEIVING); - assert!(snapshots.path(&commit).exists()); - } - let source = snapshots.source(&remote.display().to_string(), &commit); - let checkouts = Checkouts::open(root.path().join("checkouts")) - .await - .unwrap(); - let checkout = checkouts.checkout(&source.repository, None).await.unwrap(); - assert_eq!(checkout.commit, commit); - assert_eq!( - tokio::fs::read_to_string(checkout.path("local.txt").await.unwrap()) - .await - .unwrap(), - "local\n" - ); - // Only the snapshot of the same repository and commit is replaced. - let pinned = GitRepository { - url: remote.display().to_string(), - branch: "main".into(), - commit: Some(commit.clone()), - }; - let other = GitRepository { - url: "https://example.com/other.git".into(), - ..pinned.clone() - }; - assert_eq!( - SnapshotSource::checkout(Some(&source), &pinned), - &source.repository - ); - assert_eq!(SnapshotSource::checkout(Some(&source), &other), &other); - // Nothing staged is left behind. - let staged = std::fs::read_dir(root.path().join("snapshots/staging")).unwrap(); - assert_eq!(staged.count(), 0); - } - - /// Oversized, malformed, and corrupted bundles, and bases the repository - /// lacks, are refused with their own errors, and a snapshot whose - /// deployment is refused is not kept. - #[tokio::test] - async fn refuses_oversized_invalid_and_unfetchable_bundles() { - let root = tempfile::tempdir().unwrap(); - let (base, _) = fixture(root.path()); - let remote = root.path().join("remote"); - let snapshots = snapshots(root.path()).await; - let thin = bundle(root.path(), &format!("^{base}")); - let length = thin.len() as u64; - - // Announced, and only found while streaming. - let announced = snapshots - .receive( - body(&thin), - (Some(length), length - 1), - "unused", - &checkouts(1 << 30), - ) - .await; - assert!(matches!(announced, Err(SnapshotError::TooLarge { .. }))); - let streamed = receive(&snapshots, thin.clone(), length - 1, &remote).await; - assert!(matches!(streamed, Err(SnapshotError::TooLarge { .. }))); - - let garbage = receive(&snapshots, b"not a bundle\n\n".to_vec(), 1 << 20, &remote).await; - assert!(matches!(garbage, Err(SnapshotError::Invalid(_)))); - // `git bundle verify` accepts a truncated pack; unbundling does not. - let truncated = receive( - &snapshots, - thin[..thin.len() - 40].to_vec(), - 1 << 20, - &remote, - ); - assert!(matches!(truncated.await, Err(SnapshotError::Invalid(_)))); - - // A snapshot whose acceptance is refused is not kept. - let received = receive(&snapshots, thin.clone(), 1 << 20, &remote) - .await - .unwrap(); - let commit = received.commit.clone(); - let refused = snapshots - .keep(received, async { - Err::<(), _>(SnapshotError::Invalid("refused")) - }) - .await; - assert!(refused.is_err()); - assert!(!snapshots.path(&commit).exists()); - - // Its files must fit a checkout: `local.txt` and `app.toml` take 10 bytes. - let url = remote.display().to_string(); - let expands = snapshots - .receive(body(&thin), (None, 1 << 20), &url, &checkouts(9)) - .await; - assert!(matches!( - expands, - Err(SnapshotError::TreeTooLarge { limit: 9 }) - )); - - sh(root.path(), "git init -q -b main empty"); - let unfetchable = receive(&snapshots, thin, 1 << 20, &root.path().join("empty")).await; - assert!( - matches!(unfetchable, Err(SnapshotError::BaseUnavailable { prerequisites }) if prerequisites == [base]) - ); - } - - /// A thin bundle of a history that merged a branch forked before its - /// base needs the base and that fork point, and its base is the one - /// they share. Prerequisites that are not one history are refused. - #[tokio::test] - async fn thin_bundles_of_merges_need_their_base_and_its_ancestors() { - let root = tempfile::tempdir().unwrap(); - let base = sh( - root.path(), - "git init -q -b main remote && cd remote - echo a > a && git add . && git commit -qm a && git switch -qc side - echo s > s && git add . && git commit -qm s && git switch -q main - echo b > a && git commit -qam b && git rev-parse HEAD", - ); - let commit = sh( - root.path(), - "git clone -q remote work && cd work && git merge -q --no-edit origin/side - git update-ref refs/heads/snapshot HEAD && git rev-parse HEAD", - ); - let remote = root.path().join("remote"); - let snapshots = snapshots(root.path()).await; - let merged = bundle(root.path(), &format!("^{base}")); - let received = receive(&snapshots, merged, 1 << 20, &remote).await.unwrap(); - assert_eq!((received.commit, received.base), (commit, Some(base))); - // Excluding both parents of the merge leaves two unrelated bases. - let unrelated = bundle(root.path(), "^HEAD^1 ^HEAD^2"); - let refused = receive(&snapshots, unrelated, 1 << 20, &remote).await; - assert!(matches!(refused, Err(SnapshotError::Invalid(_)))); - } - - /// A body that stops sending gives up its permit. - #[tokio::test(start_paused = true)] - async fn stalled_uploads_time_out() { - let root = tempfile::tempdir().unwrap(); - let snapshots = snapshots(root.path()).await; - let stalled = futures_util::stream::pending::>(); - let received = snapshots - .receive(stalled, (None, 1 << 20), "unused", &checkouts(1 << 30)) - .await; - assert!(matches!(received, Err(SnapshotError::TimedOut))); - assert_eq!( - snapshots.receiving.available_permits(), - Snapshots::RECEIVING - ); - } - - #[test] - fn headers_name_one_snapshot_and_its_prerequisites() { - let (a, b) = ("a".repeat(40), "b".repeat(40)); - let parse = |lines: &[String]| BundleHeader::parse(lines); - let header = |lines: &[&str]| { - lines - .iter() - .map(|line| (*line).to_owned()) - .collect::>() - }; - assert_eq!( - parse(&header(&[ - "# v3 git bundle", - "@object-format=sha1", - &format!("-{b} subject"), - &format!("-{a}"), - &format!("{b} refs/heads/snapshot"), - ])), - Some(BundleHeader { - reference: "refs/heads/snapshot".into(), - commit: b.clone(), - prerequisites: vec![a.clone(), b.clone()], - }) - ); - let mut many = vec!["# v2 git bundle".to_owned()]; - many.extend((0..=BundleHeader::PREREQUISITES).map(|n| format!("-{n:040x}"))); - many.push(format!("{b} refs/heads/snapshot")); - assert_eq!(parse(&many), None); - for invalid in [ - header(&["# v4 git bundle", &format!("{b} refs/heads/snapshot")]), - header(&[ - "# v2 git bundle", - "@object-format=sha1", - &format!("{b} refs/heads/x"), - ]), - header(&[ - "# v3 git bundle", - "@filter=blob:none", - &format!("{b} refs/heads/x"), - ]), - header(&[ - "# v2 git bundle", - &format!("{b} refs/heads/x"), - &format!("{a} refs/heads/y"), - ]), - header(&[ - "# v2 git bundle", - &format!("-{a}"), - &format!("-{a}"), - &format!("{b} refs/x"), - ]), - header(&["# v2 git bundle", &format!("{b} HEAD")]), - header(&["# v2 git bundle", &format!("{b} refs/heads/a:refs/heads/b")]), - header(&["# v2 git bundle", &format!("{b} refs/heads/../x")]), - header(&["# v2 git bundle", "1234 refs/heads/x"]), - header(&["# v2 git bundle"]), - ] { - assert_eq!(parse(&invalid), None, "{invalid:?}"); - } - } - - /// Pruning keeps exactly the snapshots still needed. - #[tokio::test] - async fn prune_keeps_only_needed_snapshots() { - let root = tempfile::tempdir().unwrap(); - let snapshots = snapshots(root.path()).await; - let (kept, removed) = ("a".repeat(40), "b".repeat(40)); - for commit in [&kept, &removed] { - std::fs::create_dir(snapshots.path(commit)).unwrap(); - } - let needed = vec![kept.clone()]; - snapshots.prune(async { Ok(needed) }).await.unwrap(); - assert!(snapshots.path(&kept).exists()); - assert!(!snapshots.path(&removed).exists()); - assert!(root.path().join("snapshots/staging").exists()); - } -} +mod tests; diff --git a/apps/piqueld/src/git/snapshot/tests.rs b/apps/piqueld/src/git/snapshot/tests.rs new file mode 100644 index 000000000..77cfefca4 --- /dev/null +++ b/apps/piqueld/src/git/snapshot/tests.rs @@ -0,0 +1,324 @@ +use super::*; + +/// Runs `script` in `directory` with a fixed Git identity, returning its +/// trimmed output. +fn sh(directory: &Path, script: &str) -> String { + let output = std::process::Command::new("sh") + .args(["-ec", script]) + .current_dir(directory) + .env("GIT_AUTHOR_NAME", "Test") + .env("GIT_AUTHOR_EMAIL", "test@example.com") + .env("GIT_COMMITTER_NAME", "Test") + .env("GIT_COMMITTER_EMAIL", "test@example.com") + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + String::from_utf8(output.stdout).unwrap().trim().to_owned() +} + +/// A repository `remote` with two commits, and a clone whose snapshot +/// commit on top of them adds `local.txt`. Returns the base and the +/// snapshot commits. +fn fixture(root: &Path) -> (String, String) { + sh( + root, + "git init -q -b main remote + cd remote && echo one > app.toml && git add . && git commit -qm one + echo two > app.toml && git commit -qam two && cd .. + git clone -q remote work && cd work && echo local > local.txt && git add . + git commit -qm snapshot && git update-ref refs/heads/snapshot HEAD", + ); + ( + sh(&root.join("remote"), "git rev-parse HEAD"), + sh(&root.join("work"), "git rev-parse HEAD"), + ) +} + +/// The bytes of a bundle of `work`'s snapshot ref, with `arguments`. +fn bundle(root: &Path, arguments: &str) -> Vec { + sh( + &root.join("work"), + &format!("git bundle create -q ../x.bundle refs/heads/snapshot {arguments}"), + ); + std::fs::read(root.join("x.bundle")).unwrap() +} + +fn body(bytes: &[u8]) -> impl Stream> { + futures_util::stream::iter( + bytes + .chunks(1000) + .map(|chunk| Ok(Bytes::copy_from_slice(chunk))) + .collect::>(), + ) +} + +/// Checkouts within `max_bytes`; only their limit is used. +fn checkouts(max_bytes: u64) -> Checkouts { + Checkouts::new( + PathBuf::from("unused"), + std::num::NonZeroU64::new(max_bytes).unwrap(), + ) +} + +/// Snapshots kept in `root/snapshots`. +async fn snapshots(root: &Path) -> Snapshots { + Snapshots::open(root.join("snapshots")).await.unwrap() +} + +async fn receive<'a>( + snapshots: &'a Snapshots, + bytes: Vec, + limit: u64, + url: &Path, +) -> Result, SnapshotError> { + let url = url.display().to_string(); + snapshots + .receive(body(&bytes), (None, limit), &url, &checkouts(1 << 30)) + .await +} + +/// A thin bundle needs its base, which is fetched from the repository; +/// a complete one needs nothing. Either is checked out from its own +/// repository once kept, and holds its upload permit until then, so +/// uploads waiting to be accepted never pile up on disk. +#[tokio::test] +async fn receives_thin_and_complete_bundles() { + let root = tempfile::tempdir().unwrap(); + let (base, commit) = fixture(root.path()); + let remote = root.path().join("remote"); + let snapshots = snapshots(root.path()).await; + let thin = bundle(root.path(), &format!("^{base}")); + let complete = bundle(root.path(), ""); + assert!(thin.len() < complete.len()); + for (bytes, expected) in [(thin, Some(base)), (complete, None)] { + let received = receive(&snapshots, bytes, 1 << 20, &remote).await.unwrap(); + assert_eq!((&received.commit, &received.base), (&commit, &expected)); + let permits = || snapshots.receiving.available_permits(); + assert_eq!(permits(), Snapshots::RECEIVING - 1); + let commit = received.commit.clone(); + let kept = snapshots + .keep(received, async { Ok::<_, SnapshotError>(()) }) + .await; + assert!(kept.is_ok()); + assert_eq!(permits(), Snapshots::RECEIVING); + assert!(snapshots.path(&commit).exists()); + } + let source = snapshots.source(&remote.display().to_string(), &commit); + let checkouts = Checkouts::open(root.path().join("checkouts")) + .await + .unwrap(); + let checkout = checkouts.checkout(&source.repository, None).await.unwrap(); + assert_eq!(checkout.commit, commit); + assert_eq!( + tokio::fs::read_to_string(checkout.path("local.txt").await.unwrap()) + .await + .unwrap(), + "local\n" + ); + // Only the snapshot of the same repository and commit is replaced. + let pinned = GitRepository { + url: remote.display().to_string(), + branch: "main".into(), + commit: Some(commit.clone()), + }; + let other = GitRepository { + url: "https://example.com/other.git".into(), + ..pinned.clone() + }; + assert_eq!( + SnapshotSource::checkout(Some(&source), &pinned), + &source.repository + ); + assert_eq!(SnapshotSource::checkout(Some(&source), &other), &other); + // Nothing staged is left behind. + let staged = std::fs::read_dir(root.path().join("snapshots/staging")).unwrap(); + assert_eq!(staged.count(), 0); +} + +/// Oversized, malformed, and corrupted bundles, and bases the repository +/// lacks, are refused with their own errors, and a snapshot whose +/// deployment is refused is not kept. +#[tokio::test] +async fn refuses_oversized_invalid_and_unfetchable_bundles() { + let root = tempfile::tempdir().unwrap(); + let (base, _) = fixture(root.path()); + let remote = root.path().join("remote"); + let snapshots = snapshots(root.path()).await; + let thin = bundle(root.path(), &format!("^{base}")); + let length = thin.len() as u64; + + // Announced, and only found while streaming. + let announced = snapshots + .receive( + body(&thin), + (Some(length), length - 1), + "unused", + &checkouts(1 << 30), + ) + .await; + assert!(matches!(announced, Err(SnapshotError::TooLarge { .. }))); + let streamed = receive(&snapshots, thin.clone(), length - 1, &remote).await; + assert!(matches!(streamed, Err(SnapshotError::TooLarge { .. }))); + + let garbage = receive(&snapshots, b"not a bundle\n\n".to_vec(), 1 << 20, &remote).await; + assert!(matches!(garbage, Err(SnapshotError::Invalid(_)))); + // `git bundle verify` accepts a truncated pack; unbundling does not. + let truncated = receive( + &snapshots, + thin[..thin.len() - 40].to_vec(), + 1 << 20, + &remote, + ); + assert!(matches!(truncated.await, Err(SnapshotError::Invalid(_)))); + + // A snapshot whose acceptance is refused is not kept. + let received = receive(&snapshots, thin.clone(), 1 << 20, &remote) + .await + .unwrap(); + let commit = received.commit.clone(); + let refused = snapshots + .keep(received, async { + Err::<(), _>(SnapshotError::Invalid("refused")) + }) + .await; + assert!(refused.is_err()); + assert!(!snapshots.path(&commit).exists()); + + // Its files must fit a checkout: `local.txt` and `app.toml` take 10 bytes. + let url = remote.display().to_string(); + let expands = snapshots + .receive(body(&thin), (None, 1 << 20), &url, &checkouts(9)) + .await; + assert!(matches!( + expands, + Err(SnapshotError::TreeTooLarge { limit: 9 }) + )); + + sh(root.path(), "git init -q -b main empty"); + let unfetchable = receive(&snapshots, thin, 1 << 20, &root.path().join("empty")).await; + assert!( + matches!(unfetchable, Err(SnapshotError::BaseUnavailable { prerequisites }) if prerequisites == [base]) + ); +} + +/// A thin bundle of a history that merged a branch forked before its +/// base needs the base and that fork point, and its base is the one +/// they share. Prerequisites that are not one history are refused. +#[tokio::test] +async fn thin_bundles_of_merges_need_their_base_and_its_ancestors() { + let root = tempfile::tempdir().unwrap(); + let base = sh( + root.path(), + "git init -q -b main remote && cd remote + echo a > a && git add . && git commit -qm a && git switch -qc side + echo s > s && git add . && git commit -qm s && git switch -q main + echo b > a && git commit -qam b && git rev-parse HEAD", + ); + let commit = sh( + root.path(), + "git clone -q remote work && cd work && git merge -q --no-edit origin/side + git update-ref refs/heads/snapshot HEAD && git rev-parse HEAD", + ); + let remote = root.path().join("remote"); + let snapshots = snapshots(root.path()).await; + let merged = bundle(root.path(), &format!("^{base}")); + let received = receive(&snapshots, merged, 1 << 20, &remote).await.unwrap(); + assert_eq!((received.commit, received.base), (commit, Some(base))); + // Excluding both parents of the merge leaves two unrelated bases. + let unrelated = bundle(root.path(), "^HEAD^1 ^HEAD^2"); + let refused = receive(&snapshots, unrelated, 1 << 20, &remote).await; + assert!(matches!(refused, Err(SnapshotError::Invalid(_)))); +} + +/// A body that stops sending gives up its permit. +#[tokio::test(start_paused = true)] +async fn stalled_uploads_time_out() { + let root = tempfile::tempdir().unwrap(); + let snapshots = snapshots(root.path()).await; + let stalled = futures_util::stream::pending::>(); + let received = snapshots + .receive(stalled, (None, 1 << 20), "unused", &checkouts(1 << 30)) + .await; + assert!(matches!(received, Err(SnapshotError::TimedOut))); + assert_eq!( + snapshots.receiving.available_permits(), + Snapshots::RECEIVING + ); +} + +#[test] +fn headers_name_one_snapshot_and_its_prerequisites() { + let (a, b) = ("a".repeat(40), "b".repeat(40)); + let parse = |lines: &[String]| BundleHeader::parse(lines); + let header = |lines: &[&str]| { + lines + .iter() + .map(|line| (*line).to_owned()) + .collect::>() + }; + assert_eq!( + parse(&header(&[ + "# v3 git bundle", + "@object-format=sha1", + &format!("-{b} subject"), + &format!("-{a}"), + &format!("{b} refs/heads/snapshot"), + ])), + Some(BundleHeader { + reference: "refs/heads/snapshot".into(), + commit: b.clone(), + prerequisites: vec![a.clone(), b.clone()], + }) + ); + let mut many = vec!["# v2 git bundle".to_owned()]; + many.extend((0..=BundleHeader::PREREQUISITES).map(|n| format!("-{n:040x}"))); + many.push(format!("{b} refs/heads/snapshot")); + assert_eq!(parse(&many), None); + for invalid in [ + header(&["# v4 git bundle", &format!("{b} refs/heads/snapshot")]), + header(&[ + "# v2 git bundle", + "@object-format=sha1", + &format!("{b} refs/heads/x"), + ]), + header(&[ + "# v3 git bundle", + "@filter=blob:none", + &format!("{b} refs/heads/x"), + ]), + header(&[ + "# v2 git bundle", + &format!("{b} refs/heads/x"), + &format!("{a} refs/heads/y"), + ]), + header(&[ + "# v2 git bundle", + &format!("-{a}"), + &format!("-{a}"), + &format!("{b} refs/x"), + ]), + header(&["# v2 git bundle", &format!("{b} HEAD")]), + header(&["# v2 git bundle", &format!("{b} refs/heads/a:refs/heads/b")]), + header(&["# v2 git bundle", &format!("{b} refs/heads/../x")]), + header(&["# v2 git bundle", "1234 refs/heads/x"]), + header(&["# v2 git bundle"]), + ] { + assert_eq!(parse(&invalid), None, "{invalid:?}"); + } +} + +/// Pruning keeps exactly the snapshots still needed. +#[tokio::test] +async fn prune_keeps_only_needed_snapshots() { + let root = tempfile::tempdir().unwrap(); + let snapshots = snapshots(root.path()).await; + let (kept, removed) = ("a".repeat(40), "b".repeat(40)); + for commit in [&kept, &removed] { + std::fs::create_dir(snapshots.path(commit)).unwrap(); + } + let needed = vec![kept.clone()]; + snapshots.prune(async { Ok(needed) }).await.unwrap(); + assert!(snapshots.path(&kept).exists()); + assert!(!snapshots.path(&removed).exists()); + assert!(root.path().join("snapshots/staging").exists()); +} diff --git a/apps/piqueld/src/operations.rs b/apps/piqueld/src/operations/mod.rs similarity index 71% rename from apps/piqueld/src/operations.rs rename to apps/piqueld/src/operations/mod.rs index fc48ac040..2478a9929 100644 --- a/apps/piqueld/src/operations.rs +++ b/apps/piqueld/src/operations/mod.rs @@ -474,243 +474,4 @@ impl crate::application::BoundaryError { } #[cfg(test)] -mod tests { - use super::{DiagnosticCode, OperationError}; - use piqueld_docker::DockerError; - use std::error::Error; - - #[tokio::test] - async fn command_diagnostics_keep_stage_and_exit_code_without_output() { - let error = piqueld_docker::command::LoggedCommand::run_recorded( - tokio::process::Command::new("sh").args(["-c", "printf private-token >&2; exit 7"]), - "clone Git repository", - None, - ) - .await - .unwrap_err(); - let diagnostic = crate::application::BoundaryError::GitBuild(error).diagnostic(); - assert_eq!( - diagnostic.causes, - [ - "Command stage: clone Git repository", - "Command exit code: 7" - ] - ); - assert!( - !serde_json::to_string(&diagnostic) - .unwrap() - .contains("private-token") - ); - } - - #[test] - fn operation_errors_retain_causes_without_exposing_them_publicly() { - let diagnostic = "token=internal-secret"; - let error = OperationError::from(DockerError::RequestSource { - operation: "inspect service", - source: Box::new(std::io::Error::other(diagnostic)), - }); - assert_eq!(error.code(), "docker_request_failed"); - assert!(!error.message().contains(diagnostic)); - let cause = error.source().unwrap().source().unwrap(); - assert!(cause.is::()); - assert_eq!(cause.to_string(), diagnostic); - - let journal = OperationError::from(piqueld_store::StoreError::DatabaseSource( - sqlx::Error::PoolClosed, - )); - assert_eq!(journal.code(), "journal_unavailable"); - assert!( - journal - .source() - .unwrap() - .source() - .unwrap() - .is::() - ); - - let git = OperationError::GitBuildFailed(anyhow::anyhow!(diagnostic)); - assert_eq!(git.code(), "git_build_failed"); - assert_eq!(git.source().unwrap().to_string(), diagnostic); - assert!(!git.message().contains(diagnostic)); - } - - #[test] - fn only_a_missing_manifest_file_reads_as_not_found() { - for (kind, code) in [ - (std::io::ErrorKind::NotFound, "manifest_not_found"), - (std::io::ErrorKind::PermissionDenied, "manifest_invalid"), - ] { - let error = anyhow::Error::from(std::io::Error::from(kind)).context("manifest path"); - assert_eq!(OperationError::manifest_input(error).code(), code); - } - } - - /// `DockerError::diagnostic_code` drives retries, and - /// `docker_classification` the operation's diagnostic; they must agree. - #[test] - fn docker_errors_classify_alike_for_retries_and_diagnostics() { - let rejected = |status_code| bollard::errors::Error::DockerResponseServerError { - status_code, - message: String::new(), - }; - for error in [ - DockerError::Unavailable("op"), - DockerError::UnavailableSource { - operation: "op", - source: "cause".into(), - }, - DockerError::NotManager, - DockerError::IncompatibleSwarm, - DockerError::OwnershipConflict, - DockerError::ConfigurationConflict, - DockerError::Validation("op"), - DockerError::ImageResolution("op"), - DockerError::ImageResolutionSource { - operation: "op", - source: rejected(401), - }, - DockerError::ImageResolutionSource { - operation: "op", - source: rejected(500), - }, - DockerError::NetworkInUse(rejected(400)), - DockerError::NetworkRemoving(rejected(500)), - DockerError::Request("op"), - DockerError::RequestSource { - operation: "op", - source: "cause".into(), - }, - ] { - assert_eq!( - OperationError::docker_classification(&error).diagnostic_code(), - error.diagnostic_code(), - "{error:?}" - ); - } - } - - #[test] - fn registry_failures_keep_classification_and_original_status() { - for (status_code, expected) in [ - (401, "image_resolution_rejected"), - (408, "image_resolution_failed"), - (429, "image_resolution_failed"), - (500, "image_resolution_failed"), - ] { - let error = OperationError::from(DockerError::ImageResolutionSource { - operation: "pull image", - source: bollard::errors::Error::DockerResponseServerError { - status_code, - message: "internal registry diagnostic".into(), - }, - }); - assert_eq!(error.code(), expected); - assert!( - error - .source() - .unwrap() - .source() - .unwrap() - .is::() - ); - assert!(!error.message().contains("internal registry diagnostic")); - let diagnostic = error.diagnostic(); - assert!( - diagnostic - .causes - .contains(&format!("Docker returned HTTP status {status_code}")) - ); - assert!( - !serde_json::to_string(&diagnostic) - .unwrap() - .contains("internal registry diagnostic") - ); - } - } - - #[test] - fn preparation_diagnostics_preserve_safe_typed_causes() { - let error = - crate::application::BoundaryError::Runtime(DockerError::ImageResolutionSource { - operation: "pull image", - source: bollard::errors::Error::DockerResponseServerError { - status_code: 401, - message: "registry-secret".into(), - }, - }); - let diagnostic = error.diagnostic(); - assert_eq!(diagnostic.code, "image_resolution_rejected"); - assert_eq!( - diagnostic.causes, - [ - "Docker operation: pull image", - "Docker returned HTTP status 401" - ] - ); - assert!( - !serde_json::to_string(&diagnostic) - .unwrap() - .contains("registry-secret") - ); - let io = crate::application::BoundaryError::GitBuild( - anyhow::Error::from(std::io::Error::new( - std::io::ErrorKind::PermissionDenied, - "secret path", - )) - .context("repository URL with secret"), - ) - .diagnostic(); - assert!(io.causes.contains(&"I/O failure: PermissionDenied".into())); - assert!(!serde_json::to_string(&io).unwrap().contains("secret")); - let storage = OperationError::Journal(piqueld_store::StoreError::DatabaseSource( - sqlx::Error::PoolClosed, - )) - .diagnostic(); - assert!( - storage - .causes - .contains(&"Database connection pool is closed".into()) - ); - let compilation = - crate::application::BoundaryError::Compilation(vec![piqueld_core::CompileError { - resource: "web".into(), - code: piqueld_core::ApiErrorCode::SourceUnresolved.into(), - message: "service source has not been resolved to an immutable image".into(), - }]) - .diagnostic(); - assert!(compilation.causes[0].contains("web")); - assert!( - compilation.causes[0].contains(piqueld_core::ApiErrorCode::SourceUnresolved.as_str()) - ); - } - - #[test] - fn swarm_bootstrap_errors_keep_distinct_diagnostic_guidance() { - for (error, expected_code, expected_action) in [ - ( - DockerError::Unavailable("checking Swarm"), - DiagnosticCode::DockerUnavailable, - "Check Docker Engine availability", - ), - ( - DockerError::NotManager, - DiagnosticCode::SwarmManagerUnavailable, - "single-node Swarm", - ), - ( - DockerError::IncompatibleSwarm, - DiagnosticCode::SwarmTopologyUnsupported, - "single-node Swarm", - ), - ] { - let diagnostic = piqueld_core::observability::Diagnostic::new( - "bootstrap".into(), - error.diagnostic_code(), - error.to_string(), - ); - assert_eq!(diagnostic.code, expected_code.as_str()); - assert!(diagnostic.next_action.contains(expected_action)); - } - } -} +mod tests; diff --git a/apps/piqueld/src/operations/tests.rs b/apps/piqueld/src/operations/tests.rs new file mode 100644 index 000000000..c45ae5622 --- /dev/null +++ b/apps/piqueld/src/operations/tests.rs @@ -0,0 +1,235 @@ +use super::{DiagnosticCode, OperationError}; +use piqueld_docker::DockerError; +use std::error::Error; + +#[tokio::test] +async fn command_diagnostics_keep_stage_and_exit_code_without_output() { + let error = piqueld_docker::command::LoggedCommand::run_recorded( + tokio::process::Command::new("sh").args(["-c", "printf private-token >&2; exit 7"]), + "clone Git repository", + None, + ) + .await + .unwrap_err(); + let diagnostic = crate::application::BoundaryError::GitBuild(error).diagnostic(); + assert_eq!( + diagnostic.causes, + [ + "Command stage: clone Git repository", + "Command exit code: 7" + ] + ); + assert!( + !serde_json::to_string(&diagnostic) + .unwrap() + .contains("private-token") + ); +} + +#[test] +fn operation_errors_retain_causes_without_exposing_them_publicly() { + let diagnostic = "token=internal-secret"; + let error = OperationError::from(DockerError::RequestSource { + operation: "inspect service", + source: Box::new(std::io::Error::other(diagnostic)), + }); + assert_eq!(error.code(), "docker_request_failed"); + assert!(!error.message().contains(diagnostic)); + let cause = error.source().unwrap().source().unwrap(); + assert!(cause.is::()); + assert_eq!(cause.to_string(), diagnostic); + + let journal = OperationError::from(piqueld_store::StoreError::DatabaseSource( + sqlx::Error::PoolClosed, + )); + assert_eq!(journal.code(), "journal_unavailable"); + assert!( + journal + .source() + .unwrap() + .source() + .unwrap() + .is::() + ); + + let git = OperationError::GitBuildFailed(anyhow::anyhow!(diagnostic)); + assert_eq!(git.code(), "git_build_failed"); + assert_eq!(git.source().unwrap().to_string(), diagnostic); + assert!(!git.message().contains(diagnostic)); +} + +#[test] +fn only_a_missing_manifest_file_reads_as_not_found() { + for (kind, code) in [ + (std::io::ErrorKind::NotFound, "manifest_not_found"), + (std::io::ErrorKind::PermissionDenied, "manifest_invalid"), + ] { + let error = anyhow::Error::from(std::io::Error::from(kind)).context("manifest path"); + assert_eq!(OperationError::manifest_input(error).code(), code); + } +} + +/// `DockerError::diagnostic_code` drives retries, and +/// `docker_classification` the operation's diagnostic; they must agree. +#[test] +fn docker_errors_classify_alike_for_retries_and_diagnostics() { + let rejected = |status_code| bollard::errors::Error::DockerResponseServerError { + status_code, + message: String::new(), + }; + for error in [ + DockerError::Unavailable("op"), + DockerError::UnavailableSource { + operation: "op", + source: "cause".into(), + }, + DockerError::NotManager, + DockerError::IncompatibleSwarm, + DockerError::OwnershipConflict, + DockerError::ConfigurationConflict, + DockerError::Validation("op"), + DockerError::ImageResolution("op"), + DockerError::ImageResolutionSource { + operation: "op", + source: rejected(401), + }, + DockerError::ImageResolutionSource { + operation: "op", + source: rejected(500), + }, + DockerError::NetworkInUse(rejected(400)), + DockerError::NetworkRemoving(rejected(500)), + DockerError::Request("op"), + DockerError::RequestSource { + operation: "op", + source: "cause".into(), + }, + ] { + assert_eq!( + OperationError::docker_classification(&error).diagnostic_code(), + error.diagnostic_code(), + "{error:?}" + ); + } +} + +#[test] +fn registry_failures_keep_classification_and_original_status() { + for (status_code, expected) in [ + (401, "image_resolution_rejected"), + (408, "image_resolution_failed"), + (429, "image_resolution_failed"), + (500, "image_resolution_failed"), + ] { + let error = OperationError::from(DockerError::ImageResolutionSource { + operation: "pull image", + source: bollard::errors::Error::DockerResponseServerError { + status_code, + message: "internal registry diagnostic".into(), + }, + }); + assert_eq!(error.code(), expected); + assert!( + error + .source() + .unwrap() + .source() + .unwrap() + .is::() + ); + assert!(!error.message().contains("internal registry diagnostic")); + let diagnostic = error.diagnostic(); + assert!( + diagnostic + .causes + .contains(&format!("Docker returned HTTP status {status_code}")) + ); + assert!( + !serde_json::to_string(&diagnostic) + .unwrap() + .contains("internal registry diagnostic") + ); + } +} + +#[test] +fn preparation_diagnostics_preserve_safe_typed_causes() { + let error = crate::application::BoundaryError::Runtime(DockerError::ImageResolutionSource { + operation: "pull image", + source: bollard::errors::Error::DockerResponseServerError { + status_code: 401, + message: "registry-secret".into(), + }, + }); + let diagnostic = error.diagnostic(); + assert_eq!(diagnostic.code, "image_resolution_rejected"); + assert_eq!( + diagnostic.causes, + [ + "Docker operation: pull image", + "Docker returned HTTP status 401" + ] + ); + assert!( + !serde_json::to_string(&diagnostic) + .unwrap() + .contains("registry-secret") + ); + let io = crate::application::BoundaryError::GitBuild( + anyhow::Error::from(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "secret path", + )) + .context("repository URL with secret"), + ) + .diagnostic(); + assert!(io.causes.contains(&"I/O failure: PermissionDenied".into())); + assert!(!serde_json::to_string(&io).unwrap().contains("secret")); + let storage = OperationError::Journal(piqueld_store::StoreError::DatabaseSource( + sqlx::Error::PoolClosed, + )) + .diagnostic(); + assert!( + storage + .causes + .contains(&"Database connection pool is closed".into()) + ); + let compilation = + crate::application::BoundaryError::Compilation(vec![piqueld_core::CompileError { + resource: "web".into(), + code: piqueld_core::ApiErrorCode::SourceUnresolved.into(), + message: "service source has not been resolved to an immutable image".into(), + }]) + .diagnostic(); + assert!(compilation.causes[0].contains("web")); + assert!(compilation.causes[0].contains(piqueld_core::ApiErrorCode::SourceUnresolved.as_str())); +} + +#[test] +fn swarm_bootstrap_errors_keep_distinct_diagnostic_guidance() { + for (error, expected_code, expected_action) in [ + ( + DockerError::Unavailable("checking Swarm"), + DiagnosticCode::DockerUnavailable, + "Check Docker Engine availability", + ), + ( + DockerError::NotManager, + DiagnosticCode::SwarmManagerUnavailable, + "single-node Swarm", + ), + ( + DockerError::IncompatibleSwarm, + DiagnosticCode::SwarmTopologyUnsupported, + "single-node Swarm", + ), + ] { + let diagnostic = piqueld_core::observability::Diagnostic::new( + "bootstrap".into(), + error.diagnostic_code(), + error.to_string(), + ); + assert_eq!(diagnostic.code, expected_code.as_str()); + assert!(diagnostic.next_action.contains(expected_action)); + } +} diff --git a/apps/piqueld/src/tailnet/mod.rs b/apps/piqueld/src/tailnet/mod.rs index 6ced6685b..3a745ac07 100644 --- a/apps/piqueld/src/tailnet/mod.rs +++ b/apps/piqueld/src/tailnet/mod.rs @@ -158,122 +158,4 @@ impl Tailscaled { } #[cfg(test)] -mod tests { - use super::*; - use piqueld_config::tailscale::{FakeLocalApi, ServeConfig}; - - #[tokio::test(start_paused = true)] - async fn noninteractive_commands_time_out_but_login_can_wait() { - for operation in ["serve", "up"] { - let mut command = Command::new("sh"); - command.args(["-c", "exec sleep 600"]); - let result = tokio::time::timeout( - COMMAND_TIMEOUT * 2, - Tailscaled::run_command(&mut command, operation), - ) - .await; - if operation == "up" { - assert!(result.is_err(), "interactive login must keep waiting"); - } else { - let error = result.unwrap().unwrap_err().to_string(); - assert!( - error.contains(&format!("tailscale {operation} timed out")), - "{error}" - ); - } - } - } - - /// The node's certificate expiry comes from the `LocalAPI`'s PEM, and a - /// refused certificate explains how to enable them. - #[tokio::test] - async fn certificate_expiry_is_read_from_the_local_api() { - let certificate = { - use openssl::{asn1::Asn1Time, hash::MessageDigest, pkey::PKey, rsa::Rsa, x509}; - let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap(); - let mut builder = x509::X509Builder::new().unwrap(); - builder.set_pubkey(&key).unwrap(); - builder - .set_not_before(&Asn1Time::from_unix(1_700_000_000).unwrap()) - .unwrap(); - builder - .set_not_after(&Asn1Time::from_unix(1_800_000_000).unwrap()) - .unwrap(); - builder.sign(&key, MessageDigest::sha256()).unwrap(); - String::from_utf8(builder.build().to_pem().unwrap()).unwrap() - }; - let fake = FakeLocalApi::serve(&[ - ( - "/localapi/v0/cert/piqueld.tail1234.ts.net?type=cert", - 200, - &certificate, - ), - ( - "/localapi/v0/cert/other.tail1234.ts.net?type=cert", - 500, - "invalid domain \"other.tail1234.ts.net\"; must be one of [\"piqueld.tail1234.ts.net\"]\n", - ), - ]).unwrap(); - let tailscaled = Tailscaled::at(fake.socket().to_owned()); - let expiry = tailscaled - .certificate_expiry_ms("piqueld.tail1234.ts.net") - .await - .unwrap(); - assert_eq!(expiry, 1_800_000_000_000); - let refused = tailscaled - .certificate_expiry_ms("other.tail1234.ts.net") - .await - .unwrap_err(); - let refused = format!("{refused:#}"); - assert!( - refused.starts_with("failed to obtain the tailnet HTTPS certificate"), - "{refused}" - ); - assert!(refused.contains("HTTP 500"), "{refused}"); - assert!(refused.contains("invalid domain"), "{refused}"); - } - - /// A port forwarding to a live listener is refused, and one whose - /// listener refuses connections is taken over, as is an unserved port. A - /// port whose owner can't be reached, or served any other way, is - /// refused. - #[tokio::test] - async fn only_unserved_or_stale_ports_are_taken_over() { - let bind = || tokio::net::TcpListener::bind("127.0.0.1:0"); - let listener = bind().await.unwrap(); - let live = listener.local_addr().unwrap(); - // Its daemon is gone: nothing listens there any more. - let stale = bind().await.unwrap().local_addr().unwrap(); - let config = format!( - r#"{{"TCP":{{ - "7001":{{"TCPForward":"{live}","TerminateTLS":"node.ts.net","ProxyProtocol":2}}, - "7002":{{"TCPForward":"{stale}"}}, - "443":{{"HTTPS":true}} - }},"Web":{{}}}}"# - ); - let fake = FakeLocalApi::serve(&[("/localapi/v0/serve-config", 200, &config)]).unwrap(); - let tailscaled = &Tailscaled::at(fake.socket().to_owned()); - let check = |port| async move { - Tailscaled::check_takeover(port, tailscaled.serving(port).await.unwrap()).await - }; - assert_eq!( - tailscaled.serving(7001).await.unwrap(), - PortUse::Forwarded(live) - ); - let refused = check(7001).await.unwrap_err().to_string(); - assert!(refused.contains("still accepts connections"), "{refused}"); - check(7002).await.unwrap(); - // TEST-NET-1 never answers: a timeout or an unreachable network. - let unreachable: ServeConfig = - serde_json::from_str(r#"{"TCP":{"7004":{"TCPForward":"192.0.2.1:7"}}}"#).unwrap(); - let refused = Tailscaled::check_takeover(7004, unreachable.port(7004)) - .await - .unwrap_err(); - assert!( - format!("{refused:#}").contains("192.0.2.1:7"), - "{refused:#}" - ); - check(7003).await.unwrap(); - check(443).await.unwrap_err(); - } -} +mod tests; diff --git a/apps/piqueld/src/tailnet/tests.rs b/apps/piqueld/src/tailnet/tests.rs new file mode 100644 index 000000000..3391a2f7c --- /dev/null +++ b/apps/piqueld/src/tailnet/tests.rs @@ -0,0 +1,117 @@ +use super::*; +use piqueld_config::tailscale::{FakeLocalApi, ServeConfig}; + +#[tokio::test(start_paused = true)] +async fn noninteractive_commands_time_out_but_login_can_wait() { + for operation in ["serve", "up"] { + let mut command = Command::new("sh"); + command.args(["-c", "exec sleep 600"]); + let result = tokio::time::timeout( + COMMAND_TIMEOUT * 2, + Tailscaled::run_command(&mut command, operation), + ) + .await; + if operation == "up" { + assert!(result.is_err(), "interactive login must keep waiting"); + } else { + let error = result.unwrap().unwrap_err().to_string(); + assert!( + error.contains(&format!("tailscale {operation} timed out")), + "{error}" + ); + } + } +} + +/// The node's certificate expiry comes from the `LocalAPI`'s PEM, and a +/// refused certificate explains how to enable them. +#[tokio::test] +async fn certificate_expiry_is_read_from_the_local_api() { + let certificate = { + use openssl::{asn1::Asn1Time, hash::MessageDigest, pkey::PKey, rsa::Rsa, x509}; + let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap(); + let mut builder = x509::X509Builder::new().unwrap(); + builder.set_pubkey(&key).unwrap(); + builder + .set_not_before(&Asn1Time::from_unix(1_700_000_000).unwrap()) + .unwrap(); + builder + .set_not_after(&Asn1Time::from_unix(1_800_000_000).unwrap()) + .unwrap(); + builder.sign(&key, MessageDigest::sha256()).unwrap(); + String::from_utf8(builder.build().to_pem().unwrap()).unwrap() + }; + let fake = FakeLocalApi::serve(&[ + ( + "/localapi/v0/cert/piqueld.tail1234.ts.net?type=cert", + 200, + &certificate, + ), + ( + "/localapi/v0/cert/other.tail1234.ts.net?type=cert", + 500, + "invalid domain \"other.tail1234.ts.net\"; must be one of [\"piqueld.tail1234.ts.net\"]\n", + ), + ]).unwrap(); + let tailscaled = Tailscaled::at(fake.socket().to_owned()); + let expiry = tailscaled + .certificate_expiry_ms("piqueld.tail1234.ts.net") + .await + .unwrap(); + assert_eq!(expiry, 1_800_000_000_000); + let refused = tailscaled + .certificate_expiry_ms("other.tail1234.ts.net") + .await + .unwrap_err(); + let refused = format!("{refused:#}"); + assert!( + refused.starts_with("failed to obtain the tailnet HTTPS certificate"), + "{refused}" + ); + assert!(refused.contains("HTTP 500"), "{refused}"); + assert!(refused.contains("invalid domain"), "{refused}"); +} + +/// A port forwarding to a live listener is refused, and one whose +/// listener refuses connections is taken over, as is an unserved port. A +/// port whose owner can't be reached, or served any other way, is +/// refused. +#[tokio::test] +async fn only_unserved_or_stale_ports_are_taken_over() { + let bind = || tokio::net::TcpListener::bind("127.0.0.1:0"); + let listener = bind().await.unwrap(); + let live = listener.local_addr().unwrap(); + // Its daemon is gone: nothing listens there any more. + let stale = bind().await.unwrap().local_addr().unwrap(); + let config = format!( + r#"{{"TCP":{{ + "7001":{{"TCPForward":"{live}","TerminateTLS":"node.ts.net","ProxyProtocol":2}}, + "7002":{{"TCPForward":"{stale}"}}, + "443":{{"HTTPS":true}} + }},"Web":{{}}}}"# + ); + let fake = FakeLocalApi::serve(&[("/localapi/v0/serve-config", 200, &config)]).unwrap(); + let tailscaled = &Tailscaled::at(fake.socket().to_owned()); + let check = |port| async move { + Tailscaled::check_takeover(port, tailscaled.serving(port).await.unwrap()).await + }; + assert_eq!( + tailscaled.serving(7001).await.unwrap(), + PortUse::Forwarded(live) + ); + let refused = check(7001).await.unwrap_err().to_string(); + assert!(refused.contains("still accepts connections"), "{refused}"); + check(7002).await.unwrap(); + // TEST-NET-1 never answers: a timeout or an unreachable network. + let unreachable: ServeConfig = + serde_json::from_str(r#"{"TCP":{"7004":{"TCPForward":"192.0.2.1:7"}}}"#).unwrap(); + let refused = Tailscaled::check_takeover(7004, unreachable.port(7004)) + .await + .unwrap_err(); + assert!( + format!("{refused:#}").contains("192.0.2.1:7"), + "{refused:#}" + ); + check(7003).await.unwrap(); + check(443).await.unwrap_err(); +}