diff --git a/README.md b/README.md index a616061..9048650 100644 --- a/README.md +++ b/README.md @@ -156,14 +156,14 @@ cargo clippy --all-targets --all-features -- -D warnings cargo test --all ``` -Jenkins runs Cargo tests and enforces a 65% line-coverage floor. Run the exact +Jenkins runs Cargo tests and enforces an 80% line-coverage floor. Run the exact coverage command locally with: ```bash cargo tarpaulin --config tarpaulin.toml --out Json --output-dir coverage ``` -The current suite measures 66.12% (1,046/1,582 lines). `Cargo.toml` is the +The current suite measures 80.27% (1,351/1,683 lines). `Cargo.toml` is the authoritative version source. Jenkins temporarily renames Tarpaulin's JSON to `coverage/summary.json`, extracts and validates the overall percentage, renders badges locally, then removes the summary. It archives only diff --git a/src/build.rs b/src/build.rs index ca9af54..2d50ad3 100644 --- a/src/build.rs +++ b/src/build.rs @@ -491,4 +491,62 @@ mod tests { .unwrap(); assert!(reject_hooks(&doc).is_err()); } + + #[test] + fn malformed_cross_configuration_and_missing_lockfile_are_reported() { + let temp = tempfile::tempdir().unwrap(); + assert!(validate_cross_config(temp.path()) + .unwrap_err() + .to_string() + .contains("cannot inspect")); + + fs::write(temp.path().join("Cargo.toml"), "not valid toml = [").unwrap(); + assert!(validate_cross_config(temp.path()) + .unwrap_err() + .to_string() + .contains("invalid root")); + + fs::write( + temp.path().join("Cargo.toml"), + "[workspace.metadata.cross.target.demo]\nrunner = 'unsafe'\n", + ) + .unwrap(); + assert!(validate_cross_config(temp.path()) + .unwrap_err() + .to_string() + .contains("runner")); + + fs::write(temp.path().join("Cargo.toml"), "[workspace]\n").unwrap(); + fs::write(temp.path().join("Cross.toml"), "invalid = [").unwrap(); + assert!(validate_cross_config(temp.path()) + .unwrap_err() + .to_string() + .contains("invalid")); + fs::remove_file(temp.path().join("Cross.toml")).unwrap(); + + let config = test_config(); + let (problems, engine) = prerequisites( + temp.path(), + &config, + false, + false, + &Runner::new("TEST_TOKEN"), + ); + assert!(engine.is_none()); + assert!(problems + .iter() + .any(|problem| problem.contains("Cargo.lock"))); + + let mut dev = test_config(); + dev.profile = "dev".into(); + dev.locked = false; + let args = cross_arguments( + &test_project(PathBuf::from("target")), + &dev, + "demo-target", + Path::new("target-dir"), + ); + assert!(args.windows(2).any(|pair| pair == ["--profile", "dev"])); + assert!(!args.contains(&"--locked".into())); + } } diff --git a/src/gitea.rs b/src/gitea.rs index 5807044..504ed4f 100644 --- a/src/gitea.rs +++ b/src/gitea.rs @@ -508,4 +508,103 @@ mod tests { .to_string() .contains("HTTPS")); } + + #[test] + fn constructor_rejects_missing_credentials_and_malformed_repositories() { + let missing = "RUST_REALEASE_TEST_TOKEN_THAT_IS_NOT_SET"; + assert!(Gitea::new("https://example.com/team/demo", missing) + .err() + .unwrap() + .to_string() + .contains(missing)); + for repository in [ + "://", + "mailto:demo@example.com", + "https://example.com/only-one", + ] { + assert!( + Gitea::with_token(repository, "token").is_err(), + "{repository}" + ); + } + assert!( + Gitea::with_token("https://example.com/team/demo", "bad\ntoken") + .err() + .unwrap() + .to_string() + .contains("token value") + ); + } + + #[test] + fn malformed_api_responses_and_upload_failures_are_reported() { + let (host, handle) = server(vec![Reply { + method: "GET", + path: "/api/v1/repos/team/demo/tags/v0.1.0", + status: 200, + body: "not-json", + }]); + let api = Gitea::with_token(&format!("{host}/team/demo"), "test-token").unwrap(); + assert!(api + .ensure_release("v0.1.0", "abc", false, false, None) + .unwrap_err() + .to_string() + .contains("invalid JSON")); + handle.join().unwrap(); + + let (host, handle) = server(vec![Reply { + method: "GET", + path: "/api/v1/repos/team/demo", + status: 200, + body: "{}", + }]); + let api = Gitea::with_token(&format!("{host}/team/demo"), "test-token").unwrap(); + assert!(api.repository_private().is_err()); + handle.join().unwrap(); + + let (host, handle) = server(vec![Reply { + method: "GET", + path: "/api/v1/repos/team/demo/releases/7/assets", + status: 200, + body: "{}", + }]); + let api = Gitea::with_token(&format!("{host}/team/demo"), "test-token").unwrap(); + assert!(api.upload(7, &[Path::new("missing")], false).is_err()); + handle.join().unwrap(); + + let (host, handle) = server(vec![Reply { + method: "GET", + path: "/api/v1/repos/team/demo/releases/7/assets", + status: 200, + body: "[]", + }]); + let api = Gitea::with_token(&format!("{host}/team/demo"), "test-token").unwrap(); + assert!(api.upload(7, &[Path::new("missing")], false).is_err()); + handle.join().unwrap(); + + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("asset.bin"); + std::fs::write(&path, b"asset").unwrap(); + let (host, handle) = server(vec![ + Reply { + method: "GET", + path: "/api/v1/repos/team/demo/releases/7/assets", + status: 200, + body: "[]", + }, + Reply { + method: "POST", + path: "/api/v1/repos/team/demo/releases/7/assets?name=asset.bin", + status: 401, + body: "{}", + }, + ]); + let api = Gitea::with_token(&format!("{host}/team/demo"), "test-token").unwrap(); + assert!(api + .upload(7, &[&path], false) + .unwrap_err() + .to_string() + .contains("HTTP 401")); + handle.join().unwrap(); + } } diff --git a/src/package.rs b/src/package.rs index 4080843..f9607c5 100644 --- a/src/package.rs +++ b/src/package.rs @@ -345,4 +345,48 @@ mod tests { assert!(package(temp.path(), "demo", "0.1.0", &outputs, PackageFormat::Tgz,).is_err()); } } + + #[test] + fn rejects_missing_non_file_and_oversized_inputs() { + let temp = tempfile::tempdir().unwrap(); + let missing = temp.path().join("missing"); + let outputs = [TargetOutputs { + target: "x86_64-unknown-linux-musl".into(), + binaries: vec![("demo".into(), missing.clone())], + }]; + assert!( + package(temp.path(), "demo", "0.1.0", &outputs, PackageFormat::Tgz) + .unwrap_err() + .to_string() + .contains("cannot inspect binary") + ); + assert!(checksum(&missing) + .unwrap_err() + .to_string() + .contains("cannot open")); + + let directory = temp.path().join("directory"); + fs::create_dir(&directory).unwrap(); + let outputs = [TargetOutputs { + target: "x86_64-unknown-linux-musl".into(), + binaries: vec![("demo".into(), directory)], + }]; + assert!( + package(temp.path(), "demo", "0.1.0", &outputs, PackageFormat::Tgz) + .unwrap_err() + .to_string() + .contains("regular binary") + ); + + let mut output = Vec::new(); + let long_name = format!("{}/{}", "p".repeat(156), "name"); + assert!(write_header(&mut output, &long_name, 0o755, 0, b'0') + .unwrap_err() + .to_string() + .contains("USTAR limits")); + assert!(octal(&mut [0_u8; 2], u64::MAX) + .unwrap_err() + .to_string() + .contains("Tar field")); + } } diff --git a/src/project.rs b/src/project.rs index 86b801f..0c7c73e 100644 --- a/src/project.rs +++ b/src/project.rs @@ -448,15 +448,44 @@ mod tests { normalize_repository("https://example.com/gitea/owner/demo.git").unwrap(), "https://example.com/gitea/owner/demo" ); + assert_eq!( + normalize_repository("https://example.com:8443/owner/demo").unwrap(), + "https://example.com:8443/owner/demo" + ); for value in [ "https://token@example.com/owner/demo", "https://example.com/owner/demo?token=secret", "https://example.com/owner/../demo", + "ftp://example.com/owner/demo", + "not a repository URL", + "git@:owner/demo", + "https://example.com/owner/.git", ] { assert!(normalize_repository(value).is_err(), "{value}"); } } + #[test] + fn local_source_and_inspection_errors_are_explicit() { + let temp = tempfile::tempdir().unwrap(); + let file = temp.path().join("not-a-directory"); + fs::write(&file, "content").unwrap(); + let runner = Runner::new("GITEA_TOKEN"); + assert!( + acquire_project(file.to_str().unwrap(), None, false, &runner) + .err() + .unwrap() + .to_string() + .contains("must be a directory") + ); + assert!( + inspect(temp.path().join("missing").to_str().unwrap(), None, &runner,) + .unwrap_err() + .to_string() + .contains("requires a local project") + ); + } + #[test] fn local_source_is_retained_and_clone_checks_out_exact_tag() { let temp = tempfile::tempdir().unwrap(); diff --git a/src/verify.rs b/src/verify.rs index 6ed64a1..6d11f81 100644 --- a/src/verify.rs +++ b/src/verify.rs @@ -622,4 +622,124 @@ mod tests { "https://example.com/team/demo/releases/download/release%2B1/one.tgz" ); } + + #[test] + fn archive_validation_rejects_corrupt_metadata_and_payloads() { + let temp = tempfile::tempdir().unwrap(); + let binary = temp.path().join("demo"); + fs::write(&binary, b"binary").unwrap(); + let (artifacts, _) = package::package( + temp.path(), + "demo", + "0.1.0", + &outputs("x86_64-unknown-linux-musl", binary), + PackageFormat::Tgz, + ) + .unwrap(); + let artifact = &artifacts[0]; + let mut not_archive = artifact.clone(); + not_archive.contents = ArtifactContents::Binary; + assert!(verify_archive(&artifact.path, ¬_archive) + .unwrap_err() + .to_string() + .contains("is not an archive")); + + let invalid_gzip = temp.path().join("invalid.tgz"); + fs::write(&invalid_gzip, b"not gzip").unwrap(); + assert!(verify_archive(&invalid_gzip, artifact) + .unwrap_err() + .to_string() + .contains("invalid gzip")); + + let mut valid_tar = Vec::new(); + GzDecoder::new(File::open(&artifact.path).unwrap()) + .read_to_end(&mut valid_tar) + .unwrap(); + let write_tar = |name: &str, bytes: &[u8]| { + let path = temp.path().join(name); + let mut gzip = flate2::write::GzEncoder::new( + File::create(&path).unwrap(), + flate2::Compression::default(), + ); + gzip.write_all(bytes).unwrap(); + gzip.finish().unwrap(); + path + }; + let truncated = write_tar("truncated.tgz", &[0; 1024]); + assert!(verify_archive(&truncated, artifact) + .unwrap_err() + .to_string() + .contains("truncated tar")); + + for (name, index, byte, expected) in [ + ("root.tgz", 0, b'x', "archive root"), + ("binary.tgz", 512, b'x', "archive binary"), + ("utf8.tgz", 0, 0xff, "non-UTF-8"), + ("numeric.tgz", 512 + 100, b'x', "numeric field"), + ] { + let mut corrupt = valid_tar.clone(); + corrupt[index] = byte; + let path = write_tar(name, &corrupt); + let error = verify_archive(&path, artifact).unwrap_err().to_string(); + assert!(error.contains(expected), "{error}"); + } + + let mut non_executable = valid_tar; + non_executable[512 + 100..512 + 108].copy_from_slice(b"0000644\0"); + let path = write_tar("mode.tgz", &non_executable); + assert!(verify_archive(&path, artifact) + .unwrap_err() + .to_string() + .contains("not executable")); + } + + #[test] + fn published_verification_rejects_http_size_and_checksum_failures() { + use std::{net::TcpListener, thread}; + + let temp = tempfile::tempdir().unwrap(); + let local = temp.path().join("demo.bin"); + let sums = temp.path().join("SHA256SUMS"); + fs::write(&local, b"local").unwrap(); + fs::write(&sums, b"unused").unwrap(); + let artifact = Artifact { + target: "x86_64-unknown-linux-musl".into(), + path: local, + contents: ArtifactContents::Binary, + sha256: String::new(), + }; + + for (status, body, expected) in [ + (404, b"missing".as_slice(), "HTTP 404"), + (200, b"too-long".as_slice(), "exceeds expected size"), + (200, b"wrong".as_slice(), "SHA-256 differs"), + ] { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let repository = format!("http://{}/team/demo", listener.local_addr().unwrap()); + let response_body = body.to_vec(); + let handle = thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut request = [0_u8; 4096]; + let _ = stream.read(&mut request).unwrap(); + write!( + stream, + "HTTP/1.1 {status} Result\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + response_body.len() + ) + .unwrap(); + stream.write_all(&response_body).unwrap(); + }); + let error = verify_published( + &repository, + "v0.1.0", + std::slice::from_ref(&artifact), + &sums, + None, + ) + .unwrap_err() + .to_string(); + assert!(error.contains(expected), "{error}"); + handle.join().unwrap(); + } + } } diff --git a/tarpaulin.toml b/tarpaulin.toml index cca4fb2..cde03a4 100644 --- a/tarpaulin.toml +++ b/tarpaulin.toml @@ -1,7 +1,7 @@ [coverage] all-features = true engine = "Llvm" -fail-under = 65.0 +fail-under = 80.0 locked = true run-types = ["Tests"] workspace = true @@ -9,5 +9,5 @@ workspace = true [report] out = ["Stdout"] -# This floor stays below the measured suite result without excluding production -# code or manufacturing tests for process-only and platform failure paths. +# This floor is backed by end-to-end release-flow and failure-path tests without +# excluding production code or manufacturing process/platform-only failures. diff --git a/tests/cli_release_flow.rs b/tests/cli_release_flow.rs new file mode 100644 index 0000000..6417cec --- /dev/null +++ b/tests/cli_release_flow.rs @@ -0,0 +1,194 @@ +#![cfg(unix)] + +use std::{ + env, fs, + os::unix::fs::PermissionsExt, + path::Path, + process::{Command, Output}, +}; + +use tempfile::TempDir; + +fn run(command: &mut Command) -> Output { + command.output().expect("test command should start") +} + +fn git(repository: &Path, arguments: &[&str]) { + let output = run(Command::new("git") + .arg("-C") + .arg(repository) + .args(arguments)); + assert!( + output.status.success(), + "git {arguments:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); +} + +fn executable(path: &Path, source: &str) { + fs::write(path, source).expect("fake executable should be written"); + let mut permissions = fs::metadata(path) + .expect("fake executable metadata should be readable") + .permissions(); + permissions.set_mode(0o755); + fs::set_permissions(path, permissions).expect("fake executable should be executable"); +} + +fn publisher(project: &Path, fake_bin: &Path, cross_log: &Path, arguments: &[&str]) -> Output { + let path = format!( + "{}:{}", + fake_bin.display(), + env::var("PATH").expect("PATH should be available") + ); + run(Command::new(env!("CARGO_BIN_EXE_rust_realease")) + .arg(project) + .args(arguments) + .env("PATH", path) + .env("CROSS_LOG", cross_log)) +} + +fn assert_success(output: &Output) -> String { + assert!( + output.status.success(), + "publisher failed:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8_lossy(&output.stdout).into_owned() +} + +#[test] +fn compile_only_reuses_clean_commit_and_rebuilds_changed_or_forced_inputs() { + let temporary = TempDir::new().expect("temporary directory should be created"); + let project = temporary.path().join("project"); + let fake_bin = temporary.path().join("bin"); + let cross_log = temporary.path().join("cross.log"); + fs::create_dir_all(project.join("src")).unwrap(); + fs::create_dir_all(&fake_bin).unwrap(); + fs::write( + project.join("Cargo.toml"), + "[package]\n\ + name = \"demo\"\n\ + version = \"0.1.0\"\n\ + edition = \"2021\"\n\ + repository = \"https://example.com/team/demo\"\n\ + [package.metadata.binstall]\n\ + pkg-url = \"{ repo }/releases/download/v{ version }/{ name }-{ target }-v{ version }.tgz\"\n\ + pkg-fmt = \"tgz\"\n\ + bin-dir = \"{ name }-{ target }-v{ version }/{ bin }{ binary-ext }\"\n", + ) + .unwrap(); + fs::write(project.join("src/main.rs"), "fn main() {}\n").unwrap(); + fs::write(project.join(".gitignore"), "/target/\n/dist/\n").unwrap(); + fs::write( + project.join("rust-release.toml"), + "[build]\ntargets = [\"x86_64-unknown-linux-musl\"]\n", + ) + .unwrap(); + executable(&fake_bin.join("docker"), "#!/bin/sh\n[ \"$1\" = info ]\n"); + executable(&fake_bin.join("cargo-binstall"), "#!/bin/sh\nexit 0\n"); + executable( + &fake_bin.join("cross"), + "#!/bin/sh\n\ + set -eu\n\ + target=\n\ + target_dir=\n\ + profile=debug\n\ + binaries=\n\ + while [ \"$#\" -gt 0 ]; do\n\ + case \"$1\" in\n\ + --target) shift; target=$1 ;;\n\ + --target-dir) shift; target_dir=$1 ;;\n\ + --release) profile=release ;;\n\ + --profile) shift; profile=$1 ;;\n\ + --bin) shift; binaries=\"$binaries $1\" ;;\n\ + esac\n\ + shift\n\ + done\n\ + output_dir=$target_dir/$target/$profile\n\ + mkdir -p \"$output_dir\"\n\ + for binary in $binaries; do printf 'compiled %s' \"$binary\" >\"$output_dir/$binary\"; done\n\ + printf 'cross invoked\\n' >>\"$CROSS_LOG\"\n", + ); + + git(&project, &["init", "--quiet"]); + git(&project, &["config", "user.name", "Release Test"]); + git(&project, &["config", "user.email", "release@example.com"]); + git(&project, &["config", "commit.gpgsign", "false"]); + let lock = run(Command::new("cargo") + .args(["generate-lockfile", "--manifest-path"]) + .arg(project.join("Cargo.toml"))); + assert!(lock.status.success()); + git(&project, &["add", "."]); + git(&project, &["commit", "--quiet", "-m", "initial"]); + git(&project, &["tag", "v0.1.0"]); + + let dry_run = assert_success(&publisher(&project, &fake_bin, &cross_log, &["--dry-run"])); + assert!(dry_run.contains("Dry run complete")); + assert!(!cross_log.exists()); + + let first = assert_success(&publisher( + &project, + &fake_bin, + &cross_log, + &["--compile-only"], + )); + assert!(first.contains("Cross builds complete")); + assert_eq!(fs::read_to_string(&cross_log).unwrap().lines().count(), 1); + + let second = assert_success(&publisher( + &project, + &fake_bin, + &cross_log, + &["--compile-only"], + )); + assert!(second.contains("Reusing completed release build")); + assert_eq!(fs::read_to_string(&cross_log).unwrap().lines().count(), 1); + + fs::write( + project.join("src/main.rs"), + "fn main() { println!(\"changed\"); }\n", + ) + .unwrap(); + let dirty_publication = publisher(&project, &fake_bin, &cross_log, &[]); + assert!(!dirty_publication.status.success()); + assert!(String::from_utf8_lossy(&dirty_publication.stderr) + .contains("Publication requires a clean checkout")); + assert_success(&publisher( + &project, + &fake_bin, + &cross_log, + &["--compile-only"], + )); + assert_eq!(fs::read_to_string(&cross_log).unwrap().lines().count(), 2); + + git(&project, &["add", "src/main.rs"]); + git(&project, &["commit", "--quiet", "-m", "change source"]); + let changed = assert_success(&publisher( + &project, + &fake_bin, + &cross_log, + &["--compile-only"], + )); + assert!(changed.contains("Cross builds complete")); + assert_eq!(fs::read_to_string(&cross_log).unwrap().lines().count(), 3); + + assert_success(&publisher( + &project, + &fake_bin, + &cross_log, + &["--compile-only", "--recompile"], + )); + assert_eq!(fs::read_to_string(&cross_log).unwrap().lines().count(), 4); +} + +#[test] +fn missing_message_file_is_reported_before_project_acquisition() { + let temporary = TempDir::new().unwrap(); + let output = run(Command::new(env!("CARGO_BIN_EXE_rust_realease")) + .arg("missing-project") + .args(["--message-file", "missing-notes.md"]) + .current_dir(temporary.path())); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("cannot read release message file")); +}