From e321a8798bddc3dc417bdb20b37c24abdbb2e608 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 5 Oct 2026 10:46:33 +0200 Subject: [PATCH] feat: support Gitea token files --- README.md | 185 +++++++++++---------------------------- docs/advanced-usage.md | 46 +++++++++- release.sh | 9 +- src/cli.rs | 77 +++++++++++++++- src/gitea.rs | 2 +- src/prepare.rs | 105 ++++++++++++---------- src/runner.rs | 16 +++- tests/release_wrapper.rs | 8 +- 8 files changed, 254 insertions(+), 194 deletions(-) diff --git a/README.md b/README.md index 9048650..4392f5e 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,22 @@ # rust_realease -![version](https://assets.dandaedre.com/coverage/idle-org/rust_realease/main/version.svg) -![tests](https://assets.dandaedre.com/coverage/idle-org/rust_realease/main/test.svg) -![test coverage](https://assets.dandaedre.com/coverage/idle-org/rust_realease/main/coverage.svg) +![current version](https://assets.dandaedre.com/coverage/idle-org/rust_realease/main/version.svg) +![test status](https://assets.dandaedre.com/coverage/idle-org/rust_realease/main/test.svg) +![line coverage](https://assets.dandaedre.com/coverage/idle-org/rust_realease/main/coverage.svg) -`rust_realease` builds and publishes the binaries 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 cargo-binstall-compatible `.tgz` archives, directly downloadable executables, or both, writes `SHA256SUMS`, uploads the assets, and verifies release downloads. It can also prepare a project for release with explicit commit, tag, and push options. +`rust_realease` builds Rust binary packages for multiple targets and publishes +them as Gitea release assets. It is intended for maintainers who want +repeatable Cross builds, checksums, cargo-binstall archives, and post-upload +verification without maintaining a separate release pipeline. -## Install +## Prerequisites and installation -The preferred installation method is cargo-binstall, which downloads the matching prebuilt release artifact: +Install [Git](https://git-scm.com/), +[Cross](https://github.com/cross-rs/cross), and a Cross-compatible Docker or +Podman backend. The default archive format also requires +[cargo-binstall](https://github.com/cargo-bins/cargo-binstall). + +Install the latest prebuilt release: ```bash cargo binstall --git https://proxy.dandaedre.com/gitea/idle-org/rust_realease \ @@ -16,171 +24,82 @@ cargo binstall --git https://proxy.dandaedre.com/gitea/idle-org/rust_realease \ rust_realease --help ``` -To build and publish releases, also install Git, Cross, and Docker or Podman. Install cargo-binstall itself when producing the default `tgz` artifacts and running end-to-end installation verification. A working container backend is needed for release builds. - -For development, or when a prebuilt artifact is unavailable for the host, install from this checkout: +To build the current checkout instead: ```bash cargo install --path . --locked ``` -To run from this checkout without installing, use `cargo run -- SOURCE [OPTIONS]`. +## Quick start -## Start with a project - -Preview a local project or remote Git repository: +Preview a local project without changing files, building binaries, or +contacting Gitea: ```bash rust_realease ./my-tool --dry-run -rust_realease https://gitea.example.org/owner/my-tool.git --dry-run ``` -For a workspace, select the exact Cargo package name: +The preview reports the selected package and binaries, expected version tag, +metadata changes, build targets, artifact names, prerequisites, and release +destination. It exits nonzero when something needs attention. Select a package +explicitly when the source is a workspace: ```bash rust_realease ./my-workspace --package my-tool --dry-run ``` -Each run handles one package and all of its Cargo binary targets. A dry run reports the package, version, expected tag, metadata changes, build targets, artifact names, prerequisites, and release destination. It writes no project files, builds no binaries, and changes no Git refs or releases. It exits nonzero when it finds requirements that still need attention. - -Interactive terminals use colored status markers. Cross builds report elapsed -time for every target and for the complete build. Redirected output and CI logs -remain plain. - -## Prepare a release - -Preview the project changes first: - -```bash -rust_realease ./my-tool --prepare-repo --dry-run -``` - -Apply the preparation locally: - -```bash -rust_realease ./my-tool --prepare-repo -``` - -Preparation repairs supported `Cargo.toml` release metadata, updates known `.gitignore` and `Cross.toml` settings, and generates a missing `Cargo.lock`. It exits before building or publishing. Review and commit local changes yourself, or authorize the Git steps explicitly from a clean checkout: - -```bash -rust_realease ./my-tool --prepare-repo \ - --commit-preparation --create-tag --push-preparation -``` - -If you only want to add or repair the recommended `[package.metadata.binstall]` entries in `Cargo.toml`, use the existing metadata-only path: - -```bash -rust_realease ./my-tool --fix-metadata --stop-after metadata -``` - -Preview the same change without writing it by adding `--dry-run`. The generated values follow the archive layout produced by `rust_realease`, including the configured release tag prefix. - -The preparation commit uses your configured Git author and signing settings. The tag is annotated and follows your Git tag-signing configuration (`git config tag.gpgsign true` to sign it); an existing tag is never moved. The branch and tag are pushed atomically without force. Use `--cross-image-tag main` only when you want preparation to set Cross images for the selected targets. - -## Build local artifacts +Build local artifacts through the package stage with: ```bash rust_realease ./my-tool --compile-only ``` -This runs host `cargo check` and `cargo test`, builds the selected targets with Cross, and writes the configured artifacts plus `SHA256SUMS` into a new `dist/release-*/` directory. It does not contact Gitea. The default targets are: +Artifacts and `SHA256SUMS` are written under `dist/release-*/`. -- `x86_64-unknown-linux-musl` -- `aarch64-unknown-linux-musl` -- `x86_64-pc-windows-gnu` +## Publish a Gitea release -Override the matrix with repeatable `--target TARGET` options. Use `--stop-after verify` for host checks alone. +The package version must match a local tag, and the same tag must already +exist on the remote. Publication also requires a clean checkout and an HTTPS +Gitea release destination. -A completed Cross build from a clean checkout is reused automatically when the Git commit and build settings still match. Packaging is repeated so the upload always gets a newly validated artifact set. Pass `--recompile` to ignore the completed-build cache and build every target again. Dirty checkouts are never reused. - -Use `--artifact-format binary` when you only want raw executables, or `--artifact-format both` to publish raw executables alongside the default cargo-binstall archives: +Store a Gitea access token in a single-line UTF-8 file and pass it directly: ```bash -rust_realease ./my-tool --artifact-format binary --compile-only -rust_realease ./my-tool --artifact-format both +rust_realease ./my-tool --token-file ../gitea_token.txt ``` -## Publish to Gitea +The token file takes precedence over the configured token environment +variable. Without `--token-file`, the default is `GITEA_TOKEN`. Grant the token +repository read and release write access; preparation pushes also require code +write access. Tokens are redacted from diagnostics and are not passed to Cargo +or Cross child processes. -The package version and release tag must agree. For version `0.1.0`, the default tag is `v0.1.0`. Before ordinary publication, the local tag must point to the checkout and the matching remote tag must exist. Publication requires a clean checkout and an HTTPS Gitea destination. +Use `--prepare-repo --dry-run` to preview supported metadata and repository +preparation before publishing. See the advanced guide for explicit commit, +tag, push, release-note, private-repository, and asset-replacement workflows. -Set a Gitea token in the environment and run the command without `--stop-after`: +## Documentation -```bash -read -r -s -p 'Gitea token: ' GITEA_TOKEN -printf '\n' -export GITEA_TOKEN -rust_realease ./my-tool -``` - -Add release notes inline or read them from a UTF-8 file: - -```bash -rust_realease ./my-tool -m "Highlights and upgrade notes" -rust_realease ./my-tool --message-file CHANGELOG.md -``` - -The two message options are mutually exclusive. Supplying notes also updates the body when the tagged Gitea release already exists; omitting them preserves an existing body. - -To publish `rust_realease` itself, install the current publisher and use the -repository wrapper. It reads the token from a file without placing it in the -process arguments and publishes both archive and standalone-binary assets: - -```bash -cargo install --path . --locked -./release.sh ../gitea_token.txt --compile-only -./release.sh ../gitea_token.txt --dry-run -./release.sh ../gitea_token.txt -``` - -For a remote repository, select the exact tag to check out: - -```bash -rust_realease https://gitea.example.org/owner/my-tool.git --tag v0.1.0 -``` - -If Git uses an internal repository URL but releases must use a public proxy, add an exact repository fallback to a project `rust-release.toml` or to the user configuration. The public fallback is used for Cargo metadata, Gitea publication, download verification, and cargo-binstall while the configured Git origin remains valid for cloning and preparation pushes. See [Advanced usage](docs/advanced-usage.md#configuration) for the file locations and an example. - -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 - -See [Advanced usage](docs/advanced-usage.md) for configuration, metadata, workspace behavior, stage controls, artifact layout, token handling, and troubleshooting. Run `rust_realease --help` for the complete option list. +- [Advanced usage](docs/advanced-usage.md) covers sources, configuration, + metadata preparation, pipeline stages, artifact formats, authentication, + this repository's release procedure, and troubleshooting. +- `rust_realease --help` is the complete option reference. ## Development +From the repository root, run: + ```bash cargo fmt --check cargo clippy --all-targets --all-features -- -D warnings -cargo test --all +cargo test --locked --all ``` -Jenkins runs Cargo tests and enforces an 80% line-coverage floor. Run the exact -coverage command locally with: +Jenkins enforces an 80% line-coverage floor. The opt-in real cargo-binstall +fixture requires its external test repository and is ignored by the ordinary +test suite; its setup is documented in [Advanced usage](docs/advanced-usage.md#disposable-release-fixture). -```bash -cargo tarpaulin --config tarpaulin.toml --out Json --output-dir coverage -``` +## License and support -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 -`coverage/version.svg`, `coverage/test.svg`, and `coverage/coverage.svg`, with -fingerprinting. Successful `main` builds publish those files atomically under -`/mnt/assets/coverage/idle-org/rust_realease/main/`, serving: - -- `https://assets.dandaedre.com/coverage/idle-org/rust_realease/main/version.svg` -- `https://assets.dandaedre.com/coverage/idle-org/rust_realease/main/test.svg` -- `https://assets.dandaedre.com/coverage/idle-org/rust_realease/main/coverage.svg` - -The asset server must mount published assets read-only, disable directory -listings, serve SVG with a restrictive content security policy, and revalidate -these mutable URLs or use a short cache lifetime. Cross builds and live Gitea -releases remain separate release checks. The small -[target_test_project fixture](https://proxy.dandaedre.com/gitea/idle-org/target_test_project) -is maintained in its own repository for fast target matrix experiments. Clone -it separately when needed; it is not part of this checkout. - -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`. +This project is licensed under the [MIT License](LICENSE). Report problems in +the canonical [Gitea repository](https://proxy.dandaedre.com/gitea/idle-org/rust_realease/issues). diff --git a/docs/advanced-usage.md b/docs/advanced-usage.md index 5da0063..8d020e7 100644 --- a/docs/advanced-usage.md +++ b/docs/advanced-usage.md @@ -11,6 +11,13 @@ rust_realease ./target_test_project --dry-run Its public [v0.1.3 release](https://proxy.dandaedre.com/gitea/idle-org/target_test_project/releases/tag/v0.1.3) was used to validate preparation, all three default Cross targets, published checksums, and isolated cargo-binstall installs. Use a new version and tag for future publication tests; release assets with the same names are deliberately treated as collisions. +With cargo-binstall installed, run the opt-in isolated install fixture for all +three targets with: + +```bash +cargo test --locked real_binstall_installs_local_release_fixture -- --ignored +``` + ## Sources and package selection `SOURCE` can be a local directory, an HTTP(S) Git URL, an SSH URL, or an SCP-style URL such as `git@host:owner/repo.git`. Remote sources are cloned into a managed checkout. Use `--keep-workdir` to retain that checkout and its artifacts; preparation retains remote checkouts automatically. Local sources are never deleted. @@ -91,7 +98,7 @@ For repositories whose build scripts need a selected Rust toolchain inside Cross `--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. A successful Cross build from a clean checkout records its Git commit, package, targets, profile, lock mode, container engine, active Rust toolchain, and binary list. A later run with the same inputs reuses those regular binary files from Cargo's target directory; dirty checkouts, changed inputs, missing files, and invalid cache records build in a fresh target directory instead. `--recompile` explicitly bypasses a matching completed build. `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. 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. `-m/--message TEXT` sets release notes, while `--message-file PATH` reads them from a UTF-8 file; they are mutually exclusive. Notes are included when creating a release and replace the body of an existing tagged release when explicitly supplied. 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 authentication is configured. `--prerelease` and `--draft` set properties when a release is created; reusing a release preserves its existing settings. `-m/--message TEXT` sets release notes, while `--message-file PATH` reads them from a UTF-8 file; they are mutually exclusive. Notes are included when creating a release and replace the body of an existing tagged release when explicitly supplied. Asset replacement is not transactional: if an upload fails after a matching asset is deleted, retry the publication explicitly. ## Artifact contract @@ -108,10 +115,45 @@ Windows archive members have an `.exe` suffix. Raw assets are target-qualified t ## Authentication and security -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`. +Authenticated Gitea API publication requires HTTPS. Pass `--token-file PATH` to read one token from a UTF-8 file; trailing line endings are ignored, while empty and multiline files are rejected. The file takes precedence over the configured environment variable. Without that option, the token comes from `gitea.token-env`, which defaults to `GITEA_TOKEN`. Tokens are never accepted as a positional argument or URL. Child Cargo and Cross processes do not receive them. 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. Private assets are verified with authenticated downloads and do not establish public installability. +## Releasing this repository + +Install the publisher from the checkout, then use the repository wrapper. The +wrapper selects this package, publishes both archive and standalone binary +assets, and forwards its token file to `--token-file`: + +```bash +cargo install --path . --locked +./release.sh ../gitea_token.txt --compile-only +./release.sh ../gitea_token.txt --dry-run +./release.sh ../gitea_token.txt +``` + +## CI badge pipeline + +Jenkins runs the locked test suite and Tarpaulin configuration, enforces the +80% line-coverage floor, and renders version, test, and coverage SVGs with the +scripts in `scripts/`. It validates and archives exactly +`coverage/version.svg`, `coverage/test.svg`, and `coverage/coverage.svg`. +Every `main` build publishes those files during post-build cleanup under +`/mnt/assets/coverage/idle-org/rust_realease/main/` for the public badge URLs +used by the README; other branches do not publish them. A failed build renders +the test badge as failing and the coverage badge as unavailable. + +Run the same coverage command locally with: + +```bash +cargo tarpaulin --config tarpaulin.toml --out Json --output-dir coverage +``` + +The asset server must mount the published directory read-only, disable +directory listings, serve SVG with a restrictive content security policy, and +revalidate the mutable URLs or use a short cache lifetime. Cross builds and +live Gitea releases remain separate release checks. + ## Troubleshooting - **Missing tag:** prepare and push the expected tag explicitly, or use `--prepare-repo --commit-preparation --create-tag --push-preparation` from a clean checkout. diff --git a/release.sh b/release.sh index 819e3b0..62e6b7c 100755 --- a/release.sh +++ b/release.sh @@ -20,14 +20,6 @@ if ! command -v rust_realease >/dev/null 2>&1; then exit 2 fi -GITEA_TOKEN= -IFS= read -r GITEA_TOKEN <"$token_file" || : -if [ -z "$GITEA_TOKEN" ]; then - echo "token file is empty: $token_file" >&2 - exit 2 -fi -export GITEA_TOKEN - repository_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) manifest_version=$(sed -n 's/^version = "\([^"]*\)"/\1/p' "$repository_dir/Cargo.toml" | head -n 1) @@ -35,6 +27,7 @@ set -- \ "$repository_dir" \ --package rust_realease \ --artifact-format both \ + --token-file "$token_file" \ "$@" case "$manifest_version" in *-*) set -- "$@" --prerelease ;; diff --git a/src/cli.rs b/src/cli.rs index fe646d9..888979f 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -79,6 +79,9 @@ pub struct Cli { pub cross_image_tag: Option, #[arg(long)] pub repository_url: Option, + /// Read the Gitea access token from a UTF-8 file instead of the configured environment variable. + #[arg(long, value_name = "PATH")] + pub token_file: Option, #[arg(long)] pub config: Option, /// Release tgz archives, raw binaries, or both. @@ -112,7 +115,14 @@ pub fn run(mut args: Cli) -> Result<(), Error> { })?), None => args.message.clone(), }; - let acquisition_runner = Runner::new("GITEA_TOKEN").with_verbose(args.verbose); + let file_token = args + .token_file + .as_deref() + .map(read_token_file) + .transpose()?; + let acquisition_runner = Runner::new("GITEA_TOKEN") + .with_secret(file_token.as_deref()) + .with_verbose(args.verbose); let checkout = project::acquire_project( &args.source, if args.prepare_repo { @@ -134,7 +144,9 @@ pub fn run(mut args: Cli) -> Result<(), Error> { package_format: args.artifact_format, }, )?; - let runner = Runner::new(&config.token_env).with_verbose(args.verbose); + let runner = Runner::new(&config.token_env) + .with_secret(file_token.as_deref()) + .with_verbose(args.verbose); let root = checkout .root .to_str() @@ -233,6 +245,7 @@ pub fn run(mut args: Cli) -> Result<(), Error> { prepare::Options { tag: &tag, image_tag: args.cross_image_tag.as_deref(), + token: file_token.as_deref(), dry_run: args.dry_run, commit: args.commit_preparation, create_tag: args.create_tag, @@ -292,7 +305,10 @@ pub fn run(mut args: Cli) -> Result<(), Error> { .is_none_or(|stage| stage.order() >= Stage::Binstall.order()); let publication = if publishing { project::validate_checkout_tag(&checkout.root, &tag, &runner)?; - let api = Gitea::new(&repository, &config.token_env)?; + let api = match file_token.as_deref() { + Some(token) => Gitea::with_token(&repository, token)?, + None => 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())); @@ -419,6 +435,37 @@ pub fn run(mut args: Cli) -> Result<(), Error> { Ok(()) } +fn read_token_file(path: &std::path::Path) -> Result { + if !path.is_file() { + return Err(Error(format!( + "Gitea token file is not a regular file: {}", + path.display() + ))); + } + let mut token = std::fs::read_to_string(path).map_err(|e| { + Error(format!( + "cannot read Gitea token file {}: {e}", + path.display() + )) + })?; + while token.ends_with(['\r', '\n']) { + token.pop(); + } + if token.is_empty() { + return Err(Error(format!( + "Gitea token file is empty: {}", + path.display() + ))); + } + if token.contains(['\r', '\n']) { + return Err(Error(format!( + "Gitea token file must contain exactly one token: {}", + path.display() + ))); + } + Ok(token) +} + #[cfg(test)] mod tests { use super::*; @@ -539,4 +586,28 @@ mod tests { ]) .is_err()); } + + #[test] + fn token_file_accepts_one_token_and_trailing_newlines() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("token"); + fs::write(&path, "secret-token\r\n").unwrap(); + assert_eq!(read_token_file(&path).unwrap(), "secret-token"); + + fs::write(&path, "first\nsecond\n").unwrap(); + assert!(read_token_file(&path).is_err()); + fs::write(&path, "\n").unwrap(); + assert!(read_token_file(&path).is_err()); + } + + #[test] + fn token_file_option_parses_as_a_path() { + let args = + Cli::try_parse_from(["rust_realease", ".", "--token-file", "secrets/gitea-token"]) + .unwrap(); + assert_eq!( + args.token_file.as_deref(), + Some(Path::new("secrets/gitea-token")) + ); + } } diff --git a/src/gitea.rs b/src/gitea.rs index 504ed4f..02fff0c 100644 --- a/src/gitea.rs +++ b/src/gitea.rs @@ -43,7 +43,7 @@ impl Gitea { Self::with_token(repository, &token) } - fn with_token(repository: &str, token: &str) -> Result { + pub(crate) fn with_token(repository: &str, token: &str) -> Result { let parsed = url::Url::parse(repository) .map_err(|_| Error("Invalid release repository URL.".into()))?; let parts: Vec<_> = parsed diff --git a/src/prepare.rs b/src/prepare.rs index 0a82f25..3c7b890 100644 --- a/src/prepare.rs +++ b/src/prepare.rs @@ -15,6 +15,7 @@ use toml_edit::{value, Array, DocumentMut, Item, Table}; pub struct Options<'a> { pub tag: &'a str, pub image_tag: Option<&'a str>, + pub token: Option<&'a str>, pub dry_run: bool, pub commit: bool, pub create_tag: bool, @@ -354,7 +355,15 @@ pub fn run( project::validate_checkout_tag(root, options.tag, runner)?; } if let Some(branch) = branch { - push_preparation(root, &branch, options.tag, repository, config, runner)?; + push_preparation( + root, + &branch, + options.tag, + repository, + config, + options.token, + runner, + )?; } println!("Repository preparation complete. Review the changes, then run the publisher without --prepare-repo."); Ok(()) @@ -366,6 +375,7 @@ fn push_preparation( tag: &str, repository: &str, config: &Config, + token: Option<&str>, runner: &Runner, ) -> Result<(), Error> { let origin = runner.text("git", &["remote", "get-url", "--push", "origin"], root)?; @@ -375,50 +385,53 @@ fn push_preparation( let branch_ref = format!("HEAD:refs/heads/{branch}"); let tag_ref = format!("refs/tags/{tag}"); if origin.starts_with("https://") { - if let Ok(token) = std::env::var(&config.token_env) { - if !token.is_empty() { - let helper = tempfile::Builder::new() - .prefix("rust-release-askpass-") - .tempdir() - .map_err(|e| Error(format!("cannot create askpass helper: {e}")))?; - let script = helper.path().join("askpass"); - fs::write(&script, "#!/bin/sh\ncase \"$1\" in *sername*) printf 'token\\n';; *) printf '%s\\n' \"$PUBLISHER_GIT_TOKEN\";; esac\n").map_err(|e| Error(format!("cannot write askpass helper: {e}")))?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(&script, fs::Permissions::from_mode(0o700)) - .map_err(|e| Error(format!("cannot chmod askpass helper: {e}")))?; - } - let helper_path = script - .to_str() - .ok_or_else(|| Error("Askpass helper path is not UTF-8.".into()))?; - return runner - .output_with( - "git", - &[ - "-c", - "credential.helper=", - "-c", - "core.hooksPath=/dev/null", - "push", - "--atomic", - "origin", - &branch_ref, - &tag_ref, - ], - root, - &[ - ("GIT_ASKPASS", helper_path), - ("GIT_TERMINAL_PROMPT", "0"), - ("PUBLISHER_GIT_TOKEN", &token), - ("GIT_TRACE", "0"), - ("GIT_TRACE_CURL", "0"), - ("GIT_TRACE2", "0"), - ], - &[], - ) - .map(|_| ()); + let environment_token = std::env::var(&config.token_env).ok(); + if let Some(token) = token.or_else(|| { + environment_token + .as_deref() + .filter(|token| !token.is_empty()) + }) { + let helper = tempfile::Builder::new() + .prefix("rust-release-askpass-") + .tempdir() + .map_err(|e| Error(format!("cannot create askpass helper: {e}")))?; + let script = helper.path().join("askpass"); + fs::write(&script, "#!/bin/sh\ncase \"$1\" in *sername*) printf 'token\\n';; *) printf '%s\\n' \"$PUBLISHER_GIT_TOKEN\";; esac\n").map_err(|e| Error(format!("cannot write askpass helper: {e}")))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&script, fs::Permissions::from_mode(0o700)) + .map_err(|e| Error(format!("cannot chmod askpass helper: {e}")))?; } + let helper_path = script + .to_str() + .ok_or_else(|| Error("Askpass helper path is not UTF-8.".into()))?; + return runner + .output_with( + "git", + &[ + "-c", + "credential.helper=", + "-c", + "core.hooksPath=/dev/null", + "push", + "--atomic", + "origin", + &branch_ref, + &tag_ref, + ], + root, + &[ + ("GIT_ASKPASS", helper_path), + ("GIT_TERMINAL_PROMPT", "0"), + ("PUBLISHER_GIT_TOKEN", token), + ("GIT_TRACE", "0"), + ("GIT_TRACE_CURL", "0"), + ("GIT_TRACE2", "0"), + ], + &[], + ) + .map(|_| ()); } } runner.output_with( @@ -536,6 +549,7 @@ mod tests { Options { tag: "v0.1.0", image_tag: Some("main"), + token: None, dry_run, commit, create_tag, @@ -703,6 +717,7 @@ mod tests { let options = Options { tag: "v0.1.0", image_tag: None, + token: None, dry_run: true, commit: true, create_tag: true, @@ -753,6 +768,7 @@ mod tests { Options { tag: "v0.1.0", image_tag: None, + token: None, dry_run: true, commit: true, create_tag: true, @@ -811,6 +827,7 @@ mod tests { Options { tag: "v0.1.0", image_tag: None, + token: None, dry_run: false, commit: true, create_tag: true, diff --git a/src/runner.rs b/src/runner.rs index 1c68041..69644a4 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -4,6 +4,7 @@ use std::{path::Path, process::Command, sync::OnceLock}; pub struct Runner { token_env: String, + secrets: Vec, verbose: bool, } @@ -11,10 +12,18 @@ impl Runner { pub fn new(token_env: &str) -> Self { Self { token_env: token_env.to_owned(), + secrets: Vec::new(), verbose: false, } } + pub fn with_secret(mut self, secret: Option<&str>) -> Self { + if let Some(secret) = secret.filter(|secret| !secret.is_empty()) { + self.secrets.push(secret.to_owned()); + } + self + } + pub fn with_verbose(mut self, verbose: bool) -> Self { self.verbose = verbose; self @@ -86,6 +95,9 @@ impl Runner { pub fn redact(&self, text: &str) -> String { let mut without_token = text.to_owned(); + for secret in &self.secrets { + without_token = without_token.replace(secret, "[REDACTED]"); + } for name in ["GITEA_TOKEN", self.token_env.as_str()] { if let Ok(secret) = std::env::var(name) { if !secret.is_empty() { @@ -107,13 +119,15 @@ mod tests { use super::*; #[test] fn redacts_token_and_urls_and_keeps_token_out_of_child() { - let runner = Runner::new("RUST_RELEASE_TEST_SECRET"); + let runner = + Runner::new("RUST_RELEASE_TEST_SECRET").with_secret(Some("token-loaded-from-file")); let secret = "unit-test-secret-value"; std::env::set_var("RUST_RELEASE_TEST_SECRET", secret); let message = runner .redact("failed https://user:password@example.com/repo and unit-test-secret-value"); assert!(!message.contains(secret)); assert!(!message.contains("password")); + assert_eq!(runner.redact("token-loaded-from-file"), "[REDACTED]"); let child = runner.text("env", &[], Path::new(".")).unwrap(); assert!(!child.contains("RUST_RELEASE_TEST_SECRET")); std::env::set_var("RUST_RELEASE_TEST_REMOVED", "remove-me"); diff --git a/tests/release_wrapper.rs b/tests/release_wrapper.rs index 8953576..963fa82 100644 --- a/tests/release_wrapper.rs +++ b/tests/release_wrapper.rs @@ -26,7 +26,7 @@ fn git(repository: &Path, arguments: &[&str]) -> Output { } #[test] -fn release_wrapper_passes_the_token_and_preserves_the_ssh_origin() { +fn release_wrapper_passes_the_token_file_and_preserves_the_ssh_origin() { let temporary = TempDir::new().expect("temporary directory should be created"); let repository = temporary.path().join("repository"); let fake_bin = temporary.path().join("bin"); @@ -51,7 +51,7 @@ fn release_wrapper_passes_the_token_and_preserves_the_ssh_origin() { fs::write( &fake_release, "#!/bin/sh\n\ - [ \"$GITEA_TOKEN\" = test-token ] || exit 91\n\ + [ -z \"${GITEA_TOKEN:-}\" ] || exit 91\n\ git -C \"$1\" remote get-url origin >\"$OBSERVED_ORIGIN\"\n\ cat \"$1/rust-release.toml\" >\"$OBSERVED_CONFIG\"\n\ printf '%s\\n' \"$@\" >\"$OBSERVED_ARGS\"\n", @@ -103,6 +103,10 @@ fn release_wrapper_passes_the_token_and_preserves_the_ssh_origin() { let arguments = fs::read_to_string(&observed_args).expect("fake release should record publisher arguments"); assert!(arguments.lines().any(|argument| argument == "both")); + assert!(arguments.lines().any(|argument| argument == "--token-file")); + assert!(arguments + .lines() + .any(|argument| argument == repository.join("token.txt").to_string_lossy())); assert!(arguments.lines().any(|argument| argument == "--dry-run")); assert!(!arguments.lines().any(|argument| argument == "--prerelease")); }