diff --git a/Cargo.lock b/Cargo.lock index 5a76901..57636d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1011,6 +1011,16 @@ dependencies = [ "libc", ] +[[package]] +name = "crc-fast" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e75b2483e97a5a7da73ac68a05b629f9c53cff58d8ed1c77866079e18b00dba5" +dependencies = [ + "digest 0.10.7", + "spin 0.10.1", +] + [[package]] name = "crc32c" version = "0.6.8" @@ -4157,6 +4167,16 @@ version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8863b587001c1b9a8a4e36008cebc6b3612cb1226fe2de94858e06092687b608" +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", +] + [[package]] name = "md5" version = "0.8.1" @@ -4328,7 +4348,7 @@ dependencies = [ "httparse", "memchr", "mime", - "spin", + "spin 0.9.9", "version_check", ] @@ -4503,17 +4523,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1796bc93603f78c5760a69f2d58badc9618d22adade0a95385bb2adbae4eb94" dependencies = [ "async-trait", + "aws-lc-rs", + "base64 0.23.1", "bytes", "chrono", + "crc-fast", + "form_urlencoded", "futures-channel", "futures-core", "futures-util", "http", + "http-body-util", "humantime", + "hyper", "itertools 0.15.0", + "md-5", "nix 0.31.3", "parking_lot", "percent-encoding", + "quick-xml 0.41.0", + "rand 0.10.3", + "reqwest", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", "thiserror 2.0.21", "tokio", "tracing", @@ -5016,7 +5050,7 @@ checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb" dependencies = [ "base64 0.23.1", "indexmap", - "quick-xml", + "quick-xml 0.42.0", "serde", "time", ] @@ -5324,6 +5358,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "quick-xml" version = "0.42.0" @@ -5614,6 +5658,7 @@ dependencies = [ "bytes", "futures-core", "futures-util", + "h2", "http", "http-body", "http-body-util", @@ -6458,6 +6503,12 @@ version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +[[package]] +name = "spin" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" + [[package]] name = "spki" version = "0.8.1" diff --git a/Cargo.toml b/Cargo.toml index 49b43ca..c15ca24 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,7 +68,7 @@ chacha20poly1305 = "0.11.0" # storage turso = "0.8.3" -object_store = { version = "0.14.2", default-features = false, features = ["fs"] } +object_store = { version = "0.14.2", default-features = false, features = ["fs", "aws"] } multer = "3.1.0" # outgoing mail (forge-web): SMTP over rustls, no native TLS diff --git a/config/forge.example.toml b/config/forge.example.toml index c61e2d9..ddb9259 100644 --- a/config/forge.example.toml +++ b/config/forge.example.toml @@ -52,6 +52,45 @@ trusted_proxies = [] # Largest accepted release asset, in MiB. # max_asset_mb = 512 +# Where release assets and CI artifacts are stored (see docs/backup.md, "Blob storage backends"). +# [storage] +# "fs" keeps blobs under /blobs (the default). "r2" stores them in a Cloudflare R2 bucket, +# the recommended off-host option. "s3" stores them in any other S3-compatible bucket (AWS, MinIO, Garage). +# backend = "fs" +# [storage.r2] +# Only read when backend = "r2". account_id, bucket, access_key_id and secret_access_key_file are required. +# The endpoint is derived from account_id, so there is no endpoint or region to set. +# Cloudflare account id, the 32-character hex string from the dashboard. +# account_id = "0123456789abcdef0123456789abcdef" +# Name of the R2 bucket that holds the blobs. +# bucket = "forge-blobs" +# Jurisdiction the bucket was created in: "eu", "fedramp", or empty for the global default. +# jurisdiction = "" +# Key prefix inside the bucket. Empty stores keys at the bucket root. +# prefix = "" +# Access key id of an R2 API token with object read and write on this bucket. +# access_key_id = "forge" +# File holding the token's secret access key, mode 0600. Its contents are trimmed. +# secret_access_key_file = "/etc/forge/r2-secret" +# [storage.s3] +# Only read when backend = "s3". Bucket, region, access_key_id and secret_access_key_file are required. +# Name of the bucket that holds the blobs. +# bucket = "forge-blobs" +# Signing region, such as "eu-central-1". MinIO and Garage accept any value. +# region = "us-east-1" +# Full URL of a non-AWS endpoint. Empty uses AWS. +# endpoint = "https://minio.internal:9000" +# Key prefix inside the bucket. Empty stores keys at the bucket root. +# prefix = "" +# Access key id. +# access_key_id = "forge" +# File holding the secret access key, mode 0600. Its contents are trimmed. +# secret_access_key_file = "/etc/forge/s3-secret" +# Permit an http:// endpoint. Only for a store on a trusted private network. +# allow_http = false +# Use bucket.host addressing instead of host/bucket. Off suits MinIO, Garage and most self-hosted stores. +# virtual_hosted_style = false + # Standby replication (see docs/backup.md). Empty target disables it. When target is set, # identity_file and known_hosts_file are required. # [replication] diff --git a/crates/forge-ci/src/config.rs b/crates/forge-ci/src/config.rs index 7f28fa7..1eb52d8 100644 --- a/crates/forge-ci/src/config.rs +++ b/crates/forge-ci/src/config.rs @@ -33,6 +33,10 @@ pub const MAX_WORKFLOW_NAME_CHARS: usize = 40; pub const MAX_CACHE_ENTRIES: usize = 8; /// Longest `cache` entry, in characters. pub const MAX_CACHE_PATH_CHARS: usize = 200; +/// Largest number of `[release] assets` entries. +pub const MAX_RELEASE_ASSETS: usize = 32; +/// Longest `[release] title` template, in characters, after trimming. +pub const MAX_RELEASE_TITLE_CHARS: usize = 200; /// A parsed and validated workflow. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -47,6 +51,83 @@ pub struct CiConfig { /// The `[jobs.]` tables, keyed by job name. #[serde(default)] pub jobs: BTreeMap, + /// The `[release]` table. Optional; when set, a tag run that fully succeeds publishes a release. + #[serde(default)] + pub release: Option, +} + +/// The `[release]` table. Requires `on.tags`. See docs/ci.md, Releases. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct ReleaseSpec { + /// `":"` entries. The glob matches the job's flattened artifact names. + pub assets: Vec, + pub prerelease: Prerelease, + pub draft: bool, + pub notes: ReleaseNotes, + /// Template with the placeholder `{tag}`, e.g. `"Release {tag}"`. + pub title: String, +} + +impl Default for ReleaseSpec { + fn default() -> Self { + Self { + assets: Vec::new(), + prerelease: Prerelease::Auto, + draft: false, + notes: ReleaseNotes::Commits, + title: "{tag}".to_string(), + } + } +} + +/// The `prerelease` key: `"auto"`, `true` or `false`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Prerelease { + /// A release is a prerelease when its tag contains `-`, e.g. `v1.2.0-rc1`. + Auto, + Always, + Never, +} + +impl Serialize for Prerelease { + fn serialize(&self, serializer: S) -> Result { + match self { + Prerelease::Auto => serializer.serialize_str("auto"), + Prerelease::Always => serializer.serialize_bool(true), + Prerelease::Never => serializer.serialize_bool(false), + } + } +} + +impl<'de> Deserialize<'de> for Prerelease { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Flag(bool), + Text(String), + } + match Raw::deserialize(deserializer)? { + Raw::Flag(true) => Ok(Prerelease::Always), + Raw::Flag(false) => Ok(Prerelease::Never), + Raw::Text(text) if text == "auto" => Ok(Prerelease::Auto), + Raw::Text(text) => Err(serde::de::Error::custom(format!( + "prerelease must be \"auto\", true or false, got {text:?}" + ))), + } + } +} + +/// The `notes` key. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ReleaseNotes { + /// One line per commit since the previous release tag. + Commits, + /// No notes. + #[serde(rename = "none")] + Off, } /// The `[on]` table. @@ -142,6 +223,12 @@ impl CiConfig { } } + /// Whether a run for this event should publish a release when every job succeeds: a + /// `[release]` table is set and the event is a tag that matches `on.tags`. + pub fn wants_release(&self, ev: &Event) -> bool { + self.release.is_some() && matches!(ev, Event::Tag { .. }) && self.triggered_by(ev) + } + /// Job names in dependency order. Ties are broken by name, so the order is stable. /// Jobs in a cycle, or with unknown needs, are left out. [`parse_config`] rejects both. pub fn job_order(&self) -> Vec<&str> { @@ -192,6 +279,9 @@ impl CiConfig { for (name, job) in &self.jobs { validate_job(name, job, &self.jobs)?; } + if let Some(release) = &self.release { + validate_release(release, &self.on, &self.jobs)?; + } let order = self.job_order(); if order.len() != self.jobs.len() { let job = self @@ -206,6 +296,37 @@ impl CiConfig { } } +impl ReleaseSpec { + /// Whether the release for `tag` is a prerelease. + pub fn is_prerelease(&self, tag: &str) -> bool { + match self.prerelease { + Prerelease::Auto => tag.contains('-'), + Prerelease::Always => true, + Prerelease::Never => false, + } + } + + /// The release title for `tag`: the template with `{tag}` replaced. + pub fn title_for(&self, tag: &str) -> String { + self.title.trim().replace("{tag}", tag) + } + + /// Whether an artifact of `job`, under its flattened `artifact_name`, is selected by an + /// `assets` entry. Entries that do not name `job` never match. + pub fn asset_matches(&self, job: &str, artifact_name: &str) -> bool { + self.assets.iter().any(|asset| { + asset_selector(asset).is_some_and(|(selected_job, glob)| { + selected_job == job && matches_any(&[glob.to_string()], artifact_name) + }) + }) + } +} + +/// Splits an `assets` entry into its job and glob. Validation guarantees the `:`. +fn asset_selector(asset: &str) -> Option<(&str, &str)> { + asset.split_once(':') +} + fn matches_any(globs: &[String], value: &str) -> bool { globs .iter() @@ -368,6 +489,79 @@ fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> { Ok(()) } +/// Checks the `[release]` table against the triggers and jobs: tags must be configured, there +/// are at most [`MAX_RELEASE_ASSETS`] assets, each one is valid for [`validate_release_asset`], +/// and the title is valid for [`validate_release_title`]. +fn validate_release( + release: &ReleaseSpec, + on: &Triggers, + jobs: &BTreeMap, +) -> Result<(), ConfigError> { + if on.tags.is_empty() { + return Err(ConfigError::ReleaseWithoutTags); + } + if release.assets.len() > MAX_RELEASE_ASSETS { + return Err(ConfigError::TooManyReleaseAssets { + count: release.assets.len(), + max: MAX_RELEASE_ASSETS, + }); + } + for asset in &release.assets { + validate_release_asset(asset, jobs)?; + } + validate_release_title(&release.title) +} + +/// An asset is `job:glob`. The job must exist and declare artifacts. The glob is matched against +/// flattened artifact names, which never contain `/`, so a glob with `/` is rejected. +fn validate_release_asset( + asset: &str, + jobs: &BTreeMap, +) -> Result<(), ConfigError> { + let invalid = |reason: String| ConfigError::InvalidReleaseAsset { + asset: asset.to_string(), + reason, + }; + let Some((job, glob)) = asset_selector(asset) else { + return Err(invalid("must be \"job:glob\"".into())); + }; + let Some(spec) = jobs.get(job) else { + return Err(invalid(format!("job {job:?} is not defined"))); + }; + if spec.artifacts.is_empty() { + return Err(invalid(format!("job {job:?} declares no artifacts"))); + } + if glob.is_empty() { + return Err(invalid("glob must not be empty".into())); + } + if glob.contains('/') { + return Err(invalid( + "glob must not contain \"/\", artifact names are flattened".into(), + )); + } + build_glob(glob) + .map(|_| ()) + .map_err(|e| invalid(e.to_string())) +} + +/// A title template: non-blank after trimming, at most [`MAX_RELEASE_TITLE_CHARS`] characters, +/// and no control characters. +fn validate_release_title(title: &str) -> Result<(), ConfigError> { + let invalid = |reason: String| ConfigError::InvalidReleaseTitle(reason); + if title.trim().is_empty() { + return Err(invalid("must not be empty".into())); + } + if title.trim().chars().count() > MAX_RELEASE_TITLE_CHARS { + return Err(invalid(format!( + "must be at most {MAX_RELEASE_TITLE_CHARS} characters" + ))); + } + if title.chars().any(char::is_control) { + return Err(invalid("must not contain control characters".into())); + } + Ok(()) +} + fn validate_job( name: &str, job: &JobSpec, @@ -889,4 +1083,201 @@ artifacts = ["target/release/forge"] ConfigError::Toml(_) )); } + + /// A tag-triggered workflow with a `build` job that has artifacts, plus `[release]` body. + fn release_toml(release: &str) -> String { + format!( + "[on]\ntags = [\"v*\"]\n{}\n[release]\n{release}\n", + job_toml("artifacts = [\"dist/*\"]") + ) + } + + fn release_of(text: &str) -> ReleaseSpec { + parse_config(text).unwrap().release.expect("release set") + } + + #[test] + fn release_defaults() { + let release = release_of(&release_toml("")); + assert!(release.assets.is_empty()); + assert_eq!(release.prerelease, Prerelease::Auto); + assert!(!release.draft); + assert_eq!(release.notes, ReleaseNotes::Commits); + assert_eq!(release.title, "{tag}"); + assert_eq!(release, ReleaseSpec::default()); + } + + #[test] + fn release_full_table_parses() { + let text = release_toml( + "assets = [\"build:dist_*\", \"build:SHA256SUMS\"]\n\ + prerelease = true\ndraft = true\nnotes = \"none\"\ntitle = \"Release {tag}\"", + ); + let release = release_of(&text); + assert_eq!( + release.assets, + vec!["build:dist_*".to_string(), "build:SHA256SUMS".to_string()] + ); + assert_eq!(release.prerelease, Prerelease::Always); + assert!(release.draft); + assert_eq!(release.notes, ReleaseNotes::Off); + assert_eq!(release.title, "Release {tag}"); + } + + #[test] + fn release_prerelease_values() { + assert_eq!( + release_of(&release_toml("prerelease = \"auto\"")).prerelease, + Prerelease::Auto + ); + assert_eq!( + release_of(&release_toml("prerelease = false")).prerelease, + Prerelease::Never + ); + assert!(matches!( + err_of(&release_toml("prerelease = \"yes\"")), + ConfigError::Toml(_) + )); + } + + #[test] + fn release_notes_values() { + assert_eq!( + release_of(&release_toml("notes = \"commits\"")).notes, + ReleaseNotes::Commits + ); + assert!(matches!( + err_of(&release_toml("notes = \"all\"")), + ConfigError::Toml(_) + )); + } + + #[test] + fn release_unknown_keys_are_rejected() { + assert!(matches!( + err_of(&release_toml("bogus = 1")), + ConfigError::Toml(_) + )); + } + + #[test] + fn release_requires_tags() { + let text = format!("[release]\n{}", job_toml("artifacts = [\"dist/*\"]")); + assert_eq!(err_of(&text), ConfigError::ReleaseWithoutTags); + } + + #[test] + fn release_asset_must_be_job_and_glob() { + for bad in ["build", ":dist_*", "build:", "ghost:dist_*", "build:a/b"] { + let text = release_toml(&format!("assets = [{bad:?}]")); + assert!( + matches!(err_of(&text), ConfigError::InvalidReleaseAsset { .. }), + "asset {bad:?} should be rejected: {:?}", + err_of(&text) + ); + } + let text = release_toml("assets = [\"build:[\"]"); + assert!(matches!( + err_of(&text), + ConfigError::InvalidReleaseAsset { .. } + )); + } + + #[test] + fn release_asset_job_must_declare_artifacts() { + let text = format!( + "[on]\ntags = [\"v*\"]\n{}\n[release]\nassets = [\"build:x\"]\n", + job_toml("") + ); + match err_of(&text) { + ConfigError::InvalidReleaseAsset { asset, reason } => { + assert_eq!(asset, "build:x"); + assert!(reason.contains("no artifacts"), "{reason}"); + } + other => panic!("unexpected error {other:?}"), + } + } + + #[test] + fn release_assets_are_capped() { + let entries: Vec = (0..=MAX_RELEASE_ASSETS) + .map(|_| "build:dist_*".to_string()) + .collect(); + let text = release_toml(&format!("assets = {entries:?}")); + assert_eq!( + err_of(&text), + ConfigError::TooManyReleaseAssets { + count: MAX_RELEASE_ASSETS + 1, + max: MAX_RELEASE_ASSETS + } + ); + let text = release_toml(&format!("assets = {:?}", &entries[..MAX_RELEASE_ASSETS])); + assert!(parse_config(&text).is_ok()); + } + + #[test] + fn release_title_validation() { + for bad in ["", " ", "a\\u0007b"] { + let text = release_toml(&format!("title = \"{bad}\"")); + assert!( + matches!(err_of(&text), ConfigError::InvalidReleaseTitle(_)), + "title {bad:?} should be rejected" + ); + } + let over = "t".repeat(MAX_RELEASE_TITLE_CHARS + 1); + let text = release_toml(&format!("title = \"{over}\"")); + assert!(matches!(err_of(&text), ConfigError::InvalidReleaseTitle(_))); + let at_limit = "t".repeat(MAX_RELEASE_TITLE_CHARS); + assert!(parse_config(&release_toml(&format!("title = \"{at_limit}\""))).is_ok()); + } + + #[test] + fn release_title_for_fills_tag() { + assert_eq!(ReleaseSpec::default().title_for("v1.2.0"), "v1.2.0"); + let release = release_of(&release_toml("title = \"Release {tag}\"")); + assert_eq!(release.title_for("v1.2.0"), "Release v1.2.0"); + let fixed = release_of(&release_toml("title = \"Stable\"")); + assert_eq!(fixed.title_for("v1.2.0"), "Stable"); + } + + #[test] + fn release_prerelease_auto_logic() { + let auto = ReleaseSpec::default(); + assert!(auto.is_prerelease("v1.2.0-rc1")); + assert!(auto.is_prerelease("v2.0.0-beta.3")); + assert!(!auto.is_prerelease("v1.2.0")); + let always = release_of(&release_toml("prerelease = true")); + assert!(always.is_prerelease("v1.2.0")); + let never = release_of(&release_toml("prerelease = false")); + assert!(!never.is_prerelease("v1.2.0-rc1")); + } + + #[test] + fn release_asset_matching() { + let release = release_of(&release_toml( + "assets = [\"build:forge-*-linux-*\", \"build:SHA256SUMS\"]", + )); + assert!(release.asset_matches("build", "forge-1.2.0-linux-x86_64")); + assert!(release.asset_matches("build", "SHA256SUMS")); + assert!(!release.asset_matches("build", "forge-1.2.0-darwin-arm64")); + assert!(!release.asset_matches("build", "SHA256SUMS.sig")); + // The same glob under another job name does not match. + assert!(!release.asset_matches("lint", "SHA256SUMS")); + assert!(!ReleaseSpec::default().asset_matches("build", "SHA256SUMS")); + } + + #[test] + fn wants_release_only_for_matching_tags() { + let text = release_toml(""); + let cfg = parse_config(&text).unwrap(); + assert!(cfg.wants_release(&Event::Tag { tag: "v1.2.0" })); + assert!(!cfg.wants_release(&Event::Tag { tag: "release-1" })); + assert!(!cfg.wants_release(&Event::Push { branch: "main" })); + assert!(!cfg.wants_release(&Event::Manual)); + assert!(!cfg.wants_release(&Event::PullRequest)); + + let without = parse_config(&format!("[on]\ntags = [\"v*\"]\n{}", job_toml(""))).unwrap(); + assert!(without.release.is_none()); + assert!(!without.wants_release(&Event::Tag { tag: "v1.2.0" })); + } } diff --git a/crates/forge-ci/src/error.rs b/crates/forge-ci/src/error.rs index 5584ed8..0a1109f 100644 --- a/crates/forge-ci/src/error.rs +++ b/crates/forge-ci/src/error.rs @@ -71,6 +71,18 @@ pub enum ConfigError { #[error("job {job:?}: duplicate cache path {path:?}")] DuplicateCachePath { job: String, path: String }, + #[error("[release] needs at least one tag glob in [on] tags")] + ReleaseWithoutTags, + + #[error("[release] lists {count} assets, the limit is {max}")] + TooManyReleaseAssets { count: usize, max: usize }, + + #[error("invalid release asset {asset:?}: {reason}")] + InvalidReleaseAsset { asset: String, reason: String }, + + #[error("invalid release title: {0}")] + InvalidReleaseTitle(String), + #[error("invalid {kind} glob {pattern:?}: {reason}")] InvalidTriggerGlob { kind: &'static str, diff --git a/crates/forge-core/src/config.rs b/crates/forge-core/src/config.rs index 9d0af30..9dd9b6b 100644 --- a/crates/forge-core/src/config.rs +++ b/crates/forge-core/src/config.rs @@ -81,6 +81,9 @@ pub struct Config { /// Release asset limits, from the `[releases]` section. #[serde(default)] pub releases: ReleasesConfig, + /// Where release assets and CI artifacts are stored, from the `[storage]` section. + #[serde(default)] + pub storage: StorageConfig, /// Standby replication, from the `[replication]` section. An empty `target` disables it. #[serde(default)] pub replication: ReplicationConfig, @@ -358,6 +361,168 @@ impl Default for ReleasesConfig { } } +/// Blob storage for release assets and CI artifacts, from the `[storage]` section. See +/// `docs/backup.md`. The default keeps blobs on the local disk under `/blobs`. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct StorageConfig { + /// `fs` (local disk, the default) or `s3` (any S3-compatible object store). + pub backend: StorageBackend, + /// Settings for `backend = "s3"`, from the `[storage.s3]` table. Ignored for `fs` and `r2`. + pub s3: S3Config, + /// Settings for `backend = "r2"`, from the `[storage.r2]` table. Ignored for `fs` and `s3`. + pub r2: R2Config, +} + +/// Blob backend. See `StorageConfig::backend`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum StorageBackend { + #[default] + Fs, + S3, + /// Cloudflare R2, configured by account rather than by endpoint. See `R2Config`. + R2, +} + +/// S3-compatible object store settings, from the `[storage.s3]` table. Works with AWS S3, MinIO, +/// Garage, Cloudflare R2 and similar. The secret is read from a file, so it stays out of this config. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct S3Config { + /// Bucket that holds the blobs. Required. + pub bucket: String, + /// Signing region, such as `eu-central-1`, or `auto` for R2. Required. + pub region: String, + /// Full URL of a non-AWS endpoint, such as `https://s3.example.internal:9000`. Empty uses AWS. + pub endpoint: String, + /// Key prefix inside the bucket, such as `forge/`. Empty stores keys at the bucket root. + pub prefix: String, + /// Access key id. Required. + pub access_key_id: String, + /// File holding the secret access key (mode 0600). Its contents are trimmed. Required. + pub secret_access_key_file: PathBuf, + /// Permit an `http://` endpoint. Only for a store on a trusted private network. + pub allow_http: bool, + /// Address buckets as subdomains (`bucket.host`) instead of paths (`host/bucket`). Path style is + /// the default because MinIO, Garage and most self-hosted stores expect it. + pub virtual_hosted_style: bool, +} + +/// Cloudflare R2 settings, from the `[storage.r2]` table. The endpoint is derived from the account +/// id and jurisdiction, so the S3 wire details never appear in the config. The secret is read from +/// a file, as for `S3Config`. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct R2Config { + /// Cloudflare account id, the 32-character hex string from the dashboard. Required. + pub account_id: String, + /// Bucket that holds the blobs. Required. + pub bucket: String, + /// `""` (the default, global), `"eu"`, or `"fedramp"`. Must match the jurisdiction the bucket + /// was created in, or requests fail. + pub jurisdiction: String, + /// Key prefix inside the bucket, such as `forge/`. Empty stores keys at the bucket root. + pub prefix: String, + /// Access key id of an R2 API token with object read and write. Required. + pub access_key_id: String, + /// File holding the secret access key (mode 0600). Its contents are trimmed. Required. + pub secret_access_key_file: PathBuf, +} + +impl R2Config { + /// The S3 API endpoint for this account and jurisdiction. Path-style, https only. + pub fn endpoint(&self) -> String { + match self.jurisdiction.as_str() { + "" => format!("https://{}.r2.cloudflarestorage.com", self.account_id), + jurisdiction => format!( + "https://{}.{jurisdiction}.r2.cloudflarestorage.com", + self.account_id + ), + } + } +} + +/// Fails unless `value` is non-empty after trimming. `section` names the table in the message. +fn require(section: &str, field: &str, value: &str) -> Result<()> { + if value.trim().is_empty() { + return Err(Error::Config(format!( + "[{section}] {field} is required when backend = \"{}\"", + section.trim_start_matches("storage.") + ))); + } + Ok(()) +} + +/// Checks that the secret file named by `[section]` exists and is a file. +fn check_secret_file(section: &str, path: &Path) -> Result<()> { + if path.as_os_str().is_empty() { + return Err(Error::Config(format!( + "[{section}] secret_access_key_file is required when backend = \"{}\"", + section.trim_start_matches("storage.") + ))); + } + if !path.is_file() { + return Err(Error::Config(format!( + "[{section}] secret_access_key_file {} is not a readable file", + path.display() + ))); + } + Ok(()) +} + +impl StorageConfig { + fn validate(&self) -> Result<()> { + match self.backend { + StorageBackend::Fs => Ok(()), + StorageBackend::S3 => self.validate_s3(), + StorageBackend::R2 => self.validate_r2(), + } + } + + fn validate_s3(&self) -> Result<()> { + let s3 = &self.s3; + require("storage.s3", "bucket", &s3.bucket)?; + require("storage.s3", "region", &s3.region)?; + require("storage.s3", "access_key_id", &s3.access_key_id)?; + check_secret_file("storage.s3", &s3.secret_access_key_file)?; + if !s3.endpoint.is_empty() { + if !(s3.endpoint.starts_with("https://") || s3.endpoint.starts_with("http://")) { + return Err(Error::Config( + "[storage.s3] endpoint must start with https:// or http://".into(), + )); + } + if s3.endpoint.starts_with("http://") && !s3.allow_http { + return Err(Error::Config( + "[storage.s3] endpoint is http:// but allow_http is false".into(), + )); + } + } + Ok(()) + } + + fn validate_r2(&self) -> Result<()> { + let r2 = &self.r2; + require("storage.r2", "account_id", &r2.account_id)?; + // The account id becomes part of the host name, so only hex digits are allowed. + if !r2.account_id.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(Error::Config( + "[storage.r2] account_id must contain only hex digits (copy it from the Cloudflare dashboard)".into(), + )); + } + require("storage.r2", "bucket", &r2.bucket)?; + require("storage.r2", "access_key_id", &r2.access_key_id)?; + check_secret_file("storage.r2", &r2.secret_access_key_file)?; + if !matches!(r2.jurisdiction.as_str(), "" | "eu" | "fedramp") { + return Err(Error::Config(format!( + "[storage.r2] jurisdiction must be \"eu\", \"fedramp\", or left empty, not \"{}\"", + r2.jurisdiction + ))); + } + Ok(()) + } +} + /// Scheduled backups, from the `[backup]` section. See `docs/backup.md`. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] @@ -455,6 +620,7 @@ impl Config { config.backup.validate()?; config.replication.validate()?; config.self_update.validate()?; + config.storage.validate()?; Ok(config) } } @@ -627,7 +793,10 @@ mod tests { let base = format!("{DEV_DEFAULTS}\n[self_update]\nenabled = true\n"); for repo in ["", "forge", "a/b/c", "/forge", "owner/"] { std::fs::write(&path, format!("{base}repo = \"{repo}\"\n")).unwrap(); - assert!(Config::load(&path).is_err(), "repo `{repo}` should be refused"); + assert!( + Config::load(&path).is_err(), + "repo `{repo}` should be refused" + ); } std::fs::write(&path, format!("{base}repo = \"Tahinli/forge\"\n")).unwrap(); let cfg = Config::load(&path).unwrap(); @@ -662,4 +831,235 @@ mod tests { std::fs::write(&path, format!("{DEV_DEFAULTS}\n[backup]\nbogus = 1\n")).unwrap(); assert!(matches!(Config::load(&path), Err(Error::Config(_)))); } + + #[test] + fn storage_section_defaults_to_fs() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + std::fs::write(&path, DEV_DEFAULTS).unwrap(); + let cfg = Config::load(&path).unwrap(); + assert_eq!(cfg.storage.backend, StorageBackend::Fs); + assert!(cfg.storage.s3.bucket.is_empty()); + assert!(!cfg.storage.s3.allow_http); + assert!(!cfg.storage.s3.virtual_hosted_style); + } + + #[test] + fn s3_backend_requires_bucket_region_and_credentials() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + let secret = dir.path().join("secret"); + std::fs::write(&secret, "s3cret\n").unwrap(); + let secret = secret.display(); + let full = format!( + "{DEV_DEFAULTS}\n[storage]\nbackend = \"s3\"\n[storage.s3]\nbucket = \"forge\"\nregion = \"eu-central-1\"\naccess_key_id = \"AKIA\"\nsecret_access_key_file = \"{secret}\"\n" + ); + std::fs::write(&path, &full).unwrap(); + let cfg = Config::load(&path).unwrap(); + assert_eq!(cfg.storage.backend, StorageBackend::S3); + assert_eq!(cfg.storage.s3.bucket, "forge"); + assert_eq!(cfg.storage.s3.region, "eu-central-1"); + + for missing in [ + "bucket", + "region", + "access_key_id", + "secret_access_key_file", + ] { + let text: String = full + .lines() + .filter(|line| !line.starts_with(missing)) + .collect::>() + .join("\n"); + std::fs::write(&path, &text).unwrap(); + assert!( + matches!(Config::load(&path), Err(Error::Config(_))), + "{missing} should be required" + ); + } + } + + #[test] + fn s3_secret_file_must_exist() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + let text = format!( + "{DEV_DEFAULTS}\n[storage]\nbackend = \"s3\"\n[storage.s3]\nbucket = \"forge\"\nregion = \"auto\"\naccess_key_id = \"AKIA\"\nsecret_access_key_file = \"{}\"\n", + dir.path().join("absent").display() + ); + std::fs::write(&path, text).unwrap(); + assert!(matches!(Config::load(&path), Err(Error::Config(_)))); + } + + #[test] + fn s3_endpoint_scheme_is_checked() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + let secret = dir.path().join("secret"); + std::fs::write(&secret, "s3cret").unwrap(); + let base = format!( + "{DEV_DEFAULTS}\n[storage]\nbackend = \"s3\"\n[storage.s3]\nbucket = \"forge\"\nregion = \"us-east-1\"\naccess_key_id = \"AKIA\"\nsecret_access_key_file = \"{}\"\n", + secret.display() + ); + for (endpoint, ok) in [ + ("minio.internal:9000", false), + ("https://s3.example.internal", true), + ("http://minio.internal:9000", false), + ] { + std::fs::write(&path, format!("{base}endpoint = \"{endpoint}\"\n")).unwrap(); + assert_eq!(Config::load(&path).is_ok(), ok, "endpoint `{endpoint}`"); + } + std::fs::write( + &path, + format!("{base}endpoint = \"http://minio.internal:9000\"\nallow_http = true\n"), + ) + .unwrap(); + assert!(Config::load(&path).is_ok()); + } + + #[test] + fn storage_rejects_unknown_keys() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + std::fs::write(&path, format!("{DEV_DEFAULTS}\n[storage]\nbogus = 1\n")).unwrap(); + assert!(matches!(Config::load(&path), Err(Error::Config(_)))); + std::fs::write( + &path, + format!("{DEV_DEFAULTS}\n[storage.s3]\nsecret_access_key = \"x\"\n"), + ) + .unwrap(); + assert!(matches!(Config::load(&path), Err(Error::Config(_)))); + // R2 users never set an endpoint or region, so those keys are refused outright. + for key in ["endpoint = \"https://x\"", "region = \"auto\"", "bogus = 1"] { + std::fs::write(&path, format!("{DEV_DEFAULTS}\n[storage.r2]\n{key}\n")).unwrap(); + assert!( + matches!(Config::load(&path), Err(Error::Config(_))), + "{key}" + ); + } + } + + /// A complete `[storage.r2]` table with a real secret file, minus any lines the caller drops. + fn r2_config_text(dir: &Path, drop: &[&str], extra: &str) -> String { + let secret = dir.join("r2-secret"); + std::fs::write(&secret, "r2s3cret\n").unwrap(); + let base = format!( + "{DEV_DEFAULTS}\n[storage]\nbackend = \"r2\"\n[storage.r2]\naccount_id = \"0123abcd\"\nbucket = \"forge\"\naccess_key_id = \"AKIA\"\nsecret_access_key_file = \"{}\"\n", + secret.display() + ); + let kept: String = base + .lines() + .filter(|line| !drop.iter().any(|d| line.starts_with(d))) + .map(|line| format!("{line}\n")) + .collect(); + format!("{kept}{extra}") + } + + #[test] + fn r2_backend_parses_and_derives_its_endpoint() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + std::fs::write( + &path, + r2_config_text(dir.path(), &[], "prefix = \"forge/\"\n"), + ) + .unwrap(); + let cfg = Config::load(&path).unwrap(); + assert_eq!(cfg.storage.backend, StorageBackend::R2); + assert_eq!(cfg.storage.r2.bucket, "forge"); + assert_eq!(cfg.storage.r2.prefix, "forge/"); + assert_eq!( + cfg.storage.r2.endpoint(), + "https://0123abcd.r2.cloudflarestorage.com" + ); + } + + #[test] + fn r2_endpoint_follows_jurisdiction() { + let cases = [ + ("", "https://acct.r2.cloudflarestorage.com"), + ("eu", "https://acct.eu.r2.cloudflarestorage.com"), + ("fedramp", "https://acct.fedramp.r2.cloudflarestorage.com"), + ]; + for (jurisdiction, expected) in cases { + let cfg = R2Config { + account_id: "acct".into(), + jurisdiction: jurisdiction.into(), + ..R2Config::default() + }; + assert_eq!(cfg.endpoint(), expected, "jurisdiction `{jurisdiction}`"); + } + } + + #[test] + fn r2_backend_requires_its_fields() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + std::fs::write(&path, r2_config_text(dir.path(), &[], "")).unwrap(); + assert!(Config::load(&path).is_ok()); + for missing in [ + "account_id", + "bucket", + "access_key_id", + "secret_access_key_file", + ] { + std::fs::write(&path, r2_config_text(dir.path(), &[missing], "")).unwrap(); + assert!( + matches!(Config::load(&path), Err(Error::Config(_))), + "{missing} should be required" + ); + } + } + + #[test] + fn r2_account_id_must_be_hex() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + for bad in ["evil.example.com/", "acct id", "xyz"] { + let text = r2_config_text( + dir.path(), + &["account_id"], + &format!("account_id = \"{bad}\"\n"), + ); + std::fs::write(&path, text).unwrap(); + assert!( + matches!(Config::load(&path), Err(Error::Config(_))), + "`{bad}`" + ); + } + } + + #[test] + fn r2_jurisdiction_must_be_known() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + for (value, ok) in [ + ("", true), + ("eu", true), + ("fedramp", true), + ("us", false), + ("EU", false), + ] { + let text = r2_config_text( + dir.path(), + &["jurisdiction"], + &format!("jurisdiction = \"{value}\"\n"), + ); + std::fs::write(&path, text).unwrap(); + assert_eq!(Config::load(&path).is_ok(), ok, "jurisdiction `{value}`"); + } + } + + #[test] + fn r2_secret_file_must_exist() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + let text = r2_config_text(dir.path(), &["secret_access_key_file"], "") + + &format!( + "secret_access_key_file = \"{}\"\n", + dir.path().join("absent").display() + ); + std::fs::write(&path, text).unwrap(); + assert!(matches!(Config::load(&path), Err(Error::Config(_)))); + } } diff --git a/crates/forge-core/src/releases.rs b/crates/forge-core/src/releases.rs index de81b16..e6cd529 100644 --- a/crates/forge-core/src/releases.rs +++ b/crates/forge-core/src/releases.rs @@ -59,7 +59,7 @@ pub struct NewRelease<'a> { pub author_id: &'a str, } -/// The editable fields of a release. The tag and its target never change. +/// The editable fields of a release. The tag and its target are changed with `set_release_tag`. #[derive(Debug, Clone, Copy)] pub struct ReleaseEdit<'a> { pub title: &'a str, diff --git a/crates/forge-core/src/store/releases.rs b/crates/forge-core/src/store/releases.rs index b4b6495..a2aee5f 100644 --- a/crates/forge-core/src/store/releases.rs +++ b/crates/forge-core/src/store/releases.rs @@ -281,6 +281,52 @@ impl Store { .ok_or_else(missing_row) } + /// Swaps the file of an existing asset in one statement. The row takes the new asset's id, + /// size, digest, content type, uploader and time, and keeps its release, name and download + /// count. The new blob must already be written under `assets/`; the caller deletes the + /// old blob after this returns. `NotFound` when `old_id` is gone. + pub async fn replace_asset(&self, old_id: &str, new: &NewAsset<'_>) -> Result { + let size = i64::try_from(new.size).map_err(|_| Error::Invalid("asset too large".into()))?; + let changed = { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE release_assets SET id = ?2, size = ?3, sha256 = ?4, content_type = ?5, \ + uploader_id = ?6, created_at = ?7 WHERE id = ?1", + ( + old_id.to_string(), + new.id.to_string(), + size, + new.sha256.to_string(), + new.content_type.to_string(), + new.uploader_id.to_string(), + now_stamp(), + ), + ) + .await + .map_err(db_err)? + }; + if changed != 1 { + return Err(Error::NotFound); + } + self.release_asset_by_id(new.id) + .await? + .ok_or_else(missing_row) + } + + /// Points a release at another tag and commit. A tag another release already uses is + /// `Conflict`. Returns false when the release is gone. + pub async fn set_release_tag(&self, id: &str, tag: &str, target_oid: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE releases SET tag = ?2, target_oid = ?3 WHERE id = ?1", + (id.to_string(), tag.to_string(), target_oid.to_string()), + ) + .await + .map_err(|e| insert_err(e, "a release already exists for this tag"))?; + Ok(changed == 1) + } + /// Deletes one asset row. Returns false when it is already gone. pub async fn delete_release_asset(&self, id: &str) -> Result { let conn = self.inner.conn.lock().await; @@ -328,7 +374,10 @@ mod tests { async fn store_with_repo() -> (tempfile::TempDir, Store, String, String) { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); - let user = store.create_user("tahinli", None, "h", false).await.unwrap(); + let user = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let repo = store .create_repo(&user.id, "proj", "", crate::Visibility::Public, "main") .await @@ -444,6 +493,102 @@ mod tests { assert_eq!(store.delete_release(&rel.id).await.unwrap(), None); } + #[tokio::test] + async fn replacing_an_asset_swaps_its_file_and_keeps_name_and_count() { + let (_dir, store, user, repo) = store_with_repo().await; + let rel = store + .create_release(&new_release(&repo, &user, "v1", false)) + .await + .unwrap(); + store + .add_asset(&NewAsset { + id: "a1", + release_id: &rel.id, + name: "app.bin", + size: 3, + sha256: "x", + content_type: "application/gzip", + uploader_id: &user, + }) + .await + .unwrap(); + store.count_asset_download("a1").await.unwrap(); + + let replaced = store + .replace_asset( + "a1", + &NewAsset { + id: "a2", + release_id: &rel.id, + name: "app.bin", + size: 5, + sha256: "y", + content_type: "text/plain", + uploader_id: &user, + }, + ) + .await + .unwrap(); + assert_eq!(replaced.id, "a2"); + assert_eq!(replaced.name, "app.bin"); + assert_eq!(replaced.size, 5); + assert_eq!(replaced.sha256, "y"); + assert_eq!(replaced.content_type, "text/plain"); + assert_eq!(replaced.download_count, 1, "the counter survives"); + assert!(store.release_asset_by_id("a1").await.unwrap().is_none()); + assert_eq!( + store.repo_release_asset_ids(&repo).await.unwrap(), + vec!["a2".to_string()] + ); + + let gone = store + .replace_asset( + "a1", + &NewAsset { + id: "a3", + release_id: &rel.id, + name: "app.bin", + size: 1, + sha256: "z", + content_type: "text/plain", + uploader_id: &user, + }, + ) + .await; + assert!(matches!(gone, Err(Error::NotFound)), "{gone:?}"); + } + + #[tokio::test] + async fn retagging_moves_the_release_and_refuses_a_tag_another_release_uses() { + let (_dir, store, user, repo) = store_with_repo().await; + let first = store + .create_release(&new_release(&repo, &user, "v1", true)) + .await + .unwrap(); + store + .create_release(&new_release(&repo, &user, "v2", true)) + .await + .unwrap(); + let new_target = "1111111111111111111111111111111111111111"; + assert!( + store + .set_release_tag(&first.id, "v1b", new_target) + .await + .unwrap() + ); + let moved = store.release(&first.id).await.unwrap().unwrap(); + assert_eq!(moved.tag, "v1b"); + assert_eq!(moved.target_oid, new_target); + let taken = store.set_release_tag(&first.id, "v2", new_target).await; + assert!(matches!(taken, Err(Error::Conflict(_))), "{taken:?}"); + assert!( + !store + .set_release_tag("missing", "v9", new_target) + .await + .unwrap() + ); + } + #[test] fn asset_names_and_content_types_are_cleaned() { assert!(valid_asset_name("app-1.0_linux+x86.tar.gz")); diff --git a/crates/forge-git/src/tags.rs b/crates/forge-git/src/tags.rs index 2e974f0..a4d3286 100644 --- a/crates/forge-git/src/tags.rs +++ b/crates/forge-git/src/tags.rs @@ -47,6 +47,86 @@ pub async fn create_lightweight_tag( .await } +/// Moves `refs/tags/` from `old` to `new`, but only if it still points at `old`. A stale +/// `old` gives `Error::RefMoved` and leaves the tag alone. The caller reads the tag first. +pub async fn move_lightweight_tag( + env: &GitEnv, + repo: &Path, + name: &str, + new: &str, + old: &str, +) -> Result<()> { + if !valid_tag_name(name) { + return Err(Error::InvalidInput(format!("invalid tag name: {name:?}"))); + } + validate_oid(new)?; + validate_oid(old)?; + let refname = format!("refs/tags/{name}"); + let result = git(env, "update-ref") + .git_dir(repo) + .user_arg(&refname)? + .user_arg(new)? + .user_arg(old)? + .status() + .await; + match result { + Err(Error::Failed(msg)) + if msg.contains("but expected") || msg.contains("unable to resolve reference") => + { + Err(Error::RefMoved(refname)) + } + other => other, + } +} + +/// The closest tag reachable from the parent of `oid`, as `(tag name, commit id)`. Lightweight and +/// annotated tags both count. `None` when no tag is reachable or `oid` has no parent. +pub async fn previous_tag( + env: &GitEnv, + repo: &Path, + oid: &str, +) -> crate::error::Result> { + validate_oid(oid)?; + let parent = format!("{oid}^"); + let described = git(env, "describe") + .git_dir(repo) + .arg("--tags") + .arg("--abbrev=0") + .user_revs(&[&parent])? + .output() + .await; + let Ok(out) = described else { + return Ok(None); + }; + let name = String::from_utf8_lossy(&out).trim().to_owned(); + if name.is_empty() { + return Ok(None); + } + let commit = git(env, "rev-parse") + .git_dir(repo) + .user_arg(&format!("{name}^{{commit}}"))? + .output() + .await?; + let commit = String::from_utf8_lossy(&commit).trim().to_owned(); + Ok(Some((name, commit))) +} + +/// True when `oid` is a full object id that names a commit in the repo. A malformed id or a +/// missing object is `false`, so this is safe to use on user input. +pub async fn commit_exists(env: &GitEnv, repo: &Path, oid: &str) -> bool { + if validate_oid(oid).is_err() { + return false; + } + match git(env, "cat-file") + .git_dir(repo) + .arg("-e") + .user_arg(&format!("{oid}^{{commit}}")) + { + Ok(cmd) => cmd.status().await.is_ok(), + Err(_) => false, + } +} + #[cfg(test)] mod tests { use super::valid_tag_name; diff --git a/crates/forge-web/src/api/mod.rs b/crates/forge-web/src/api/mod.rs index ce1316e..0cf901e 100644 --- a/crates/forge-web/src/api/mod.rs +++ b/crates/forge-web/src/api/mod.rs @@ -4,6 +4,7 @@ //! `{"error": "..."}` with a matching status code. Anonymous callers get 401 whenever they cannot //! use a repo, the same as git, so missing and hidden repos look identical to them. +pub mod releases; pub mod statuses; use std::net::IpAddr; diff --git a/crates/forge-web/src/api/releases.rs b/crates/forge-web/src/api/releases.rs new file mode 100644 index 0000000..e98b30b --- /dev/null +++ b/crates/forge-web/src/api/releases.rs @@ -0,0 +1,884 @@ +//! Release routes of the token API (documented in docs/api.md). +//! +//! Reads are public for public repos. Drafts are only listed or fetched by callers with write +//! access, and everyone else gets the same 404 as for a missing release. Writes need a token with +//! the `repo` scope and write access. The business rules live in `release_ops`; these handlers +//! translate input and output only. + +use std::io; + +use forge_core::releases::{Release, ReleaseAsset}; +use forge_core::{Action, Repo as CoreRepo, User}; +use futures_util::StreamExt; +use http::header::CONTENT_TYPE; +use serde::Deserialize; +use serde_json::{Value, json}; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::headers; +use topcoat::router::response::Response; +use topcoat::router::{Body, StatusCode, path_param, route}; + +use crate::api::{self, Refusal}; +use crate::client_ip::client_ip; +use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError}; +use crate::state::AppState; +use crate::views::enc; + +path_param!(owner); +path_param!(repo); +path_param!(id); +path_param!(tag); +path_param!(asset); + +/// Body of `POST .../releases`. Only `tag` is required. +#[derive(Deserialize)] +struct CreateBody { + tag: String, + target: Option, + title: Option, + body: Option, + draft: Option, + prerelease: Option, +} + +/// Body of `PATCH .../releases/{id}`. Omitted fields keep their current values. +#[derive(Deserialize)] +struct PatchBody { + title: Option, + body: Option, + draft: Option, + prerelease: Option, + tag: Option, + target: Option, +} + +#[route(GET "/api/v1/repos/{owner}/{repo}/releases")] +async fn list_releases(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let (repo, can_write) = match read_context(cx).await { + Ok(found) => found, + Err(res) => return Ok(*res), + }; + let releases = match state.store.list_releases(&repo.id).await { + Ok(releases) => releases, + Err(e) => return Ok(*api::internal(e)), + }; + let mut out = Vec::new(); + for release in releases.iter().filter(|r| can_write || !r.draft) { + match release_json(state, &repo, release).await { + Ok(value) => out.push(value), + Err(res) => return Ok(*res), + } + } + Ok(api::json(StatusCode::OK, &Value::Array(out))) +} + +#[route(GET "/api/v1/repos/{owner}/{repo}/releases/tags/{tag}")] +async fn get_release_by_tag(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let (repo, can_write) = match read_context(cx).await { + Ok(found) => found, + Err(res) => return Ok(*res), + }; + let tag_name = path_param::(cx); + let release = match state.store.release_by_tag(&repo.id, tag_name).await { + Ok(Some(release)) if can_write || !release.draft => release, + Ok(_) => return Ok(not_found()), + Err(e) => return Ok(*api::internal(e)), + }; + match release_json(state, &repo, &release).await { + Ok(value) => Ok(api::json(StatusCode::OK, &value)), + Err(res) => Ok(*res), + } +} + +#[route(POST "/api/v1/repos/{owner}/{repo}/releases")] +async fn create_release(cx: &Cx, body: Body) -> topcoat::Result { + let state = app_context::(cx); + let (repo, user) = match write_context(cx).await { + Ok(found) => found, + Err(res) => return Ok(*res), + }; + let bytes = match api::read_body(body, MAX_JSON_BYTES).await { + Ok(bytes) => bytes, + Err(res) => return Ok(*res), + }; + let input: CreateBody = match serde_json::from_slice(&bytes) { + Ok(input) => input, + Err(e) => { + return Ok(api::error( + StatusCode::BAD_REQUEST, + &format!("invalid JSON body: {e}"), + )); + } + }; + let title = input.title.unwrap_or_else(|| input.tag.clone()); + let created = release_ops::create( + state, + &repo, + &user, + CreateRelease { + tag: input.tag, + target: input.target, + title, + body: input.body.unwrap_or_default(), + draft: input.draft.unwrap_or(false), + prerelease: input.prerelease.unwrap_or(false), + }, + ) + .await; + let created = match created { + Ok(created) => created, + Err(e) => return Ok(*release_failure(e)), + }; + match release_json(state, &repo, &created).await { + Ok(value) => Ok(api::json(StatusCode::CREATED, &value)), + Err(res) => Ok(*res), + } +} + +#[route(PATCH "/api/v1/repos/{owner}/{repo}/releases/{id}")] +async fn edit_release(cx: &Cx, body: Body) -> topcoat::Result { + let state = app_context::(cx); + let (repo, user) = match write_context(cx).await { + Ok(found) => found, + Err(res) => return Ok(*res), + }; + let release = match release_in_repo(state, &repo, path_param::(cx)).await { + Ok(release) => release, + Err(res) => return Ok(*res), + }; + let bytes = match api::read_body(body, MAX_JSON_BYTES).await { + Ok(bytes) => bytes, + Err(res) => return Ok(*res), + }; + let patch: PatchBody = match serde_json::from_slice(&bytes) { + Ok(patch) => patch, + Err(e) => { + return Ok(api::error( + StatusCode::BAD_REQUEST, + &format!("invalid JSON body: {e}"), + )); + } + }; + let edit = EditRelease { + title: patch.title.unwrap_or_else(|| release.title.clone()), + body: patch.body.unwrap_or_else(|| release.body.clone()), + draft: patch.draft.unwrap_or(release.draft), + prerelease: patch.prerelease.unwrap_or(release.prerelease), + tag: patch.tag, + target: patch.target, + }; + let edited = match release_ops::update(state, &repo, &user, &release, edit).await { + Ok(edited) => edited, + Err(e) => return Ok(*release_failure(e)), + }; + match release_json(state, &repo, &edited).await { + Ok(value) => Ok(api::json(StatusCode::OK, &value)), + Err(res) => Ok(*res), + } +} + +#[route(DELETE "/api/v1/repos/{owner}/{repo}/releases/{id}")] +async fn delete_release(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let (repo, user) = match write_context(cx).await { + Ok(found) => found, + Err(res) => return Ok(*res), + }; + let release = match release_in_repo(state, &repo, path_param::(cx)).await { + Ok(release) => release, + Err(res) => return Ok(*res), + }; + match release_ops::delete(state, &repo, &user, &release).await { + Ok(()) => Ok(no_content()), + Err(e) => Ok(*release_failure(e)), + } +} + +/// Streams the raw request body into an asset. `201` for a new name, `200` when it replaces one. +#[route(PUT "/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}")] +async fn upload_asset(cx: &Cx, body: Body) -> topcoat::Result { + let state = app_context::(cx); + let (repo, user) = match write_context(cx).await { + Ok(found) => found, + Err(res) => return Ok(*res), + }; + let release = match release_in_repo(state, &repo, path_param::(cx)).await { + Ok(release) => release, + Err(res) => return Ok(*res), + }; + let content_type = headers(cx) + .get(CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let max_bytes = state + .config + .releases + .max_asset_mb + .saturating_mul(1024 * 1024); + // The body is streamed chunk by chunk into the blob store; nothing buffers the whole file. + let stream = Box::pin( + body.into_data_stream() + .map(|chunk| chunk.map_err(io::Error::other)), + ); + let stored = release_ops::put_asset( + state, + &repo, + &release, + &user, + path_param::(cx), + content_type.as_deref(), + stream, + max_bytes, + ) + .await; + let (asset, replaced) = match stored { + Ok(stored) => stored, + Err(e) => return Ok(*release_failure(e)), + }; + let status = if replaced { + StatusCode::OK + } else { + StatusCode::CREATED + }; + Ok(api::json( + status, + &asset_json(&state.config.base_url, &repo, &release, &asset), + )) +} + +#[route(DELETE "/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}")] +async fn delete_asset(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let (repo, _user) = match write_context(cx).await { + Ok(found) => found, + Err(res) => return Ok(*res), + }; + let release = match release_in_repo(state, &repo, path_param::(cx)).await { + Ok(release) => release, + Err(res) => return Ok(*res), + }; + match release_ops::delete_asset(state, &repo, &release, path_param::(cx)).await { + Ok(()) => Ok(no_content()), + Err(e) => Ok(*release_failure(e)), + } +} + +/// Largest accepted JSON body, in bytes. +const MAX_JSON_BYTES: usize = 64 * 1024; + +/// Authenticates an optional caller and loads the repo for reading. Also reports whether the +/// caller may write, which decides whether drafts are visible. +async fn read_context(cx: &Cx) -> Result<(CoreRepo, bool), Refusal> { + let state = app_context::(cx); + let actor = api::authenticate(state, client_ip(cx), headers(cx)).await?; + let repo = api::load_repo( + state, + actor.as_ref(), + path_param::(cx), + path_param::(cx), + Action::Read, + ) + .await?; + let can_write = api::load_repo( + state, + actor.as_ref(), + path_param::(cx), + path_param::(cx), + Action::Write, + ) + .await + .is_ok(); + Ok((repo, can_write)) +} + +/// Authenticates a required caller with write access and loads the repo. +async fn write_context(cx: &Cx) -> Result<(CoreRepo, User), Refusal> { + let state = app_context::(cx); + let actor = api::authenticate(state, client_ip(cx), headers(cx)).await?; + let repo = api::load_repo( + state, + actor.as_ref(), + path_param::(cx), + path_param::(cx), + Action::Write, + ) + .await?; + match actor { + Some(user) => Ok((repo, user)), + None => Err(Box::new(api::unauthorized())), + } +} + +/// The release with this id, which must belong to `repo`. Anything else is a 404, so ids from +/// other repos cannot be probed. Callers of this function already have write access. +async fn release_in_repo(state: &AppState, repo: &CoreRepo, id: &str) -> Result { + match state.store.release(id).await { + Ok(Some(release)) if release.repo_id == repo.id => Ok(release), + Ok(_) => Err(Box::new(not_found())), + Err(e) => Err(api::internal(e)), + } +} + +/// The release JSON with its assets. +async fn release_json( + state: &AppState, + repo: &CoreRepo, + release: &Release, +) -> Result { + let assets = state + .store + .list_release_assets(&release.id) + .await + .map_err(api::internal)?; + let base = state.config.base_url.trim_end_matches('/'); + let assets: Vec = assets + .iter() + .map(|asset| asset_json(base, repo, release, asset)) + .collect(); + Ok(json!({ + "id": release.id, + "tag": release.tag, + "target": release.target_oid, + "title": release.title, + "body": release.body, + "draft": release.draft, + "prerelease": release.prerelease, + "author": release.author_name, + "created_at": release.created_at, + "published_at": release.published_at, + "html_url": format!("{base}/{}/{}/releases/tag/{}", repo.owner_name, repo.name, enc(&release.tag)), + "assets": assets, + })) +} + +/// The asset JSON. `download_url` is the web download route, which enforces draft visibility. +fn asset_json(base: &str, repo: &CoreRepo, release: &Release, asset: &ReleaseAsset) -> Value { + let base = base.trim_end_matches('/'); + json!({ + "id": asset.id, + "name": asset.name, + "size": asset.size, + "sha256": asset.sha256, + "content_type": asset.content_type, + "download_count": asset.download_count, + "created_at": asset.created_at, + "download_url": format!( + "{base}/{}/{}/releases/download/{}/{}", + repo.owner_name, + repo.name, + enc(&release.tag), + enc(&asset.name) + ), + }) +} + +/// Maps a release failure: internal errors are logged and hidden, the rest keep their message. +fn release_failure(e: ReleaseError) -> Refusal { + match e { + ReleaseError::Internal(cause) => api::internal(cause), + other => Box::new(api::error(other.status(), &other.message())), + } +} + +fn not_found() -> Response { + api::error(StatusCode::NOT_FOUND, "release not found") +} + +fn no_content() -> Response { + let mut res = Response::new(Body::from(String::new())); + *res.status_mut() = StatusCode::NO_CONTENT; + res +} + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + use std::sync::Arc; + + use forge_core::releases::NewRelease; + use forge_core::token::{generate_token, hash_token}; + use forge_core::{Role, Store, User, Visibility}; + use forge_git::repo::{init_bare, repo_path}; + use http::header::{AUTHORIZATION, CONTENT_TYPE}; + use topcoat::router::request::Request; + use topcoat::router::{Body, Router, to_bytes}; + + use crate::test_support::{app_router, test_state}; + + const OWNER: &str = "tahinli"; + const REPO: &str = "proj"; + const MIB: u64 = 1024 * 1024; + + fn git(dir: &Path, args: &[&str]) -> String { + let out = std::process::Command::new("git") + .current_dir(dir) + .args(args) + .output() + .expect("git runs"); + assert!(out.status.success(), "git {args:?} failed"); + String::from_utf8_lossy(&out.stdout).trim().to_owned() + } + + struct Fixture { + _tmp: tempfile::TempDir, + router: Router, + store: Store, + owner: User, + owner_token: String, + reader_token: String, + stranger_token: String, + scopeless_token: String, + } + + /// `tahinli/proj` is public with `main` holding one commit. `bob` reads it, `carol` has no + /// access, and every user has a token. `max_mb` replaces the asset size limit when given. + async fn fixture(max_mb: Option) -> Fixture { + let tmp = tempfile::tempdir().expect("tempdir"); + let mut state = test_state(tmp.path()).await; + if let Some(mb) = max_mb { + let mut config = (*state.config).clone(); + config.releases.max_asset_mb = mb; + state.config = Arc::new(config); + } + let store = state.store.clone(); + let owner = store + .create_user(OWNER, None, "not-a-real-hash", false) + .await + .expect("owner"); + let bob = store + .create_user("bob", None, "not-a-real-hash", false) + .await + .expect("bob"); + let carol = store + .create_user("carol", None, "not-a-real-hash", false) + .await + .expect("carol"); + let repo = store + .create_repo(&owner.id, REPO, "", Visibility::Public, "main") + .await + .expect("repo"); + store + .set_collaborator(&repo.id, &bob.id, Role::Read) + .await + .expect("collaborator"); + + let bare: PathBuf = repo_path(&state.git.data_dir, &repo.id).expect("repo path"); + init_bare(&state.git, &bare, "main").await.expect("init"); + let work = tmp.path().join("work"); + git(tmp.path(), &["init", "-b", "main", "work"]); + std::fs::write(work.join("file.txt"), "one").expect("write"); + git(&work, &["add", "file.txt"]); + git(&work, &["commit", "-m", "one"]); + git(&work, &["push", bare.to_str().expect("utf8"), "main"]); + + let owner_token = token_for(&store, &owner.id, &["repo"]).await; + let reader_token = token_for(&store, &bob.id, &["repo"]).await; + let stranger_token = token_for(&store, &carol.id, &["repo"]).await; + let scopeless_token = token_for(&store, &owner.id, &[]).await; + Fixture { + router: app_router(state), + _tmp: tmp, + store, + owner, + owner_token, + reader_token, + stranger_token, + scopeless_token, + } + } + + async fn token_for(store: &Store, user_id: &str, scopes: &[&str]) -> String { + let raw = generate_token(); + let scopes: Vec = scopes.iter().map(|s| (*s).to_owned()).collect(); + store + .create_token(user_id, "test", &hash_token(&raw), &scopes, None) + .await + .expect("token"); + raw + } + + fn bearer(raw: &str) -> String { + format!("Bearer {raw}") + } + + /// Sends one request through the router: `(status, json body)`. + async fn send( + router: &Router, + method: &str, + uri: &str, + auth: Option<&str>, + content_type: Option<&str>, + body: Vec, + ) -> (u16, serde_json::Value) { + let mut builder = Request::builder().method(method).uri(uri); + if let Some(auth) = auth { + builder = builder.header(AUTHORIZATION, auth); + } + if let Some(content_type) = content_type { + builder = builder.header(CONTENT_TYPE, content_type); + } + let req = builder.body(Body::from(body)).unwrap(); + let res = router.handle(req).await; + let status = res.status().as_u16(); + let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); + let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null); + (status, json) + } + + async fn post_json(f: &Fixture, auth: Option<&str>, json: &str) -> (u16, serde_json::Value) { + send( + &f.router, + "POST", + &releases_uri(""), + auth, + Some("application/json"), + json.as_bytes().to_vec(), + ) + .await + } + + fn releases_uri(rest: &str) -> String { + format!("/api/v1/repos/{OWNER}/{REPO}/releases{rest}") + } + + /// Creates a release through the API and returns its id. + async fn create(f: &Fixture, json: &str) -> String { + let (status, body) = post_json(f, Some(&bearer(&f.owner_token)), json).await; + assert_eq!(status, 201, "{body}"); + body["id"].as_str().expect("id").to_owned() + } + + async fn upload(f: &Fixture, id: &str, name: &str, bytes: Vec) -> (u16, serde_json::Value) { + send( + &f.router, + "PUT", + &releases_uri(&format!("/{id}/assets/{name}")), + Some(&bearer(&f.owner_token)), + Some("application/octet-stream"), + bytes, + ) + .await + } + + #[tokio::test] + async fn anonymous_and_bad_tokens_are_unauthorized() { + let f = fixture(None).await; + let (status, body) = post_json(&f, None, r#"{"tag":"v1"}"#).await; + assert_eq!(status, 401); + assert!(body["error"].is_string()); + let (status, _) = + post_json(&f, Some("Bearer forge_not_a_real_token"), r#"{"tag":"v1"}"#).await; + assert_eq!(status, 401); + } + + #[tokio::test] + async fn token_without_repo_scope_is_forbidden() { + let f = fixture(None).await; + let (status, _) = post_json(&f, Some(&bearer(&f.scopeless_token)), r#"{"tag":"v1"}"#).await; + assert_eq!(status, 403); + } + + #[tokio::test] + async fn read_only_collaborator_cannot_write() { + let f = fixture(None).await; + let auth = bearer(&f.reader_token); + let (status, body) = post_json(&f, Some(&auth), r#"{"tag":"v1"}"#).await; + assert_eq!(status, 403, "{body}"); + let id = create(&f, r#"{"tag":"v1","target":"main"}"#).await; + let (status, _) = upload(&f, &id, "app.bin", b"x".to_vec()).await; + assert_eq!(status, 201); + let (status, _) = send( + &f.router, + "DELETE", + &releases_uri(&format!("/{id}")), + Some(&auth), + None, + Vec::new(), + ) + .await; + assert_eq!(status, 403); + } + + #[tokio::test] + async fn create_list_and_get_by_tag() { + let f = fixture(None).await; + let (status, body) = post_json( + &f, + Some(&bearer(&f.owner_token)), + r#"{"tag":"v1.0","target":"main","body":"notes"}"#, + ) + .await; + assert_eq!(status, 201, "{body}"); + assert_eq!(body["title"], "v1.0", "the title defaults to the tag"); + assert_eq!(body["body"], "notes"); + assert_eq!(body["draft"], false); + assert_eq!(body["author"], OWNER); + assert_eq!(body["assets"], serde_json::json!([])); + assert_eq!(body["target"].as_str().map(str::len), Some(40)); + assert!( + body["html_url"] + .as_str() + .unwrap() + .ends_with("/releases/tag/v1.0") + ); + + create(&f, r#"{"tag":"v0.9","target":"main"}"#).await; + let (status, list) = + send(&f.router, "GET", &releases_uri(""), None, None, Vec::new()).await; + assert_eq!(status, 200); + let tags: Vec<&str> = list + .as_array() + .unwrap() + .iter() + .map(|r| r["tag"].as_str().unwrap()) + .collect(); + assert_eq!(tags.len(), 2); + assert!(tags.contains(&"v1.0") && tags.contains(&"v0.9")); + + let (status, one) = send( + &f.router, + "GET", + &releases_uri("/tags/v1.0"), + None, + None, + Vec::new(), + ) + .await; + assert_eq!(status, 200); + assert_eq!(one["tag"], "v1.0"); + let (status, _) = send( + &f.router, + "GET", + &releases_uri("/tags/missing"), + None, + None, + Vec::new(), + ) + .await; + assert_eq!(status, 404); + } + + #[tokio::test] + async fn patch_keeps_omitted_fields() { + let f = fixture(None).await; + let id = create( + &f, + r#"{"tag":"v2","target":"main","title":"Two","body":"keep me"}"#, + ) + .await; + let (status, body) = send( + &f.router, + "PATCH", + &releases_uri(&format!("/{id}")), + Some(&bearer(&f.owner_token)), + Some("application/json"), + br#"{"title":"Second"}"#.to_vec(), + ) + .await; + assert_eq!(status, 200, "{body}"); + assert_eq!(body["title"], "Second"); + assert_eq!(body["body"], "keep me"); + assert_eq!(body["tag"], "v2"); + assert_eq!(body["prerelease"], false); + + let (status, body) = send( + &f.router, + "PATCH", + &releases_uri(&format!("/{id}")), + Some(&bearer(&f.owner_token)), + Some("application/json"), + br#"{"draft":true}"#.to_vec(), + ) + .await; + assert_eq!(status, 200, "{body}"); + assert_eq!(body["draft"], true); + assert_eq!(body["title"], "Second"); + } + + #[tokio::test] + async fn upload_is_201_then_200_on_replace() { + let f = fixture(None).await; + let id = create(&f, r#"{"tag":"v1","target":"main"}"#).await; + let (status, body) = upload(&f, &id, "app.bin", b"one".to_vec()).await; + assert_eq!(status, 201, "{body}"); + assert_eq!(body["size"], 3); + assert_eq!(body["content_type"], "application/octet-stream"); + let url = body["download_url"].as_str().expect("download_url"); + assert!( + url.ends_with("/tahinli/proj/releases/download/v1/app.bin"), + "{url}" + ); + + let (status, body) = upload(&f, &id, "app.bin", b"two!".to_vec()).await; + assert_eq!(status, 200, "{body}"); + assert_eq!(body["size"], 4); + + let (status, one) = send( + &f.router, + "GET", + &releases_uri("/tags/v1"), + None, + None, + Vec::new(), + ) + .await; + assert_eq!(status, 200); + assert_eq!(one["assets"].as_array().map(Vec::len), Some(1)); + assert_eq!(one["assets"][0]["size"], 4); + } + + #[tokio::test] + async fn oversized_upload_is_413() { + let f = fixture(Some(1)).await; + let id = create(&f, r#"{"tag":"v1","target":"main"}"#).await; + let (status, body) = upload(&f, &id, "big.bin", vec![0u8; (MIB + 1) as usize]).await; + assert_eq!(status, 413, "{body}"); + assert!(body["error"].is_string()); + } + + #[tokio::test] + async fn delete_asset_then_release() { + let f = fixture(None).await; + let id = create(&f, r#"{"tag":"v1","target":"main"}"#).await; + let (_, asset) = upload(&f, &id, "app.bin", b"x".to_vec()).await; + let asset_id = asset["id"].as_str().unwrap().to_owned(); + let auth = bearer(&f.owner_token); + + let (status, _) = send( + &f.router, + "DELETE", + &releases_uri(&format!("/{id}/assets/{asset_id}")), + Some(&auth), + None, + Vec::new(), + ) + .await; + assert_eq!(status, 204); + let (_, one) = send( + &f.router, + "GET", + &releases_uri("/tags/v1"), + None, + None, + Vec::new(), + ) + .await; + assert_eq!(one["assets"], serde_json::json!([])); + + let (status, _) = send( + &f.router, + "DELETE", + &releases_uri(&format!("/{id}")), + Some(&auth), + None, + Vec::new(), + ) + .await; + assert_eq!(status, 204); + let (status, _) = send( + &f.router, + "GET", + &releases_uri("/tags/v1"), + None, + None, + Vec::new(), + ) + .await; + assert_eq!(status, 404); + } + + #[tokio::test] + async fn release_of_another_repo_is_not_found() { + let f = fixture(None).await; + let other = f + .store + .create_repo(&f.owner.id, "other", "", Visibility::Public, "main") + .await + .expect("other repo"); + let foreign = f + .store + .create_release(&NewRelease { + repo_id: &other.id, + tag: "v1", + target_oid: &"0".repeat(40), + title: "foreign", + body: "", + draft: false, + prerelease: false, + author_id: &f.owner.id, + }) + .await + .expect("foreign release"); + let auth = bearer(&f.owner_token); + let (status, _) = send( + &f.router, + "PATCH", + &releases_uri(&format!("/{}", foreign.id)), + Some(&auth), + Some("application/json"), + br#"{"title":"hijack"}"#.to_vec(), + ) + .await; + assert_eq!(status, 404); + let (status, _) = send( + &f.router, + "DELETE", + &releases_uri(&format!("/{}", foreign.id)), + Some(&auth), + None, + Vec::new(), + ) + .await; + assert_eq!(status, 404); + let (status, _) = upload(&f, &foreign.id, "app.bin", b"x".to_vec()).await; + assert_eq!(status, 404); + } + + #[tokio::test] + async fn draft_is_hidden_from_anonymous_and_non_writers() { + let f = fixture(None).await; + create(&f, r#"{"tag":"wip","target":"main","draft":true}"#).await; + let (status, list) = + send(&f.router, "GET", &releases_uri(""), None, None, Vec::new()).await; + assert_eq!(status, 200); + assert_eq!(list, serde_json::json!([])); + let (status, _) = send( + &f.router, + "GET", + &releases_uri("/tags/wip"), + None, + None, + Vec::new(), + ) + .await; + assert_eq!(status, 404); + + let stranger = bearer(&f.stranger_token); + let (status, list) = send( + &f.router, + "GET", + &releases_uri(""), + Some(&stranger), + None, + Vec::new(), + ) + .await; + assert_eq!(status, 200); + assert_eq!(list, serde_json::json!([])); + + let owner = bearer(&f.owner_token); + let (status, one) = send( + &f.router, + "GET", + &releases_uri("/tags/wip"), + Some(&owner), + None, + Vec::new(), + ) + .await; + assert_eq!(status, 200); + assert_eq!(one["draft"], true); + } +} diff --git a/crates/forge-web/src/blobs.rs b/crates/forge-web/src/blobs.rs index f41109e..505a9d6 100644 --- a/crates/forge-web/src/blobs.rs +++ b/crates/forge-web/src/blobs.rs @@ -1,5 +1,8 @@ -//! Blob storage for release assets. A thin wrapper over object_store's local filesystem backend, -//! so an S3 backend can replace it later without touching the pages. +//! Blob storage for release assets and CI artifacts. A thin wrapper over object_store, backed by +//! the local filesystem (the default), any S3-compatible store, or Cloudflare R2, chosen by `[storage]`. +//! +//! Only operations that every backend supports are used. `rename` is a server-side copy followed +//! by a delete on S3, and a delete of a missing key is not an error on either backend. //! //! Keys are `assets/`. Writes stream through object_store's multipart upload, which //! assembles the object in a temporary file and renames it into place on `finish`. Every chunk @@ -10,10 +13,13 @@ use std::path::Path; use std::sync::Arc; use bytes::Bytes; +use forge_core::config::{R2Config, S3Config, StorageBackend, StorageConfig}; use forge_core::{Error, Result}; use futures_util::{StreamExt, TryStreamExt, stream::BoxStream}; +use object_store::aws::AmazonS3Builder; use object_store::local::LocalFileSystem; use object_store::path::Path as ObjectPath; +use object_store::prefix::PrefixStore; use object_store::{ObjectStore, ObjectStoreExt, WriteMultipart}; use sha2::{Digest, Sha256}; @@ -34,6 +40,20 @@ where Error::Io(std::io::Error::other(e)) } +/// What `BlobStore::s3_store` needs to reach an S3-compatible bucket. Built from `[storage.s3]` +/// or derived from `[storage.r2]`. +struct S3Connection<'a> { + bucket: &'a str, + region: &'a str, + /// `None` uses AWS. + endpoint: Option<&'a str>, + prefix: &'a str, + access_key_id: &'a str, + secret_access_key_file: &'a Path, + allow_http: bool, + virtual_hosted_style: bool, +} + /// The blob store rooted at `/blobs`. Cheap to clone. #[derive(Clone)] pub struct BlobStore { @@ -47,15 +67,84 @@ pub struct BlobRead { } impl BlobStore { + /// Opens the backend chosen by `[storage]`. `fs` keeps blobs under `/blobs`. + pub fn from_config(cfg: &StorageConfig, data_dir: &Path) -> Result { + match cfg.backend { + StorageBackend::Fs => Self::open(&data_dir.join("blobs")), + StorageBackend::S3 => Self::s3(&cfg.s3), + StorageBackend::R2 => Self::r2(&cfg.r2), + } + } + /// Opens the store at `root`, creating the directory if needed. pub fn open(root: &Path) -> Result { std::fs::create_dir_all(root)?; let fs = LocalFileSystem::new_with_prefix(root).map_err(storage_err)?; - Ok(Self { - store: Arc::new(fs), + Ok(Self::from_store(Arc::new(fs))) + } + + /// Opens an S3-compatible bucket. The secret is read from its file here, once at startup. + fn s3(cfg: &S3Config) -> Result { + Self::s3_store(S3Connection { + bucket: &cfg.bucket, + region: &cfg.region, + endpoint: (!cfg.endpoint.is_empty()).then_some(cfg.endpoint.as_str()), + prefix: &cfg.prefix, + access_key_id: &cfg.access_key_id, + secret_access_key_file: &cfg.secret_access_key_file, + allow_http: cfg.allow_http, + virtual_hosted_style: cfg.virtual_hosted_style, + }) + } + + /// Opens a Cloudflare R2 bucket. The endpoint comes from the account id and jurisdiction, and + /// R2 ignores the region, so the signing region is the literal `auto`. Path style and https only. + /// + /// Defaults checked against R2 (object_store 0.14): conditional writes use ETag preconditions, + /// which R2 supports; no `x-amz-checksum-*` headers are sent unless a checksum algorithm is set, + /// so none is set here; and payloads are SigV4-signed, which R2 accepts. Do not enable + /// `with_unsigned_payload` or a checksum algorithm without retesting against R2. + fn r2(cfg: &R2Config) -> Result { + let endpoint = cfg.endpoint(); + Self::s3_store(S3Connection { + bucket: &cfg.bucket, + region: "auto", + endpoint: Some(&endpoint), + prefix: &cfg.prefix, + access_key_id: &cfg.access_key_id, + secret_access_key_file: &cfg.secret_access_key_file, + allow_http: false, + virtual_hosted_style: false, }) } + /// The constructor shared by every S3-compatible backend. + fn s3_store(conn: S3Connection<'_>) -> Result { + let secret = std::fs::read_to_string(conn.secret_access_key_file)?; + let mut builder = AmazonS3Builder::new() + .with_bucket_name(conn.bucket) + .with_region(conn.region) + .with_access_key_id(conn.access_key_id) + .with_secret_access_key(secret.trim()) + .with_allow_http(conn.allow_http) + .with_virtual_hosted_style_request(conn.virtual_hosted_style); + if let Some(endpoint) = conn.endpoint { + builder = builder.with_endpoint(endpoint); + } + let s3 = builder.build().map_err(storage_err)?; + let prefix = conn.prefix.trim_matches('/'); + let store: Arc = if prefix.is_empty() { + Arc::new(s3) + } else { + Arc::new(PrefixStore::new(s3, prefix)) + }; + Ok(Self::from_store(store)) + } + + fn from_store(store: Arc) -> Self { + Self { store } + } + /// Starts a write of `key`. The bytes are not visible under `key` until `finish`. pub async fn begin(&self, key: &str, max_bytes: u64) -> Result { let upload = self @@ -141,3 +230,114 @@ impl BlobWriter { let _ = self.writer.abort().await; } } + +#[cfg(test)] +mod tests { + use object_store::memory::InMemory; + + use super::*; + + /// The operations the pages use, run against any backend. + async fn exercise(blobs: &BlobStore) { + let mut writer = blobs.begin("tmp/upload", 1024).await.unwrap(); + writer.push(b"hello ").await.unwrap(); + writer.push(b"world").await.unwrap(); + let (size, digest) = writer.finish().await.unwrap(); + assert_eq!(size, 11); + assert_eq!(digest, hex::encode(Sha256::digest(b"hello world"))); + + blobs.rename("tmp/upload", &asset_key("a1")).await.unwrap(); + assert!(blobs.read("tmp/upload").await.unwrap().is_none()); + let read = blobs.read(&asset_key("a1")).await.unwrap().unwrap(); + assert_eq!(read.size, 11); + let chunks: Vec = read.stream.try_collect().await.unwrap(); + assert_eq!(chunks.concat(), b"hello world"); + + blobs.delete(&asset_key("a1")).await.unwrap(); + blobs.delete(&asset_key("a1")).await.unwrap(); + assert!(blobs.read(&asset_key("a1")).await.unwrap().is_none()); + } + + #[tokio::test] + async fn fs_backend_round_trip() { + let dir = tempfile::tempdir().unwrap(); + let blobs = BlobStore::open(&dir.path().join("blobs")).unwrap(); + exercise(&blobs).await; + } + + #[tokio::test] + async fn non_fs_backend_round_trip() { + // InMemory has no rename, so this exercises the copy-then-delete path an S3 store takes. + let blobs = BlobStore::from_store(Arc::new(InMemory::new())); + exercise(&blobs).await; + } + + #[tokio::test] + async fn upload_past_the_limit_is_refused() { + let blobs = BlobStore::from_store(Arc::new(InMemory::new())); + let mut writer = blobs.begin("tmp/big", 4).await.unwrap(); + writer.push(b"abc").await.unwrap(); + assert!(writer.push(b"de").await.is_err()); + writer.abort().await; + assert!(blobs.read("tmp/big").await.unwrap().is_none()); + } + + #[test] + fn fs_config_uses_blobs_under_data_dir() { + let dir = tempfile::tempdir().unwrap(); + let cfg = StorageConfig::default(); + BlobStore::from_config(&cfg, dir.path()).unwrap(); + assert!(dir.path().join("blobs").is_dir()); + } + + #[test] + fn s3_config_reads_the_secret_file() { + let dir = tempfile::tempdir().unwrap(); + let secret = dir.path().join("secret"); + std::fs::write(&secret, "s3cret\n").unwrap(); + let cfg = S3Config { + bucket: "forge".into(), + region: "us-east-1".into(), + endpoint: "http://127.0.0.1:9000".into(), + prefix: "/forge/".into(), + access_key_id: "AKIA".into(), + secret_access_key_file: secret, + allow_http: true, + virtual_hosted_style: false, + }; + assert!(BlobStore::s3(&cfg).is_ok()); + let missing = S3Config { + secret_access_key_file: dir.path().join("absent"), + ..cfg + }; + assert!(BlobStore::s3(&missing).is_err()); + } + + #[test] + fn r2_config_builds_a_store_from_the_secret_file() { + let dir = tempfile::tempdir().unwrap(); + let secret = dir.path().join("secret"); + std::fs::write(&secret, "r2s3cret\n").unwrap(); + let cfg = StorageConfig { + backend: StorageBackend::R2, + r2: R2Config { + account_id: "0123abcd".into(), + bucket: "forge".into(), + jurisdiction: "eu".into(), + prefix: "/forge/".into(), + access_key_id: "AKIA".into(), + secret_access_key_file: secret, + }, + ..StorageConfig::default() + }; + BlobStore::from_config(&cfg, dir.path()).unwrap(); + let missing = StorageConfig { + r2: R2Config { + secret_access_key_file: dir.path().join("absent"), + ..cfg.r2.clone() + }, + ..cfg + }; + assert!(BlobStore::from_config(&missing, dir.path()).is_err()); + } +} diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 09b2430..268b5be 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -89,6 +89,7 @@ pub async fn serve(config: Config) -> forge_core::Result<()> { Arc::new(crate::mail::LogMailer::new(data_dir.join("mail-log"))) } }; + let blobs = crate::blobs::BlobStore::from_config(&config.storage, &data_dir)?; let state = AppState { config: Arc::new(config), store, @@ -101,7 +102,7 @@ pub async fn serve(config: Config) -> forge_core::Result<()> { throttle: Arc::new(crate::throttle::Throttle::default()), webhook_waker: Arc::new(Notify::new()), mirror_waker: Arc::new(Notify::new()), - blobs: crate::blobs::BlobStore::open(&data_dir.join("blobs"))?, + blobs, replication: Arc::new(crate::replication::ReplicationQueue::default()), ci_waker: Arc::new(Notify::new()), mailer, diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index 021a7ed..d46ac3a 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -12,7 +12,7 @@ use forge_ci::proto::{ FinishRequest, HeartbeatResponse, JobAssignment, Outcome, RegisterRequest, RegisterResponse, }; use forge_core::Error as CoreError; -use forge_core::ci::{CiJob, CiRun, CiRunner, JobState}; +use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, RunState}; use futures_util::StreamExt; use http::header::HeaderValue; use serde_json::json; @@ -774,6 +774,11 @@ async fn finish_job( } // A run that just went green may deploy the forge itself. self_update::maybe_deploy(state, &run).await; + // A tag run that went green may publish a release. The request does not wait for it. + if run.state == RunState::Success { + let (state, run) = (state.clone(), run.clone()); + tokio::spawn(async move { crate::ci::release::on_run_finished(&state, &run).await }); + } Ok(run.state.as_str()) } diff --git a/crates/forge-web/src/ci/mod.rs b/crates/forge-web/src/ci/mod.rs index 4db9970..0be24e3 100644 --- a/crates/forge-web/src/ci/mod.rs +++ b/crates/forge-web/src/ci/mod.rs @@ -13,6 +13,7 @@ use crate::state::AppState; pub mod api; pub mod live; pub mod reaper; +pub mod release; pub mod schedule; pub use live::CiLive; diff --git a/crates/forge-web/src/ci/release.rs b/crates/forge-web/src/ci/release.rs new file mode 100644 index 0000000..9dfab5d --- /dev/null +++ b/crates/forge-web/src/ci/release.rs @@ -0,0 +1,705 @@ +//! Publishes a release when a tag run finishes with every job succeeded and the workflow at the +//! run's commit has a `[release]` table (see docs/ci.md, Releases). The finish handler spawns +//! [`on_run_finished`], so the runner's request is not slowed down. +//! +//! The run is idempotent. A release that already exists keeps its title, notes and draft state and +//! only gets the selected artifacts; an asset with the same name is replaced. +//! +//! The release is made as the run's actor. A system run has no actor, and an organization never +//! acts, so those fall back to the repo owner, then to the ghost account (`status_creator`). +//! +//! The outcome is written as one `[forge]` line at the end of the log of the run's last finished +//! job, so it shows on the run's job pages with the rest of the output. + +use forge_ci::config::{Event, ReleaseNotes, ReleaseSpec}; +use forge_core::ci::{CiJob, CiRun, RunState}; +use forge_core::releases::{MAX_BODY_CHARS, MAX_TITLE_CHARS, Release}; +use forge_core::{Repo, User}; +use forge_git::browse::CommitInfo; +use forge_git::history::log; +use forge_git::pulls::{is_ancestor, range_log}; +use forge_git::repo::repo_path; +use forge_git::tags::previous_tag; +use tokio::io::AsyncWriteExt; + +use super::api::fit_to_cap; +use super::{artifact_key, log_path, schedule, status_creator}; +use crate::release_ops::{self, CreateRelease, ReleaseError}; +use crate::state::AppState; + +/// Most commits listed in the notes. Older commits are left out. +const MAX_NOTE_COMMITS: usize = 200; +const MIB: u64 = 1024 * 1024; + +/// Runs after a run finished. Does nothing unless the run is a successful tag run and the workflow +/// at its commit asks for a release for this tag. Failures are logged and written to the job log; +/// they never fail the caller. +pub async fn on_run_finished(state: &AppState, run: &CiRun) { + if run.state != RunState::Success { + return; + } + let Some(tag) = run.git_ref.strip_prefix("refs/tags/") else { + return; + }; + let repo = match state.store.repo_by_id(&run.repo_id).await { + Ok(Some(repo)) => repo, + Ok(None) => return, + Err(e) => { + tracing::error!(error = %e, run_id = %run.id, "release: loading the repo failed"); + return; + } + }; + let Some(config) = schedule::config_at(state, &repo.id, &run.commit_oid).await else { + return; + }; + let Some(spec) = config + .release + .as_ref() + .filter(|_| config.wants_release(&Event::Tag { tag })) + else { + return; + }; + + let text = publish(state, &repo, run, tag, spec).await; + let jobs = match state.store.jobs_for_run(&run.id).await { + Ok(jobs) => jobs, + Err(e) => { + tracing::error!(error = %e, run_id = %run.id, "release: listing the jobs failed"); + return; + } + }; + if let Some(job) = jobs.iter().max_by(|a, b| a.finished_at.cmp(&b.finished_at)) { + note(state, job, &text).await; + } +} + +/// Creates or finds the release, attaches the selected artifacts, and describes the outcome. +async fn publish( + state: &AppState, + repo: &Repo, + run: &CiRun, + tag: &str, + spec: &ReleaseSpec, +) -> String { + let Some(actor) = actor_of(state, repo, run).await else { + return format!("Could not publish release {tag}: no user to publish as"); + }; + let release = match release_for(state, repo, run, tag, spec, &actor).await { + Ok(release) => release, + Err(reason) => return format!("Could not publish release {tag}: {reason}"), + }; + + let jobs = match state.store.jobs_for_run(&run.id).await { + Ok(jobs) => jobs, + Err(e) => { + tracing::error!(error = %e, run_id = %run.id, "release: listing the jobs failed"); + return format!("Could not publish release {tag}: could not list the jobs"); + } + }; + let max_bytes = state.config.releases.max_asset_mb.saturating_mul(MIB); + let mut attached = 0usize; + let mut failed: Vec = Vec::new(); + for job in &jobs { + let artifacts = match state.store.list_artifacts(&job.id).await { + Ok(artifacts) => artifacts, + Err(e) => { + tracing::error!(error = %e, job_id = %job.id, "release: listing artifacts failed"); + failed.push(format!("{}: could not list the artifacts", job.name)); + continue; + } + }; + for artifact in artifacts + .iter() + .filter(|a| spec.asset_matches(&job.name, &a.name)) + { + match attach( + state, + repo, + &release, + &actor, + &artifact.id, + &artifact.name, + max_bytes, + ) + .await + { + Ok(()) => attached += 1, + Err(reason) => { + tracing::error!(run_id = %run.id, tag, artifact = %artifact.name, %reason, "release: attaching an asset failed"); + failed.push(format!("{}: {reason}", artifact.name)); + } + } + } + } + + let mut text = format!("Published release {tag} with {attached} assets."); + if !failed.is_empty() { + text.push_str(&format!(" {} failed: {}.", failed.len(), failed.join(", "))); + } + text +} + +/// The person the release is made as: the run's actor, or the fallback of `status_creator`. +async fn actor_of(state: &AppState, repo: &Repo, run: &CiRun) -> Option { + let id = status_creator(state, repo, &run.actor_id).await?; + match state.store.user_by_id(&id).await { + Ok(user) => user, + Err(e) => { + tracing::error!(error = %e, run_id = %run.id, "release: loading the actor failed"); + None + } + } +} + +/// The existing release for `tag`, or a new one made from the spec. A release made by another run +/// in the meantime (a `Conflict`) is read back instead. +async fn release_for( + state: &AppState, + repo: &Repo, + run: &CiRun, + tag: &str, + spec: &ReleaseSpec, + actor: &User, +) -> Result { + match state.store.release_by_tag(&repo.id, tag).await { + Ok(Some(existing)) => return Ok(existing), + Ok(None) => {} + Err(e) => { + tracing::error!(error = %e, run_id = %run.id, "release: reading the release failed"); + return Err("could not read the release".to_owned()); + } + } + + let input = CreateRelease { + tag: tag.to_owned(), + target: Some(run.commit_oid.clone()), + title: spec.title_for(tag).chars().take(MAX_TITLE_CHARS).collect(), + body: notes(state, repo, run, tag, spec).await, + draft: spec.draft, + prerelease: spec.is_prerelease(tag), + }; + match release_ops::create(state, repo, actor, input).await { + Ok(release) => Ok(release), + Err(ReleaseError::Conflict(_)) => match state.store.release_by_tag(&repo.id, tag).await { + Ok(Some(existing)) => Ok(existing), + _ => Err("a release for this tag could not be made".to_owned()), + }, + Err(e) => { + tracing::error!(error = ?e, run_id = %run.id, tag, "release: creating the release failed"); + Err(e.message()) + } + } +} + +/// Stores one artifact as an asset of `release`, replacing an asset with the same name. +async fn attach( + state: &AppState, + repo: &Repo, + release: &Release, + actor: &User, + artifact_id: &str, + name: &str, + max_bytes: u64, +) -> Result<(), String> { + let read = match state.blobs.read(&artifact_key(artifact_id)).await { + Ok(Some(read)) => read, + Ok(None) => return Err("the file is missing from storage".to_owned()), + Err(e) => { + tracing::error!(error = %e, artifact_id, "release: reading an artifact failed"); + return Err("the file could not be read".to_owned()); + } + }; + release_ops::put_asset( + state, + repo, + release, + actor, + name, + None, + read.stream, + max_bytes, + ) + .await + .map(|_| ()) + .map_err(|e| { + tracing::error!(error = ?e, artifact_id, "release: storing an asset failed"); + e.message() + }) +} + +/// The notes for a new release, or an empty string when the spec turns them off. A git failure +/// leaves the notes empty and is logged; the release is still made. +async fn notes( + state: &AppState, + repo: &Repo, + run: &CiRun, + tag: &str, + spec: &ReleaseSpec, +) -> String { + if matches!(spec.notes, ReleaseNotes::Off) { + return String::new(); + } + match changelog(state, repo, run, tag).await { + Ok(text) => text, + Err(e) => { + tracing::error!(error = %e, run_id = %run.id, tag, "release: building the notes failed"); + String::new() + } + } +} + +/// The commit list since the previous release. The previous release is the newest other +/// published release whose target is an ancestor of this commit. Without one, it is the closest +/// git tag reachable from the commit. Without either, the list is capped at the newest commits. +async fn changelog( + state: &AppState, + repo: &Repo, + run: &CiRun, + tag: &str, +) -> Result { + let dir = repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?; + let env = &state.git; + + let releases = state + .store + .list_releases(&repo.id) + .await + .map_err(|e| e.to_string())?; + let mut previous: Option<(String, String)> = None; + for release in releases.iter().filter(|r| !r.draft && r.tag != tag) { + if is_ancestor(env, &dir, &release.target_oid, &run.commit_oid) + .await + .unwrap_or(false) + { + previous = Some((release.tag.clone(), release.target_oid.clone())); + break; + } + } + if previous.is_none() { + previous = previous_tag(env, &dir, &run.commit_oid) + .await + .map_err(|e| e.to_string())?; + } + + let commits = match &previous { + Some((_, base)) => { + let mut commits = range_log(env, &dir, base, &run.commit_oid, MAX_NOTE_COMMITS) + .await + .map_err(|e| e.to_string())?; + commits.reverse(); + commits + } + None => log(env, &dir, &run.commit_oid, None, 0, MAX_NOTE_COMMITS) + .await + .map_err(|e| e.to_string())?, + }; + let footer = previous + .as_ref() + .map(|(name, _)| format!("Full changelog: {name}...{tag}")); + Ok(bullets(&commits, footer.as_deref())) +} + +/// One `- subject (shortsha)` line per commit, newest first, then the footer. Commits that would +/// push the notes past the body limit are left out. +fn bullets(commits: &[CommitInfo], footer: Option<&str>) -> String { + let footer_len = footer.map_or(0, |f| f.chars().count() + 2); + let mut body = String::new(); + let mut used = 0usize; + for commit in commits { + let short = commit.oid.get(..7).unwrap_or(&commit.oid); + let line = format!("- {} ({short})\n", commit.summary); + let len = line.chars().count(); + if used + len + footer_len > MAX_BODY_CHARS { + break; + } + used += len; + body.push_str(&line); + } + let mut body = body.trim_end().to_owned(); + if let Some(footer) = footer { + if !body.is_empty() { + body.push_str("\n\n"); + } + body.push_str(footer); + } + body +} + +/// Appends one `[forge]` line to the log of `job`. Respects the log size cap. A failure is logged; +/// the outcome is not lost, it is also in the tracing output. +async fn note(state: &AppState, job: &CiJob, text: &str) { + let line = format!("[forge] {text}\n"); + let cap = state.config.ci.max_log_mb.saturating_mul(MIB); + let path = log_path(&state.config.data_dir, &job.id); + let current = match tokio::fs::metadata(&path).await { + Ok(meta) => meta.len(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, + Err(e) => { + tracing::error!(error = %e, job_id = %job.id, "release: reading the job log failed"); + return; + } + }; + let bytes = fit_to_cap(current, cap, line.as_bytes()); + if bytes.is_empty() { + return; + } + let written: std::io::Result<()> = async { + if let Some(parent) = path.parent() { + tokio::fs::create_dir_all(parent).await?; + } + let mut file = tokio::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .await?; + file.write_all(&bytes).await?; + file.flush().await + } + .await; + if let Err(e) = written { + tracing::error!(error = %e, job_id = %job.id, "release: writing the job log failed"); + return; + } + if let Err(e) = state.store.add_log_bytes(&job.id, bytes.len() as i64).await { + tracing::error!(error = %e, job_id = %job.id, "release: counting the job log bytes failed"); + return; + } + state.ci_live.bump_job(&job.id); +} + +#[cfg(test)] +mod tests { + use forge_core::ci::{CiArtifact, JobState}; + + use super::*; + use crate::ci::schedule::CONFIG_PATH; + use crate::ci::schedule::tests::{Fixture, ZERO, fixture, git, land, push}; + use crate::post_update::after_ref_update; + + /// A tag release workflow with two jobs. Only `build` feeds the release, through `dist_*`. + const RELEASE: &str = r#" +[on] +push = ["main"] +tags = ["v*"] + +[jobs.build] +image = "alpine:3" +run = "make" +artifacts = ["dist/*"] + +[jobs.docs] +image = "alpine:3" +run = "make docs" +artifacts = ["site/*"] + +[release] +assets = ["build:dist_*"] +title = "forge {tag}" +"#; + + /// Finishes the jobs of `run_id` in order. The job named `failing` fails; the others succeed. + async fn finish_all(fx: &Fixture, run_id: &str, failing: Option<&str>) { + loop { + let jobs = fx.state.store.jobs_for_run(run_id).await.expect("jobs"); + let Some(job) = jobs.iter().find(|j| !j.state.is_terminal()) else { + break; + }; + let fails = failing == Some(job.name.as_str()); + let (outcome, code) = if fails { + (JobState::Failure, 1) + } else { + (JobState::Success, 0) + }; + fx.state + .store + .finish_job(&job.id, outcome, Some(code), None) + .await + .expect("finish"); + } + } + + async fn run_of(fx: &Fixture, number: i64) -> CiRun { + fx.state + .store + .run_by_number(&fx.repo.id, number) + .await + .expect("query") + .expect("run") + } + + async fn job_of(fx: &Fixture, run: &CiRun, name: &str) -> CiJob { + fx.state + .store + .jobs_for_run(&run.id) + .await + .expect("jobs") + .into_iter() + .find(|j| j.name == name) + .expect("job") + } + + /// Stores `body` as an artifact of `job`, the way the upload handler does. + async fn add_artifact(fx: &Fixture, job: &CiJob, name: &str, body: &[u8]) -> CiArtifact { + let tmp = format!("ci/tmp/{}", ulid::Ulid::generate()); + let mut writer = fx.state.blobs.begin(&tmp, 1 << 30).await.expect("begin"); + writer.push(body).await.expect("push"); + let (size, sha) = writer.finish().await.expect("finish"); + let artifact = fx + .state + .store + .add_artifact(&job.id, name, size as i64, &sha) + .await + .expect("artifact"); + fx.state + .blobs + .rename(&tmp, &artifact_key(&artifact.id)) + .await + .expect("rename"); + artifact + } + + /// Commits an empty change with `message` and returns the commit. + fn commit_message(work: &std::path::Path, message: &str) -> String { + git(work, &["commit", "--allow-empty", "-m", message]); + git(work, &["rev-parse", "HEAD"]) + } + + async fn release_named(fx: &Fixture, tag: &str) -> Option { + fx.state + .store + .release_by_tag(&fx.repo.id, tag) + .await + .expect("query") + } + + async fn asset_names(fx: &Fixture, release: &Release) -> Vec<(String, u64)> { + let mut assets: Vec<(String, u64)> = fx + .state + .store + .list_release_assets(&release.id) + .await + .expect("assets") + .into_iter() + .map(|a| (a.name, a.size)) + .collect(); + assets.sort(); + assets + } + + #[tokio::test] + async fn tag_run_publishes_release_with_matching_assets() { + let fx = fixture().await; + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; + let run = run_of(&fx, 1).await; + let build = job_of(&fx, &run, "build").await; + let docs = job_of(&fx, &run, "docs").await; + add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await; + add_artifact(&fx, &build, "dist_SHA256SUMS", b"sums").await; + add_artifact(&fx, &docs, "dist_docs-only", b"x").await; + add_artifact(&fx, &docs, "site_index.html", b"").await; + finish_all(&fx, &run.id, None).await; + let run = run_of(&fx, 1).await; + assert_eq!(run.state, RunState::Success); + + on_run_finished(&fx.state, &run).await; + + let release = release_named(&fx, "v1.0").await.expect("release made"); + assert_eq!(release.title, "forge v1.0"); + assert_eq!(release.target_oid, run.commit_oid); + assert!(!release.draft); + assert!(!release.prerelease); + assert_eq!(release.author_id, fx.owner.id); + assert_eq!( + asset_names(&fx, &release).await, + vec![ + ("dist_SHA256SUMS".to_owned(), 4), + ("dist_forge-linux-x86_64".to_owned(), 6), + ], + "only build's dist_* artifacts are attached" + ); + + let mut log_text = String::new(); + for job in fx.state.store.jobs_for_run(&run.id).await.expect("jobs") { + let path = crate::ci::log_path(&fx.state.config.data_dir, &job.id); + if let Ok(text) = std::fs::read_to_string(path) { + log_text.push_str(&text); + } + } + assert!(log_text.contains("[forge] Published release v1.0 with 2 assets.")); + } + + #[tokio::test] + async fn notes_list_commits_since_the_previous_release() { + let fx = fixture().await; + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; + finish_all(&fx, &run_of(&fx, 1).await.id, None).await; + on_run_finished(&fx.state, &run_of(&fx, 1).await).await; + + commit_message(&fx.work, "feat: one"); + let oid = commit_message(&fx.work, "fix: two"); + land(&fx, &oid, "refs/tags/v1.1"); + after_ref_update( + &fx.state, + &fx.repo, + &fx.owner.id, + "refs/tags/v1.1", + ZERO, + &oid, + ) + .await + .expect("post update"); + finish_all(&fx, &run_of(&fx, 2).await.id, None).await; + on_run_finished(&fx.state, &run_of(&fx, 2).await).await; + + let release = release_named(&fx, "v1.1").await.expect("release made"); + let short = &oid[..7]; + assert!( + release + .body + .starts_with(&format!("- fix: two ({short})\n- feat: one (")) + ); + assert!(release.body.ends_with("Full changelog: v1.0...v1.1")); + assert!( + !release.body.contains("- change ("), + "older commits are not repeated" + ); + } + + #[tokio::test] + async fn existing_manual_release_keeps_its_fields_and_gets_assets() { + let fx = fixture().await; + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; + let run = run_of(&fx, 1).await; + let manual = release_ops::create( + &fx.state, + &fx.repo, + &fx.owner, + CreateRelease { + tag: "v1.0".to_owned(), + target: None, + title: "Hand made".to_owned(), + body: "Keep me".to_owned(), + draft: true, + prerelease: true, + }, + ) + .await + .expect("manual release"); + let build = job_of(&fx, &run, "build").await; + add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await; + finish_all(&fx, &run.id, None).await; + + on_run_finished(&fx.state, &run_of(&fx, 1).await).await; + + let release = release_named(&fx, "v1.0").await.expect("release"); + assert_eq!(release.id, manual.id); + assert_eq!(release.title, "Hand made"); + assert_eq!(release.body, "Keep me"); + assert!(release.draft); + assert!(release.prerelease); + assert_eq!(asset_names(&fx, &release).await.len(), 1); + } + + #[tokio::test] + async fn failed_run_creates_no_release() { + let fx = fixture().await; + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; + let run = run_of(&fx, 1).await; + let build = job_of(&fx, &run, "build").await; + add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await; + finish_all(&fx, &run.id, Some("docs")).await; + let run = run_of(&fx, 1).await; + assert_eq!(run.state, RunState::Failure); + + on_run_finished(&fx.state, &run).await; + + assert!(release_named(&fx, "v1.0").await.is_none()); + } + + #[tokio::test] + async fn branch_push_run_creates_no_release() { + let fx = fixture().await; + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/heads/main").await; + let run = run_of(&fx, 1).await; + finish_all(&fx, &run.id, None).await; + + on_run_finished(&fx.state, &run_of(&fx, 1).await).await; + + assert!(release_named(&fx, "v1.0").await.is_none()); + assert!(release_named(&fx, "main").await.is_none()); + } + + #[tokio::test] + async fn rerun_replaces_assets_by_name() { + let fx = fixture().await; + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; + let first = run_of(&fx, 1).await; + let build = job_of(&fx, &first, "build").await; + add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"one").await; + finish_all(&fx, &first.id, None).await; + on_run_finished(&fx.state, &run_of(&fx, 1).await).await; + + let second = fx + .state + .store + .rerun(&first.id, &fx.owner.id) + .await + .expect("rerun"); + let build = job_of(&fx, &second, "build").await; + add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"second!").await; + finish_all(&fx, &second.id, None).await; + on_run_finished(&fx.state, &run_of(&fx, 2).await).await; + + let release = release_named(&fx, "v1.0").await.expect("release"); + assert_eq!( + asset_names(&fx, &release).await, + vec![("dist_forge-linux-x86_64".to_owned(), 7)] + ); + } + + /// No release exists for the earlier tag, so the notes start from the closest git tag. + #[tokio::test] + async fn notes_fall_back_to_the_previous_git_tag() { + let fx = fixture().await; + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; + commit_message(&fx.work, "feat: one"); + let oid = commit_message(&fx.work, "fix: two"); + land(&fx, &oid, "refs/tags/v1.1"); + after_ref_update(&fx.state, &fx.repo, &fx.owner.id, "refs/tags/v1.1", ZERO, &oid) + .await + .expect("post update"); + finish_all(&fx, &run_of(&fx, 2).await.id, None).await; + on_run_finished(&fx.state, &run_of(&fx, 2).await).await; + + let release = release_named(&fx, "v1.1").await.expect("release made"); + assert!(release.body.starts_with("- fix: two (")); + assert!(release.body.contains("- feat: one (")); + assert!(release.body.ends_with("Full changelog: v1.0...v1.1")); + assert!(release_named(&fx, "v1.0").await.is_none()); + } + + #[test] + fn bullets_put_the_footer_last_and_respect_the_limit() { + let commit = |oid: &str, summary: &str| CommitInfo { + oid: oid.to_owned(), + parents: Vec::new(), + author_name: String::new(), + author_email: String::new(), + author_time: 0, + committer_name: String::new(), + committer_email: String::new(), + committer_time: 0, + summary: summary.to_owned(), + message: String::new(), + }; + let commits = vec![ + commit("abcdef1234567", "new"), + commit("1234567abcdef", "old"), + ]; + assert_eq!( + bullets(&commits, Some("Full changelog: a...b")), + "- new (abcdef1)\n- old (1234567)\n\nFull changelog: a...b" + ); + assert_eq!(bullets(&[], None), ""); + } +} diff --git a/crates/forge-web/src/ci/schedule.rs b/crates/forge-web/src/ci/schedule.rs index f8e6fe6..9a174da 100644 --- a/crates/forge-web/src/ci/schedule.rs +++ b/crates/forge-web/src/ci/schedule.rs @@ -284,6 +284,15 @@ fn plan_jobs(cfg: &CiConfig) -> forge_core::Result> { } /// Reads and parses `.forge/ci.toml` at `commit` from the repo `repo_id`. +/// The workflow at `commit`, when it is a valid file. Used by the release hook, which reads the +/// config the run itself was made from. +pub(super) async fn config_at(state: &AppState, repo_id: &str, commit: &str) -> Option { + match load(state, repo_id, commit).await { + Loaded::Valid(config) => Some(config), + Loaded::Missing | Loaded::Invalid(_) => None, + } +} + async fn load(state: &AppState, repo_id: &str, commit: &str) -> Loaded { let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, repo_id) { Ok(path) => path, @@ -368,7 +377,7 @@ where } #[cfg(test)] -mod tests { +pub(super) mod tests { use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; @@ -386,7 +395,7 @@ mod tests { use crate::post_update::after_ref_update; use crate::test_support::test_state; - const ZERO: &str = "0000000000000000000000000000000000000000"; + pub(in crate::ci) const ZERO: &str = "0000000000000000000000000000000000000000"; const CONFIG: &str = r#" [on] @@ -412,7 +421,7 @@ image = "alpine:3" run = "make" "#; - const CONFIG_TAGS: &str = r#" + pub(in crate::ci) const CONFIG_TAGS: &str = r#" [on] push = [] tags = ["v*"] @@ -441,7 +450,7 @@ image = "alpine:3" run = "make" "#; - fn git(dir: &Path, args: &[&str]) -> String { + pub(in crate::ci) fn git(dir: &Path, args: &[&str]) -> String { let out = std::process::Command::new("git") .arg("-C") .arg(dir) @@ -460,16 +469,16 @@ run = "make" String::from_utf8_lossy(&out.stdout).trim().to_string() } - struct Fixture { - _tmp: TempDir, - state: AppState, - repo: Repo, - owner: User, - bare: PathBuf, - work: PathBuf, + pub(in crate::ci) struct Fixture { + pub(in crate::ci) _tmp: TempDir, + pub(in crate::ci) state: AppState, + pub(in crate::ci) repo: Repo, + pub(in crate::ci) owner: User, + pub(in crate::ci) bare: PathBuf, + pub(in crate::ci) work: PathBuf, } - async fn fixture() -> Fixture { + pub(in crate::ci) async fn fixture() -> Fixture { let tmp = tempfile::tempdir().expect("tempdir"); let state = test_state(tmp.path()).await; let owner = state @@ -499,7 +508,7 @@ run = "make" } /// Commits `files` in the work tree and returns the new commit. - fn commit(work: &Path, files: &[(&str, &str)]) -> String { + pub(in crate::ci) fn commit(work: &Path, files: &[(&str, &str)]) -> String { for (path, text) in files { let full = work.join(path); if let Some(parent) = full.parent() { @@ -513,7 +522,7 @@ run = "make" } /// Makes `oid` the tip of `refname` in the bare repo. Fetch runs no hooks, unlike a push. - fn land(fx: &Fixture, oid: &str, refname: &str) { + pub(in crate::ci) fn land(fx: &Fixture, oid: &str, refname: &str) { let work = fx.work.to_str().expect("utf8 path"); git( &fx.bare, @@ -522,7 +531,7 @@ run = "make" } /// Commits `files`, lands them on `refname`, and runs the post-update hook for the update. - async fn push(fx: &Fixture, files: &[(&str, &str)], refname: &str) -> String { + pub(in crate::ci) async fn push(fx: &Fixture, files: &[(&str, &str)], refname: &str) -> String { let oid = commit(&fx.work, files); land(fx, &oid, refname); after_ref_update(&fx.state, &fx.repo, &fx.owner.id, refname, ZERO, &oid) @@ -539,7 +548,7 @@ run = "make" jobs.iter().find(|j| j.name == name).map(|j| j.state) } - async fn runs_total(fx: &Fixture) -> u64 { + pub(in crate::ci) async fn runs_total(fx: &Fixture) -> u64 { fx.state .store .list_runs(&fx.repo.id, 1, 50) diff --git a/crates/forge-web/src/i18n/releases_ci.rs b/crates/forge-web/src/i18n/releases_ci.rs index 6b3b8c1..cccbf2c 100644 --- a/crates/forge-web/src/i18n/releases_ci.rs +++ b/crates/forge-web/src/i18n/releases_ci.rs @@ -67,6 +67,7 @@ pub enum K { RelSaved, RelDeleted, RelAssetUploaded, + RelAssetReplaced, RelAssetDeleted, RelAssetTooLarge, RelAssetExists, @@ -79,7 +80,6 @@ pub enum K { // Release form errors. RelErrTagName, RelErrReleaseExists, - RelErrChooseBranch, // Release pages. Releases, @@ -112,6 +112,12 @@ pub enum K { UploadAsset, DeleteReleaseHelp, YesDeleteRelease, + EditTagHelp, + EditTargetLabel, + CurrentCommit, + TargetMoveHelp, + TargetLockedHelp, + ReplaceAsset, } pub fn t(lang: Lang, key: K) -> &'static str { @@ -239,6 +245,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (RelDeleted, Tr) => "Sรผrรผm silindi. Etiket korundu.", (RelAssetUploaded, En) => "Asset uploaded.", (RelAssetUploaded, Tr) => "Dosya yรผklendi.", + (RelAssetReplaced, En) => "Asset replaced. Downloads now serve the new file.", + (RelAssetReplaced, Tr) => "Dosya deฤŸiลŸtirildi. ฤฐndirmeler artฤฑk yeni dosyayฤฑ sunar.", (RelAssetDeleted, En) => "Asset deleted.", (RelAssetDeleted, Tr) => "Dosya silindi.", (RelAssetTooLarge, En) => { @@ -286,8 +294,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { (RelErrReleaseExists, Tr) => { "Bu etiket iรงin zaten bir sรผrรผm var. Bunun yerine o sรผrรผmรผ dรผzenleyin." } - (RelErrChooseBranch, En) => "Choose a branch to create the tag on.", - (RelErrChooseBranch, Tr) => "Etiketin oluลŸturulacaฤŸฤฑ bir dal seรงin.", (Releases, En) => "Releases", (Releases, Tr) => "Sรผrรผmler", @@ -355,6 +361,26 @@ pub fn t(lang: Lang, key: K) -> &'static str { (DeleteReleaseHelp, Tr) => "Sรผrรผmรผ ve dosyalarฤฑnฤฑ siler. Git etiketi korunur.", (YesDeleteRelease, En) => "Yes, delete this release", (YesDeleteRelease, Tr) => "Evet, bu sรผrรผmรผ sil", + (EditTagHelp, En) => { + "Enter a new name to create the tag at the target you pick, or at the current commit. Enter an existing tag name to adopt it; if you also pick a target, it must be that tag's commit." + } + (EditTagHelp, Tr) => { + "Yeni bir ad girerek etiketi seรงtiฤŸiniz dalda ya da mevcut commit'te oluลŸturun. Var olan bir etiket adฤฑ girerseniz o etiket kullanฤฑlฤฑr; hedef de seรงtiyseniz o etiketin commit'i olmalฤฑdฤฑr." + } + (EditTargetLabel, En) => "Move tag to branch (optional)", + (EditTargetLabel, Tr) => "Etiketi dala taลŸฤฑ (isteฤŸe baฤŸlฤฑ)", + (CurrentCommit, En) => "Keep the current commit", + (CurrentCommit, Tr) => "Mevcut commit'i koru", + (TargetMoveHelp, En) => "The tag can only move while the release is a draft.", + (TargetMoveHelp, Tr) => "Etiket yalnฤฑzca sรผrรผm taslakken taลŸฤฑnabilir.", + (TargetLockedHelp, En) => { + "Published releases keep their commit. To point at another commit, enter a new tag." + } + (TargetLockedHelp, Tr) => { + "YayฤฑmlanmฤฑลŸ sรผrรผmler commit'lerini korur. BaลŸka bir commit'i gรถstermek iรงin yeni bir etiket girin." + } + (ReplaceAsset, En) => "Replace", + (ReplaceAsset, Tr) => "DeฤŸiลŸtir", } } @@ -496,6 +522,7 @@ mod tests { K::RelSaved, K::RelDeleted, K::RelAssetUploaded, + K::RelAssetReplaced, K::RelAssetDeleted, K::RelAssetTooLarge, K::RelAssetExists, @@ -506,7 +533,6 @@ mod tests { K::RelAssetEmpty, K::RelErrTagName, K::RelErrReleaseExists, - K::RelErrChooseBranch, K::Releases, K::NewRelease, K::EditRelease, @@ -537,6 +563,12 @@ mod tests { K::UploadAsset, K::DeleteReleaseHelp, K::YesDeleteRelease, + K::EditTagHelp, + K::EditTargetLabel, + K::CurrentCommit, + K::TargetMoveHelp, + K::TargetLockedHelp, + K::ReplaceAsset, ]; #[test] diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index a6ce3da..c17b530 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -37,6 +37,7 @@ mod pages; mod post_update; mod pulls_sync; mod raw; +mod release_ops; mod render; mod replication; mod self_update; diff --git a/crates/forge-web/src/pages/releases.rs b/crates/forge-web/src/pages/releases.rs index 74a180d..e9ebed7 100644 --- a/crates/forge-web/src/pages/releases.rs +++ b/crates/forge-web/src/pages/releases.rs @@ -4,17 +4,16 @@ //! //! A release names a git tag. When the tag does not exist yet it is created as a lightweight tag //! at the head of the chosen branch, through `after_ref_update`. Deleting a release keeps the tag. -//! Asset bytes are streamed to and from the blob store (see `blobs.rs`). Downloads are served as +//! Asset bytes are streamed to and from the blob store (see `blobs.rs`). An upload under a name the +//! release already has replaces that asset in place; the edit page offers this as a Replace control. Downloads are served as //! attachments with `nosniff`, and each completed start counts one download. use forge_core::releases::{ - MAX_BODY_CHARS, MAX_TITLE_CHARS, NewAsset, NewRelease, Release, ReleaseAsset, ReleaseEdit, - clean_content_type, valid_asset_name, + MAX_BODY_CHARS, MAX_TITLE_CHARS, Release, ReleaseAsset, valid_asset_name, }; -use forge_core::webhooks::WebhookEvent; use forge_core::{Action, Denied, Repo as CoreRepo, User, authorize}; use forge_git::browse::RefKind; -use forge_git::tags::{create_lightweight_tag, valid_tag_name}; +use forge_git::tags::valid_tag_name; use futures_util::TryStreamExt; use http::header::{CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_TYPE}; use http_body::Frame; @@ -30,7 +29,7 @@ use topcoat::router::{Body, HeaderName, HeaderValue, StatusCode, page, path_para use topcoat::view::{Unescaped, View, component, view}; use crate::auth::require_csrf; -use crate::blobs::{BlobWriter, asset_key}; +use crate::blobs::asset_key; use crate::i18n::{ self, Key, Lang, releases_ci::{self as g, K}, @@ -39,11 +38,10 @@ use crate::pages::refs::load_refs; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; use crate::pages::repo_mirrors::stamp_in_tz; -use crate::post_update::after_ref_update; +use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError}; use crate::render::markdown::render_markdown; use crate::state::AppState; -use crate::views::{alert, enc, shell, user_facing_message, user_link}; -use crate::webhooks::emit::{Sender, emit}; +use crate::views::{alert, enc, shell, user_link}; path_param!(owner); path_param!(repo); @@ -54,16 +52,13 @@ path_param!(name); /// Multipart framing allowed on top of the file itself when checking `Content-Length`. const MULTIPART_OVERHEAD: u64 = 64 * 1024; -/// The all-zero object id that means "no ref yet" in ref updates. -fn zero_oid(len: usize) -> String { - "0".repeat(len) -} /// Notice words (the only text a `?notice=` query can show), their text and whether they are errors. -const NOTICES: [(&str, K, bool); 11] = [ +const NOTICES: [(&str, K, bool); 12] = [ ("saved", K::RelSaved, false), ("deleted", K::RelDeleted, false), ("asset-uploaded", K::RelAssetUploaded, false), + ("asset-replaced", K::RelAssetReplaced, false), ("asset-deleted", K::RelAssetDeleted, false), ("asset-too-large", K::RelAssetTooLarge, true), ("asset-exists", K::RelAssetExists, true), @@ -286,12 +281,16 @@ struct CreateForm { draft: Option, } -/// The edit-release form fields. +/// The edit-release form fields. `tag` and `target` are the optional retag fields. #[derive(Deserialize)] struct EditForm { #[serde(default)] csrf: String, #[serde(default)] + tag: String, + #[serde(default)] + target: String, + #[serde(default)] title: String, #[serde(default)] body: String, @@ -342,11 +341,13 @@ async fn release_form( csrf: String, lang: Lang, is_new: bool, + move_target: bool, draft: FormDraft, branches: Vec, submit: &'static str, ) -> Result { let tag_hint = g::t(lang, K::TagHint); + let edit_tag_help = g::t(lang, K::EditTagHelp); Ok(view! {
if let Some(message) = draft.error { @@ -368,7 +369,25 @@ async fn release_form( } else { -

(g::t(lang, K::Tag)) ": " (draft.tag.as_str())

+ +

(edit_tag_help)

+ if move_target { + +

(g::t(lang, K::TargetMoveHelp))

+ } else { +

(g::t(lang, K::TargetLockedHelp))

+ } }