From 09603f4c5737bd353b07b1fae543933bd3571089 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 17 Sep 2026 02:24:08 +0200 Subject: [PATCH] Verify private Gitea assets and exercise isolated binstall --- AGENT_TASKS.md | 29 ++--- README.md | 6 +- docs/advanced-usage.md | 8 +- src/cli.rs | 16 ++- src/gitea.rs | 23 ++++ src/verify.rs | 240 +++++++++++++++++++++++++++++++++++++++-- 6 files changed, 292 insertions(+), 30 deletions(-) diff --git a/AGENT_TASKS.md b/AGENT_TASKS.md index ed7b988..68b22bb 100644 --- a/AGENT_TASKS.md +++ b/AGENT_TASKS.md @@ -14,11 +14,13 @@ The user explicitly requested removal of the Python implementation and its launc - Defer live API release tests until a disposable token is provided. - Use the small `target_test_project` submodule for fast build and cross-target experiments. -Current Rust milestone: inspection, metadata, preparation, host verification, Cross build, packaging, Gitea publication, anonymous downloads, and isolated cargo-binstall orchestration are implemented. Gitea paths pass local HTTP mock tests; live publication and real cargo-binstall installation still need a disposable token. Preparation has disposable Git tests for dry-run, commit, tag safety, destination refusal, and an atomic branch/tag push to a local bare remote. The tiny fixture built and packaged all three default targets locally. The Python worker, its tests, `release.sh`, and `requirements.txt` were removed at the user's request. +Current Rust milestone: inspection, metadata, preparation, host verification, Cross build, packaging, Gitea publication, anonymous downloads, authenticated private downloads, and isolated cargo-binstall orchestration are implemented. The disposable private `target_test_project` release was created with all three target archives and SHA256SUMS; an opt-in live test verified their authenticated downloads, checksums, and layouts. Public anonymous download and real cargo-binstall installation still need a public disposable release. Preparation has disposable Git tests for dry-run, commit, tag safety, destination refusal, and an atomic branch/tag push to a local bare remote. The tiny fixture built and packaged all three default targets locally. The Python worker, its tests, `release.sh`, and `requirements.txt` were removed at the user's request. + +The opt-in real `cargo-binstall` integration fixture installs all three archive contracts from a temporary local HTTP server into isolated directories. Its test-only invocation permits HTTP; production verification continues to require HTTPS. The private live Gitea release does not allow cargo-binstall downloads, even with `GITEA_TOKEN` set. Rust-only install check after cleanup: `cargo install --path . --locked --offline --root /tmp/rust_realease_install --target-dir target` succeeded, and the installed binary reported version `0.1.0`. Formatting, Clippy, and all 26 Rust tests passed. -Progress tracking: check a task only when the Rust behavior is implemented and locally verified. Keep live release gates open until a disposable Gitea token is provided. The old Python baseline had 45 passing tests and two opt-in tests skipped before removal. CI runs Cargo tests only; Cross and live Gitea tests are separate checks. Next work: real disposable release, public download, and isolated cargo-binstall validation. +Progress tracking: check a task only when the Rust behavior is implemented and locally verified. Keep public release and cargo-binstall gates open until a public disposable repository is available. The old Python baseline had 45 passing tests and two opt-in tests skipped before removal. CI runs Cargo tests only; Cross and live Gitea tests are separate checks. Parity note: Python and Rust `target_test_project --dry-run --stop-after verify` both report the missing local release tag and exit nonzero. The Rust dry run now reports this as a prerequisite without creating a tag. Python and Rust metadata-stage runs both succeed on the fixture. Output formatting differs; full fixture parity remains open. @@ -572,8 +574,8 @@ Test-only as useful: ### Tests - [x] Local/mock HTTP asset server integration. -- [ ] Real cargo-binstall integration fixture. -- [ ] Check all three default target artifact layouts. +- [x] Real cargo-binstall integration fixture (local HTTP, opt-in). +- [x] Check all three default target artifact layouts. ### Gate @@ -691,20 +693,21 @@ Use a repository specifically safe for integration testing. ### Publication -- [ ] Matching remote tag is validated. -- [ ] Release is created or reused. -- [ ] All assets upload. +- [x] Matching remote tag is validated. +- [x] Release is created or reused (creation verified on private fixture). +- [x] All assets upload. - [ ] Anonymous downloads work. -- [ ] Checksums/layouts verify. +- [x] Authenticated private downloads work. +- [x] Checksums/layouts verify for the private fixture. - [ ] cargo-binstall installs from the live release into a temporary location. ### Safety -- [ ] No unrelated repo files modified. -- [ ] No unrelated release assets touched. -- [ ] No token appears in logs. -- [ ] No force push. -- [ ] No tag movement. +- [x] No unrelated repo files modified in the disposable fixture. +- [x] No unrelated release assets touched in the new release. +- [x] No token appears in logs from this live run. +- [x] No force push. +- [x] No tag movement. ### Gate diff --git a/README.md b/README.md index ca55c60..45c212a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # rust_realease -`rust_realease` builds and publishes one binary from a Rust package to a Gitea release. Give it a local project directory or a Git URL. It inspects Cargo metadata, checks the version tag, builds the selected targets with Cross, creates `.tgz` archives and `SHA256SUMS`, uploads them, and verifies the public downloads. It can also prepare a project for release with explicit commit, tag, and push options. +`rust_realease` builds and publishes one binary from a Rust package to a Gitea release. Give it a local project directory or a Git URL. It inspects Cargo metadata, checks the version tag, builds the selected targets with Cross, creates `.tgz` archives and `SHA256SUMS`, uploads them, and verifies release downloads. It can also prepare a project for release with explicit commit, tag, and push options. ## Install @@ -86,7 +86,7 @@ For a remote repository, select the exact tag to check out: rust_realease https://gitea.example.org/owner/my-tool.git --tag v0.1.0 ``` -The token account needs repository read access and release write access. `--push-preparation` additionally needs code write access. The token is read from `GITEA_TOKEN` by default and is kept out of child build processes. Published assets must be publicly downloadable for the final anonymous download and `cargo-binstall` checks. An existing asset with the same name stops the upload; `--replace-assets` explicitly permits replacing matching assets. +The token account needs repository read access and release write access. `--push-preparation` additionally needs code write access. The token is read from `GITEA_TOKEN` by default and is kept out of child build processes. Public releases are verified by anonymous downloads. Private releases are downloaded with Gitea authentication; use `--skip-binstall-test` for them because cargo-binstall cannot install from their private attachment URLs. An existing asset with the same name stops the upload; `--replace-assets` explicitly permits replacing matching assets. ## More options @@ -101,3 +101,5 @@ cargo test --all ``` Jenkins runs Cargo tests only. Cross builds and live Gitea releases are separate release checks. The small `target_test_project` submodule provides a fast target matrix fixture. + +With `cargo-binstall` installed, run the opt-in isolated install fixture for all three targets with `cargo test real_binstall_installs_local_release_fixture -- --ignored`. diff --git a/docs/advanced-usage.md b/docs/advanced-usage.md index 33bc1e3..4eb2aee 100644 --- a/docs/advanced-usage.md +++ b/docs/advanced-usage.md @@ -53,9 +53,9 @@ For repositories whose build scripts need a selected Rust toolchain inside Cross ## Pipeline stages -`--stop-after` can stop at `inspect`, `metadata`, `verify`, `build`, `package`, `release`, `upload`, or `binstall`. `verify` runs host `cargo check` and `cargo test`; `--skip-tests` skips only tests. Release builds use fresh target directories to avoid stale build-script output. `release` creates or reuses the Gitea release; `upload` uploads archives and checksums. The final stage downloads assets anonymously, checks their checksums and archive layout, and runs isolated `cargo-binstall` installs for each target. `--skip-binstall-test` skips that install check, while retaining download verification. +`--stop-after` can stop at `inspect`, `metadata`, `verify`, `build`, `package`, `release`, `upload`, or `binstall`. `verify` runs host `cargo check` and `cargo test`; `--skip-tests` skips only tests. Release builds use fresh target directories to avoid stale build-script output. `release` creates or reuses the Gitea release; `upload` uploads archives and checksums. The final stage downloads assets anonymously for public repositories or with Gitea authentication for private repositories, checks their checksums and archive layout, and runs isolated `cargo-binstall` installs for public targets. `--skip-binstall-test` skips that install check, while retaining download verification. -`--draft --stop-after upload` is useful when a release must stay private for review. Full verification needs public downloads. `--prerelease` and `--draft` set properties when a release is created; reusing a release preserves its existing settings. Asset replacement is not transactional: if an upload fails after a matching asset is deleted, retry the publication explicitly. +`--draft --stop-after upload` is useful when a release must stay private for review. Private repositories require `--skip-binstall-test`; cargo-binstall cannot fetch their attachment URLs, even when `GITEA_TOKEN` is set. `--prerelease` and `--draft` set properties when a release is created; reusing a release preserves its existing settings. Asset replacement is not transactional: if an upload fails after a matching asset is deleted, retry the publication explicitly. ## Artifact contract @@ -73,7 +73,7 @@ Windows archives contain `my-tool.exe`. `SHA256SUMS` lists the final archive che Authenticated Gitea API publication requires HTTPS. The token comes from the configured environment variable, never from a positional argument or URL. Child Cargo and Cross processes do not receive it. An HTTPS preparation push to the matching release repository can use the token through a temporary askpass helper; SSH pushes use normal Git credentials. Grant the token account code read and release write access, plus code write when using `--push-preparation`. -Normal publication does not create a commit, tag, or push. Existing asset names cause an error unless `--replace-assets` is set; unrelated assets are not deleted. Draft or private assets cannot pass anonymous verification. +Normal publication does not create a commit, tag, or push. Existing asset names cause an error unless `--replace-assets` is set; unrelated assets are not deleted. Private assets are verified with authenticated downloads and do not establish public installability. ## Troubleshooting @@ -81,7 +81,7 @@ Normal publication does not create a commit, tag, or push. Existing asset names - **Missing Cargo.lock:** run preparation or use `--unlocked` when unlocked resolution is intentional. - **Container unavailable:** start Docker or Podman. `CROSS_CONTAINER_ENGINE` can select `docker` or `podman`. - **Cross image or native library failure:** configure an appropriate Cross image and target libraries in the project. The publisher does not substitute an MSVC target or hide linker failures. -- **Private release verification failure:** publish the release before the final verification stage, or stop at `upload` for a draft workflow. +- **Private release installation:** pass `--skip-binstall-test` to verify the uploaded assets with Gitea authentication. Use a public disposable release to test real cargo-binstall installation. - **Asset collision:** inspect the existing release; use `--replace-assets` only when replacement is intended. `cargo-binstall` verification installs into temporary directories and does not run foreign-target binaries. Plain registry based `cargo binstall my-tool` additionally requires a published crate with the release metadata; this tool does not publish crates. diff --git a/src/cli.rs b/src/cli.rs index 72a242b..b9f5e96 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -296,6 +296,10 @@ pub fn run(args: Cli) -> Result<(), Error> { } let commit = project::head_commit(&checkout.root, &runner)?; let api = Gitea::new(&repository, &config.token_env)?; + let private = api.repository_private()?; + if private && needs_binstall { + return Err(Error("This repository is private; cargo-binstall cannot verify its private release downloads. Rerun with --skip-binstall-test to verify uploaded assets with Gitea authentication.".into())); + } let release = api.ensure_release(&tag, &commit, args.draft, args.prerelease)?; println!("Release ready: {tag}"); if args.stop_after == Some(Stage::Release) { @@ -310,7 +314,17 @@ pub fn run(args: Cli) -> Result<(), Error> { if release.draft { return Err(Error("Draft uploaded. Public verification requires publishing the draft; use --stop-after upload for draft workflows.".into())); } - verify::verify_published(&repository, &tag, &artifacts, &sums)?; + verify::verify_published( + &repository, + &tag, + &artifacts, + &sums, + if private { + Some(api.download_client()) + } else { + None + }, + )?; if !args.skip_binstall_test { verify::verify_binstall(&checkout.root, &selected, &config.targets, &runner)?; } diff --git a/src/gitea.rs b/src/gitea.rs index af51723..8caefd0 100644 --- a/src/gitea.rs +++ b/src/gitea.rs @@ -149,6 +149,16 @@ impl Gitea { .map_err(|_| Error("Gitea release response is missing id or draft state.".into())) } + pub fn repository_private(&self) -> Result { + self.request(Method::GET, "", None, false)? + .and_then(|repository| repository.get("private").and_then(Value::as_bool)) + .ok_or_else(|| Error("Gitea repository response is missing visibility.".into())) + } + + pub fn download_client(&self) -> &Client { + &self.client + } + fn assets(&self, release_id: u64) -> Result, Error> { let response = self .request( @@ -446,6 +456,19 @@ mod tests { } } + #[test] + fn reads_repository_visibility_before_private_verification() { + let (host, handle) = server(vec![Reply { + method: "GET", + path: "/api/v1/repos/team/demo", + status: 200, + body: r#"{"private":true}"#, + }]); + let api = Gitea::with_token(&format!("{host}/team/demo"), "test-token").unwrap(); + assert!(api.repository_private().unwrap()); + assert_eq!(handle.join().unwrap().len(), 1); + } + #[test] fn encodes_tag_and_requires_https() { assert_eq!(encode("v1.0+build"), "v1.0%2Bbuild"); diff --git a/src/verify.rs b/src/verify.rs index 7542916..5751a17 100644 --- a/src/verify.rs +++ b/src/verify.rs @@ -115,16 +115,20 @@ pub fn verify_published( tag: &str, artifacts: &[Artifact], sums: &Path, + authenticated_client: Option<&Client>, ) -> Result<(), Error> { let downloads = tempfile::Builder::new() .prefix("rust-realease-download-") .tempdir() .map_err(|e| Error(format!("cannot create download directory: {e}")))?; - let client = Client::builder() - .timeout(Duration::from_secs(120)) - .redirect(reqwest::redirect::Policy::limited(10)) - .build() - .map_err(|_| Error("Cannot initialize anonymous download client.".into()))?; + let client = match authenticated_client { + Some(client) => client.clone(), + None => Client::builder() + .timeout(Duration::from_secs(120)) + .redirect(reqwest::redirect::Policy::limited(10)) + .build() + .map_err(|_| Error("Cannot initialize anonymous download client.".into()))?, + }; for local in artifacts .iter() .map(|a| a.path.as_path()) @@ -137,10 +141,10 @@ pub fn verify_published( let mut response = client .get(asset_url(repository, tag, filename)) .send() - .map_err(|_| Error(format!("{filename}: public download failed.")))?; + .map_err(|_| Error(format!("{filename}: release download failed.")))?; if response.status() != reqwest::StatusCode::OK { return Err(Error(format!( - "{filename}: public download returned HTTP {}.", + "{filename}: release download returned HTTP {}.", response.status().as_u16() ))); } @@ -160,7 +164,7 @@ pub fn verify_published( loop { let n = response .read(&mut buffer) - .map_err(|_| Error(format!("{filename}: public download failed.")))?; + .map_err(|_| Error(format!("{filename}: release download failed.")))?; if n == 0 { break; } @@ -217,6 +221,16 @@ pub fn verify_binstall( project: &SelectedPackage, targets: &[String], runner: &Runner, +) -> Result<(), Error> { + verify_binstall_with_options(root, project, targets, runner, false) +} + +fn verify_binstall_with_options( + root: &Path, + project: &SelectedPackage, + targets: &[String], + runner: &Runner, + allow_insecure_http: bool, ) -> Result<(), Error> { for target in targets { let temp = tempfile::Builder::new() @@ -229,7 +243,10 @@ pub fn verify_binstall( .map_err(|e| Error(format!("cannot create isolated Cargo home: {e}")))?; fs::create_dir_all(&install) .map_err(|e| Error(format!("cannot create isolated install root: {e}")))?; - let args = binstall_arguments(project, target, &install); + let mut args = binstall_arguments(project, target, &install); + if allow_insecure_http { + args.push("--allow-insecure-http".into()); + } let borrowed: Vec<_> = args.iter().map(String::as_str).collect(); let cargo_home = cargo_home .to_str() @@ -249,6 +266,50 @@ pub fn verify_binstall( #[cfg(test)] mod tests { use super::*; + #[test] + #[ignore = "requires RUST_RELEASE_LIVE_* variables and a disposable Gitea release"] + fn live_release_downloads_match_local_artifacts() { + let required = |name: &str| std::env::var(name).expect("set live release test variables"); + let repository = required("RUST_RELEASE_LIVE_REPOSITORY"); + let tag = required("RUST_RELEASE_LIVE_TAG"); + let name = required("RUST_RELEASE_LIVE_NAME"); + let version = required("RUST_RELEASE_LIVE_VERSION"); + let directory = std::path::PathBuf::from(required("RUST_RELEASE_LIVE_ARTIFACTS")); + let targets = [ + "x86_64-unknown-linux-musl", + "aarch64-unknown-linux-musl", + "x86_64-pc-windows-gnu", + ]; + let artifacts = targets + .iter() + .map(|target| { + let path = directory.join(policy::archive_name(&name, target, &version)); + Ok(Artifact { + target: (*target).into(), + sha256: package::checksum(&path)?, + path, + root: policy::archive_root(&name, target, &version), + binary: policy::binary_filename(&name, target), + }) + }) + .collect::, Error>>() + .unwrap(); + let api = crate::gitea::Gitea::new(&repository, "GITEA_TOKEN").unwrap(); + let private = api.repository_private().unwrap(); + verify_published( + &repository, + &tag, + &artifacts, + &directory.join("SHA256SUMS"), + if private { + Some(api.download_client()) + } else { + None + }, + ) + .unwrap(); + } + #[test] fn anonymous_downloads_match_local_archives_and_checksums() { use std::{net::TcpListener, thread}; @@ -295,10 +356,169 @@ mod tests { stream.write_all(&body).unwrap(); } }); - verify_published(&repository, "v0.1.0", &artifacts, &sums).unwrap(); + verify_published(&repository, "v0.1.0", &artifacts, &sums, None).unwrap(); handle.join().unwrap(); } + #[test] + fn authenticated_private_downloads_match_local_assets() { + use std::{net::TcpListener, thread}; + let temp = tempfile::tempdir().unwrap(); + let binary = temp.path().join("demo"); + fs::write(&binary, b"binary").unwrap(); + let (artifacts, sums) = package::package( + temp.path(), + "demo", + "0.1.0", + "demo", + &[("x86_64-unknown-linux-musl".into(), binary)], + ) + .unwrap(); + let bodies = [ + fs::read(&artifacts[0].path).unwrap(), + fs::read(&sums).unwrap(), + ]; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let repository = format!("http://{}/team/demo", listener.local_addr().unwrap()); + let handle = thread::spawn(move || { + for body in bodies { + let (mut stream, _) = listener.accept().unwrap(); + let mut buffer = [0_u8; 4096]; + let count = stream.read(&mut buffer).unwrap(); + let request = String::from_utf8_lossy(&buffer[..count]); + assert!(request + .lines() + .any(|line| line.eq_ignore_ascii_case("authorization: token test-token"))); + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ) + .unwrap(); + stream.write_all(&body).unwrap(); + } + }); + let mut headers = reqwest::header::HeaderMap::new(); + headers.insert( + reqwest::header::AUTHORIZATION, + reqwest::header::HeaderValue::from_static("token test-token"), + ); + let client = Client::builder() + .default_headers(headers) + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + verify_published(&repository, "v0.1.0", &artifacts, &sums, Some(&client)).unwrap(); + handle.join().unwrap(); + } + + #[test] + #[ignore = "requires cargo-binstall and a local HTTP listener"] + fn real_binstall_installs_local_release_fixture() { + use std::{ + collections::HashMap, + net::TcpListener, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + thread, + }; + let temp = tempfile::tempdir().unwrap(); + let targets = [ + "x86_64-unknown-linux-musl".to_owned(), + "aarch64-unknown-linux-musl".to_owned(), + "x86_64-pc-windows-gnu".to_owned(), + ]; + let outputs = targets + .iter() + .map(|target| { + let binary = temp.path().join(format!("binary-{target}")); + fs::write(&binary, format!("fixture binary for {target}"))?; + Ok((target.clone(), binary)) + }) + .collect::, std::io::Error>>() + .unwrap(); + let (artifacts, _) = + package::package(temp.path(), "demo", "0.1.0", "demo", &outputs).unwrap(); + let archives = artifacts + .iter() + .map(|artifact| { + ( + artifact + .path + .file_name() + .unwrap() + .to_str() + .unwrap() + .to_owned(), + fs::read(&artifact.path).unwrap(), + ) + }) + .collect::>(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let repository = format!("http://{}/team/demo", listener.local_addr().unwrap()); + fs::create_dir(temp.path().join("src")).unwrap(); + fs::write(temp.path().join("src/main.rs"), "fn main() {}\n").unwrap(); + let manifest = temp.path().join("Cargo.toml"); + fs::write(&manifest, format!("[package]\nname='demo'\nversion='0.1.0'\nedition='2021'\nrepository='{repository}'\n[package.metadata.binstall]\npkg-url='{{ repo }}/releases/download/v{{ version }}/{{ name }}-{{ target }}-v{{ version }}.tgz'\npkg-fmt='tgz'\nbin-dir='{{ name }}-{{ target }}-v{{ version }}/{{ bin }}{{ binary-ext }}'\n")).unwrap(); + let done = Arc::new(AtomicBool::new(false)); + let server_done = Arc::clone(&done); + let handle = thread::spawn(move || { + while !server_done.load(Ordering::Relaxed) { + match listener.accept() { + Ok((mut stream, _)) => { + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut request = Vec::new(); + let mut buffer = [0_u8; 4096]; + while !request.windows(4).any(|w| w == b"\r\n\r\n") { + let count = stream.read(&mut buffer).unwrap(); + if count == 0 { + break; + } + request.extend_from_slice(&buffer[..count]); + } + let request = String::from_utf8_lossy(&request); + let requested_archive = request + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|path| path.rsplit('/').next()) + .and_then(|name| archives.get(name)); + let body = requested_archive.map_or(&[][..], Vec::as_slice); + write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).unwrap(); + stream.write_all(body).unwrap(); + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(10)); + } + Err(error) => panic!("local HTTP listener failed: {error}"), + } + } + }); + let project = SelectedPackage { + name: "demo".into(), + version: "0.1.0".into(), + binary: "demo".into(), + manifest, + repository: Some(repository), + target_directory: temp.path().join("target"), + }; + let result = verify_binstall_with_options( + temp.path(), + &project, + &targets, + &Runner::new("GITEA_TOKEN"), + true, + ); + done.store(true, Ordering::Relaxed); + handle.join().unwrap(); + result.unwrap(); + } + #[test] fn local_archive_validation_and_binstall_command() { let temp = tempfile::tempdir().unwrap();