CI auto-releases, releases REST API, asset replace, retag, R2/S3 storage
Browse files at this commit51b2bbf0cf834e6d5e45fdae8b5bd2c4ed34bdb7Parent: 9261c0f- feat
- CI auto-releases, releases REST API, asset replace, retag, R2/S3 storage
28 changed files +4543 -341
- Cargo.lock +53 -2
- Cargo.toml +1 -1
- config/forge.example.toml +39 -0
- crates/forge-ci/src/config.rs +391 -0
- crates/forge-ci/src/error.rs +12 -0
- crates/forge-core/src/config.rs +401 -1
- crates/forge-core/src/releases.rs +1 -1
- crates/forge-core/src/store/releases.rs +146 -1
- crates/forge-git/src/tags.rs +80 -0
- crates/forge-web/src/api/mod.rs +1 -0
- crates/forge-web/src/api/releases.rs +884 -0
- crates/forge-web/src/blobs.rs +204 -4
- crates/forge-web/src/boot.rs +2 -1
- crates/forge-web/src/ci/api.rs +6 -1
- crates/forge-web/src/ci/mod.rs +1 -0
- crates/forge-web/src/ci/release.rs +705 -0
- crates/forge-web/src/ci/schedule.rs +25 -16
- crates/forge-web/src/i18n/releases_ci.rs +36 -4
- crates/forge-web/src/main.rs +1 -0
- crates/forge-web/src/pages/releases.rs +281 -306
- crates/forge-web/src/pages/releases_tests.rs +470 -1
- crates/forge-web/src/pages/settings_security.rs +1 -0
- crates/forge-web/src/release_ops.rs +527 -0
- crates/forge-web/src/test_support.rs +1 -0
- docs/api.md +169 -1
- docs/backup.md +21 -1
- docs/ci.md +75 -0
- style/main.scss +9 -0
Cargo.lockmodified+53 -2
| @@ -1011,6 +1011,16 @@ dependencies = [ | |||
| 1011 | "libc", | 1011 | "libc", |
| 1012 | ] | 1012 | ] |
| 1013 | 1013 | ||
| 1014 | +[[package]] | ||
| 1015 | +name = "crc-fast" | ||
| 1016 | +version = "1.10.0" | ||
| 1017 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1018 | +checksum = "e75b2483e97a5a7da73ac68a05b629f9c53cff58d8ed1c77866079e18b00dba5" | ||
| 1019 | +dependencies = [ | ||
| 1020 | + "digest 0.10.7", | ||
| 1021 | + "spin 0.10.1", | ||
| 1022 | +] | ||
| 1023 | + | ||
| 1014 | [[package]] | 1024 | [[package]] |
| 1015 | name = "crc32c" | 1025 | name = "crc32c" |
| 1016 | version = "0.6.8" | 1026 | version = "0.6.8" |
| @@ -4157,6 +4167,16 @@ version = "0.9.2" | |||
| 4157 | source = "registry+https://github.com/rust-lang/crates.io-index" | 4167 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 4158 | checksum = "8863b587001c1b9a8a4e36008cebc6b3612cb1226fe2de94858e06092687b608" | 4168 | checksum = "8863b587001c1b9a8a4e36008cebc6b3612cb1226fe2de94858e06092687b608" |
| 4159 | 4169 | ||
| 4170 | +[[package]] | ||
| 4171 | +name = "md-5" | ||
| 4172 | +version = "0.11.0" | ||
| 4173 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4174 | +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" | ||
| 4175 | +dependencies = [ | ||
| 4176 | + "cfg-if", | ||
| 4177 | + "digest 0.11.3", | ||
| 4178 | +] | ||
| 4179 | + | ||
| 4160 | [[package]] | 4180 | [[package]] |
| 4161 | name = "md5" | 4181 | name = "md5" |
| 4162 | version = "0.8.1" | 4182 | version = "0.8.1" |
| @@ -4328,7 +4348,7 @@ dependencies = [ | |||
| 4328 | "httparse", | 4348 | "httparse", |
| 4329 | "memchr", | 4349 | "memchr", |
| 4330 | "mime", | 4350 | "mime", |
| 4331 | - "spin", | 4351 | + "spin 0.9.9", |
| 4332 | "version_check", | 4352 | "version_check", |
| 4333 | ] | 4353 | ] |
| 4334 | 4354 | ||
| @@ -4503,17 +4523,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 4503 | checksum = "f1796bc93603f78c5760a69f2d58badc9618d22adade0a95385bb2adbae4eb94" | 4523 | checksum = "f1796bc93603f78c5760a69f2d58badc9618d22adade0a95385bb2adbae4eb94" |
| 4504 | dependencies = [ | 4524 | dependencies = [ |
| 4505 | "async-trait", | 4525 | "async-trait", |
| 4526 | + "aws-lc-rs", | ||
| 4527 | + "base64 0.23.1", | ||
| 4506 | "bytes", | 4528 | "bytes", |
| 4507 | "chrono", | 4529 | "chrono", |
| 4530 | + "crc-fast", | ||
| 4531 | + "form_urlencoded", | ||
| 4508 | "futures-channel", | 4532 | "futures-channel", |
| 4509 | "futures-core", | 4533 | "futures-core", |
| 4510 | "futures-util", | 4534 | "futures-util", |
| 4511 | "http", | 4535 | "http", |
| 4536 | + "http-body-util", | ||
| 4512 | "humantime", | 4537 | "humantime", |
| 4538 | + "hyper", | ||
| 4513 | "itertools 0.15.0", | 4539 | "itertools 0.15.0", |
| 4540 | + "md-5", | ||
| 4514 | "nix 0.31.3", | 4541 | "nix 0.31.3", |
| 4515 | "parking_lot", | 4542 | "parking_lot", |
| 4516 | "percent-encoding", | 4543 | "percent-encoding", |
| 4544 | + "quick-xml 0.41.0", | ||
| 4545 | + "rand 0.10.3", | ||
| 4546 | + "reqwest", | ||
| 4547 | + "rustls-pki-types", | ||
| 4548 | + "serde", | ||
| 4549 | + "serde_json", | ||
| 4550 | + "serde_urlencoded", | ||
| 4517 | "thiserror 2.0.21", | 4551 | "thiserror 2.0.21", |
| 4518 | "tokio", | 4552 | "tokio", |
| 4519 | "tracing", | 4553 | "tracing", |
| @@ -5016,7 +5050,7 @@ checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb" | |||
| 5016 | dependencies = [ | 5050 | dependencies = [ |
| 5017 | "base64 0.23.1", | 5051 | "base64 0.23.1", |
| 5018 | "indexmap", | 5052 | "indexmap", |
| 5019 | - "quick-xml", | 5053 | + "quick-xml 0.42.0", |
| 5020 | "serde", | 5054 | "serde", |
| 5021 | "time", | 5055 | "time", |
| 5022 | ] | 5056 | ] |
| @@ -5324,6 +5358,16 @@ version = "2.0.1" | |||
| 5324 | source = "registry+https://github.com/rust-lang/crates.io-index" | 5358 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 5325 | checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" | 5359 | checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" |
| 5326 | 5360 | ||
| 5361 | +[[package]] | ||
| 5362 | +name = "quick-xml" | ||
| 5363 | +version = "0.41.0" | ||
| 5364 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5365 | +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" | ||
| 5366 | +dependencies = [ | ||
| 5367 | + "memchr", | ||
| 5368 | + "serde", | ||
| 5369 | +] | ||
| 5370 | + | ||
| 5327 | [[package]] | 5371 | [[package]] |
| 5328 | name = "quick-xml" | 5372 | name = "quick-xml" |
| 5329 | version = "0.42.0" | 5373 | version = "0.42.0" |
| @@ -5614,6 +5658,7 @@ dependencies = [ | |||
| 5614 | "bytes", | 5658 | "bytes", |
| 5615 | "futures-core", | 5659 | "futures-core", |
| 5616 | "futures-util", | 5660 | "futures-util", |
| 5661 | + "h2", | ||
| 5617 | "http", | 5662 | "http", |
| 5618 | "http-body", | 5663 | "http-body", |
| 5619 | "http-body-util", | 5664 | "http-body-util", |
| @@ -6458,6 +6503,12 @@ version = "0.9.9" | |||
| 6458 | source = "registry+https://github.com/rust-lang/crates.io-index" | 6503 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 6459 | checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" | 6504 | checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" |
| 6460 | 6505 | ||
| 6506 | +[[package]] | ||
| 6507 | +name = "spin" | ||
| 6508 | +version = "0.10.1" | ||
| 6509 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 6510 | +checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" | ||
| 6511 | + | ||
| 6461 | [[package]] | 6512 | [[package]] |
| 6462 | name = "spki" | 6513 | name = "spki" |
| 6463 | version = "0.8.1" | 6514 | version = "0.8.1" |
Cargo.tomlmodified+1 -1
| @@ -68,7 +68,7 @@ chacha20poly1305 = "0.11.0" | |||
| 68 | 68 | ||
| 69 | # storage | 69 | # storage |
| 70 | turso = "0.8.3" | 70 | turso = "0.8.3" |
| 71 | -object_store = { version = "0.14.2", default-features = false, features = ["fs"] } | 71 | +object_store = { version = "0.14.2", default-features = false, features = ["fs", "aws"] } |
| 72 | multer = "3.1.0" | 72 | multer = "3.1.0" |
| 73 | 73 | ||
| 74 | # outgoing mail (forge-web): SMTP over rustls, no native TLS | 74 | # outgoing mail (forge-web): SMTP over rustls, no native TLS |
config/forge.example.tomlmodified+39 -0
| @@ -52,6 +52,45 @@ trusted_proxies = [] | |||
| 52 | # Largest accepted release asset, in MiB. | 52 | # Largest accepted release asset, in MiB. |
| 53 | # max_asset_mb = 512 | 53 | # max_asset_mb = 512 |
| 54 | 54 | ||
| 55 | +# Where release assets and CI artifacts are stored (see docs/backup.md, "Blob storage backends"). | ||
| 56 | +# [storage] | ||
| 57 | +# "fs" keeps blobs under <data_dir>/blobs (the default). "r2" stores them in a Cloudflare R2 bucket, | ||
| 58 | +# the recommended off-host option. "s3" stores them in any other S3-compatible bucket (AWS, MinIO, Garage). | ||
| 59 | +# backend = "fs" | ||
| 60 | +# [storage.r2] | ||
| 61 | +# Only read when backend = "r2". account_id, bucket, access_key_id and secret_access_key_file are required. | ||
| 62 | +# The endpoint is derived from account_id, so there is no endpoint or region to set. | ||
| 63 | +# Cloudflare account id, the 32-character hex string from the dashboard. | ||
| 64 | +# account_id = "0123456789abcdef0123456789abcdef" | ||
| 65 | +# Name of the R2 bucket that holds the blobs. | ||
| 66 | +# bucket = "forge-blobs" | ||
| 67 | +# Jurisdiction the bucket was created in: "eu", "fedramp", or empty for the global default. | ||
| 68 | +# jurisdiction = "" | ||
| 69 | +# Key prefix inside the bucket. Empty stores keys at the bucket root. | ||
| 70 | +# prefix = "" | ||
| 71 | +# Access key id of an R2 API token with object read and write on this bucket. | ||
| 72 | +# access_key_id = "forge" | ||
| 73 | +# File holding the token's secret access key, mode 0600. Its contents are trimmed. | ||
| 74 | +# secret_access_key_file = "/etc/forge/r2-secret" | ||
| 75 | +# [storage.s3] | ||
| 76 | +# Only read when backend = "s3". Bucket, region, access_key_id and secret_access_key_file are required. | ||
| 77 | +# Name of the bucket that holds the blobs. | ||
| 78 | +# bucket = "forge-blobs" | ||
| 79 | +# Signing region, such as "eu-central-1". MinIO and Garage accept any value. | ||
| 80 | +# region = "us-east-1" | ||
| 81 | +# Full URL of a non-AWS endpoint. Empty uses AWS. | ||
| 82 | +# endpoint = "https://minio.internal:9000" | ||
| 83 | +# Key prefix inside the bucket. Empty stores keys at the bucket root. | ||
| 84 | +# prefix = "" | ||
| 85 | +# Access key id. | ||
| 86 | +# access_key_id = "forge" | ||
| 87 | +# File holding the secret access key, mode 0600. Its contents are trimmed. | ||
| 88 | +# secret_access_key_file = "/etc/forge/s3-secret" | ||
| 89 | +# Permit an http:// endpoint. Only for a store on a trusted private network. | ||
| 90 | +# allow_http = false | ||
| 91 | +# Use bucket.host addressing instead of host/bucket. Off suits MinIO, Garage and most self-hosted stores. | ||
| 92 | +# virtual_hosted_style = false | ||
| 93 | + | ||
| 55 | # Standby replication (see docs/backup.md). Empty target disables it. When target is set, | 94 | # Standby replication (see docs/backup.md). Empty target disables it. When target is set, |
| 56 | # identity_file and known_hosts_file are required. | 95 | # identity_file and known_hosts_file are required. |
| 57 | # [replication] | 96 | # [replication] |
crates/forge-ci/src/config.rsmodified+391 -0
| @@ -33,6 +33,10 @@ pub const MAX_WORKFLOW_NAME_CHARS: usize = 40; | |||
| 33 | pub const MAX_CACHE_ENTRIES: usize = 8; | 33 | pub const MAX_CACHE_ENTRIES: usize = 8; |
| 34 | /// Longest `cache` entry, in characters. | 34 | /// Longest `cache` entry, in characters. |
| 35 | pub const MAX_CACHE_PATH_CHARS: usize = 200; | 35 | pub const MAX_CACHE_PATH_CHARS: usize = 200; |
| 36 | +/// Largest number of `[release] assets` entries. | ||
| 37 | +pub const MAX_RELEASE_ASSETS: usize = 32; | ||
| 38 | +/// Longest `[release] title` template, in characters, after trimming. | ||
| 39 | +pub const MAX_RELEASE_TITLE_CHARS: usize = 200; | ||
| 36 | 40 | ||
| 37 | /// A parsed and validated workflow. | 41 | /// A parsed and validated workflow. |
| 38 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | 42 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| @@ -47,6 +51,83 @@ pub struct CiConfig { | |||
| 47 | /// The `[jobs.<name>]` tables, keyed by job name. | 51 | /// The `[jobs.<name>]` tables, keyed by job name. |
| 48 | #[serde(default)] | 52 | #[serde(default)] |
| 49 | pub jobs: BTreeMap<String, JobSpec>, | 53 | pub jobs: BTreeMap<String, JobSpec>, |
| 54 | + /// The `[release]` table. Optional; when set, a tag run that fully succeeds publishes a release. | ||
| 55 | + #[serde(default)] | ||
| 56 | + pub release: Option<ReleaseSpec>, | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// The `[release]` table. Requires `on.tags`. See docs/ci.md, Releases. | ||
| 60 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| 61 | +#[serde(deny_unknown_fields, default)] | ||
| 62 | +pub struct ReleaseSpec { | ||
| 63 | + /// `"<job>:<glob>"` entries. The glob matches the job's flattened artifact names. | ||
| 64 | + pub assets: Vec<String>, | ||
| 65 | + pub prerelease: Prerelease, | ||
| 66 | + pub draft: bool, | ||
| 67 | + pub notes: ReleaseNotes, | ||
| 68 | + /// Template with the placeholder `{tag}`, e.g. `"Release {tag}"`. | ||
| 69 | + pub title: String, | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +impl Default for ReleaseSpec { | ||
| 73 | + fn default() -> Self { | ||
| 74 | + Self { | ||
| 75 | + assets: Vec::new(), | ||
| 76 | + prerelease: Prerelease::Auto, | ||
| 77 | + draft: false, | ||
| 78 | + notes: ReleaseNotes::Commits, | ||
| 79 | + title: "{tag}".to_string(), | ||
| 80 | + } | ||
| 81 | + } | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/// The `prerelease` key: `"auto"`, `true` or `false`. | ||
| 85 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 86 | +pub enum Prerelease { | ||
| 87 | + /// A release is a prerelease when its tag contains `-`, e.g. `v1.2.0-rc1`. | ||
| 88 | + Auto, | ||
| 89 | + Always, | ||
| 90 | + Never, | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +impl Serialize for Prerelease { | ||
| 94 | + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { | ||
| 95 | + match self { | ||
| 96 | + Prerelease::Auto => serializer.serialize_str("auto"), | ||
| 97 | + Prerelease::Always => serializer.serialize_bool(true), | ||
| 98 | + Prerelease::Never => serializer.serialize_bool(false), | ||
| 99 | + } | ||
| 100 | + } | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +impl<'de> Deserialize<'de> for Prerelease { | ||
| 104 | + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { | ||
| 105 | + #[derive(Deserialize)] | ||
| 106 | + #[serde(untagged)] | ||
| 107 | + enum Raw { | ||
| 108 | + Flag(bool), | ||
| 109 | + Text(String), | ||
| 110 | + } | ||
| 111 | + match Raw::deserialize(deserializer)? { | ||
| 112 | + Raw::Flag(true) => Ok(Prerelease::Always), | ||
| 113 | + Raw::Flag(false) => Ok(Prerelease::Never), | ||
| 114 | + Raw::Text(text) if text == "auto" => Ok(Prerelease::Auto), | ||
| 115 | + Raw::Text(text) => Err(serde::de::Error::custom(format!( | ||
| 116 | + "prerelease must be \"auto\", true or false, got {text:?}" | ||
| 117 | + ))), | ||
| 118 | + } | ||
| 119 | + } | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/// The `notes` key. | ||
| 123 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] | ||
| 124 | +#[serde(rename_all = "lowercase")] | ||
| 125 | +pub enum ReleaseNotes { | ||
| 126 | + /// One line per commit since the previous release tag. | ||
| 127 | + Commits, | ||
| 128 | + /// No notes. | ||
| 129 | + #[serde(rename = "none")] | ||
| 130 | + Off, | ||
| 50 | } | 131 | } |
| 51 | 132 | ||
| 52 | /// The `[on]` table. | 133 | /// The `[on]` table. |
| @@ -142,6 +223,12 @@ impl CiConfig { | |||
| 142 | } | 223 | } |
| 143 | } | 224 | } |
| 144 | 225 | ||
| 226 | + /// Whether a run for this event should publish a release when every job succeeds: a | ||
| 227 | + /// `[release]` table is set and the event is a tag that matches `on.tags`. | ||
| 228 | + pub fn wants_release(&self, ev: &Event) -> bool { | ||
| 229 | + self.release.is_some() && matches!(ev, Event::Tag { .. }) && self.triggered_by(ev) | ||
| 230 | + } | ||
| 231 | + | ||
| 145 | /// Job names in dependency order. Ties are broken by name, so the order is stable. | 232 | /// Job names in dependency order. Ties are broken by name, so the order is stable. |
| 146 | /// Jobs in a cycle, or with unknown needs, are left out. [`parse_config`] rejects both. | 233 | /// Jobs in a cycle, or with unknown needs, are left out. [`parse_config`] rejects both. |
| 147 | pub fn job_order(&self) -> Vec<&str> { | 234 | pub fn job_order(&self) -> Vec<&str> { |
| @@ -192,6 +279,9 @@ impl CiConfig { | |||
| 192 | for (name, job) in &self.jobs { | 279 | for (name, job) in &self.jobs { |
| 193 | validate_job(name, job, &self.jobs)?; | 280 | validate_job(name, job, &self.jobs)?; |
| 194 | } | 281 | } |
| 282 | + if let Some(release) = &self.release { | ||
| 283 | + validate_release(release, &self.on, &self.jobs)?; | ||
| 284 | + } | ||
| 195 | let order = self.job_order(); | 285 | let order = self.job_order(); |
| 196 | if order.len() != self.jobs.len() { | 286 | if order.len() != self.jobs.len() { |
| 197 | let job = self | 287 | let job = self |
| @@ -206,6 +296,37 @@ impl CiConfig { | |||
| 206 | } | 296 | } |
| 207 | } | 297 | } |
| 208 | 298 | ||
| 299 | +impl ReleaseSpec { | ||
| 300 | + /// Whether the release for `tag` is a prerelease. | ||
| 301 | + pub fn is_prerelease(&self, tag: &str) -> bool { | ||
| 302 | + match self.prerelease { | ||
| 303 | + Prerelease::Auto => tag.contains('-'), | ||
| 304 | + Prerelease::Always => true, | ||
| 305 | + Prerelease::Never => false, | ||
| 306 | + } | ||
| 307 | + } | ||
| 308 | + | ||
| 309 | + /// The release title for `tag`: the template with `{tag}` replaced. | ||
| 310 | + pub fn title_for(&self, tag: &str) -> String { | ||
| 311 | + self.title.trim().replace("{tag}", tag) | ||
| 312 | + } | ||
| 313 | + | ||
| 314 | + /// Whether an artifact of `job`, under its flattened `artifact_name`, is selected by an | ||
| 315 | + /// `assets` entry. Entries that do not name `job` never match. | ||
| 316 | + pub fn asset_matches(&self, job: &str, artifact_name: &str) -> bool { | ||
| 317 | + self.assets.iter().any(|asset| { | ||
| 318 | + asset_selector(asset).is_some_and(|(selected_job, glob)| { | ||
| 319 | + selected_job == job && matches_any(&[glob.to_string()], artifact_name) | ||
| 320 | + }) | ||
| 321 | + }) | ||
| 322 | + } | ||
| 323 | +} | ||
| 324 | + | ||
| 325 | +/// Splits an `assets` entry into its job and glob. Validation guarantees the `:`. | ||
| 326 | +fn asset_selector(asset: &str) -> Option<(&str, &str)> { | ||
| 327 | + asset.split_once(':') | ||
| 328 | +} | ||
| 329 | + | ||
| 209 | fn matches_any(globs: &[String], value: &str) -> bool { | 330 | fn matches_any(globs: &[String], value: &str) -> bool { |
| 210 | globs | 331 | globs |
| 211 | .iter() | 332 | .iter() |
| @@ -368,6 +489,79 @@ fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> { | |||
| 368 | Ok(()) | 489 | Ok(()) |
| 369 | } | 490 | } |
| 370 | 491 | ||
| 492 | +/// Checks the `[release]` table against the triggers and jobs: tags must be configured, there | ||
| 493 | +/// are at most [`MAX_RELEASE_ASSETS`] assets, each one is valid for [`validate_release_asset`], | ||
| 494 | +/// and the title is valid for [`validate_release_title`]. | ||
| 495 | +fn validate_release( | ||
| 496 | + release: &ReleaseSpec, | ||
| 497 | + on: &Triggers, | ||
| 498 | + jobs: &BTreeMap<String, JobSpec>, | ||
| 499 | +) -> Result<(), ConfigError> { | ||
| 500 | + if on.tags.is_empty() { | ||
| 501 | + return Err(ConfigError::ReleaseWithoutTags); | ||
| 502 | + } | ||
| 503 | + if release.assets.len() > MAX_RELEASE_ASSETS { | ||
| 504 | + return Err(ConfigError::TooManyReleaseAssets { | ||
| 505 | + count: release.assets.len(), | ||
| 506 | + max: MAX_RELEASE_ASSETS, | ||
| 507 | + }); | ||
| 508 | + } | ||
| 509 | + for asset in &release.assets { | ||
| 510 | + validate_release_asset(asset, jobs)?; | ||
| 511 | + } | ||
| 512 | + validate_release_title(&release.title) | ||
| 513 | +} | ||
| 514 | + | ||
| 515 | +/// An asset is `job:glob`. The job must exist and declare artifacts. The glob is matched against | ||
| 516 | +/// flattened artifact names, which never contain `/`, so a glob with `/` is rejected. | ||
| 517 | +fn validate_release_asset( | ||
| 518 | + asset: &str, | ||
| 519 | + jobs: &BTreeMap<String, JobSpec>, | ||
| 520 | +) -> Result<(), ConfigError> { | ||
| 521 | + let invalid = |reason: String| ConfigError::InvalidReleaseAsset { | ||
| 522 | + asset: asset.to_string(), | ||
| 523 | + reason, | ||
| 524 | + }; | ||
| 525 | + let Some((job, glob)) = asset_selector(asset) else { | ||
| 526 | + return Err(invalid("must be \"job:glob\"".into())); | ||
| 527 | + }; | ||
| 528 | + let Some(spec) = jobs.get(job) else { | ||
| 529 | + return Err(invalid(format!("job {job:?} is not defined"))); | ||
| 530 | + }; | ||
| 531 | + if spec.artifacts.is_empty() { | ||
| 532 | + return Err(invalid(format!("job {job:?} declares no artifacts"))); | ||
| 533 | + } | ||
| 534 | + if glob.is_empty() { | ||
| 535 | + return Err(invalid("glob must not be empty".into())); | ||
| 536 | + } | ||
| 537 | + if glob.contains('/') { | ||
| 538 | + return Err(invalid( | ||
| 539 | + "glob must not contain \"/\", artifact names are flattened".into(), | ||
| 540 | + )); | ||
| 541 | + } | ||
| 542 | + build_glob(glob) | ||
| 543 | + .map(|_| ()) | ||
| 544 | + .map_err(|e| invalid(e.to_string())) | ||
| 545 | +} | ||
| 546 | + | ||
| 547 | +/// A title template: non-blank after trimming, at most [`MAX_RELEASE_TITLE_CHARS`] characters, | ||
| 548 | +/// and no control characters. | ||
| 549 | +fn validate_release_title(title: &str) -> Result<(), ConfigError> { | ||
| 550 | + let invalid = |reason: String| ConfigError::InvalidReleaseTitle(reason); | ||
| 551 | + if title.trim().is_empty() { | ||
| 552 | + return Err(invalid("must not be empty".into())); | ||
| 553 | + } | ||
| 554 | + if title.trim().chars().count() > MAX_RELEASE_TITLE_CHARS { | ||
| 555 | + return Err(invalid(format!( | ||
| 556 | + "must be at most {MAX_RELEASE_TITLE_CHARS} characters" | ||
| 557 | + ))); | ||
| 558 | + } | ||
| 559 | + if title.chars().any(char::is_control) { | ||
| 560 | + return Err(invalid("must not contain control characters".into())); | ||
| 561 | + } | ||
| 562 | + Ok(()) | ||
| 563 | +} | ||
| 564 | + | ||
| 371 | fn validate_job( | 565 | fn validate_job( |
| 372 | name: &str, | 566 | name: &str, |
| 373 | job: &JobSpec, | 567 | job: &JobSpec, |
| @@ -889,4 +1083,201 @@ artifacts = ["target/release/forge"] | |||
| 889 | ConfigError::Toml(_) | 1083 | ConfigError::Toml(_) |
| 890 | )); | 1084 | )); |
| 891 | } | 1085 | } |
| 1086 | + | ||
| 1087 | + /// A tag-triggered workflow with a `build` job that has artifacts, plus `[release]` body. | ||
| 1088 | + fn release_toml(release: &str) -> String { | ||
| 1089 | + format!( | ||
| 1090 | + "[on]\ntags = [\"v*\"]\n{}\n[release]\n{release}\n", | ||
| 1091 | + job_toml("artifacts = [\"dist/*\"]") | ||
| 1092 | + ) | ||
| 1093 | + } | ||
| 1094 | + | ||
| 1095 | + fn release_of(text: &str) -> ReleaseSpec { | ||
| 1096 | + parse_config(text).unwrap().release.expect("release set") | ||
| 1097 | + } | ||
| 1098 | + | ||
| 1099 | + #[test] | ||
| 1100 | + fn release_defaults() { | ||
| 1101 | + let release = release_of(&release_toml("")); | ||
| 1102 | + assert!(release.assets.is_empty()); | ||
| 1103 | + assert_eq!(release.prerelease, Prerelease::Auto); | ||
| 1104 | + assert!(!release.draft); | ||
| 1105 | + assert_eq!(release.notes, ReleaseNotes::Commits); | ||
| 1106 | + assert_eq!(release.title, "{tag}"); | ||
| 1107 | + assert_eq!(release, ReleaseSpec::default()); | ||
| 1108 | + } | ||
| 1109 | + | ||
| 1110 | + #[test] | ||
| 1111 | + fn release_full_table_parses() { | ||
| 1112 | + let text = release_toml( | ||
| 1113 | + "assets = [\"build:dist_*\", \"build:SHA256SUMS\"]\n\ | ||
| 1114 | + prerelease = true\ndraft = true\nnotes = \"none\"\ntitle = \"Release {tag}\"", | ||
| 1115 | + ); | ||
| 1116 | + let release = release_of(&text); | ||
| 1117 | + assert_eq!( | ||
| 1118 | + release.assets, | ||
| 1119 | + vec!["build:dist_*".to_string(), "build:SHA256SUMS".to_string()] | ||
| 1120 | + ); | ||
| 1121 | + assert_eq!(release.prerelease, Prerelease::Always); | ||
| 1122 | + assert!(release.draft); | ||
| 1123 | + assert_eq!(release.notes, ReleaseNotes::Off); | ||
| 1124 | + assert_eq!(release.title, "Release {tag}"); | ||
| 1125 | + } | ||
| 1126 | + | ||
| 1127 | + #[test] | ||
| 1128 | + fn release_prerelease_values() { | ||
| 1129 | + assert_eq!( | ||
| 1130 | + release_of(&release_toml("prerelease = \"auto\"")).prerelease, | ||
| 1131 | + Prerelease::Auto | ||
| 1132 | + ); | ||
| 1133 | + assert_eq!( | ||
| 1134 | + release_of(&release_toml("prerelease = false")).prerelease, | ||
| 1135 | + Prerelease::Never | ||
| 1136 | + ); | ||
| 1137 | + assert!(matches!( | ||
| 1138 | + err_of(&release_toml("prerelease = \"yes\"")), | ||
| 1139 | + ConfigError::Toml(_) | ||
| 1140 | + )); | ||
| 1141 | + } | ||
| 1142 | + | ||
| 1143 | + #[test] | ||
| 1144 | + fn release_notes_values() { | ||
| 1145 | + assert_eq!( | ||
| 1146 | + release_of(&release_toml("notes = \"commits\"")).notes, | ||
| 1147 | + ReleaseNotes::Commits | ||
| 1148 | + ); | ||
| 1149 | + assert!(matches!( | ||
| 1150 | + err_of(&release_toml("notes = \"all\"")), | ||
| 1151 | + ConfigError::Toml(_) | ||
| 1152 | + )); | ||
| 1153 | + } | ||
| 1154 | + | ||
| 1155 | + #[test] | ||
| 1156 | + fn release_unknown_keys_are_rejected() { | ||
| 1157 | + assert!(matches!( | ||
| 1158 | + err_of(&release_toml("bogus = 1")), | ||
| 1159 | + ConfigError::Toml(_) | ||
| 1160 | + )); | ||
| 1161 | + } | ||
| 1162 | + | ||
| 1163 | + #[test] | ||
| 1164 | + fn release_requires_tags() { | ||
| 1165 | + let text = format!("[release]\n{}", job_toml("artifacts = [\"dist/*\"]")); | ||
| 1166 | + assert_eq!(err_of(&text), ConfigError::ReleaseWithoutTags); | ||
| 1167 | + } | ||
| 1168 | + | ||
| 1169 | + #[test] | ||
| 1170 | + fn release_asset_must_be_job_and_glob() { | ||
| 1171 | + for bad in ["build", ":dist_*", "build:", "ghost:dist_*", "build:a/b"] { | ||
| 1172 | + let text = release_toml(&format!("assets = [{bad:?}]")); | ||
| 1173 | + assert!( | ||
| 1174 | + matches!(err_of(&text), ConfigError::InvalidReleaseAsset { .. }), | ||
| 1175 | + "asset {bad:?} should be rejected: {:?}", | ||
| 1176 | + err_of(&text) | ||
| 1177 | + ); | ||
| 1178 | + } | ||
| 1179 | + let text = release_toml("assets = [\"build:[\"]"); | ||
| 1180 | + assert!(matches!( | ||
| 1181 | + err_of(&text), | ||
| 1182 | + ConfigError::InvalidReleaseAsset { .. } | ||
| 1183 | + )); | ||
| 1184 | + } | ||
| 1185 | + | ||
| 1186 | + #[test] | ||
| 1187 | + fn release_asset_job_must_declare_artifacts() { | ||
| 1188 | + let text = format!( | ||
| 1189 | + "[on]\ntags = [\"v*\"]\n{}\n[release]\nassets = [\"build:x\"]\n", | ||
| 1190 | + job_toml("") | ||
| 1191 | + ); | ||
| 1192 | + match err_of(&text) { | ||
| 1193 | + ConfigError::InvalidReleaseAsset { asset, reason } => { | ||
| 1194 | + assert_eq!(asset, "build:x"); | ||
| 1195 | + assert!(reason.contains("no artifacts"), "{reason}"); | ||
| 1196 | + } | ||
| 1197 | + other => panic!("unexpected error {other:?}"), | ||
| 1198 | + } | ||
| 1199 | + } | ||
| 1200 | + | ||
| 1201 | + #[test] | ||
| 1202 | + fn release_assets_are_capped() { | ||
| 1203 | + let entries: Vec<String> = (0..=MAX_RELEASE_ASSETS) | ||
| 1204 | + .map(|_| "build:dist_*".to_string()) | ||
| 1205 | + .collect(); | ||
| 1206 | + let text = release_toml(&format!("assets = {entries:?}")); | ||
| 1207 | + assert_eq!( | ||
| 1208 | + err_of(&text), | ||
| 1209 | + ConfigError::TooManyReleaseAssets { | ||
| 1210 | + count: MAX_RELEASE_ASSETS + 1, | ||
| 1211 | + max: MAX_RELEASE_ASSETS | ||
| 1212 | + } | ||
| 1213 | + ); | ||
| 1214 | + let text = release_toml(&format!("assets = {:?}", &entries[..MAX_RELEASE_ASSETS])); | ||
| 1215 | + assert!(parse_config(&text).is_ok()); | ||
| 1216 | + } | ||
| 1217 | + | ||
| 1218 | + #[test] | ||
| 1219 | + fn release_title_validation() { | ||
| 1220 | + for bad in ["", " ", "a\\u0007b"] { | ||
| 1221 | + let text = release_toml(&format!("title = \"{bad}\"")); | ||
| 1222 | + assert!( | ||
| 1223 | + matches!(err_of(&text), ConfigError::InvalidReleaseTitle(_)), | ||
| 1224 | + "title {bad:?} should be rejected" | ||
| 1225 | + ); | ||
| 1226 | + } | ||
| 1227 | + let over = "t".repeat(MAX_RELEASE_TITLE_CHARS + 1); | ||
| 1228 | + let text = release_toml(&format!("title = \"{over}\"")); | ||
| 1229 | + assert!(matches!(err_of(&text), ConfigError::InvalidReleaseTitle(_))); | ||
| 1230 | + let at_limit = "t".repeat(MAX_RELEASE_TITLE_CHARS); | ||
| 1231 | + assert!(parse_config(&release_toml(&format!("title = \"{at_limit}\""))).is_ok()); | ||
| 1232 | + } | ||
| 1233 | + | ||
| 1234 | + #[test] | ||
| 1235 | + fn release_title_for_fills_tag() { | ||
| 1236 | + assert_eq!(ReleaseSpec::default().title_for("v1.2.0"), "v1.2.0"); | ||
| 1237 | + let release = release_of(&release_toml("title = \"Release {tag}\"")); | ||
| 1238 | + assert_eq!(release.title_for("v1.2.0"), "Release v1.2.0"); | ||
| 1239 | + let fixed = release_of(&release_toml("title = \"Stable\"")); | ||
| 1240 | + assert_eq!(fixed.title_for("v1.2.0"), "Stable"); | ||
| 1241 | + } | ||
| 1242 | + | ||
| 1243 | + #[test] | ||
| 1244 | + fn release_prerelease_auto_logic() { | ||
| 1245 | + let auto = ReleaseSpec::default(); | ||
| 1246 | + assert!(auto.is_prerelease("v1.2.0-rc1")); | ||
| 1247 | + assert!(auto.is_prerelease("v2.0.0-beta.3")); | ||
| 1248 | + assert!(!auto.is_prerelease("v1.2.0")); | ||
| 1249 | + let always = release_of(&release_toml("prerelease = true")); | ||
| 1250 | + assert!(always.is_prerelease("v1.2.0")); | ||
| 1251 | + let never = release_of(&release_toml("prerelease = false")); | ||
| 1252 | + assert!(!never.is_prerelease("v1.2.0-rc1")); | ||
| 1253 | + } | ||
| 1254 | + | ||
| 1255 | + #[test] | ||
| 1256 | + fn release_asset_matching() { | ||
| 1257 | + let release = release_of(&release_toml( | ||
| 1258 | + "assets = [\"build:forge-*-linux-*\", \"build:SHA256SUMS\"]", | ||
| 1259 | + )); | ||
| 1260 | + assert!(release.asset_matches("build", "forge-1.2.0-linux-x86_64")); | ||
| 1261 | + assert!(release.asset_matches("build", "SHA256SUMS")); | ||
| 1262 | + assert!(!release.asset_matches("build", "forge-1.2.0-darwin-arm64")); | ||
| 1263 | + assert!(!release.asset_matches("build", "SHA256SUMS.sig")); | ||
| 1264 | + // The same glob under another job name does not match. | ||
| 1265 | + assert!(!release.asset_matches("lint", "SHA256SUMS")); | ||
| 1266 | + assert!(!ReleaseSpec::default().asset_matches("build", "SHA256SUMS")); | ||
| 1267 | + } | ||
| 1268 | + | ||
| 1269 | + #[test] | ||
| 1270 | + fn wants_release_only_for_matching_tags() { | ||
| 1271 | + let text = release_toml(""); | ||
| 1272 | + let cfg = parse_config(&text).unwrap(); | ||
| 1273 | + assert!(cfg.wants_release(&Event::Tag { tag: "v1.2.0" })); | ||
| 1274 | + assert!(!cfg.wants_release(&Event::Tag { tag: "release-1" })); | ||
| 1275 | + assert!(!cfg.wants_release(&Event::Push { branch: "main" })); | ||
| 1276 | + assert!(!cfg.wants_release(&Event::Manual)); | ||
| 1277 | + assert!(!cfg.wants_release(&Event::PullRequest)); | ||
| 1278 | + | ||
| 1279 | + let without = parse_config(&format!("[on]\ntags = [\"v*\"]\n{}", job_toml(""))).unwrap(); | ||
| 1280 | + assert!(without.release.is_none()); | ||
| 1281 | + assert!(!without.wants_release(&Event::Tag { tag: "v1.2.0" })); | ||
| 1282 | + } | ||
| 892 | } | 1283 | } |
crates/forge-ci/src/error.rsmodified+12 -0
| @@ -71,6 +71,18 @@ pub enum ConfigError { | |||
| 71 | #[error("job {job:?}: duplicate cache path {path:?}")] | 71 | #[error("job {job:?}: duplicate cache path {path:?}")] |
| 72 | DuplicateCachePath { job: String, path: String }, | 72 | DuplicateCachePath { job: String, path: String }, |
| 73 | 73 | ||
| 74 | + #[error("[release] needs at least one tag glob in [on] tags")] | ||
| 75 | + ReleaseWithoutTags, | ||
| 76 | + | ||
| 77 | + #[error("[release] lists {count} assets, the limit is {max}")] | ||
| 78 | + TooManyReleaseAssets { count: usize, max: usize }, | ||
| 79 | + | ||
| 80 | + #[error("invalid release asset {asset:?}: {reason}")] | ||
| 81 | + InvalidReleaseAsset { asset: String, reason: String }, | ||
| 82 | + | ||
| 83 | + #[error("invalid release title: {0}")] | ||
| 84 | + InvalidReleaseTitle(String), | ||
| 85 | + | ||
| 74 | #[error("invalid {kind} glob {pattern:?}: {reason}")] | 86 | #[error("invalid {kind} glob {pattern:?}: {reason}")] |
| 75 | InvalidTriggerGlob { | 87 | InvalidTriggerGlob { |
| 76 | kind: &'static str, | 88 | kind: &'static str, |
crates/forge-core/src/config.rsmodified+401 -1
| @@ -81,6 +81,9 @@ pub struct Config { | |||
| 81 | /// Release asset limits, from the `[releases]` section. | 81 | /// Release asset limits, from the `[releases]` section. |
| 82 | #[serde(default)] | 82 | #[serde(default)] |
| 83 | pub releases: ReleasesConfig, | 83 | pub releases: ReleasesConfig, |
| 84 | + /// Where release assets and CI artifacts are stored, from the `[storage]` section. | ||
| 85 | + #[serde(default)] | ||
| 86 | + pub storage: StorageConfig, | ||
| 84 | /// Standby replication, from the `[replication]` section. An empty `target` disables it. | 87 | /// Standby replication, from the `[replication]` section. An empty `target` disables it. |
| 85 | #[serde(default)] | 88 | #[serde(default)] |
| 86 | pub replication: ReplicationConfig, | 89 | pub replication: ReplicationConfig, |
| @@ -358,6 +361,168 @@ impl Default for ReleasesConfig { | |||
| 358 | } | 361 | } |
| 359 | } | 362 | } |
| 360 | 363 | ||
| 364 | +/// Blob storage for release assets and CI artifacts, from the `[storage]` section. See | ||
| 365 | +/// `docs/backup.md`. The default keeps blobs on the local disk under `<data_dir>/blobs`. | ||
| 366 | +#[derive(Debug, Clone, Default, Deserialize)] | ||
| 367 | +#[serde(deny_unknown_fields, default)] | ||
| 368 | +pub struct StorageConfig { | ||
| 369 | + /// `fs` (local disk, the default) or `s3` (any S3-compatible object store). | ||
| 370 | + pub backend: StorageBackend, | ||
| 371 | + /// Settings for `backend = "s3"`, from the `[storage.s3]` table. Ignored for `fs` and `r2`. | ||
| 372 | + pub s3: S3Config, | ||
| 373 | + /// Settings for `backend = "r2"`, from the `[storage.r2]` table. Ignored for `fs` and `s3`. | ||
| 374 | + pub r2: R2Config, | ||
| 375 | +} | ||
| 376 | + | ||
| 377 | +/// Blob backend. See `StorageConfig::backend`. | ||
| 378 | +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] | ||
| 379 | +#[serde(rename_all = "lowercase")] | ||
| 380 | +pub enum StorageBackend { | ||
| 381 | + #[default] | ||
| 382 | + Fs, | ||
| 383 | + S3, | ||
| 384 | + /// Cloudflare R2, configured by account rather than by endpoint. See `R2Config`. | ||
| 385 | + R2, | ||
| 386 | +} | ||
| 387 | + | ||
| 388 | +/// S3-compatible object store settings, from the `[storage.s3]` table. Works with AWS S3, MinIO, | ||
| 389 | +/// Garage, Cloudflare R2 and similar. The secret is read from a file, so it stays out of this config. | ||
| 390 | +#[derive(Debug, Clone, Default, Deserialize)] | ||
| 391 | +#[serde(deny_unknown_fields, default)] | ||
| 392 | +pub struct S3Config { | ||
| 393 | + /// Bucket that holds the blobs. Required. | ||
| 394 | + pub bucket: String, | ||
| 395 | + /// Signing region, such as `eu-central-1`, or `auto` for R2. Required. | ||
| 396 | + pub region: String, | ||
| 397 | + /// Full URL of a non-AWS endpoint, such as `https://s3.example.internal:9000`. Empty uses AWS. | ||
| 398 | + pub endpoint: String, | ||
| 399 | + /// Key prefix inside the bucket, such as `forge/`. Empty stores keys at the bucket root. | ||
| 400 | + pub prefix: String, | ||
| 401 | + /// Access key id. Required. | ||
| 402 | + pub access_key_id: String, | ||
| 403 | + /// File holding the secret access key (mode 0600). Its contents are trimmed. Required. | ||
| 404 | + pub secret_access_key_file: PathBuf, | ||
| 405 | + /// Permit an `http://` endpoint. Only for a store on a trusted private network. | ||
| 406 | + pub allow_http: bool, | ||
| 407 | + /// Address buckets as subdomains (`bucket.host`) instead of paths (`host/bucket`). Path style is | ||
| 408 | + /// the default because MinIO, Garage and most self-hosted stores expect it. | ||
| 409 | + pub virtual_hosted_style: bool, | ||
| 410 | +} | ||
| 411 | + | ||
| 412 | +/// Cloudflare R2 settings, from the `[storage.r2]` table. The endpoint is derived from the account | ||
| 413 | +/// id and jurisdiction, so the S3 wire details never appear in the config. The secret is read from | ||
| 414 | +/// a file, as for `S3Config`. | ||
| 415 | +#[derive(Debug, Clone, Default, Deserialize)] | ||
| 416 | +#[serde(deny_unknown_fields, default)] | ||
| 417 | +pub struct R2Config { | ||
| 418 | + /// Cloudflare account id, the 32-character hex string from the dashboard. Required. | ||
| 419 | + pub account_id: String, | ||
| 420 | + /// Bucket that holds the blobs. Required. | ||
| 421 | + pub bucket: String, | ||
| 422 | + /// `""` (the default, global), `"eu"`, or `"fedramp"`. Must match the jurisdiction the bucket | ||
| 423 | + /// was created in, or requests fail. | ||
| 424 | + pub jurisdiction: String, | ||
| 425 | + /// Key prefix inside the bucket, such as `forge/`. Empty stores keys at the bucket root. | ||
| 426 | + pub prefix: String, | ||
| 427 | + /// Access key id of an R2 API token with object read and write. Required. | ||
| 428 | + pub access_key_id: String, | ||
| 429 | + /// File holding the secret access key (mode 0600). Its contents are trimmed. Required. | ||
| 430 | + pub secret_access_key_file: PathBuf, | ||
| 431 | +} | ||
| 432 | + | ||
| 433 | +impl R2Config { | ||
| 434 | + /// The S3 API endpoint for this account and jurisdiction. Path-style, https only. | ||
| 435 | + pub fn endpoint(&self) -> String { | ||
| 436 | + match self.jurisdiction.as_str() { | ||
| 437 | + "" => format!("https://{}.r2.cloudflarestorage.com", self.account_id), | ||
| 438 | + jurisdiction => format!( | ||
| 439 | + "https://{}.{jurisdiction}.r2.cloudflarestorage.com", | ||
| 440 | + self.account_id | ||
| 441 | + ), | ||
| 442 | + } | ||
| 443 | + } | ||
| 444 | +} | ||
| 445 | + | ||
| 446 | +/// Fails unless `value` is non-empty after trimming. `section` names the table in the message. | ||
| 447 | +fn require(section: &str, field: &str, value: &str) -> Result<()> { | ||
| 448 | + if value.trim().is_empty() { | ||
| 449 | + return Err(Error::Config(format!( | ||
| 450 | + "[{section}] {field} is required when backend = \"{}\"", | ||
| 451 | + section.trim_start_matches("storage.") | ||
| 452 | + ))); | ||
| 453 | + } | ||
| 454 | + Ok(()) | ||
| 455 | +} | ||
| 456 | + | ||
| 457 | +/// Checks that the secret file named by `[section]` exists and is a file. | ||
| 458 | +fn check_secret_file(section: &str, path: &Path) -> Result<()> { | ||
| 459 | + if path.as_os_str().is_empty() { | ||
| 460 | + return Err(Error::Config(format!( | ||
| 461 | + "[{section}] secret_access_key_file is required when backend = \"{}\"", | ||
| 462 | + section.trim_start_matches("storage.") | ||
| 463 | + ))); | ||
| 464 | + } | ||
| 465 | + if !path.is_file() { | ||
| 466 | + return Err(Error::Config(format!( | ||
| 467 | + "[{section}] secret_access_key_file {} is not a readable file", | ||
| 468 | + path.display() | ||
| 469 | + ))); | ||
| 470 | + } | ||
| 471 | + Ok(()) | ||
| 472 | +} | ||
| 473 | + | ||
| 474 | +impl StorageConfig { | ||
| 475 | + fn validate(&self) -> Result<()> { | ||
| 476 | + match self.backend { | ||
| 477 | + StorageBackend::Fs => Ok(()), | ||
| 478 | + StorageBackend::S3 => self.validate_s3(), | ||
| 479 | + StorageBackend::R2 => self.validate_r2(), | ||
| 480 | + } | ||
| 481 | + } | ||
| 482 | + | ||
| 483 | + fn validate_s3(&self) -> Result<()> { | ||
| 484 | + let s3 = &self.s3; | ||
| 485 | + require("storage.s3", "bucket", &s3.bucket)?; | ||
| 486 | + require("storage.s3", "region", &s3.region)?; | ||
| 487 | + require("storage.s3", "access_key_id", &s3.access_key_id)?; | ||
| 488 | + check_secret_file("storage.s3", &s3.secret_access_key_file)?; | ||
| 489 | + if !s3.endpoint.is_empty() { | ||
| 490 | + if !(s3.endpoint.starts_with("https://") || s3.endpoint.starts_with("http://")) { | ||
| 491 | + return Err(Error::Config( | ||
| 492 | + "[storage.s3] endpoint must start with https:// or http://".into(), | ||
| 493 | + )); | ||
| 494 | + } | ||
| 495 | + if s3.endpoint.starts_with("http://") && !s3.allow_http { | ||
| 496 | + return Err(Error::Config( | ||
| 497 | + "[storage.s3] endpoint is http:// but allow_http is false".into(), | ||
| 498 | + )); | ||
| 499 | + } | ||
| 500 | + } | ||
| 501 | + Ok(()) | ||
| 502 | + } | ||
| 503 | + | ||
| 504 | + fn validate_r2(&self) -> Result<()> { | ||
| 505 | + let r2 = &self.r2; | ||
| 506 | + require("storage.r2", "account_id", &r2.account_id)?; | ||
| 507 | + // The account id becomes part of the host name, so only hex digits are allowed. | ||
| 508 | + if !r2.account_id.chars().all(|c| c.is_ascii_hexdigit()) { | ||
| 509 | + return Err(Error::Config( | ||
| 510 | + "[storage.r2] account_id must contain only hex digits (copy it from the Cloudflare dashboard)".into(), | ||
| 511 | + )); | ||
| 512 | + } | ||
| 513 | + require("storage.r2", "bucket", &r2.bucket)?; | ||
| 514 | + require("storage.r2", "access_key_id", &r2.access_key_id)?; | ||
| 515 | + check_secret_file("storage.r2", &r2.secret_access_key_file)?; | ||
| 516 | + if !matches!(r2.jurisdiction.as_str(), "" | "eu" | "fedramp") { | ||
| 517 | + return Err(Error::Config(format!( | ||
| 518 | + "[storage.r2] jurisdiction must be \"eu\", \"fedramp\", or left empty, not \"{}\"", | ||
| 519 | + r2.jurisdiction | ||
| 520 | + ))); | ||
| 521 | + } | ||
| 522 | + Ok(()) | ||
| 523 | + } | ||
| 524 | +} | ||
| 525 | + | ||
| 361 | /// Scheduled backups, from the `[backup]` section. See `docs/backup.md`. | 526 | /// Scheduled backups, from the `[backup]` section. See `docs/backup.md`. |
| 362 | #[derive(Debug, Clone, Deserialize)] | 527 | #[derive(Debug, Clone, Deserialize)] |
| 363 | #[serde(deny_unknown_fields, default)] | 528 | #[serde(deny_unknown_fields, default)] |
| @@ -455,6 +620,7 @@ impl Config { | |||
| 455 | config.backup.validate()?; | 620 | config.backup.validate()?; |
| 456 | config.replication.validate()?; | 621 | config.replication.validate()?; |
| 457 | config.self_update.validate()?; | 622 | config.self_update.validate()?; |
| 623 | + config.storage.validate()?; | ||
| 458 | Ok(config) | 624 | Ok(config) |
| 459 | } | 625 | } |
| 460 | } | 626 | } |
| @@ -627,7 +793,10 @@ mod tests { | |||
| 627 | let base = format!("{DEV_DEFAULTS}\n[self_update]\nenabled = true\n"); | 793 | let base = format!("{DEV_DEFAULTS}\n[self_update]\nenabled = true\n"); |
| 628 | for repo in ["", "forge", "a/b/c", "/forge", "owner/"] { | 794 | for repo in ["", "forge", "a/b/c", "/forge", "owner/"] { |
| 629 | std::fs::write(&path, format!("{base}repo = \"{repo}\"\n")).unwrap(); | 795 | std::fs::write(&path, format!("{base}repo = \"{repo}\"\n")).unwrap(); |
| 630 | - assert!(Config::load(&path).is_err(), "repo `{repo}` should be refused"); | 796 | + assert!( |
| 797 | + Config::load(&path).is_err(), | ||
| 798 | + "repo `{repo}` should be refused" | ||
| 799 | + ); | ||
| 631 | } | 800 | } |
| 632 | std::fs::write(&path, format!("{base}repo = \"Tahinli/forge\"\n")).unwrap(); | 801 | std::fs::write(&path, format!("{base}repo = \"Tahinli/forge\"\n")).unwrap(); |
| 633 | let cfg = Config::load(&path).unwrap(); | 802 | let cfg = Config::load(&path).unwrap(); |
| @@ -662,4 +831,235 @@ mod tests { | |||
| 662 | std::fs::write(&path, format!("{DEV_DEFAULTS}\n[backup]\nbogus = 1\n")).unwrap(); | 831 | std::fs::write(&path, format!("{DEV_DEFAULTS}\n[backup]\nbogus = 1\n")).unwrap(); |
| 663 | assert!(matches!(Config::load(&path), Err(Error::Config(_)))); | 832 | assert!(matches!(Config::load(&path), Err(Error::Config(_)))); |
| 664 | } | 833 | } |
| 834 | + | ||
| 835 | + #[test] | ||
| 836 | + fn storage_section_defaults_to_fs() { | ||
| 837 | + let dir = tempfile::tempdir().unwrap(); | ||
| 838 | + let path = dir.path().join("forge.toml"); | ||
| 839 | + std::fs::write(&path, DEV_DEFAULTS).unwrap(); | ||
| 840 | + let cfg = Config::load(&path).unwrap(); | ||
| 841 | + assert_eq!(cfg.storage.backend, StorageBackend::Fs); | ||
| 842 | + assert!(cfg.storage.s3.bucket.is_empty()); | ||
| 843 | + assert!(!cfg.storage.s3.allow_http); | ||
| 844 | + assert!(!cfg.storage.s3.virtual_hosted_style); | ||
| 845 | + } | ||
| 846 | + | ||
| 847 | + #[test] | ||
| 848 | + fn s3_backend_requires_bucket_region_and_credentials() { | ||
| 849 | + let dir = tempfile::tempdir().unwrap(); | ||
| 850 | + let path = dir.path().join("forge.toml"); | ||
| 851 | + let secret = dir.path().join("secret"); | ||
| 852 | + std::fs::write(&secret, "s3cret\n").unwrap(); | ||
| 853 | + let secret = secret.display(); | ||
| 854 | + let full = format!( | ||
| 855 | + "{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" | ||
| 856 | + ); | ||
| 857 | + std::fs::write(&path, &full).unwrap(); | ||
| 858 | + let cfg = Config::load(&path).unwrap(); | ||
| 859 | + assert_eq!(cfg.storage.backend, StorageBackend::S3); | ||
| 860 | + assert_eq!(cfg.storage.s3.bucket, "forge"); | ||
| 861 | + assert_eq!(cfg.storage.s3.region, "eu-central-1"); | ||
| 862 | + | ||
| 863 | + for missing in [ | ||
| 864 | + "bucket", | ||
| 865 | + "region", | ||
| 866 | + "access_key_id", | ||
| 867 | + "secret_access_key_file", | ||
| 868 | + ] { | ||
| 869 | + let text: String = full | ||
| 870 | + .lines() | ||
| 871 | + .filter(|line| !line.starts_with(missing)) | ||
| 872 | + .collect::<Vec<_>>() | ||
| 873 | + .join("\n"); | ||
| 874 | + std::fs::write(&path, &text).unwrap(); | ||
| 875 | + assert!( | ||
| 876 | + matches!(Config::load(&path), Err(Error::Config(_))), | ||
| 877 | + "{missing} should be required" | ||
| 878 | + ); | ||
| 879 | + } | ||
| 880 | + } | ||
| 881 | + | ||
| 882 | + #[test] | ||
| 883 | + fn s3_secret_file_must_exist() { | ||
| 884 | + let dir = tempfile::tempdir().unwrap(); | ||
| 885 | + let path = dir.path().join("forge.toml"); | ||
| 886 | + let text = format!( | ||
| 887 | + "{DEV_DEFAULTS}\n[storage]\nbackend = \"s3\"\n[storage.s3]\nbucket = \"forge\"\nregion = \"auto\"\naccess_key_id = \"AKIA\"\nsecret_access_key_file = \"{}\"\n", | ||
| 888 | + dir.path().join("absent").display() | ||
| 889 | + ); | ||
| 890 | + std::fs::write(&path, text).unwrap(); | ||
| 891 | + assert!(matches!(Config::load(&path), Err(Error::Config(_)))); | ||
| 892 | + } | ||
| 893 | + | ||
| 894 | + #[test] | ||
| 895 | + fn s3_endpoint_scheme_is_checked() { | ||
| 896 | + let dir = tempfile::tempdir().unwrap(); | ||
| 897 | + let path = dir.path().join("forge.toml"); | ||
| 898 | + let secret = dir.path().join("secret"); | ||
| 899 | + std::fs::write(&secret, "s3cret").unwrap(); | ||
| 900 | + let base = format!( | ||
| 901 | + "{DEV_DEFAULTS}\n[storage]\nbackend = \"s3\"\n[storage.s3]\nbucket = \"forge\"\nregion = \"us-east-1\"\naccess_key_id = \"AKIA\"\nsecret_access_key_file = \"{}\"\n", | ||
| 902 | + secret.display() | ||
| 903 | + ); | ||
| 904 | + for (endpoint, ok) in [ | ||
| 905 | + ("minio.internal:9000", false), | ||
| 906 | + ("https://s3.example.internal", true), | ||
| 907 | + ("http://minio.internal:9000", false), | ||
| 908 | + ] { | ||
| 909 | + std::fs::write(&path, format!("{base}endpoint = \"{endpoint}\"\n")).unwrap(); | ||
| 910 | + assert_eq!(Config::load(&path).is_ok(), ok, "endpoint `{endpoint}`"); | ||
| 911 | + } | ||
| 912 | + std::fs::write( | ||
| 913 | + &path, | ||
| 914 | + format!("{base}endpoint = \"http://minio.internal:9000\"\nallow_http = true\n"), | ||
| 915 | + ) | ||
| 916 | + .unwrap(); | ||
| 917 | + assert!(Config::load(&path).is_ok()); | ||
| 918 | + } | ||
| 919 | + | ||
| 920 | + #[test] | ||
| 921 | + fn storage_rejects_unknown_keys() { | ||
| 922 | + let dir = tempfile::tempdir().unwrap(); | ||
| 923 | + let path = dir.path().join("forge.toml"); | ||
| 924 | + std::fs::write(&path, format!("{DEV_DEFAULTS}\n[storage]\nbogus = 1\n")).unwrap(); | ||
| 925 | + assert!(matches!(Config::load(&path), Err(Error::Config(_)))); | ||
| 926 | + std::fs::write( | ||
| 927 | + &path, | ||
| 928 | + format!("{DEV_DEFAULTS}\n[storage.s3]\nsecret_access_key = \"x\"\n"), | ||
| 929 | + ) | ||
| 930 | + .unwrap(); | ||
| 931 | + assert!(matches!(Config::load(&path), Err(Error::Config(_)))); | ||
| 932 | + // R2 users never set an endpoint or region, so those keys are refused outright. | ||
| 933 | + for key in ["endpoint = \"https://x\"", "region = \"auto\"", "bogus = 1"] { | ||
| 934 | + std::fs::write(&path, format!("{DEV_DEFAULTS}\n[storage.r2]\n{key}\n")).unwrap(); | ||
| 935 | + assert!( | ||
| 936 | + matches!(Config::load(&path), Err(Error::Config(_))), | ||
| 937 | + "{key}" | ||
| 938 | + ); | ||
| 939 | + } | ||
| 940 | + } | ||
| 941 | + | ||
| 942 | + /// A complete `[storage.r2]` table with a real secret file, minus any lines the caller drops. | ||
| 943 | + fn r2_config_text(dir: &Path, drop: &[&str], extra: &str) -> String { | ||
| 944 | + let secret = dir.join("r2-secret"); | ||
| 945 | + std::fs::write(&secret, "r2s3cret\n").unwrap(); | ||
| 946 | + let base = format!( | ||
| 947 | + "{DEV_DEFAULTS}\n[storage]\nbackend = \"r2\"\n[storage.r2]\naccount_id = \"0123abcd\"\nbucket = \"forge\"\naccess_key_id = \"AKIA\"\nsecret_access_key_file = \"{}\"\n", | ||
| 948 | + secret.display() | ||
| 949 | + ); | ||
| 950 | + let kept: String = base | ||
| 951 | + .lines() | ||
| 952 | + .filter(|line| !drop.iter().any(|d| line.starts_with(d))) | ||
| 953 | + .map(|line| format!("{line}\n")) | ||
| 954 | + .collect(); | ||
| 955 | + format!("{kept}{extra}") | ||
| 956 | + } | ||
| 957 | + | ||
| 958 | + #[test] | ||
| 959 | + fn r2_backend_parses_and_derives_its_endpoint() { | ||
| 960 | + let dir = tempfile::tempdir().unwrap(); | ||
| 961 | + let path = dir.path().join("forge.toml"); | ||
| 962 | + std::fs::write( | ||
| 963 | + &path, | ||
| 964 | + r2_config_text(dir.path(), &[], "prefix = \"forge/\"\n"), | ||
| 965 | + ) | ||
| 966 | + .unwrap(); | ||
| 967 | + let cfg = Config::load(&path).unwrap(); | ||
| 968 | + assert_eq!(cfg.storage.backend, StorageBackend::R2); | ||
| 969 | + assert_eq!(cfg.storage.r2.bucket, "forge"); | ||
| 970 | + assert_eq!(cfg.storage.r2.prefix, "forge/"); | ||
| 971 | + assert_eq!( | ||
| 972 | + cfg.storage.r2.endpoint(), | ||
| 973 | + "https://0123abcd.r2.cloudflarestorage.com" | ||
| 974 | + ); | ||
| 975 | + } | ||
| 976 | + | ||
| 977 | + #[test] | ||
| 978 | + fn r2_endpoint_follows_jurisdiction() { | ||
| 979 | + let cases = [ | ||
| 980 | + ("", "https://acct.r2.cloudflarestorage.com"), | ||
| 981 | + ("eu", "https://acct.eu.r2.cloudflarestorage.com"), | ||
| 982 | + ("fedramp", "https://acct.fedramp.r2.cloudflarestorage.com"), | ||
| 983 | + ]; | ||
| 984 | + for (jurisdiction, expected) in cases { | ||
| 985 | + let cfg = R2Config { | ||
| 986 | + account_id: "acct".into(), | ||
| 987 | + jurisdiction: jurisdiction.into(), | ||
| 988 | + ..R2Config::default() | ||
| 989 | + }; | ||
| 990 | + assert_eq!(cfg.endpoint(), expected, "jurisdiction `{jurisdiction}`"); | ||
| 991 | + } | ||
| 992 | + } | ||
| 993 | + | ||
| 994 | + #[test] | ||
| 995 | + fn r2_backend_requires_its_fields() { | ||
| 996 | + let dir = tempfile::tempdir().unwrap(); | ||
| 997 | + let path = dir.path().join("forge.toml"); | ||
| 998 | + std::fs::write(&path, r2_config_text(dir.path(), &[], "")).unwrap(); | ||
| 999 | + assert!(Config::load(&path).is_ok()); | ||
| 1000 | + for missing in [ | ||
| 1001 | + "account_id", | ||
| 1002 | + "bucket", | ||
| 1003 | + "access_key_id", | ||
| 1004 | + "secret_access_key_file", | ||
| 1005 | + ] { | ||
| 1006 | + std::fs::write(&path, r2_config_text(dir.path(), &[missing], "")).unwrap(); | ||
| 1007 | + assert!( | ||
| 1008 | + matches!(Config::load(&path), Err(Error::Config(_))), | ||
| 1009 | + "{missing} should be required" | ||
| 1010 | + ); | ||
| 1011 | + } | ||
| 1012 | + } | ||
| 1013 | + | ||
| 1014 | + #[test] | ||
| 1015 | + fn r2_account_id_must_be_hex() { | ||
| 1016 | + let dir = tempfile::tempdir().unwrap(); | ||
| 1017 | + let path = dir.path().join("forge.toml"); | ||
| 1018 | + for bad in ["evil.example.com/", "acct id", "xyz"] { | ||
| 1019 | + let text = r2_config_text( | ||
| 1020 | + dir.path(), | ||
| 1021 | + &["account_id"], | ||
| 1022 | + &format!("account_id = \"{bad}\"\n"), | ||
| 1023 | + ); | ||
| 1024 | + std::fs::write(&path, text).unwrap(); | ||
| 1025 | + assert!( | ||
| 1026 | + matches!(Config::load(&path), Err(Error::Config(_))), | ||
| 1027 | + "`{bad}`" | ||
| 1028 | + ); | ||
| 1029 | + } | ||
| 1030 | + } | ||
| 1031 | + | ||
| 1032 | + #[test] | ||
| 1033 | + fn r2_jurisdiction_must_be_known() { | ||
| 1034 | + let dir = tempfile::tempdir().unwrap(); | ||
| 1035 | + let path = dir.path().join("forge.toml"); | ||
| 1036 | + for (value, ok) in [ | ||
| 1037 | + ("", true), | ||
| 1038 | + ("eu", true), | ||
| 1039 | + ("fedramp", true), | ||
| 1040 | + ("us", false), | ||
| 1041 | + ("EU", false), | ||
| 1042 | + ] { | ||
| 1043 | + let text = r2_config_text( | ||
| 1044 | + dir.path(), | ||
| 1045 | + &["jurisdiction"], | ||
| 1046 | + &format!("jurisdiction = \"{value}\"\n"), | ||
| 1047 | + ); | ||
| 1048 | + std::fs::write(&path, text).unwrap(); | ||
| 1049 | + assert_eq!(Config::load(&path).is_ok(), ok, "jurisdiction `{value}`"); | ||
| 1050 | + } | ||
| 1051 | + } | ||
| 1052 | + | ||
| 1053 | + #[test] | ||
| 1054 | + fn r2_secret_file_must_exist() { | ||
| 1055 | + let dir = tempfile::tempdir().unwrap(); | ||
| 1056 | + let path = dir.path().join("forge.toml"); | ||
| 1057 | + let text = r2_config_text(dir.path(), &["secret_access_key_file"], "") | ||
| 1058 | + + &format!( | ||
| 1059 | + "secret_access_key_file = \"{}\"\n", | ||
| 1060 | + dir.path().join("absent").display() | ||
| 1061 | + ); | ||
| 1062 | + std::fs::write(&path, text).unwrap(); | ||
| 1063 | + assert!(matches!(Config::load(&path), Err(Error::Config(_)))); | ||
| 1064 | + } | ||
| 665 | } | 1065 | } |
crates/forge-core/src/releases.rsmodified+1 -1
| @@ -59,7 +59,7 @@ pub struct NewRelease<'a> { | |||
| 59 | pub author_id: &'a str, | 59 | pub author_id: &'a str, |
| 60 | } | 60 | } |
| 61 | 61 | ||
| 62 | -/// The editable fields of a release. The tag and its target never change. | 62 | +/// The editable fields of a release. The tag and its target are changed with `set_release_tag`. |
| 63 | #[derive(Debug, Clone, Copy)] | 63 | #[derive(Debug, Clone, Copy)] |
| 64 | pub struct ReleaseEdit<'a> { | 64 | pub struct ReleaseEdit<'a> { |
| 65 | pub title: &'a str, | 65 | pub title: &'a str, |
crates/forge-core/src/store/releases.rsmodified+146 -1
| @@ -281,6 +281,52 @@ impl Store { | |||
| 281 | .ok_or_else(missing_row) | 281 | .ok_or_else(missing_row) |
| 282 | } | 282 | } |
| 283 | 283 | ||
| 284 | + /// Swaps the file of an existing asset in one statement. The row takes the new asset's id, | ||
| 285 | + /// size, digest, content type, uploader and time, and keeps its release, name and download | ||
| 286 | + /// count. The new blob must already be written under `assets/<new.id>`; the caller deletes the | ||
| 287 | + /// old blob after this returns. `NotFound` when `old_id` is gone. | ||
| 288 | + pub async fn replace_asset(&self, old_id: &str, new: &NewAsset<'_>) -> Result<ReleaseAsset> { | ||
| 289 | + let size = i64::try_from(new.size).map_err(|_| Error::Invalid("asset too large".into()))?; | ||
| 290 | + let changed = { | ||
| 291 | + let conn = self.inner.conn.lock().await; | ||
| 292 | + conn.execute( | ||
| 293 | + "UPDATE release_assets SET id = ?2, size = ?3, sha256 = ?4, content_type = ?5, \ | ||
| 294 | + uploader_id = ?6, created_at = ?7 WHERE id = ?1", | ||
| 295 | + ( | ||
| 296 | + old_id.to_string(), | ||
| 297 | + new.id.to_string(), | ||
| 298 | + size, | ||
| 299 | + new.sha256.to_string(), | ||
| 300 | + new.content_type.to_string(), | ||
| 301 | + new.uploader_id.to_string(), | ||
| 302 | + now_stamp(), | ||
| 303 | + ), | ||
| 304 | + ) | ||
| 305 | + .await | ||
| 306 | + .map_err(db_err)? | ||
| 307 | + }; | ||
| 308 | + if changed != 1 { | ||
| 309 | + return Err(Error::NotFound); | ||
| 310 | + } | ||
| 311 | + self.release_asset_by_id(new.id) | ||
| 312 | + .await? | ||
| 313 | + .ok_or_else(missing_row) | ||
| 314 | + } | ||
| 315 | + | ||
| 316 | + /// Points a release at another tag and commit. A tag another release already uses is | ||
| 317 | + /// `Conflict`. Returns false when the release is gone. | ||
| 318 | + pub async fn set_release_tag(&self, id: &str, tag: &str, target_oid: &str) -> Result<bool> { | ||
| 319 | + let conn = self.inner.conn.lock().await; | ||
| 320 | + let changed = conn | ||
| 321 | + .execute( | ||
| 322 | + "UPDATE releases SET tag = ?2, target_oid = ?3 WHERE id = ?1", | ||
| 323 | + (id.to_string(), tag.to_string(), target_oid.to_string()), | ||
| 324 | + ) | ||
| 325 | + .await | ||
| 326 | + .map_err(|e| insert_err(e, "a release already exists for this tag"))?; | ||
| 327 | + Ok(changed == 1) | ||
| 328 | + } | ||
| 329 | + | ||
| 284 | /// Deletes one asset row. Returns false when it is already gone. | 330 | /// Deletes one asset row. Returns false when it is already gone. |
| 285 | pub async fn delete_release_asset(&self, id: &str) -> Result<bool> { | 331 | pub async fn delete_release_asset(&self, id: &str) -> Result<bool> { |
| 286 | let conn = self.inner.conn.lock().await; | 332 | let conn = self.inner.conn.lock().await; |
| @@ -328,7 +374,10 @@ mod tests { | |||
| 328 | async fn store_with_repo() -> (tempfile::TempDir, Store, String, String) { | 374 | async fn store_with_repo() -> (tempfile::TempDir, Store, String, String) { |
| 329 | let dir = tempfile::tempdir().unwrap(); | 375 | let dir = tempfile::tempdir().unwrap(); |
| 330 | let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); | 376 | let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); |
| 331 | - let user = store.create_user("tahinli", None, "h", false).await.unwrap(); | 377 | + let user = store |
| 378 | + .create_user("tahinli", None, "h", false) | ||
| 379 | + .await | ||
| 380 | + .unwrap(); | ||
| 332 | let repo = store | 381 | let repo = store |
| 333 | .create_repo(&user.id, "proj", "", crate::Visibility::Public, "main") | 382 | .create_repo(&user.id, "proj", "", crate::Visibility::Public, "main") |
| 334 | .await | 383 | .await |
| @@ -444,6 +493,102 @@ mod tests { | |||
| 444 | assert_eq!(store.delete_release(&rel.id).await.unwrap(), None); | 493 | assert_eq!(store.delete_release(&rel.id).await.unwrap(), None); |
| 445 | } | 494 | } |
| 446 | 495 | ||
| 496 | + #[tokio::test] | ||
| 497 | + async fn replacing_an_asset_swaps_its_file_and_keeps_name_and_count() { | ||
| 498 | + let (_dir, store, user, repo) = store_with_repo().await; | ||
| 499 | + let rel = store | ||
| 500 | + .create_release(&new_release(&repo, &user, "v1", false)) | ||
| 501 | + .await | ||
| 502 | + .unwrap(); | ||
| 503 | + store | ||
| 504 | + .add_asset(&NewAsset { | ||
| 505 | + id: "a1", | ||
| 506 | + release_id: &rel.id, | ||
| 507 | + name: "app.bin", | ||
| 508 | + size: 3, | ||
| 509 | + sha256: "x", | ||
| 510 | + content_type: "application/gzip", | ||
| 511 | + uploader_id: &user, | ||
| 512 | + }) | ||
| 513 | + .await | ||
| 514 | + .unwrap(); | ||
| 515 | + store.count_asset_download("a1").await.unwrap(); | ||
| 516 | + | ||
| 517 | + let replaced = store | ||
| 518 | + .replace_asset( | ||
| 519 | + "a1", | ||
| 520 | + &NewAsset { | ||
| 521 | + id: "a2", | ||
| 522 | + release_id: &rel.id, | ||
| 523 | + name: "app.bin", | ||
| 524 | + size: 5, | ||
| 525 | + sha256: "y", | ||
| 526 | + content_type: "text/plain", | ||
| 527 | + uploader_id: &user, | ||
| 528 | + }, | ||
| 529 | + ) | ||
| 530 | + .await | ||
| 531 | + .unwrap(); | ||
| 532 | + assert_eq!(replaced.id, "a2"); | ||
| 533 | + assert_eq!(replaced.name, "app.bin"); | ||
| 534 | + assert_eq!(replaced.size, 5); | ||
| 535 | + assert_eq!(replaced.sha256, "y"); | ||
| 536 | + assert_eq!(replaced.content_type, "text/plain"); | ||
| 537 | + assert_eq!(replaced.download_count, 1, "the counter survives"); | ||
| 538 | + assert!(store.release_asset_by_id("a1").await.unwrap().is_none()); | ||
| 539 | + assert_eq!( | ||
| 540 | + store.repo_release_asset_ids(&repo).await.unwrap(), | ||
| 541 | + vec!["a2".to_string()] | ||
| 542 | + ); | ||
| 543 | + | ||
| 544 | + let gone = store | ||
| 545 | + .replace_asset( | ||
| 546 | + "a1", | ||
| 547 | + &NewAsset { | ||
| 548 | + id: "a3", | ||
| 549 | + release_id: &rel.id, | ||
| 550 | + name: "app.bin", | ||
| 551 | + size: 1, | ||
| 552 | + sha256: "z", | ||
| 553 | + content_type: "text/plain", | ||
| 554 | + uploader_id: &user, | ||
| 555 | + }, | ||
| 556 | + ) | ||
| 557 | + .await; | ||
| 558 | + assert!(matches!(gone, Err(Error::NotFound)), "{gone:?}"); | ||
| 559 | + } | ||
| 560 | + | ||
| 561 | + #[tokio::test] | ||
| 562 | + async fn retagging_moves_the_release_and_refuses_a_tag_another_release_uses() { | ||
| 563 | + let (_dir, store, user, repo) = store_with_repo().await; | ||
| 564 | + let first = store | ||
| 565 | + .create_release(&new_release(&repo, &user, "v1", true)) | ||
| 566 | + .await | ||
| 567 | + .unwrap(); | ||
| 568 | + store | ||
| 569 | + .create_release(&new_release(&repo, &user, "v2", true)) | ||
| 570 | + .await | ||
| 571 | + .unwrap(); | ||
| 572 | + let new_target = "1111111111111111111111111111111111111111"; | ||
| 573 | + assert!( | ||
| 574 | + store | ||
| 575 | + .set_release_tag(&first.id, "v1b", new_target) | ||
| 576 | + .await | ||
| 577 | + .unwrap() | ||
| 578 | + ); | ||
| 579 | + let moved = store.release(&first.id).await.unwrap().unwrap(); | ||
| 580 | + assert_eq!(moved.tag, "v1b"); | ||
| 581 | + assert_eq!(moved.target_oid, new_target); | ||
| 582 | + let taken = store.set_release_tag(&first.id, "v2", new_target).await; | ||
| 583 | + assert!(matches!(taken, Err(Error::Conflict(_))), "{taken:?}"); | ||
| 584 | + assert!( | ||
| 585 | + !store | ||
| 586 | + .set_release_tag("missing", "v9", new_target) | ||
| 587 | + .await | ||
| 588 | + .unwrap() | ||
| 589 | + ); | ||
| 590 | + } | ||
| 591 | + | ||
| 447 | #[test] | 592 | #[test] |
| 448 | fn asset_names_and_content_types_are_cleaned() { | 593 | fn asset_names_and_content_types_are_cleaned() { |
| 449 | assert!(valid_asset_name("app-1.0_linux+x86.tar.gz")); | 594 | assert!(valid_asset_name("app-1.0_linux+x86.tar.gz")); |
crates/forge-git/src/tags.rsmodified+80 -0
| @@ -47,6 +47,86 @@ pub async fn create_lightweight_tag( | |||
| 47 | .await | 47 | .await |
| 48 | } | 48 | } |
| 49 | 49 | ||
| 50 | +/// Moves `refs/tags/<name>` from `old` to `new`, but only if it still points at `old`. A stale | ||
| 51 | +/// `old` gives `Error::RefMoved` and leaves the tag alone. The caller reads the tag first. | ||
| 52 | +pub async fn move_lightweight_tag( | ||
| 53 | + env: &GitEnv, | ||
| 54 | + repo: &Path, | ||
| 55 | + name: &str, | ||
| 56 | + new: &str, | ||
| 57 | + old: &str, | ||
| 58 | +) -> Result<()> { | ||
| 59 | + if !valid_tag_name(name) { | ||
| 60 | + return Err(Error::InvalidInput(format!("invalid tag name: {name:?}"))); | ||
| 61 | + } | ||
| 62 | + validate_oid(new)?; | ||
| 63 | + validate_oid(old)?; | ||
| 64 | + let refname = format!("refs/tags/{name}"); | ||
| 65 | + let result = git(env, "update-ref") | ||
| 66 | + .git_dir(repo) | ||
| 67 | + .user_arg(&refname)? | ||
| 68 | + .user_arg(new)? | ||
| 69 | + .user_arg(old)? | ||
| 70 | + .status() | ||
| 71 | + .await; | ||
| 72 | + match result { | ||
| 73 | + Err(Error::Failed(msg)) | ||
| 74 | + if msg.contains("but expected") || msg.contains("unable to resolve reference") => | ||
| 75 | + { | ||
| 76 | + Err(Error::RefMoved(refname)) | ||
| 77 | + } | ||
| 78 | + other => other, | ||
| 79 | + } | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// The closest tag reachable from the parent of `oid`, as `(tag name, commit id)`. Lightweight and | ||
| 83 | +/// annotated tags both count. `None` when no tag is reachable or `oid` has no parent. | ||
| 84 | +pub async fn previous_tag( | ||
| 85 | + env: &GitEnv, | ||
| 86 | + repo: &Path, | ||
| 87 | + oid: &str, | ||
| 88 | +) -> crate::error::Result<Option<(String, String)>> { | ||
| 89 | + validate_oid(oid)?; | ||
| 90 | + let parent = format!("{oid}^"); | ||
| 91 | + let described = git(env, "describe") | ||
| 92 | + .git_dir(repo) | ||
| 93 | + .arg("--tags") | ||
| 94 | + .arg("--abbrev=0") | ||
| 95 | + .user_revs(&[&parent])? | ||
| 96 | + .output() | ||
| 97 | + .await; | ||
| 98 | + let Ok(out) = described else { | ||
| 99 | + return Ok(None); | ||
| 100 | + }; | ||
| 101 | + let name = String::from_utf8_lossy(&out).trim().to_owned(); | ||
| 102 | + if name.is_empty() { | ||
| 103 | + return Ok(None); | ||
| 104 | + } | ||
| 105 | + let commit = git(env, "rev-parse") | ||
| 106 | + .git_dir(repo) | ||
| 107 | + .user_arg(&format!("{name}^{{commit}}"))? | ||
| 108 | + .output() | ||
| 109 | + .await?; | ||
| 110 | + let commit = String::from_utf8_lossy(&commit).trim().to_owned(); | ||
| 111 | + Ok(Some((name, commit))) | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// True when `oid` is a full object id that names a commit in the repo. A malformed id or a | ||
| 115 | +/// missing object is `false`, so this is safe to use on user input. | ||
| 116 | +pub async fn commit_exists(env: &GitEnv, repo: &Path, oid: &str) -> bool { | ||
| 117 | + if validate_oid(oid).is_err() { | ||
| 118 | + return false; | ||
| 119 | + } | ||
| 120 | + match git(env, "cat-file") | ||
| 121 | + .git_dir(repo) | ||
| 122 | + .arg("-e") | ||
| 123 | + .user_arg(&format!("{oid}^{{commit}}")) | ||
| 124 | + { | ||
| 125 | + Ok(cmd) => cmd.status().await.is_ok(), | ||
| 126 | + Err(_) => false, | ||
| 127 | + } | ||
| 128 | +} | ||
| 129 | + | ||
| 50 | #[cfg(test)] | 130 | #[cfg(test)] |
| 51 | mod tests { | 131 | mod tests { |
| 52 | use super::valid_tag_name; | 132 | use super::valid_tag_name; |
crates/forge-web/src/api/mod.rsmodified+1 -0
| @@ -4,6 +4,7 @@ | |||
| 4 | //! `{"error": "..."}` with a matching status code. Anonymous callers get 401 whenever they cannot | 4 | //! `{"error": "..."}` with a matching status code. Anonymous callers get 401 whenever they cannot |
| 5 | //! use a repo, the same as git, so missing and hidden repos look identical to them. | 5 | //! use a repo, the same as git, so missing and hidden repos look identical to them. |
| 6 | 6 | ||
| 7 | +pub mod releases; | ||
| 7 | pub mod statuses; | 8 | pub mod statuses; |
| 8 | 9 | ||
| 9 | use std::net::IpAddr; | 10 | use std::net::IpAddr; |
crates/forge-web/src/api/releases.rsadded+884 -0
| @@ -0,0 +1,884 @@ | |||
| 1 | +//! Release routes of the token API (documented in docs/api.md). | ||
| 2 | +//! | ||
| 3 | +//! Reads are public for public repos. Drafts are only listed or fetched by callers with write | ||
| 4 | +//! access, and everyone else gets the same 404 as for a missing release. Writes need a token with | ||
| 5 | +//! the `repo` scope and write access. The business rules live in `release_ops`; these handlers | ||
| 6 | +//! translate input and output only. | ||
| 7 | + | ||
| 8 | +use std::io; | ||
| 9 | + | ||
| 10 | +use forge_core::releases::{Release, ReleaseAsset}; | ||
| 11 | +use forge_core::{Action, Repo as CoreRepo, User}; | ||
| 12 | +use futures_util::StreamExt; | ||
| 13 | +use http::header::CONTENT_TYPE; | ||
| 14 | +use serde::Deserialize; | ||
| 15 | +use serde_json::{Value, json}; | ||
| 16 | +use topcoat::context::{Cx, app_context}; | ||
| 17 | +use topcoat::router::request::headers; | ||
| 18 | +use topcoat::router::response::Response; | ||
| 19 | +use topcoat::router::{Body, StatusCode, path_param, route}; | ||
| 20 | + | ||
| 21 | +use crate::api::{self, Refusal}; | ||
| 22 | +use crate::client_ip::client_ip; | ||
| 23 | +use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError}; | ||
| 24 | +use crate::state::AppState; | ||
| 25 | +use crate::views::enc; | ||
| 26 | + | ||
| 27 | +path_param!(owner); | ||
| 28 | +path_param!(repo); | ||
| 29 | +path_param!(id); | ||
| 30 | +path_param!(tag); | ||
| 31 | +path_param!(asset); | ||
| 32 | + | ||
| 33 | +/// Body of `POST .../releases`. Only `tag` is required. | ||
| 34 | +#[derive(Deserialize)] | ||
| 35 | +struct CreateBody { | ||
| 36 | + tag: String, | ||
| 37 | + target: Option<String>, | ||
| 38 | + title: Option<String>, | ||
| 39 | + body: Option<String>, | ||
| 40 | + draft: Option<bool>, | ||
| 41 | + prerelease: Option<bool>, | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +/// Body of `PATCH .../releases/{id}`. Omitted fields keep their current values. | ||
| 45 | +#[derive(Deserialize)] | ||
| 46 | +struct PatchBody { | ||
| 47 | + title: Option<String>, | ||
| 48 | + body: Option<String>, | ||
| 49 | + draft: Option<bool>, | ||
| 50 | + prerelease: Option<bool>, | ||
| 51 | + tag: Option<String>, | ||
| 52 | + target: Option<String>, | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +#[route(GET "/api/v1/repos/{owner}/{repo}/releases")] | ||
| 56 | +async fn list_releases(cx: &Cx) -> topcoat::Result<Response> { | ||
| 57 | + let state = app_context::<AppState>(cx); | ||
| 58 | + let (repo, can_write) = match read_context(cx).await { | ||
| 59 | + Ok(found) => found, | ||
| 60 | + Err(res) => return Ok(*res), | ||
| 61 | + }; | ||
| 62 | + let releases = match state.store.list_releases(&repo.id).await { | ||
| 63 | + Ok(releases) => releases, | ||
| 64 | + Err(e) => return Ok(*api::internal(e)), | ||
| 65 | + }; | ||
| 66 | + let mut out = Vec::new(); | ||
| 67 | + for release in releases.iter().filter(|r| can_write || !r.draft) { | ||
| 68 | + match release_json(state, &repo, release).await { | ||
| 69 | + Ok(value) => out.push(value), | ||
| 70 | + Err(res) => return Ok(*res), | ||
| 71 | + } | ||
| 72 | + } | ||
| 73 | + Ok(api::json(StatusCode::OK, &Value::Array(out))) | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +#[route(GET "/api/v1/repos/{owner}/{repo}/releases/tags/{tag}")] | ||
| 77 | +async fn get_release_by_tag(cx: &Cx) -> topcoat::Result<Response> { | ||
| 78 | + let state = app_context::<AppState>(cx); | ||
| 79 | + let (repo, can_write) = match read_context(cx).await { | ||
| 80 | + Ok(found) => found, | ||
| 81 | + Err(res) => return Ok(*res), | ||
| 82 | + }; | ||
| 83 | + let tag_name = path_param::<Tag>(cx); | ||
| 84 | + let release = match state.store.release_by_tag(&repo.id, tag_name).await { | ||
| 85 | + Ok(Some(release)) if can_write || !release.draft => release, | ||
| 86 | + Ok(_) => return Ok(not_found()), | ||
| 87 | + Err(e) => return Ok(*api::internal(e)), | ||
| 88 | + }; | ||
| 89 | + match release_json(state, &repo, &release).await { | ||
| 90 | + Ok(value) => Ok(api::json(StatusCode::OK, &value)), | ||
| 91 | + Err(res) => Ok(*res), | ||
| 92 | + } | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +#[route(POST "/api/v1/repos/{owner}/{repo}/releases")] | ||
| 96 | +async fn create_release(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 97 | + let state = app_context::<AppState>(cx); | ||
| 98 | + let (repo, user) = match write_context(cx).await { | ||
| 99 | + Ok(found) => found, | ||
| 100 | + Err(res) => return Ok(*res), | ||
| 101 | + }; | ||
| 102 | + let bytes = match api::read_body(body, MAX_JSON_BYTES).await { | ||
| 103 | + Ok(bytes) => bytes, | ||
| 104 | + Err(res) => return Ok(*res), | ||
| 105 | + }; | ||
| 106 | + let input: CreateBody = match serde_json::from_slice(&bytes) { | ||
| 107 | + Ok(input) => input, | ||
| 108 | + Err(e) => { | ||
| 109 | + return Ok(api::error( | ||
| 110 | + StatusCode::BAD_REQUEST, | ||
| 111 | + &format!("invalid JSON body: {e}"), | ||
| 112 | + )); | ||
| 113 | + } | ||
| 114 | + }; | ||
| 115 | + let title = input.title.unwrap_or_else(|| input.tag.clone()); | ||
| 116 | + let created = release_ops::create( | ||
| 117 | + state, | ||
| 118 | + &repo, | ||
| 119 | + &user, | ||
| 120 | + CreateRelease { | ||
| 121 | + tag: input.tag, | ||
| 122 | + target: input.target, | ||
| 123 | + title, | ||
| 124 | + body: input.body.unwrap_or_default(), | ||
| 125 | + draft: input.draft.unwrap_or(false), | ||
| 126 | + prerelease: input.prerelease.unwrap_or(false), | ||
| 127 | + }, | ||
| 128 | + ) | ||
| 129 | + .await; | ||
| 130 | + let created = match created { | ||
| 131 | + Ok(created) => created, | ||
| 132 | + Err(e) => return Ok(*release_failure(e)), | ||
| 133 | + }; | ||
| 134 | + match release_json(state, &repo, &created).await { | ||
| 135 | + Ok(value) => Ok(api::json(StatusCode::CREATED, &value)), | ||
| 136 | + Err(res) => Ok(*res), | ||
| 137 | + } | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +#[route(PATCH "/api/v1/repos/{owner}/{repo}/releases/{id}")] | ||
| 141 | +async fn edit_release(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 142 | + let state = app_context::<AppState>(cx); | ||
| 143 | + let (repo, user) = match write_context(cx).await { | ||
| 144 | + Ok(found) => found, | ||
| 145 | + Err(res) => return Ok(*res), | ||
| 146 | + }; | ||
| 147 | + let release = match release_in_repo(state, &repo, path_param::<Id>(cx)).await { | ||
| 148 | + Ok(release) => release, | ||
| 149 | + Err(res) => return Ok(*res), | ||
| 150 | + }; | ||
| 151 | + let bytes = match api::read_body(body, MAX_JSON_BYTES).await { | ||
| 152 | + Ok(bytes) => bytes, | ||
| 153 | + Err(res) => return Ok(*res), | ||
| 154 | + }; | ||
| 155 | + let patch: PatchBody = match serde_json::from_slice(&bytes) { | ||
| 156 | + Ok(patch) => patch, | ||
| 157 | + Err(e) => { | ||
| 158 | + return Ok(api::error( | ||
| 159 | + StatusCode::BAD_REQUEST, | ||
| 160 | + &format!("invalid JSON body: {e}"), | ||
| 161 | + )); | ||
| 162 | + } | ||
| 163 | + }; | ||
| 164 | + let edit = EditRelease { | ||
| 165 | + title: patch.title.unwrap_or_else(|| release.title.clone()), | ||
| 166 | + body: patch.body.unwrap_or_else(|| release.body.clone()), | ||
| 167 | + draft: patch.draft.unwrap_or(release.draft), | ||
| 168 | + prerelease: patch.prerelease.unwrap_or(release.prerelease), | ||
| 169 | + tag: patch.tag, | ||
| 170 | + target: patch.target, | ||
| 171 | + }; | ||
| 172 | + let edited = match release_ops::update(state, &repo, &user, &release, edit).await { | ||
| 173 | + Ok(edited) => edited, | ||
| 174 | + Err(e) => return Ok(*release_failure(e)), | ||
| 175 | + }; | ||
| 176 | + match release_json(state, &repo, &edited).await { | ||
| 177 | + Ok(value) => Ok(api::json(StatusCode::OK, &value)), | ||
| 178 | + Err(res) => Ok(*res), | ||
| 179 | + } | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +#[route(DELETE "/api/v1/repos/{owner}/{repo}/releases/{id}")] | ||
| 183 | +async fn delete_release(cx: &Cx) -> topcoat::Result<Response> { | ||
| 184 | + let state = app_context::<AppState>(cx); | ||
| 185 | + let (repo, user) = match write_context(cx).await { | ||
| 186 | + Ok(found) => found, | ||
| 187 | + Err(res) => return Ok(*res), | ||
| 188 | + }; | ||
| 189 | + let release = match release_in_repo(state, &repo, path_param::<Id>(cx)).await { | ||
| 190 | + Ok(release) => release, | ||
| 191 | + Err(res) => return Ok(*res), | ||
| 192 | + }; | ||
| 193 | + match release_ops::delete(state, &repo, &user, &release).await { | ||
| 194 | + Ok(()) => Ok(no_content()), | ||
| 195 | + Err(e) => Ok(*release_failure(e)), | ||
| 196 | + } | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +/// Streams the raw request body into an asset. `201` for a new name, `200` when it replaces one. | ||
| 200 | +#[route(PUT "/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}")] | ||
| 201 | +async fn upload_asset(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 202 | + let state = app_context::<AppState>(cx); | ||
| 203 | + let (repo, user) = match write_context(cx).await { | ||
| 204 | + Ok(found) => found, | ||
| 205 | + Err(res) => return Ok(*res), | ||
| 206 | + }; | ||
| 207 | + let release = match release_in_repo(state, &repo, path_param::<Id>(cx)).await { | ||
| 208 | + Ok(release) => release, | ||
| 209 | + Err(res) => return Ok(*res), | ||
| 210 | + }; | ||
| 211 | + let content_type = headers(cx) | ||
| 212 | + .get(CONTENT_TYPE) | ||
| 213 | + .and_then(|value| value.to_str().ok()) | ||
| 214 | + .map(str::to_owned); | ||
| 215 | + let max_bytes = state | ||
| 216 | + .config | ||
| 217 | + .releases | ||
| 218 | + .max_asset_mb | ||
| 219 | + .saturating_mul(1024 * 1024); | ||
| 220 | + // The body is streamed chunk by chunk into the blob store; nothing buffers the whole file. | ||
| 221 | + let stream = Box::pin( | ||
| 222 | + body.into_data_stream() | ||
| 223 | + .map(|chunk| chunk.map_err(io::Error::other)), | ||
| 224 | + ); | ||
| 225 | + let stored = release_ops::put_asset( | ||
| 226 | + state, | ||
| 227 | + &repo, | ||
| 228 | + &release, | ||
| 229 | + &user, | ||
| 230 | + path_param::<Asset>(cx), | ||
| 231 | + content_type.as_deref(), | ||
| 232 | + stream, | ||
| 233 | + max_bytes, | ||
| 234 | + ) | ||
| 235 | + .await; | ||
| 236 | + let (asset, replaced) = match stored { | ||
| 237 | + Ok(stored) => stored, | ||
| 238 | + Err(e) => return Ok(*release_failure(e)), | ||
| 239 | + }; | ||
| 240 | + let status = if replaced { | ||
| 241 | + StatusCode::OK | ||
| 242 | + } else { | ||
| 243 | + StatusCode::CREATED | ||
| 244 | + }; | ||
| 245 | + Ok(api::json( | ||
| 246 | + status, | ||
| 247 | + &asset_json(&state.config.base_url, &repo, &release, &asset), | ||
| 248 | + )) | ||
| 249 | +} | ||
| 250 | + | ||
| 251 | +#[route(DELETE "/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}")] | ||
| 252 | +async fn delete_asset(cx: &Cx) -> topcoat::Result<Response> { | ||
| 253 | + let state = app_context::<AppState>(cx); | ||
| 254 | + let (repo, _user) = match write_context(cx).await { | ||
| 255 | + Ok(found) => found, | ||
| 256 | + Err(res) => return Ok(*res), | ||
| 257 | + }; | ||
| 258 | + let release = match release_in_repo(state, &repo, path_param::<Id>(cx)).await { | ||
| 259 | + Ok(release) => release, | ||
| 260 | + Err(res) => return Ok(*res), | ||
| 261 | + }; | ||
| 262 | + match release_ops::delete_asset(state, &repo, &release, path_param::<Asset>(cx)).await { | ||
| 263 | + Ok(()) => Ok(no_content()), | ||
| 264 | + Err(e) => Ok(*release_failure(e)), | ||
| 265 | + } | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +/// Largest accepted JSON body, in bytes. | ||
| 269 | +const MAX_JSON_BYTES: usize = 64 * 1024; | ||
| 270 | + | ||
| 271 | +/// Authenticates an optional caller and loads the repo for reading. Also reports whether the | ||
| 272 | +/// caller may write, which decides whether drafts are visible. | ||
| 273 | +async fn read_context(cx: &Cx) -> Result<(CoreRepo, bool), Refusal> { | ||
| 274 | + let state = app_context::<AppState>(cx); | ||
| 275 | + let actor = api::authenticate(state, client_ip(cx), headers(cx)).await?; | ||
| 276 | + let repo = api::load_repo( | ||
| 277 | + state, | ||
| 278 | + actor.as_ref(), | ||
| 279 | + path_param::<Owner>(cx), | ||
| 280 | + path_param::<Repo>(cx), | ||
| 281 | + Action::Read, | ||
| 282 | + ) | ||
| 283 | + .await?; | ||
| 284 | + let can_write = api::load_repo( | ||
| 285 | + state, | ||
| 286 | + actor.as_ref(), | ||
| 287 | + path_param::<Owner>(cx), | ||
| 288 | + path_param::<Repo>(cx), | ||
| 289 | + Action::Write, | ||
| 290 | + ) | ||
| 291 | + .await | ||
| 292 | + .is_ok(); | ||
| 293 | + Ok((repo, can_write)) | ||
| 294 | +} | ||
| 295 | + | ||
| 296 | +/// Authenticates a required caller with write access and loads the repo. | ||
| 297 | +async fn write_context(cx: &Cx) -> Result<(CoreRepo, User), Refusal> { | ||
| 298 | + let state = app_context::<AppState>(cx); | ||
| 299 | + let actor = api::authenticate(state, client_ip(cx), headers(cx)).await?; | ||
| 300 | + let repo = api::load_repo( | ||
| 301 | + state, | ||
| 302 | + actor.as_ref(), | ||
| 303 | + path_param::<Owner>(cx), | ||
| 304 | + path_param::<Repo>(cx), | ||
| 305 | + Action::Write, | ||
| 306 | + ) | ||
| 307 | + .await?; | ||
| 308 | + match actor { | ||
| 309 | + Some(user) => Ok((repo, user)), | ||
| 310 | + None => Err(Box::new(api::unauthorized())), | ||
| 311 | + } | ||
| 312 | +} | ||
| 313 | + | ||
| 314 | +/// The release with this id, which must belong to `repo`. Anything else is a 404, so ids from | ||
| 315 | +/// other repos cannot be probed. Callers of this function already have write access. | ||
| 316 | +async fn release_in_repo(state: &AppState, repo: &CoreRepo, id: &str) -> Result<Release, Refusal> { | ||
| 317 | + match state.store.release(id).await { | ||
| 318 | + Ok(Some(release)) if release.repo_id == repo.id => Ok(release), | ||
| 319 | + Ok(_) => Err(Box::new(not_found())), | ||
| 320 | + Err(e) => Err(api::internal(e)), | ||
| 321 | + } | ||
| 322 | +} | ||
| 323 | + | ||
| 324 | +/// The release JSON with its assets. | ||
| 325 | +async fn release_json( | ||
| 326 | + state: &AppState, | ||
| 327 | + repo: &CoreRepo, | ||
| 328 | + release: &Release, | ||
| 329 | +) -> Result<Value, Refusal> { | ||
| 330 | + let assets = state | ||
| 331 | + .store | ||
| 332 | + .list_release_assets(&release.id) | ||
| 333 | + .await | ||
| 334 | + .map_err(api::internal)?; | ||
| 335 | + let base = state.config.base_url.trim_end_matches('/'); | ||
| 336 | + let assets: Vec<Value> = assets | ||
| 337 | + .iter() | ||
| 338 | + .map(|asset| asset_json(base, repo, release, asset)) | ||
| 339 | + .collect(); | ||
| 340 | + Ok(json!({ | ||
| 341 | + "id": release.id, | ||
| 342 | + "tag": release.tag, | ||
| 343 | + "target": release.target_oid, | ||
| 344 | + "title": release.title, | ||
| 345 | + "body": release.body, | ||
| 346 | + "draft": release.draft, | ||
| 347 | + "prerelease": release.prerelease, | ||
| 348 | + "author": release.author_name, | ||
| 349 | + "created_at": release.created_at, | ||
| 350 | + "published_at": release.published_at, | ||
| 351 | + "html_url": format!("{base}/{}/{}/releases/tag/{}", repo.owner_name, repo.name, enc(&release.tag)), | ||
| 352 | + "assets": assets, | ||
| 353 | + })) | ||
| 354 | +} | ||
| 355 | + | ||
| 356 | +/// The asset JSON. `download_url` is the web download route, which enforces draft visibility. | ||
| 357 | +fn asset_json(base: &str, repo: &CoreRepo, release: &Release, asset: &ReleaseAsset) -> Value { | ||
| 358 | + let base = base.trim_end_matches('/'); | ||
| 359 | + json!({ | ||
| 360 | + "id": asset.id, | ||
| 361 | + "name": asset.name, | ||
| 362 | + "size": asset.size, | ||
| 363 | + "sha256": asset.sha256, | ||
| 364 | + "content_type": asset.content_type, | ||
| 365 | + "download_count": asset.download_count, | ||
| 366 | + "created_at": asset.created_at, | ||
| 367 | + "download_url": format!( | ||
| 368 | + "{base}/{}/{}/releases/download/{}/{}", | ||
| 369 | + repo.owner_name, | ||
| 370 | + repo.name, | ||
| 371 | + enc(&release.tag), | ||
| 372 | + enc(&asset.name) | ||
| 373 | + ), | ||
| 374 | + }) | ||
| 375 | +} | ||
| 376 | + | ||
| 377 | +/// Maps a release failure: internal errors are logged and hidden, the rest keep their message. | ||
| 378 | +fn release_failure(e: ReleaseError) -> Refusal { | ||
| 379 | + match e { | ||
| 380 | + ReleaseError::Internal(cause) => api::internal(cause), | ||
| 381 | + other => Box::new(api::error(other.status(), &other.message())), | ||
| 382 | + } | ||
| 383 | +} | ||
| 384 | + | ||
| 385 | +fn not_found() -> Response { | ||
| 386 | + api::error(StatusCode::NOT_FOUND, "release not found") | ||
| 387 | +} | ||
| 388 | + | ||
| 389 | +fn no_content() -> Response { | ||
| 390 | + let mut res = Response::new(Body::from(String::new())); | ||
| 391 | + *res.status_mut() = StatusCode::NO_CONTENT; | ||
| 392 | + res | ||
| 393 | +} | ||
| 394 | + | ||
| 395 | +#[cfg(test)] | ||
| 396 | +mod tests { | ||
| 397 | + use std::path::{Path, PathBuf}; | ||
| 398 | + use std::sync::Arc; | ||
| 399 | + | ||
| 400 | + use forge_core::releases::NewRelease; | ||
| 401 | + use forge_core::token::{generate_token, hash_token}; | ||
| 402 | + use forge_core::{Role, Store, User, Visibility}; | ||
| 403 | + use forge_git::repo::{init_bare, repo_path}; | ||
| 404 | + use http::header::{AUTHORIZATION, CONTENT_TYPE}; | ||
| 405 | + use topcoat::router::request::Request; | ||
| 406 | + use topcoat::router::{Body, Router, to_bytes}; | ||
| 407 | + | ||
| 408 | + use crate::test_support::{app_router, test_state}; | ||
| 409 | + | ||
| 410 | + const OWNER: &str = "tahinli"; | ||
| 411 | + const REPO: &str = "proj"; | ||
| 412 | + const MIB: u64 = 1024 * 1024; | ||
| 413 | + | ||
| 414 | + fn git(dir: &Path, args: &[&str]) -> String { | ||
| 415 | + let out = std::process::Command::new("git") | ||
| 416 | + .current_dir(dir) | ||
| 417 | + .args(args) | ||
| 418 | + .output() | ||
| 419 | + .expect("git runs"); | ||
| 420 | + assert!(out.status.success(), "git {args:?} failed"); | ||
| 421 | + String::from_utf8_lossy(&out.stdout).trim().to_owned() | ||
| 422 | + } | ||
| 423 | + | ||
| 424 | + struct Fixture { | ||
| 425 | + _tmp: tempfile::TempDir, | ||
| 426 | + router: Router, | ||
| 427 | + store: Store, | ||
| 428 | + owner: User, | ||
| 429 | + owner_token: String, | ||
| 430 | + reader_token: String, | ||
| 431 | + stranger_token: String, | ||
| 432 | + scopeless_token: String, | ||
| 433 | + } | ||
| 434 | + | ||
| 435 | + /// `tahinli/proj` is public with `main` holding one commit. `bob` reads it, `carol` has no | ||
| 436 | + /// access, and every user has a token. `max_mb` replaces the asset size limit when given. | ||
| 437 | + async fn fixture(max_mb: Option<u64>) -> Fixture { | ||
| 438 | + let tmp = tempfile::tempdir().expect("tempdir"); | ||
| 439 | + let mut state = test_state(tmp.path()).await; | ||
| 440 | + if let Some(mb) = max_mb { | ||
| 441 | + let mut config = (*state.config).clone(); | ||
| 442 | + config.releases.max_asset_mb = mb; | ||
| 443 | + state.config = Arc::new(config); | ||
| 444 | + } | ||
| 445 | + let store = state.store.clone(); | ||
| 446 | + let owner = store | ||
| 447 | + .create_user(OWNER, None, "not-a-real-hash", false) | ||
| 448 | + .await | ||
| 449 | + .expect("owner"); | ||
| 450 | + let bob = store | ||
| 451 | + .create_user("bob", None, "not-a-real-hash", false) | ||
| 452 | + .await | ||
| 453 | + .expect("bob"); | ||
| 454 | + let carol = store | ||
| 455 | + .create_user("carol", None, "not-a-real-hash", false) | ||
| 456 | + .await | ||
| 457 | + .expect("carol"); | ||
| 458 | + let repo = store | ||
| 459 | + .create_repo(&owner.id, REPO, "", Visibility::Public, "main") | ||
| 460 | + .await | ||
| 461 | + .expect("repo"); | ||
| 462 | + store | ||
| 463 | + .set_collaborator(&repo.id, &bob.id, Role::Read) | ||
| 464 | + .await | ||
| 465 | + .expect("collaborator"); | ||
| 466 | + | ||
| 467 | + let bare: PathBuf = repo_path(&state.git.data_dir, &repo.id).expect("repo path"); | ||
| 468 | + init_bare(&state.git, &bare, "main").await.expect("init"); | ||
| 469 | + let work = tmp.path().join("work"); | ||
| 470 | + git(tmp.path(), &["init", "-b", "main", "work"]); | ||
| 471 | + std::fs::write(work.join("file.txt"), "one").expect("write"); | ||
| 472 | + git(&work, &["add", "file.txt"]); | ||
| 473 | + git(&work, &["commit", "-m", "one"]); | ||
| 474 | + git(&work, &["push", bare.to_str().expect("utf8"), "main"]); | ||
| 475 | + | ||
| 476 | + let owner_token = token_for(&store, &owner.id, &["repo"]).await; | ||
| 477 | + let reader_token = token_for(&store, &bob.id, &["repo"]).await; | ||
| 478 | + let stranger_token = token_for(&store, &carol.id, &["repo"]).await; | ||
| 479 | + let scopeless_token = token_for(&store, &owner.id, &[]).await; | ||
| 480 | + Fixture { | ||
| 481 | + router: app_router(state), | ||
| 482 | + _tmp: tmp, | ||
| 483 | + store, | ||
| 484 | + owner, | ||
| 485 | + owner_token, | ||
| 486 | + reader_token, | ||
| 487 | + stranger_token, | ||
| 488 | + scopeless_token, | ||
| 489 | + } | ||
| 490 | + } | ||
| 491 | + | ||
| 492 | + async fn token_for(store: &Store, user_id: &str, scopes: &[&str]) -> String { | ||
| 493 | + let raw = generate_token(); | ||
| 494 | + let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect(); | ||
| 495 | + store | ||
| 496 | + .create_token(user_id, "test", &hash_token(&raw), &scopes, None) | ||
| 497 | + .await | ||
| 498 | + .expect("token"); | ||
| 499 | + raw | ||
| 500 | + } | ||
| 501 | + | ||
| 502 | + fn bearer(raw: &str) -> String { | ||
| 503 | + format!("Bearer {raw}") | ||
| 504 | + } | ||
| 505 | + | ||
| 506 | + /// Sends one request through the router: `(status, json body)`. | ||
| 507 | + async fn send( | ||
| 508 | + router: &Router, | ||
| 509 | + method: &str, | ||
| 510 | + uri: &str, | ||
| 511 | + auth: Option<&str>, | ||
| 512 | + content_type: Option<&str>, | ||
| 513 | + body: Vec<u8>, | ||
| 514 | + ) -> (u16, serde_json::Value) { | ||
| 515 | + let mut builder = Request::builder().method(method).uri(uri); | ||
| 516 | + if let Some(auth) = auth { | ||
| 517 | + builder = builder.header(AUTHORIZATION, auth); | ||
| 518 | + } | ||
| 519 | + if let Some(content_type) = content_type { | ||
| 520 | + builder = builder.header(CONTENT_TYPE, content_type); | ||
| 521 | + } | ||
| 522 | + let req = builder.body(Body::from(body)).unwrap(); | ||
| 523 | + let res = router.handle(req).await; | ||
| 524 | + let status = res.status().as_u16(); | ||
| 525 | + let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); | ||
| 526 | + let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null); | ||
| 527 | + (status, json) | ||
| 528 | + } | ||
| 529 | + | ||
| 530 | + async fn post_json(f: &Fixture, auth: Option<&str>, json: &str) -> (u16, serde_json::Value) { | ||
| 531 | + send( | ||
| 532 | + &f.router, | ||
| 533 | + "POST", | ||
| 534 | + &releases_uri(""), | ||
| 535 | + auth, | ||
| 536 | + Some("application/json"), | ||
| 537 | + json.as_bytes().to_vec(), | ||
| 538 | + ) | ||
| 539 | + .await | ||
| 540 | + } | ||
| 541 | + | ||
| 542 | + fn releases_uri(rest: &str) -> String { | ||
| 543 | + format!("/api/v1/repos/{OWNER}/{REPO}/releases{rest}") | ||
| 544 | + } | ||
| 545 | + | ||
| 546 | + /// Creates a release through the API and returns its id. | ||
| 547 | + async fn create(f: &Fixture, json: &str) -> String { | ||
| 548 | + let (status, body) = post_json(f, Some(&bearer(&f.owner_token)), json).await; | ||
| 549 | + assert_eq!(status, 201, "{body}"); | ||
| 550 | + body["id"].as_str().expect("id").to_owned() | ||
| 551 | + } | ||
| 552 | + | ||
| 553 | + async fn upload(f: &Fixture, id: &str, name: &str, bytes: Vec<u8>) -> (u16, serde_json::Value) { | ||
| 554 | + send( | ||
| 555 | + &f.router, | ||
| 556 | + "PUT", | ||
| 557 | + &releases_uri(&format!("/{id}/assets/{name}")), | ||
| 558 | + Some(&bearer(&f.owner_token)), | ||
| 559 | + Some("application/octet-stream"), | ||
| 560 | + bytes, | ||
| 561 | + ) | ||
| 562 | + .await | ||
| 563 | + } | ||
| 564 | + | ||
| 565 | + #[tokio::test] | ||
| 566 | + async fn anonymous_and_bad_tokens_are_unauthorized() { | ||
| 567 | + let f = fixture(None).await; | ||
| 568 | + let (status, body) = post_json(&f, None, r#"{"tag":"v1"}"#).await; | ||
| 569 | + assert_eq!(status, 401); | ||
| 570 | + assert!(body["error"].is_string()); | ||
| 571 | + let (status, _) = | ||
| 572 | + post_json(&f, Some("Bearer forge_not_a_real_token"), r#"{"tag":"v1"}"#).await; | ||
| 573 | + assert_eq!(status, 401); | ||
| 574 | + } | ||
| 575 | + | ||
| 576 | + #[tokio::test] | ||
| 577 | + async fn token_without_repo_scope_is_forbidden() { | ||
| 578 | + let f = fixture(None).await; | ||
| 579 | + let (status, _) = post_json(&f, Some(&bearer(&f.scopeless_token)), r#"{"tag":"v1"}"#).await; | ||
| 580 | + assert_eq!(status, 403); | ||
| 581 | + } | ||
| 582 | + | ||
| 583 | + #[tokio::test] | ||
| 584 | + async fn read_only_collaborator_cannot_write() { | ||
| 585 | + let f = fixture(None).await; | ||
| 586 | + let auth = bearer(&f.reader_token); | ||
| 587 | + let (status, body) = post_json(&f, Some(&auth), r#"{"tag":"v1"}"#).await; | ||
| 588 | + assert_eq!(status, 403, "{body}"); | ||
| 589 | + let id = create(&f, r#"{"tag":"v1","target":"main"}"#).await; | ||
| 590 | + let (status, _) = upload(&f, &id, "app.bin", b"x".to_vec()).await; | ||
| 591 | + assert_eq!(status, 201); | ||
| 592 | + let (status, _) = send( | ||
| 593 | + &f.router, | ||
| 594 | + "DELETE", | ||
| 595 | + &releases_uri(&format!("/{id}")), | ||
| 596 | + Some(&auth), | ||
| 597 | + None, | ||
| 598 | + Vec::new(), | ||
| 599 | + ) | ||
| 600 | + .await; | ||
| 601 | + assert_eq!(status, 403); | ||
| 602 | + } | ||
| 603 | + | ||
| 604 | + #[tokio::test] | ||
| 605 | + async fn create_list_and_get_by_tag() { | ||
| 606 | + let f = fixture(None).await; | ||
| 607 | + let (status, body) = post_json( | ||
| 608 | + &f, | ||
| 609 | + Some(&bearer(&f.owner_token)), | ||
| 610 | + r#"{"tag":"v1.0","target":"main","body":"notes"}"#, | ||
| 611 | + ) | ||
| 612 | + .await; | ||
| 613 | + assert_eq!(status, 201, "{body}"); | ||
| 614 | + assert_eq!(body["title"], "v1.0", "the title defaults to the tag"); | ||
| 615 | + assert_eq!(body["body"], "notes"); | ||
| 616 | + assert_eq!(body["draft"], false); | ||
| 617 | + assert_eq!(body["author"], OWNER); | ||
| 618 | + assert_eq!(body["assets"], serde_json::json!([])); | ||
| 619 | + assert_eq!(body["target"].as_str().map(str::len), Some(40)); | ||
| 620 | + assert!( | ||
| 621 | + body["html_url"] | ||
| 622 | + .as_str() | ||
| 623 | + .unwrap() | ||
| 624 | + .ends_with("/releases/tag/v1.0") | ||
| 625 | + ); | ||
| 626 | + | ||
| 627 | + create(&f, r#"{"tag":"v0.9","target":"main"}"#).await; | ||
| 628 | + let (status, list) = | ||
| 629 | + send(&f.router, "GET", &releases_uri(""), None, None, Vec::new()).await; | ||
| 630 | + assert_eq!(status, 200); | ||
| 631 | + let tags: Vec<&str> = list | ||
| 632 | + .as_array() | ||
| 633 | + .unwrap() | ||
| 634 | + .iter() | ||
| 635 | + .map(|r| r["tag"].as_str().unwrap()) | ||
| 636 | + .collect(); | ||
| 637 | + assert_eq!(tags.len(), 2); | ||
| 638 | + assert!(tags.contains(&"v1.0") && tags.contains(&"v0.9")); | ||
| 639 | + | ||
| 640 | + let (status, one) = send( | ||
| 641 | + &f.router, | ||
| 642 | + "GET", | ||
| 643 | + &releases_uri("/tags/v1.0"), | ||
| 644 | + None, | ||
| 645 | + None, | ||
| 646 | + Vec::new(), | ||
| 647 | + ) | ||
| 648 | + .await; | ||
| 649 | + assert_eq!(status, 200); | ||
| 650 | + assert_eq!(one["tag"], "v1.0"); | ||
| 651 | + let (status, _) = send( | ||
| 652 | + &f.router, | ||
| 653 | + "GET", | ||
| 654 | + &releases_uri("/tags/missing"), | ||
| 655 | + None, | ||
| 656 | + None, | ||
| 657 | + Vec::new(), | ||
| 658 | + ) | ||
| 659 | + .await; | ||
| 660 | + assert_eq!(status, 404); | ||
| 661 | + } | ||
| 662 | + | ||
| 663 | + #[tokio::test] | ||
| 664 | + async fn patch_keeps_omitted_fields() { | ||
| 665 | + let f = fixture(None).await; | ||
| 666 | + let id = create( | ||
| 667 | + &f, | ||
| 668 | + r#"{"tag":"v2","target":"main","title":"Two","body":"keep me"}"#, | ||
| 669 | + ) | ||
| 670 | + .await; | ||
| 671 | + let (status, body) = send( | ||
| 672 | + &f.router, | ||
| 673 | + "PATCH", | ||
| 674 | + &releases_uri(&format!("/{id}")), | ||
| 675 | + Some(&bearer(&f.owner_token)), | ||
| 676 | + Some("application/json"), | ||
| 677 | + br#"{"title":"Second"}"#.to_vec(), | ||
| 678 | + ) | ||
| 679 | + .await; | ||
| 680 | + assert_eq!(status, 200, "{body}"); | ||
| 681 | + assert_eq!(body["title"], "Second"); | ||
| 682 | + assert_eq!(body["body"], "keep me"); | ||
| 683 | + assert_eq!(body["tag"], "v2"); | ||
| 684 | + assert_eq!(body["prerelease"], false); | ||
| 685 | + | ||
| 686 | + let (status, body) = send( | ||
| 687 | + &f.router, | ||
| 688 | + "PATCH", | ||
| 689 | + &releases_uri(&format!("/{id}")), | ||
| 690 | + Some(&bearer(&f.owner_token)), | ||
| 691 | + Some("application/json"), | ||
| 692 | + br#"{"draft":true}"#.to_vec(), | ||
| 693 | + ) | ||
| 694 | + .await; | ||
| 695 | + assert_eq!(status, 200, "{body}"); | ||
| 696 | + assert_eq!(body["draft"], true); | ||
| 697 | + assert_eq!(body["title"], "Second"); | ||
| 698 | + } | ||
| 699 | + | ||
| 700 | + #[tokio::test] | ||
| 701 | + async fn upload_is_201_then_200_on_replace() { | ||
| 702 | + let f = fixture(None).await; | ||
| 703 | + let id = create(&f, r#"{"tag":"v1","target":"main"}"#).await; | ||
| 704 | + let (status, body) = upload(&f, &id, "app.bin", b"one".to_vec()).await; | ||
| 705 | + assert_eq!(status, 201, "{body}"); | ||
| 706 | + assert_eq!(body["size"], 3); | ||
| 707 | + assert_eq!(body["content_type"], "application/octet-stream"); | ||
| 708 | + let url = body["download_url"].as_str().expect("download_url"); | ||
| 709 | + assert!( | ||
| 710 | + url.ends_with("/tahinli/proj/releases/download/v1/app.bin"), | ||
| 711 | + "{url}" | ||
| 712 | + ); | ||
| 713 | + | ||
| 714 | + let (status, body) = upload(&f, &id, "app.bin", b"two!".to_vec()).await; | ||
| 715 | + assert_eq!(status, 200, "{body}"); | ||
| 716 | + assert_eq!(body["size"], 4); | ||
| 717 | + | ||
| 718 | + let (status, one) = send( | ||
| 719 | + &f.router, | ||
| 720 | + "GET", | ||
| 721 | + &releases_uri("/tags/v1"), | ||
| 722 | + None, | ||
| 723 | + None, | ||
| 724 | + Vec::new(), | ||
| 725 | + ) | ||
| 726 | + .await; | ||
| 727 | + assert_eq!(status, 200); | ||
| 728 | + assert_eq!(one["assets"].as_array().map(Vec::len), Some(1)); | ||
| 729 | + assert_eq!(one["assets"][0]["size"], 4); | ||
| 730 | + } | ||
| 731 | + | ||
| 732 | + #[tokio::test] | ||
| 733 | + async fn oversized_upload_is_413() { | ||
| 734 | + let f = fixture(Some(1)).await; | ||
| 735 | + let id = create(&f, r#"{"tag":"v1","target":"main"}"#).await; | ||
| 736 | + let (status, body) = upload(&f, &id, "big.bin", vec![0u8; (MIB + 1) as usize]).await; | ||
| 737 | + assert_eq!(status, 413, "{body}"); | ||
| 738 | + assert!(body["error"].is_string()); | ||
| 739 | + } | ||
| 740 | + | ||
| 741 | + #[tokio::test] | ||
| 742 | + async fn delete_asset_then_release() { | ||
| 743 | + let f = fixture(None).await; | ||
| 744 | + let id = create(&f, r#"{"tag":"v1","target":"main"}"#).await; | ||
| 745 | + let (_, asset) = upload(&f, &id, "app.bin", b"x".to_vec()).await; | ||
| 746 | + let asset_id = asset["id"].as_str().unwrap().to_owned(); | ||
| 747 | + let auth = bearer(&f.owner_token); | ||
| 748 | + | ||
| 749 | + let (status, _) = send( | ||
| 750 | + &f.router, | ||
| 751 | + "DELETE", | ||
| 752 | + &releases_uri(&format!("/{id}/assets/{asset_id}")), | ||
| 753 | + Some(&auth), | ||
| 754 | + None, | ||
| 755 | + Vec::new(), | ||
| 756 | + ) | ||
| 757 | + .await; | ||
| 758 | + assert_eq!(status, 204); | ||
| 759 | + let (_, one) = send( | ||
| 760 | + &f.router, | ||
| 761 | + "GET", | ||
| 762 | + &releases_uri("/tags/v1"), | ||
| 763 | + None, | ||
| 764 | + None, | ||
| 765 | + Vec::new(), | ||
| 766 | + ) | ||
| 767 | + .await; | ||
| 768 | + assert_eq!(one["assets"], serde_json::json!([])); | ||
| 769 | + | ||
| 770 | + let (status, _) = send( | ||
| 771 | + &f.router, | ||
| 772 | + "DELETE", | ||
| 773 | + &releases_uri(&format!("/{id}")), | ||
| 774 | + Some(&auth), | ||
| 775 | + None, | ||
| 776 | + Vec::new(), | ||
| 777 | + ) | ||
| 778 | + .await; | ||
| 779 | + assert_eq!(status, 204); | ||
| 780 | + let (status, _) = send( | ||
| 781 | + &f.router, | ||
| 782 | + "GET", | ||
| 783 | + &releases_uri("/tags/v1"), | ||
| 784 | + None, | ||
| 785 | + None, | ||
| 786 | + Vec::new(), | ||
| 787 | + ) | ||
| 788 | + .await; | ||
| 789 | + assert_eq!(status, 404); | ||
| 790 | + } | ||
| 791 | + | ||
| 792 | + #[tokio::test] | ||
| 793 | + async fn release_of_another_repo_is_not_found() { | ||
| 794 | + let f = fixture(None).await; | ||
| 795 | + let other = f | ||
| 796 | + .store | ||
| 797 | + .create_repo(&f.owner.id, "other", "", Visibility::Public, "main") | ||
| 798 | + .await | ||
| 799 | + .expect("other repo"); | ||
| 800 | + let foreign = f | ||
| 801 | + .store | ||
| 802 | + .create_release(&NewRelease { | ||
| 803 | + repo_id: &other.id, | ||
| 804 | + tag: "v1", | ||
| 805 | + target_oid: &"0".repeat(40), | ||
| 806 | + title: "foreign", | ||
| 807 | + body: "", | ||
| 808 | + draft: false, | ||
| 809 | + prerelease: false, | ||
| 810 | + author_id: &f.owner.id, | ||
| 811 | + }) | ||
| 812 | + .await | ||
| 813 | + .expect("foreign release"); | ||
| 814 | + let auth = bearer(&f.owner_token); | ||
| 815 | + let (status, _) = send( | ||
| 816 | + &f.router, | ||
| 817 | + "PATCH", | ||
| 818 | + &releases_uri(&format!("/{}", foreign.id)), | ||
| 819 | + Some(&auth), | ||
| 820 | + Some("application/json"), | ||
| 821 | + br#"{"title":"hijack"}"#.to_vec(), | ||
| 822 | + ) | ||
| 823 | + .await; | ||
| 824 | + assert_eq!(status, 404); | ||
| 825 | + let (status, _) = send( | ||
| 826 | + &f.router, | ||
| 827 | + "DELETE", | ||
| 828 | + &releases_uri(&format!("/{}", foreign.id)), | ||
| 829 | + Some(&auth), | ||
| 830 | + None, | ||
| 831 | + Vec::new(), | ||
| 832 | + ) | ||
| 833 | + .await; | ||
| 834 | + assert_eq!(status, 404); | ||
| 835 | + let (status, _) = upload(&f, &foreign.id, "app.bin", b"x".to_vec()).await; | ||
| 836 | + assert_eq!(status, 404); | ||
| 837 | + } | ||
| 838 | + | ||
| 839 | + #[tokio::test] | ||
| 840 | + async fn draft_is_hidden_from_anonymous_and_non_writers() { | ||
| 841 | + let f = fixture(None).await; | ||
| 842 | + create(&f, r#"{"tag":"wip","target":"main","draft":true}"#).await; | ||
| 843 | + let (status, list) = | ||
| 844 | + send(&f.router, "GET", &releases_uri(""), None, None, Vec::new()).await; | ||
| 845 | + assert_eq!(status, 200); | ||
| 846 | + assert_eq!(list, serde_json::json!([])); | ||
| 847 | + let (status, _) = send( | ||
| 848 | + &f.router, | ||
| 849 | + "GET", | ||
| 850 | + &releases_uri("/tags/wip"), | ||
| 851 | + None, | ||
| 852 | + None, | ||
| 853 | + Vec::new(), | ||
| 854 | + ) | ||
| 855 | + .await; | ||
| 856 | + assert_eq!(status, 404); | ||
| 857 | + | ||
| 858 | + let stranger = bearer(&f.stranger_token); | ||
| 859 | + let (status, list) = send( | ||
| 860 | + &f.router, | ||
| 861 | + "GET", | ||
| 862 | + &releases_uri(""), | ||
| 863 | + Some(&stranger), | ||
| 864 | + None, | ||
| 865 | + Vec::new(), | ||
| 866 | + ) | ||
| 867 | + .await; | ||
| 868 | + assert_eq!(status, 200); | ||
| 869 | + assert_eq!(list, serde_json::json!([])); | ||
| 870 | + | ||
| 871 | + let owner = bearer(&f.owner_token); | ||
| 872 | + let (status, one) = send( | ||
| 873 | + &f.router, | ||
| 874 | + "GET", | ||
| 875 | + &releases_uri("/tags/wip"), | ||
| 876 | + Some(&owner), | ||
| 877 | + None, | ||
| 878 | + Vec::new(), | ||
| 879 | + ) | ||
| 880 | + .await; | ||
| 881 | + assert_eq!(status, 200); | ||
| 882 | + assert_eq!(one["draft"], true); | ||
| 883 | + } | ||
| 884 | +} | ||
crates/forge-web/src/blobs.rsmodified+204 -4
| @@ -1,5 +1,8 @@ | |||
| 1 | -//! Blob storage for release assets. A thin wrapper over object_store's local filesystem backend, | 1 | +//! Blob storage for release assets and CI artifacts. A thin wrapper over object_store, backed by |
| 2 | -//! so an S3 backend can replace it later without touching the pages. | 2 | +//! the local filesystem (the default), any S3-compatible store, or Cloudflare R2, chosen by `[storage]`. |
| 3 | +//! | ||
| 4 | +//! Only operations that every backend supports are used. `rename` is a server-side copy followed | ||
| 5 | +//! by a delete on S3, and a delete of a missing key is not an error on either backend. | ||
| 3 | //! | 6 | //! |
| 4 | //! Keys are `assets/<asset id>`. Writes stream through object_store's multipart upload, which | 7 | //! Keys are `assets/<asset id>`. Writes stream through object_store's multipart upload, which |
| 5 | //! assembles the object in a temporary file and renames it into place on `finish`. Every chunk | 8 | //! assembles the object in a temporary file and renames it into place on `finish`. Every chunk |
| @@ -10,10 +13,13 @@ use std::path::Path; | |||
| 10 | use std::sync::Arc; | 13 | use std::sync::Arc; |
| 11 | 14 | ||
| 12 | use bytes::Bytes; | 15 | use bytes::Bytes; |
| 16 | +use forge_core::config::{R2Config, S3Config, StorageBackend, StorageConfig}; | ||
| 13 | use forge_core::{Error, Result}; | 17 | use forge_core::{Error, Result}; |
| 14 | use futures_util::{StreamExt, TryStreamExt, stream::BoxStream}; | 18 | use futures_util::{StreamExt, TryStreamExt, stream::BoxStream}; |
| 19 | +use object_store::aws::AmazonS3Builder; | ||
| 15 | use object_store::local::LocalFileSystem; | 20 | use object_store::local::LocalFileSystem; |
| 16 | use object_store::path::Path as ObjectPath; | 21 | use object_store::path::Path as ObjectPath; |
| 22 | +use object_store::prefix::PrefixStore; | ||
| 17 | use object_store::{ObjectStore, ObjectStoreExt, WriteMultipart}; | 23 | use object_store::{ObjectStore, ObjectStoreExt, WriteMultipart}; |
| 18 | use sha2::{Digest, Sha256}; | 24 | use sha2::{Digest, Sha256}; |
| 19 | 25 | ||
| @@ -34,6 +40,20 @@ where | |||
| 34 | Error::Io(std::io::Error::other(e)) | 40 | Error::Io(std::io::Error::other(e)) |
| 35 | } | 41 | } |
| 36 | 42 | ||
| 43 | +/// What `BlobStore::s3_store` needs to reach an S3-compatible bucket. Built from `[storage.s3]` | ||
| 44 | +/// or derived from `[storage.r2]`. | ||
| 45 | +struct S3Connection<'a> { | ||
| 46 | + bucket: &'a str, | ||
| 47 | + region: &'a str, | ||
| 48 | + /// `None` uses AWS. | ||
| 49 | + endpoint: Option<&'a str>, | ||
| 50 | + prefix: &'a str, | ||
| 51 | + access_key_id: &'a str, | ||
| 52 | + secret_access_key_file: &'a Path, | ||
| 53 | + allow_http: bool, | ||
| 54 | + virtual_hosted_style: bool, | ||
| 55 | +} | ||
| 56 | + | ||
| 37 | /// The blob store rooted at `<data_dir>/blobs`. Cheap to clone. | 57 | /// The blob store rooted at `<data_dir>/blobs`. Cheap to clone. |
| 38 | #[derive(Clone)] | 58 | #[derive(Clone)] |
| 39 | pub struct BlobStore { | 59 | pub struct BlobStore { |
| @@ -47,15 +67,84 @@ pub struct BlobRead { | |||
| 47 | } | 67 | } |
| 48 | 68 | ||
| 49 | impl BlobStore { | 69 | impl BlobStore { |
| 70 | + /// Opens the backend chosen by `[storage]`. `fs` keeps blobs under `<data_dir>/blobs`. | ||
| 71 | + pub fn from_config(cfg: &StorageConfig, data_dir: &Path) -> Result<Self> { | ||
| 72 | + match cfg.backend { | ||
| 73 | + StorageBackend::Fs => Self::open(&data_dir.join("blobs")), | ||
| 74 | + StorageBackend::S3 => Self::s3(&cfg.s3), | ||
| 75 | + StorageBackend::R2 => Self::r2(&cfg.r2), | ||
| 76 | + } | ||
| 77 | + } | ||
| 78 | + | ||
| 50 | /// Opens the store at `root`, creating the directory if needed. | 79 | /// Opens the store at `root`, creating the directory if needed. |
| 51 | pub fn open(root: &Path) -> Result<Self> { | 80 | pub fn open(root: &Path) -> Result<Self> { |
| 52 | std::fs::create_dir_all(root)?; | 81 | std::fs::create_dir_all(root)?; |
| 53 | let fs = LocalFileSystem::new_with_prefix(root).map_err(storage_err)?; | 82 | let fs = LocalFileSystem::new_with_prefix(root).map_err(storage_err)?; |
| 54 | - Ok(Self { | 83 | + Ok(Self::from_store(Arc::new(fs))) |
| 55 | - store: Arc::new(fs), | 84 | + } |
| 85 | + | ||
| 86 | + /// Opens an S3-compatible bucket. The secret is read from its file here, once at startup. | ||
| 87 | + fn s3(cfg: &S3Config) -> Result<Self> { | ||
| 88 | + Self::s3_store(S3Connection { | ||
| 89 | + bucket: &cfg.bucket, | ||
| 90 | + region: &cfg.region, | ||
| 91 | + endpoint: (!cfg.endpoint.is_empty()).then_some(cfg.endpoint.as_str()), | ||
| 92 | + prefix: &cfg.prefix, | ||
| 93 | + access_key_id: &cfg.access_key_id, | ||
| 94 | + secret_access_key_file: &cfg.secret_access_key_file, | ||
| 95 | + allow_http: cfg.allow_http, | ||
| 96 | + virtual_hosted_style: cfg.virtual_hosted_style, | ||
| 97 | + }) | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + /// Opens a Cloudflare R2 bucket. The endpoint comes from the account id and jurisdiction, and | ||
| 101 | + /// R2 ignores the region, so the signing region is the literal `auto`. Path style and https only. | ||
| 102 | + /// | ||
| 103 | + /// Defaults checked against R2 (object_store 0.14): conditional writes use ETag preconditions, | ||
| 104 | + /// which R2 supports; no `x-amz-checksum-*` headers are sent unless a checksum algorithm is set, | ||
| 105 | + /// so none is set here; and payloads are SigV4-signed, which R2 accepts. Do not enable | ||
| 106 | + /// `with_unsigned_payload` or a checksum algorithm without retesting against R2. | ||
| 107 | + fn r2(cfg: &R2Config) -> Result<Self> { | ||
| 108 | + let endpoint = cfg.endpoint(); | ||
| 109 | + Self::s3_store(S3Connection { | ||
| 110 | + bucket: &cfg.bucket, | ||
| 111 | + region: "auto", | ||
| 112 | + endpoint: Some(&endpoint), | ||
| 113 | + prefix: &cfg.prefix, | ||
| 114 | + access_key_id: &cfg.access_key_id, | ||
| 115 | + secret_access_key_file: &cfg.secret_access_key_file, | ||
| 116 | + allow_http: false, | ||
| 117 | + virtual_hosted_style: false, | ||
| 56 | }) | 118 | }) |
| 57 | } | 119 | } |
| 58 | 120 | ||
| 121 | + /// The constructor shared by every S3-compatible backend. | ||
| 122 | + fn s3_store(conn: S3Connection<'_>) -> Result<Self> { | ||
| 123 | + let secret = std::fs::read_to_string(conn.secret_access_key_file)?; | ||
| 124 | + let mut builder = AmazonS3Builder::new() | ||
| 125 | + .with_bucket_name(conn.bucket) | ||
| 126 | + .with_region(conn.region) | ||
| 127 | + .with_access_key_id(conn.access_key_id) | ||
| 128 | + .with_secret_access_key(secret.trim()) | ||
| 129 | + .with_allow_http(conn.allow_http) | ||
| 130 | + .with_virtual_hosted_style_request(conn.virtual_hosted_style); | ||
| 131 | + if let Some(endpoint) = conn.endpoint { | ||
| 132 | + builder = builder.with_endpoint(endpoint); | ||
| 133 | + } | ||
| 134 | + let s3 = builder.build().map_err(storage_err)?; | ||
| 135 | + let prefix = conn.prefix.trim_matches('/'); | ||
| 136 | + let store: Arc<dyn ObjectStore> = if prefix.is_empty() { | ||
| 137 | + Arc::new(s3) | ||
| 138 | + } else { | ||
| 139 | + Arc::new(PrefixStore::new(s3, prefix)) | ||
| 140 | + }; | ||
| 141 | + Ok(Self::from_store(store)) | ||
| 142 | + } | ||
| 143 | + | ||
| 144 | + fn from_store(store: Arc<dyn ObjectStore>) -> Self { | ||
| 145 | + Self { store } | ||
| 146 | + } | ||
| 147 | + | ||
| 59 | /// Starts a write of `key`. The bytes are not visible under `key` until `finish`. | 148 | /// Starts a write of `key`. The bytes are not visible under `key` until `finish`. |
| 60 | pub async fn begin(&self, key: &str, max_bytes: u64) -> Result<BlobWriter> { | 149 | pub async fn begin(&self, key: &str, max_bytes: u64) -> Result<BlobWriter> { |
| 61 | let upload = self | 150 | let upload = self |
| @@ -141,3 +230,114 @@ impl BlobWriter { | |||
| 141 | let _ = self.writer.abort().await; | 230 | let _ = self.writer.abort().await; |
| 142 | } | 231 | } |
| 143 | } | 232 | } |
| 233 | + | ||
| 234 | +#[cfg(test)] | ||
| 235 | +mod tests { | ||
| 236 | + use object_store::memory::InMemory; | ||
| 237 | + | ||
| 238 | + use super::*; | ||
| 239 | + | ||
| 240 | + /// The operations the pages use, run against any backend. | ||
| 241 | + async fn exercise(blobs: &BlobStore) { | ||
| 242 | + let mut writer = blobs.begin("tmp/upload", 1024).await.unwrap(); | ||
| 243 | + writer.push(b"hello ").await.unwrap(); | ||
| 244 | + writer.push(b"world").await.unwrap(); | ||
| 245 | + let (size, digest) = writer.finish().await.unwrap(); | ||
| 246 | + assert_eq!(size, 11); | ||
| 247 | + assert_eq!(digest, hex::encode(Sha256::digest(b"hello world"))); | ||
| 248 | + | ||
| 249 | + blobs.rename("tmp/upload", &asset_key("a1")).await.unwrap(); | ||
| 250 | + assert!(blobs.read("tmp/upload").await.unwrap().is_none()); | ||
| 251 | + let read = blobs.read(&asset_key("a1")).await.unwrap().unwrap(); | ||
| 252 | + assert_eq!(read.size, 11); | ||
| 253 | + let chunks: Vec<Bytes> = read.stream.try_collect().await.unwrap(); | ||
| 254 | + assert_eq!(chunks.concat(), b"hello world"); | ||
| 255 | + | ||
| 256 | + blobs.delete(&asset_key("a1")).await.unwrap(); | ||
| 257 | + blobs.delete(&asset_key("a1")).await.unwrap(); | ||
| 258 | + assert!(blobs.read(&asset_key("a1")).await.unwrap().is_none()); | ||
| 259 | + } | ||
| 260 | + | ||
| 261 | + #[tokio::test] | ||
| 262 | + async fn fs_backend_round_trip() { | ||
| 263 | + let dir = tempfile::tempdir().unwrap(); | ||
| 264 | + let blobs = BlobStore::open(&dir.path().join("blobs")).unwrap(); | ||
| 265 | + exercise(&blobs).await; | ||
| 266 | + } | ||
| 267 | + | ||
| 268 | + #[tokio::test] | ||
| 269 | + async fn non_fs_backend_round_trip() { | ||
| 270 | + // InMemory has no rename, so this exercises the copy-then-delete path an S3 store takes. | ||
| 271 | + let blobs = BlobStore::from_store(Arc::new(InMemory::new())); | ||
| 272 | + exercise(&blobs).await; | ||
| 273 | + } | ||
| 274 | + | ||
| 275 | + #[tokio::test] | ||
| 276 | + async fn upload_past_the_limit_is_refused() { | ||
| 277 | + let blobs = BlobStore::from_store(Arc::new(InMemory::new())); | ||
| 278 | + let mut writer = blobs.begin("tmp/big", 4).await.unwrap(); | ||
| 279 | + writer.push(b"abc").await.unwrap(); | ||
| 280 | + assert!(writer.push(b"de").await.is_err()); | ||
| 281 | + writer.abort().await; | ||
| 282 | + assert!(blobs.read("tmp/big").await.unwrap().is_none()); | ||
| 283 | + } | ||
| 284 | + | ||
| 285 | + #[test] | ||
| 286 | + fn fs_config_uses_blobs_under_data_dir() { | ||
| 287 | + let dir = tempfile::tempdir().unwrap(); | ||
| 288 | + let cfg = StorageConfig::default(); | ||
| 289 | + BlobStore::from_config(&cfg, dir.path()).unwrap(); | ||
| 290 | + assert!(dir.path().join("blobs").is_dir()); | ||
| 291 | + } | ||
| 292 | + | ||
| 293 | + #[test] | ||
| 294 | + fn s3_config_reads_the_secret_file() { | ||
| 295 | + let dir = tempfile::tempdir().unwrap(); | ||
| 296 | + let secret = dir.path().join("secret"); | ||
| 297 | + std::fs::write(&secret, "s3cret\n").unwrap(); | ||
| 298 | + let cfg = S3Config { | ||
| 299 | + bucket: "forge".into(), | ||
| 300 | + region: "us-east-1".into(), | ||
| 301 | + endpoint: "http://127.0.0.1:9000".into(), | ||
| 302 | + prefix: "/forge/".into(), | ||
| 303 | + access_key_id: "AKIA".into(), | ||
| 304 | + secret_access_key_file: secret, | ||
| 305 | + allow_http: true, | ||
| 306 | + virtual_hosted_style: false, | ||
| 307 | + }; | ||
| 308 | + assert!(BlobStore::s3(&cfg).is_ok()); | ||
| 309 | + let missing = S3Config { | ||
| 310 | + secret_access_key_file: dir.path().join("absent"), | ||
| 311 | + ..cfg | ||
| 312 | + }; | ||
| 313 | + assert!(BlobStore::s3(&missing).is_err()); | ||
| 314 | + } | ||
| 315 | + | ||
| 316 | + #[test] | ||
| 317 | + fn r2_config_builds_a_store_from_the_secret_file() { | ||
| 318 | + let dir = tempfile::tempdir().unwrap(); | ||
| 319 | + let secret = dir.path().join("secret"); | ||
| 320 | + std::fs::write(&secret, "r2s3cret\n").unwrap(); | ||
| 321 | + let cfg = StorageConfig { | ||
| 322 | + backend: StorageBackend::R2, | ||
| 323 | + r2: R2Config { | ||
| 324 | + account_id: "0123abcd".into(), | ||
| 325 | + bucket: "forge".into(), | ||
| 326 | + jurisdiction: "eu".into(), | ||
| 327 | + prefix: "/forge/".into(), | ||
| 328 | + access_key_id: "AKIA".into(), | ||
| 329 | + secret_access_key_file: secret, | ||
| 330 | + }, | ||
| 331 | + ..StorageConfig::default() | ||
| 332 | + }; | ||
| 333 | + BlobStore::from_config(&cfg, dir.path()).unwrap(); | ||
| 334 | + let missing = StorageConfig { | ||
| 335 | + r2: R2Config { | ||
| 336 | + secret_access_key_file: dir.path().join("absent"), | ||
| 337 | + ..cfg.r2.clone() | ||
| 338 | + }, | ||
| 339 | + ..cfg | ||
| 340 | + }; | ||
| 341 | + assert!(BlobStore::from_config(&missing, dir.path()).is_err()); | ||
| 342 | + } | ||
| 343 | +} | ||
crates/forge-web/src/boot.rsmodified+2 -1
| @@ -89,6 +89,7 @@ pub async fn serve(config: Config) -> forge_core::Result<()> { | |||
| 89 | Arc::new(crate::mail::LogMailer::new(data_dir.join("mail-log"))) | 89 | Arc::new(crate::mail::LogMailer::new(data_dir.join("mail-log"))) |
| 90 | } | 90 | } |
| 91 | }; | 91 | }; |
| 92 | + let blobs = crate::blobs::BlobStore::from_config(&config.storage, &data_dir)?; | ||
| 92 | let state = AppState { | 93 | let state = AppState { |
| 93 | config: Arc::new(config), | 94 | config: Arc::new(config), |
| 94 | store, | 95 | store, |
| @@ -101,7 +102,7 @@ pub async fn serve(config: Config) -> forge_core::Result<()> { | |||
| 101 | throttle: Arc::new(crate::throttle::Throttle::default()), | 102 | throttle: Arc::new(crate::throttle::Throttle::default()), |
| 102 | webhook_waker: Arc::new(Notify::new()), | 103 | webhook_waker: Arc::new(Notify::new()), |
| 103 | mirror_waker: Arc::new(Notify::new()), | 104 | mirror_waker: Arc::new(Notify::new()), |
| 104 | - blobs: crate::blobs::BlobStore::open(&data_dir.join("blobs"))?, | 105 | + blobs, |
| 105 | replication: Arc::new(crate::replication::ReplicationQueue::default()), | 106 | replication: Arc::new(crate::replication::ReplicationQueue::default()), |
| 106 | ci_waker: Arc::new(Notify::new()), | 107 | ci_waker: Arc::new(Notify::new()), |
| 107 | mailer, | 108 | mailer, |
crates/forge-web/src/ci/api.rsmodified+6 -1
| @@ -12,7 +12,7 @@ use forge_ci::proto::{ | |||
| 12 | FinishRequest, HeartbeatResponse, JobAssignment, Outcome, RegisterRequest, RegisterResponse, | 12 | FinishRequest, HeartbeatResponse, JobAssignment, Outcome, RegisterRequest, RegisterResponse, |
| 13 | }; | 13 | }; |
| 14 | use forge_core::Error as CoreError; | 14 | use forge_core::Error as CoreError; |
| 15 | -use forge_core::ci::{CiJob, CiRun, CiRunner, JobState}; | 15 | +use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, RunState}; |
| 16 | use futures_util::StreamExt; | 16 | use futures_util::StreamExt; |
| 17 | use http::header::HeaderValue; | 17 | use http::header::HeaderValue; |
| 18 | use serde_json::json; | 18 | use serde_json::json; |
| @@ -774,6 +774,11 @@ async fn finish_job( | |||
| 774 | } | 774 | } |
| 775 | // A run that just went green may deploy the forge itself. | 775 | // A run that just went green may deploy the forge itself. |
| 776 | self_update::maybe_deploy(state, &run).await; | 776 | self_update::maybe_deploy(state, &run).await; |
| 777 | + // A tag run that went green may publish a release. The request does not wait for it. | ||
| 778 | + if run.state == RunState::Success { | ||
| 779 | + let (state, run) = (state.clone(), run.clone()); | ||
| 780 | + tokio::spawn(async move { crate::ci::release::on_run_finished(&state, &run).await }); | ||
| 781 | + } | ||
| 777 | Ok(run.state.as_str()) | 782 | Ok(run.state.as_str()) |
| 778 | } | 783 | } |
| 779 | 784 | ||
crates/forge-web/src/ci/mod.rsmodified+1 -0
| @@ -13,6 +13,7 @@ use crate::state::AppState; | |||
| 13 | pub mod api; | 13 | pub mod api; |
| 14 | pub mod live; | 14 | pub mod live; |
| 15 | pub mod reaper; | 15 | pub mod reaper; |
| 16 | +pub mod release; | ||
| 16 | pub mod schedule; | 17 | pub mod schedule; |
| 17 | 18 | ||
| 18 | pub use live::CiLive; | 19 | pub use live::CiLive; |
crates/forge-web/src/ci/release.rsadded+705 -0
| @@ -0,0 +1,705 @@ | |||
| 1 | +//! Publishes a release when a tag run finishes with every job succeeded and the workflow at the | ||
| 2 | +//! run's commit has a `[release]` table (see docs/ci.md, Releases). The finish handler spawns | ||
| 3 | +//! [`on_run_finished`], so the runner's request is not slowed down. | ||
| 4 | +//! | ||
| 5 | +//! The run is idempotent. A release that already exists keeps its title, notes and draft state and | ||
| 6 | +//! only gets the selected artifacts; an asset with the same name is replaced. | ||
| 7 | +//! | ||
| 8 | +//! The release is made as the run's actor. A system run has no actor, and an organization never | ||
| 9 | +//! acts, so those fall back to the repo owner, then to the ghost account (`status_creator`). | ||
| 10 | +//! | ||
| 11 | +//! The outcome is written as one `[forge]` line at the end of the log of the run's last finished | ||
| 12 | +//! job, so it shows on the run's job pages with the rest of the output. | ||
| 13 | + | ||
| 14 | +use forge_ci::config::{Event, ReleaseNotes, ReleaseSpec}; | ||
| 15 | +use forge_core::ci::{CiJob, CiRun, RunState}; | ||
| 16 | +use forge_core::releases::{MAX_BODY_CHARS, MAX_TITLE_CHARS, Release}; | ||
| 17 | +use forge_core::{Repo, User}; | ||
| 18 | +use forge_git::browse::CommitInfo; | ||
| 19 | +use forge_git::history::log; | ||
| 20 | +use forge_git::pulls::{is_ancestor, range_log}; | ||
| 21 | +use forge_git::repo::repo_path; | ||
| 22 | +use forge_git::tags::previous_tag; | ||
| 23 | +use tokio::io::AsyncWriteExt; | ||
| 24 | + | ||
| 25 | +use super::api::fit_to_cap; | ||
| 26 | +use super::{artifact_key, log_path, schedule, status_creator}; | ||
| 27 | +use crate::release_ops::{self, CreateRelease, ReleaseError}; | ||
| 28 | +use crate::state::AppState; | ||
| 29 | + | ||
| 30 | +/// Most commits listed in the notes. Older commits are left out. | ||
| 31 | +const MAX_NOTE_COMMITS: usize = 200; | ||
| 32 | +const MIB: u64 = 1024 * 1024; | ||
| 33 | + | ||
| 34 | +/// Runs after a run finished. Does nothing unless the run is a successful tag run and the workflow | ||
| 35 | +/// at its commit asks for a release for this tag. Failures are logged and written to the job log; | ||
| 36 | +/// they never fail the caller. | ||
| 37 | +pub async fn on_run_finished(state: &AppState, run: &CiRun) { | ||
| 38 | + if run.state != RunState::Success { | ||
| 39 | + return; | ||
| 40 | + } | ||
| 41 | + let Some(tag) = run.git_ref.strip_prefix("refs/tags/") else { | ||
| 42 | + return; | ||
| 43 | + }; | ||
| 44 | + let repo = match state.store.repo_by_id(&run.repo_id).await { | ||
| 45 | + Ok(Some(repo)) => repo, | ||
| 46 | + Ok(None) => return, | ||
| 47 | + Err(e) => { | ||
| 48 | + tracing::error!(error = %e, run_id = %run.id, "release: loading the repo failed"); | ||
| 49 | + return; | ||
| 50 | + } | ||
| 51 | + }; | ||
| 52 | + let Some(config) = schedule::config_at(state, &repo.id, &run.commit_oid).await else { | ||
| 53 | + return; | ||
| 54 | + }; | ||
| 55 | + let Some(spec) = config | ||
| 56 | + .release | ||
| 57 | + .as_ref() | ||
| 58 | + .filter(|_| config.wants_release(&Event::Tag { tag })) | ||
| 59 | + else { | ||
| 60 | + return; | ||
| 61 | + }; | ||
| 62 | + | ||
| 63 | + let text = publish(state, &repo, run, tag, spec).await; | ||
| 64 | + let jobs = match state.store.jobs_for_run(&run.id).await { | ||
| 65 | + Ok(jobs) => jobs, | ||
| 66 | + Err(e) => { | ||
| 67 | + tracing::error!(error = %e, run_id = %run.id, "release: listing the jobs failed"); | ||
| 68 | + return; | ||
| 69 | + } | ||
| 70 | + }; | ||
| 71 | + if let Some(job) = jobs.iter().max_by(|a, b| a.finished_at.cmp(&b.finished_at)) { | ||
| 72 | + note(state, job, &text).await; | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// Creates or finds the release, attaches the selected artifacts, and describes the outcome. | ||
| 77 | +async fn publish( | ||
| 78 | + state: &AppState, | ||
| 79 | + repo: &Repo, | ||
| 80 | + run: &CiRun, | ||
| 81 | + tag: &str, | ||
| 82 | + spec: &ReleaseSpec, | ||
| 83 | +) -> String { | ||
| 84 | + let Some(actor) = actor_of(state, repo, run).await else { | ||
| 85 | + return format!("Could not publish release {tag}: no user to publish as"); | ||
| 86 | + }; | ||
| 87 | + let release = match release_for(state, repo, run, tag, spec, &actor).await { | ||
| 88 | + Ok(release) => release, | ||
| 89 | + Err(reason) => return format!("Could not publish release {tag}: {reason}"), | ||
| 90 | + }; | ||
| 91 | + | ||
| 92 | + let jobs = match state.store.jobs_for_run(&run.id).await { | ||
| 93 | + Ok(jobs) => jobs, | ||
| 94 | + Err(e) => { | ||
| 95 | + tracing::error!(error = %e, run_id = %run.id, "release: listing the jobs failed"); | ||
| 96 | + return format!("Could not publish release {tag}: could not list the jobs"); | ||
| 97 | + } | ||
| 98 | + }; | ||
| 99 | + let max_bytes = state.config.releases.max_asset_mb.saturating_mul(MIB); | ||
| 100 | + let mut attached = 0usize; | ||
| 101 | + let mut failed: Vec<String> = Vec::new(); | ||
| 102 | + for job in &jobs { | ||
| 103 | + let artifacts = match state.store.list_artifacts(&job.id).await { | ||
| 104 | + Ok(artifacts) => artifacts, | ||
| 105 | + Err(e) => { | ||
| 106 | + tracing::error!(error = %e, job_id = %job.id, "release: listing artifacts failed"); | ||
| 107 | + failed.push(format!("{}: could not list the artifacts", job.name)); | ||
| 108 | + continue; | ||
| 109 | + } | ||
| 110 | + }; | ||
| 111 | + for artifact in artifacts | ||
| 112 | + .iter() | ||
| 113 | + .filter(|a| spec.asset_matches(&job.name, &a.name)) | ||
| 114 | + { | ||
| 115 | + match attach( | ||
| 116 | + state, | ||
| 117 | + repo, | ||
| 118 | + &release, | ||
| 119 | + &actor, | ||
| 120 | + &artifact.id, | ||
| 121 | + &artifact.name, | ||
| 122 | + max_bytes, | ||
| 123 | + ) | ||
| 124 | + .await | ||
| 125 | + { | ||
| 126 | + Ok(()) => attached += 1, | ||
| 127 | + Err(reason) => { | ||
| 128 | + tracing::error!(run_id = %run.id, tag, artifact = %artifact.name, %reason, "release: attaching an asset failed"); | ||
| 129 | + failed.push(format!("{}: {reason}", artifact.name)); | ||
| 130 | + } | ||
| 131 | + } | ||
| 132 | + } | ||
| 133 | + } | ||
| 134 | + | ||
| 135 | + let mut text = format!("Published release {tag} with {attached} assets."); | ||
| 136 | + if !failed.is_empty() { | ||
| 137 | + text.push_str(&format!(" {} failed: {}.", failed.len(), failed.join(", "))); | ||
| 138 | + } | ||
| 139 | + text | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// The person the release is made as: the run's actor, or the fallback of `status_creator`. | ||
| 143 | +async fn actor_of(state: &AppState, repo: &Repo, run: &CiRun) -> Option<User> { | ||
| 144 | + let id = status_creator(state, repo, &run.actor_id).await?; | ||
| 145 | + match state.store.user_by_id(&id).await { | ||
| 146 | + Ok(user) => user, | ||
| 147 | + Err(e) => { | ||
| 148 | + tracing::error!(error = %e, run_id = %run.id, "release: loading the actor failed"); | ||
| 149 | + None | ||
| 150 | + } | ||
| 151 | + } | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +/// The existing release for `tag`, or a new one made from the spec. A release made by another run | ||
| 155 | +/// in the meantime (a `Conflict`) is read back instead. | ||
| 156 | +async fn release_for( | ||
| 157 | + state: &AppState, | ||
| 158 | + repo: &Repo, | ||
| 159 | + run: &CiRun, | ||
| 160 | + tag: &str, | ||
| 161 | + spec: &ReleaseSpec, | ||
| 162 | + actor: &User, | ||
| 163 | +) -> Result<Release, String> { | ||
| 164 | + match state.store.release_by_tag(&repo.id, tag).await { | ||
| 165 | + Ok(Some(existing)) => return Ok(existing), | ||
| 166 | + Ok(None) => {} | ||
| 167 | + Err(e) => { | ||
| 168 | + tracing::error!(error = %e, run_id = %run.id, "release: reading the release failed"); | ||
| 169 | + return Err("could not read the release".to_owned()); | ||
| 170 | + } | ||
| 171 | + } | ||
| 172 | + | ||
| 173 | + let input = CreateRelease { | ||
| 174 | + tag: tag.to_owned(), | ||
| 175 | + target: Some(run.commit_oid.clone()), | ||
| 176 | + title: spec.title_for(tag).chars().take(MAX_TITLE_CHARS).collect(), | ||
| 177 | + body: notes(state, repo, run, tag, spec).await, | ||
| 178 | + draft: spec.draft, | ||
| 179 | + prerelease: spec.is_prerelease(tag), | ||
| 180 | + }; | ||
| 181 | + match release_ops::create(state, repo, actor, input).await { | ||
| 182 | + Ok(release) => Ok(release), | ||
| 183 | + Err(ReleaseError::Conflict(_)) => match state.store.release_by_tag(&repo.id, tag).await { | ||
| 184 | + Ok(Some(existing)) => Ok(existing), | ||
| 185 | + _ => Err("a release for this tag could not be made".to_owned()), | ||
| 186 | + }, | ||
| 187 | + Err(e) => { | ||
| 188 | + tracing::error!(error = ?e, run_id = %run.id, tag, "release: creating the release failed"); | ||
| 189 | + Err(e.message()) | ||
| 190 | + } | ||
| 191 | + } | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +/// Stores one artifact as an asset of `release`, replacing an asset with the same name. | ||
| 195 | +async fn attach( | ||
| 196 | + state: &AppState, | ||
| 197 | + repo: &Repo, | ||
| 198 | + release: &Release, | ||
| 199 | + actor: &User, | ||
| 200 | + artifact_id: &str, | ||
| 201 | + name: &str, | ||
| 202 | + max_bytes: u64, | ||
| 203 | +) -> Result<(), String> { | ||
| 204 | + let read = match state.blobs.read(&artifact_key(artifact_id)).await { | ||
| 205 | + Ok(Some(read)) => read, | ||
| 206 | + Ok(None) => return Err("the file is missing from storage".to_owned()), | ||
| 207 | + Err(e) => { | ||
| 208 | + tracing::error!(error = %e, artifact_id, "release: reading an artifact failed"); | ||
| 209 | + return Err("the file could not be read".to_owned()); | ||
| 210 | + } | ||
| 211 | + }; | ||
| 212 | + release_ops::put_asset( | ||
| 213 | + state, | ||
| 214 | + repo, | ||
| 215 | + release, | ||
| 216 | + actor, | ||
| 217 | + name, | ||
| 218 | + None, | ||
| 219 | + read.stream, | ||
| 220 | + max_bytes, | ||
| 221 | + ) | ||
| 222 | + .await | ||
| 223 | + .map(|_| ()) | ||
| 224 | + .map_err(|e| { | ||
| 225 | + tracing::error!(error = ?e, artifact_id, "release: storing an asset failed"); | ||
| 226 | + e.message() | ||
| 227 | + }) | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +/// The notes for a new release, or an empty string when the spec turns them off. A git failure | ||
| 231 | +/// leaves the notes empty and is logged; the release is still made. | ||
| 232 | +async fn notes( | ||
| 233 | + state: &AppState, | ||
| 234 | + repo: &Repo, | ||
| 235 | + run: &CiRun, | ||
| 236 | + tag: &str, | ||
| 237 | + spec: &ReleaseSpec, | ||
| 238 | +) -> String { | ||
| 239 | + if matches!(spec.notes, ReleaseNotes::Off) { | ||
| 240 | + return String::new(); | ||
| 241 | + } | ||
| 242 | + match changelog(state, repo, run, tag).await { | ||
| 243 | + Ok(text) => text, | ||
| 244 | + Err(e) => { | ||
| 245 | + tracing::error!(error = %e, run_id = %run.id, tag, "release: building the notes failed"); | ||
| 246 | + String::new() | ||
| 247 | + } | ||
| 248 | + } | ||
| 249 | +} | ||
| 250 | + | ||
| 251 | +/// The commit list since the previous release. The previous release is the newest other | ||
| 252 | +/// published release whose target is an ancestor of this commit. Without one, it is the closest | ||
| 253 | +/// git tag reachable from the commit. Without either, the list is capped at the newest commits. | ||
| 254 | +async fn changelog( | ||
| 255 | + state: &AppState, | ||
| 256 | + repo: &Repo, | ||
| 257 | + run: &CiRun, | ||
| 258 | + tag: &str, | ||
| 259 | +) -> Result<String, String> { | ||
| 260 | + let dir = repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?; | ||
| 261 | + let env = &state.git; | ||
| 262 | + | ||
| 263 | + let releases = state | ||
| 264 | + .store | ||
| 265 | + .list_releases(&repo.id) | ||
| 266 | + .await | ||
| 267 | + .map_err(|e| e.to_string())?; | ||
| 268 | + let mut previous: Option<(String, String)> = None; | ||
| 269 | + for release in releases.iter().filter(|r| !r.draft && r.tag != tag) { | ||
| 270 | + if is_ancestor(env, &dir, &release.target_oid, &run.commit_oid) | ||
| 271 | + .await | ||
| 272 | + .unwrap_or(false) | ||
| 273 | + { | ||
| 274 | + previous = Some((release.tag.clone(), release.target_oid.clone())); | ||
| 275 | + break; | ||
| 276 | + } | ||
| 277 | + } | ||
| 278 | + if previous.is_none() { | ||
| 279 | + previous = previous_tag(env, &dir, &run.commit_oid) | ||
| 280 | + .await | ||
| 281 | + .map_err(|e| e.to_string())?; | ||
| 282 | + } | ||
| 283 | + | ||
| 284 | + let commits = match &previous { | ||
| 285 | + Some((_, base)) => { | ||
| 286 | + let mut commits = range_log(env, &dir, base, &run.commit_oid, MAX_NOTE_COMMITS) | ||
| 287 | + .await | ||
| 288 | + .map_err(|e| e.to_string())?; | ||
| 289 | + commits.reverse(); | ||
| 290 | + commits | ||
| 291 | + } | ||
| 292 | + None => log(env, &dir, &run.commit_oid, None, 0, MAX_NOTE_COMMITS) | ||
| 293 | + .await | ||
| 294 | + .map_err(|e| e.to_string())?, | ||
| 295 | + }; | ||
| 296 | + let footer = previous | ||
| 297 | + .as_ref() | ||
| 298 | + .map(|(name, _)| format!("Full changelog: {name}...{tag}")); | ||
| 299 | + Ok(bullets(&commits, footer.as_deref())) | ||
| 300 | +} | ||
| 301 | + | ||
| 302 | +/// One `- subject (shortsha)` line per commit, newest first, then the footer. Commits that would | ||
| 303 | +/// push the notes past the body limit are left out. | ||
| 304 | +fn bullets(commits: &[CommitInfo], footer: Option<&str>) -> String { | ||
| 305 | + let footer_len = footer.map_or(0, |f| f.chars().count() + 2); | ||
| 306 | + let mut body = String::new(); | ||
| 307 | + let mut used = 0usize; | ||
| 308 | + for commit in commits { | ||
| 309 | + let short = commit.oid.get(..7).unwrap_or(&commit.oid); | ||
| 310 | + let line = format!("- {} ({short})\n", commit.summary); | ||
| 311 | + let len = line.chars().count(); | ||
| 312 | + if used + len + footer_len > MAX_BODY_CHARS { | ||
| 313 | + break; | ||
| 314 | + } | ||
| 315 | + used += len; | ||
| 316 | + body.push_str(&line); | ||
| 317 | + } | ||
| 318 | + let mut body = body.trim_end().to_owned(); | ||
| 319 | + if let Some(footer) = footer { | ||
| 320 | + if !body.is_empty() { | ||
| 321 | + body.push_str("\n\n"); | ||
| 322 | + } | ||
| 323 | + body.push_str(footer); | ||
| 324 | + } | ||
| 325 | + body | ||
| 326 | +} | ||
| 327 | + | ||
| 328 | +/// Appends one `[forge]` line to the log of `job`. Respects the log size cap. A failure is logged; | ||
| 329 | +/// the outcome is not lost, it is also in the tracing output. | ||
| 330 | +async fn note(state: &AppState, job: &CiJob, text: &str) { | ||
| 331 | + let line = format!("[forge] {text}\n"); | ||
| 332 | + let cap = state.config.ci.max_log_mb.saturating_mul(MIB); | ||
| 333 | + let path = log_path(&state.config.data_dir, &job.id); | ||
| 334 | + let current = match tokio::fs::metadata(&path).await { | ||
| 335 | + Ok(meta) => meta.len(), | ||
| 336 | + Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, | ||
| 337 | + Err(e) => { | ||
| 338 | + tracing::error!(error = %e, job_id = %job.id, "release: reading the job log failed"); | ||
| 339 | + return; | ||
| 340 | + } | ||
| 341 | + }; | ||
| 342 | + let bytes = fit_to_cap(current, cap, line.as_bytes()); | ||
| 343 | + if bytes.is_empty() { | ||
| 344 | + return; | ||
| 345 | + } | ||
| 346 | + let written: std::io::Result<()> = async { | ||
| 347 | + if let Some(parent) = path.parent() { | ||
| 348 | + tokio::fs::create_dir_all(parent).await?; | ||
| 349 | + } | ||
| 350 | + let mut file = tokio::fs::OpenOptions::new() | ||
| 351 | + .create(true) | ||
| 352 | + .append(true) | ||
| 353 | + .open(&path) | ||
| 354 | + .await?; | ||
| 355 | + file.write_all(&bytes).await?; | ||
| 356 | + file.flush().await | ||
| 357 | + } | ||
| 358 | + .await; | ||
| 359 | + if let Err(e) = written { | ||
| 360 | + tracing::error!(error = %e, job_id = %job.id, "release: writing the job log failed"); | ||
| 361 | + return; | ||
| 362 | + } | ||
| 363 | + if let Err(e) = state.store.add_log_bytes(&job.id, bytes.len() as i64).await { | ||
| 364 | + tracing::error!(error = %e, job_id = %job.id, "release: counting the job log bytes failed"); | ||
| 365 | + return; | ||
| 366 | + } | ||
| 367 | + state.ci_live.bump_job(&job.id); | ||
| 368 | +} | ||
| 369 | + | ||
| 370 | +#[cfg(test)] | ||
| 371 | +mod tests { | ||
| 372 | + use forge_core::ci::{CiArtifact, JobState}; | ||
| 373 | + | ||
| 374 | + use super::*; | ||
| 375 | + use crate::ci::schedule::CONFIG_PATH; | ||
| 376 | + use crate::ci::schedule::tests::{Fixture, ZERO, fixture, git, land, push}; | ||
| 377 | + use crate::post_update::after_ref_update; | ||
| 378 | + | ||
| 379 | + /// A tag release workflow with two jobs. Only `build` feeds the release, through `dist_*`. | ||
| 380 | + const RELEASE: &str = r#" | ||
| 381 | +[on] | ||
| 382 | +push = ["main"] | ||
| 383 | +tags = ["v*"] | ||
| 384 | + | ||
| 385 | +[jobs.build] | ||
| 386 | +image = "alpine:3" | ||
| 387 | +run = "make" | ||
| 388 | +artifacts = ["dist/*"] | ||
| 389 | + | ||
| 390 | +[jobs.docs] | ||
| 391 | +image = "alpine:3" | ||
| 392 | +run = "make docs" | ||
| 393 | +artifacts = ["site/*"] | ||
| 394 | + | ||
| 395 | +[release] | ||
| 396 | +assets = ["build:dist_*"] | ||
| 397 | +title = "forge {tag}" | ||
| 398 | +"#; | ||
| 399 | + | ||
| 400 | + /// Finishes the jobs of `run_id` in order. The job named `failing` fails; the others succeed. | ||
| 401 | + async fn finish_all(fx: &Fixture, run_id: &str, failing: Option<&str>) { | ||
| 402 | + loop { | ||
| 403 | + let jobs = fx.state.store.jobs_for_run(run_id).await.expect("jobs"); | ||
| 404 | + let Some(job) = jobs.iter().find(|j| !j.state.is_terminal()) else { | ||
| 405 | + break; | ||
| 406 | + }; | ||
| 407 | + let fails = failing == Some(job.name.as_str()); | ||
| 408 | + let (outcome, code) = if fails { | ||
| 409 | + (JobState::Failure, 1) | ||
| 410 | + } else { | ||
| 411 | + (JobState::Success, 0) | ||
| 412 | + }; | ||
| 413 | + fx.state | ||
| 414 | + .store | ||
| 415 | + .finish_job(&job.id, outcome, Some(code), None) | ||
| 416 | + .await | ||
| 417 | + .expect("finish"); | ||
| 418 | + } | ||
| 419 | + } | ||
| 420 | + | ||
| 421 | + async fn run_of(fx: &Fixture, number: i64) -> CiRun { | ||
| 422 | + fx.state | ||
| 423 | + .store | ||
| 424 | + .run_by_number(&fx.repo.id, number) | ||
| 425 | + .await | ||
| 426 | + .expect("query") | ||
| 427 | + .expect("run") | ||
| 428 | + } | ||
| 429 | + | ||
| 430 | + async fn job_of(fx: &Fixture, run: &CiRun, name: &str) -> CiJob { | ||
| 431 | + fx.state | ||
| 432 | + .store | ||
| 433 | + .jobs_for_run(&run.id) | ||
| 434 | + .await | ||
| 435 | + .expect("jobs") | ||
| 436 | + .into_iter() | ||
| 437 | + .find(|j| j.name == name) | ||
| 438 | + .expect("job") | ||
| 439 | + } | ||
| 440 | + | ||
| 441 | + /// Stores `body` as an artifact of `job`, the way the upload handler does. | ||
| 442 | + async fn add_artifact(fx: &Fixture, job: &CiJob, name: &str, body: &[u8]) -> CiArtifact { | ||
| 443 | + let tmp = format!("ci/tmp/{}", ulid::Ulid::generate()); | ||
| 444 | + let mut writer = fx.state.blobs.begin(&tmp, 1 << 30).await.expect("begin"); | ||
| 445 | + writer.push(body).await.expect("push"); | ||
| 446 | + let (size, sha) = writer.finish().await.expect("finish"); | ||
| 447 | + let artifact = fx | ||
| 448 | + .state | ||
| 449 | + .store | ||
| 450 | + .add_artifact(&job.id, name, size as i64, &sha) | ||
| 451 | + .await | ||
| 452 | + .expect("artifact"); | ||
| 453 | + fx.state | ||
| 454 | + .blobs | ||
| 455 | + .rename(&tmp, &artifact_key(&artifact.id)) | ||
| 456 | + .await | ||
| 457 | + .expect("rename"); | ||
| 458 | + artifact | ||
| 459 | + } | ||
| 460 | + | ||
| 461 | + /// Commits an empty change with `message` and returns the commit. | ||
| 462 | + fn commit_message(work: &std::path::Path, message: &str) -> String { | ||
| 463 | + git(work, &["commit", "--allow-empty", "-m", message]); | ||
| 464 | + git(work, &["rev-parse", "HEAD"]) | ||
| 465 | + } | ||
| 466 | + | ||
| 467 | + async fn release_named(fx: &Fixture, tag: &str) -> Option<Release> { | ||
| 468 | + fx.state | ||
| 469 | + .store | ||
| 470 | + .release_by_tag(&fx.repo.id, tag) | ||
| 471 | + .await | ||
| 472 | + .expect("query") | ||
| 473 | + } | ||
| 474 | + | ||
| 475 | + async fn asset_names(fx: &Fixture, release: &Release) -> Vec<(String, u64)> { | ||
| 476 | + let mut assets: Vec<(String, u64)> = fx | ||
| 477 | + .state | ||
| 478 | + .store | ||
| 479 | + .list_release_assets(&release.id) | ||
| 480 | + .await | ||
| 481 | + .expect("assets") | ||
| 482 | + .into_iter() | ||
| 483 | + .map(|a| (a.name, a.size)) | ||
| 484 | + .collect(); | ||
| 485 | + assets.sort(); | ||
| 486 | + assets | ||
| 487 | + } | ||
| 488 | + | ||
| 489 | + #[tokio::test] | ||
| 490 | + async fn tag_run_publishes_release_with_matching_assets() { | ||
| 491 | + let fx = fixture().await; | ||
| 492 | + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; | ||
| 493 | + let run = run_of(&fx, 1).await; | ||
| 494 | + let build = job_of(&fx, &run, "build").await; | ||
| 495 | + let docs = job_of(&fx, &run, "docs").await; | ||
| 496 | + add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await; | ||
| 497 | + add_artifact(&fx, &build, "dist_SHA256SUMS", b"sums").await; | ||
| 498 | + add_artifact(&fx, &docs, "dist_docs-only", b"x").await; | ||
| 499 | + add_artifact(&fx, &docs, "site_index.html", b"<html>").await; | ||
| 500 | + finish_all(&fx, &run.id, None).await; | ||
| 501 | + let run = run_of(&fx, 1).await; | ||
| 502 | + assert_eq!(run.state, RunState::Success); | ||
| 503 | + | ||
| 504 | + on_run_finished(&fx.state, &run).await; | ||
| 505 | + | ||
| 506 | + let release = release_named(&fx, "v1.0").await.expect("release made"); | ||
| 507 | + assert_eq!(release.title, "forge v1.0"); | ||
| 508 | + assert_eq!(release.target_oid, run.commit_oid); | ||
| 509 | + assert!(!release.draft); | ||
| 510 | + assert!(!release.prerelease); | ||
| 511 | + assert_eq!(release.author_id, fx.owner.id); | ||
| 512 | + assert_eq!( | ||
| 513 | + asset_names(&fx, &release).await, | ||
| 514 | + vec![ | ||
| 515 | + ("dist_SHA256SUMS".to_owned(), 4), | ||
| 516 | + ("dist_forge-linux-x86_64".to_owned(), 6), | ||
| 517 | + ], | ||
| 518 | + "only build's dist_* artifacts are attached" | ||
| 519 | + ); | ||
| 520 | + | ||
| 521 | + let mut log_text = String::new(); | ||
| 522 | + for job in fx.state.store.jobs_for_run(&run.id).await.expect("jobs") { | ||
| 523 | + let path = crate::ci::log_path(&fx.state.config.data_dir, &job.id); | ||
| 524 | + if let Ok(text) = std::fs::read_to_string(path) { | ||
| 525 | + log_text.push_str(&text); | ||
| 526 | + } | ||
| 527 | + } | ||
| 528 | + assert!(log_text.contains("[forge] Published release v1.0 with 2 assets.")); | ||
| 529 | + } | ||
| 530 | + | ||
| 531 | + #[tokio::test] | ||
| 532 | + async fn notes_list_commits_since_the_previous_release() { | ||
| 533 | + let fx = fixture().await; | ||
| 534 | + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; | ||
| 535 | + finish_all(&fx, &run_of(&fx, 1).await.id, None).await; | ||
| 536 | + on_run_finished(&fx.state, &run_of(&fx, 1).await).await; | ||
| 537 | + | ||
| 538 | + commit_message(&fx.work, "feat: one"); | ||
| 539 | + let oid = commit_message(&fx.work, "fix: two"); | ||
| 540 | + land(&fx, &oid, "refs/tags/v1.1"); | ||
| 541 | + after_ref_update( | ||
| 542 | + &fx.state, | ||
| 543 | + &fx.repo, | ||
| 544 | + &fx.owner.id, | ||
| 545 | + "refs/tags/v1.1", | ||
| 546 | + ZERO, | ||
| 547 | + &oid, | ||
| 548 | + ) | ||
| 549 | + .await | ||
| 550 | + .expect("post update"); | ||
| 551 | + finish_all(&fx, &run_of(&fx, 2).await.id, None).await; | ||
| 552 | + on_run_finished(&fx.state, &run_of(&fx, 2).await).await; | ||
| 553 | + | ||
| 554 | + let release = release_named(&fx, "v1.1").await.expect("release made"); | ||
| 555 | + let short = &oid[..7]; | ||
| 556 | + assert!( | ||
| 557 | + release | ||
| 558 | + .body | ||
| 559 | + .starts_with(&format!("- fix: two ({short})\n- feat: one (")) | ||
| 560 | + ); | ||
| 561 | + assert!(release.body.ends_with("Full changelog: v1.0...v1.1")); | ||
| 562 | + assert!( | ||
| 563 | + !release.body.contains("- change ("), | ||
| 564 | + "older commits are not repeated" | ||
| 565 | + ); | ||
| 566 | + } | ||
| 567 | + | ||
| 568 | + #[tokio::test] | ||
| 569 | + async fn existing_manual_release_keeps_its_fields_and_gets_assets() { | ||
| 570 | + let fx = fixture().await; | ||
| 571 | + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; | ||
| 572 | + let run = run_of(&fx, 1).await; | ||
| 573 | + let manual = release_ops::create( | ||
| 574 | + &fx.state, | ||
| 575 | + &fx.repo, | ||
| 576 | + &fx.owner, | ||
| 577 | + CreateRelease { | ||
| 578 | + tag: "v1.0".to_owned(), | ||
| 579 | + target: None, | ||
| 580 | + title: "Hand made".to_owned(), | ||
| 581 | + body: "Keep me".to_owned(), | ||
| 582 | + draft: true, | ||
| 583 | + prerelease: true, | ||
| 584 | + }, | ||
| 585 | + ) | ||
| 586 | + .await | ||
| 587 | + .expect("manual release"); | ||
| 588 | + let build = job_of(&fx, &run, "build").await; | ||
| 589 | + add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await; | ||
| 590 | + finish_all(&fx, &run.id, None).await; | ||
| 591 | + | ||
| 592 | + on_run_finished(&fx.state, &run_of(&fx, 1).await).await; | ||
| 593 | + | ||
| 594 | + let release = release_named(&fx, "v1.0").await.expect("release"); | ||
| 595 | + assert_eq!(release.id, manual.id); | ||
| 596 | + assert_eq!(release.title, "Hand made"); | ||
| 597 | + assert_eq!(release.body, "Keep me"); | ||
| 598 | + assert!(release.draft); | ||
| 599 | + assert!(release.prerelease); | ||
| 600 | + assert_eq!(asset_names(&fx, &release).await.len(), 1); | ||
| 601 | + } | ||
| 602 | + | ||
| 603 | + #[tokio::test] | ||
| 604 | + async fn failed_run_creates_no_release() { | ||
| 605 | + let fx = fixture().await; | ||
| 606 | + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; | ||
| 607 | + let run = run_of(&fx, 1).await; | ||
| 608 | + let build = job_of(&fx, &run, "build").await; | ||
| 609 | + add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await; | ||
| 610 | + finish_all(&fx, &run.id, Some("docs")).await; | ||
| 611 | + let run = run_of(&fx, 1).await; | ||
| 612 | + assert_eq!(run.state, RunState::Failure); | ||
| 613 | + | ||
| 614 | + on_run_finished(&fx.state, &run).await; | ||
| 615 | + | ||
| 616 | + assert!(release_named(&fx, "v1.0").await.is_none()); | ||
| 617 | + } | ||
| 618 | + | ||
| 619 | + #[tokio::test] | ||
| 620 | + async fn branch_push_run_creates_no_release() { | ||
| 621 | + let fx = fixture().await; | ||
| 622 | + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/heads/main").await; | ||
| 623 | + let run = run_of(&fx, 1).await; | ||
| 624 | + finish_all(&fx, &run.id, None).await; | ||
| 625 | + | ||
| 626 | + on_run_finished(&fx.state, &run_of(&fx, 1).await).await; | ||
| 627 | + | ||
| 628 | + assert!(release_named(&fx, "v1.0").await.is_none()); | ||
| 629 | + assert!(release_named(&fx, "main").await.is_none()); | ||
| 630 | + } | ||
| 631 | + | ||
| 632 | + #[tokio::test] | ||
| 633 | + async fn rerun_replaces_assets_by_name() { | ||
| 634 | + let fx = fixture().await; | ||
| 635 | + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; | ||
| 636 | + let first = run_of(&fx, 1).await; | ||
| 637 | + let build = job_of(&fx, &first, "build").await; | ||
| 638 | + add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"one").await; | ||
| 639 | + finish_all(&fx, &first.id, None).await; | ||
| 640 | + on_run_finished(&fx.state, &run_of(&fx, 1).await).await; | ||
| 641 | + | ||
| 642 | + let second = fx | ||
| 643 | + .state | ||
| 644 | + .store | ||
| 645 | + .rerun(&first.id, &fx.owner.id) | ||
| 646 | + .await | ||
| 647 | + .expect("rerun"); | ||
| 648 | + let build = job_of(&fx, &second, "build").await; | ||
| 649 | + add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"second!").await; | ||
| 650 | + finish_all(&fx, &second.id, None).await; | ||
| 651 | + on_run_finished(&fx.state, &run_of(&fx, 2).await).await; | ||
| 652 | + | ||
| 653 | + let release = release_named(&fx, "v1.0").await.expect("release"); | ||
| 654 | + assert_eq!( | ||
| 655 | + asset_names(&fx, &release).await, | ||
| 656 | + vec![("dist_forge-linux-x86_64".to_owned(), 7)] | ||
| 657 | + ); | ||
| 658 | + } | ||
| 659 | + | ||
| 660 | + /// No release exists for the earlier tag, so the notes start from the closest git tag. | ||
| 661 | + #[tokio::test] | ||
| 662 | + async fn notes_fall_back_to_the_previous_git_tag() { | ||
| 663 | + let fx = fixture().await; | ||
| 664 | + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; | ||
| 665 | + commit_message(&fx.work, "feat: one"); | ||
| 666 | + let oid = commit_message(&fx.work, "fix: two"); | ||
| 667 | + land(&fx, &oid, "refs/tags/v1.1"); | ||
| 668 | + after_ref_update(&fx.state, &fx.repo, &fx.owner.id, "refs/tags/v1.1", ZERO, &oid) | ||
| 669 | + .await | ||
| 670 | + .expect("post update"); | ||
| 671 | + finish_all(&fx, &run_of(&fx, 2).await.id, None).await; | ||
| 672 | + on_run_finished(&fx.state, &run_of(&fx, 2).await).await; | ||
| 673 | + | ||
| 674 | + let release = release_named(&fx, "v1.1").await.expect("release made"); | ||
| 675 | + assert!(release.body.starts_with("- fix: two (")); | ||
| 676 | + assert!(release.body.contains("- feat: one (")); | ||
| 677 | + assert!(release.body.ends_with("Full changelog: v1.0...v1.1")); | ||
| 678 | + assert!(release_named(&fx, "v1.0").await.is_none()); | ||
| 679 | + } | ||
| 680 | + | ||
| 681 | + #[test] | ||
| 682 | + fn bullets_put_the_footer_last_and_respect_the_limit() { | ||
| 683 | + let commit = |oid: &str, summary: &str| CommitInfo { | ||
| 684 | + oid: oid.to_owned(), | ||
| 685 | + parents: Vec::new(), | ||
| 686 | + author_name: String::new(), | ||
| 687 | + author_email: String::new(), | ||
| 688 | + author_time: 0, | ||
| 689 | + committer_name: String::new(), | ||
| 690 | + committer_email: String::new(), | ||
| 691 | + committer_time: 0, | ||
| 692 | + summary: summary.to_owned(), | ||
| 693 | + message: String::new(), | ||
| 694 | + }; | ||
| 695 | + let commits = vec![ | ||
| 696 | + commit("abcdef1234567", "new"), | ||
| 697 | + commit("1234567abcdef", "old"), | ||
| 698 | + ]; | ||
| 699 | + assert_eq!( | ||
| 700 | + bullets(&commits, Some("Full changelog: a...b")), | ||
| 701 | + "- new (abcdef1)\n- old (1234567)\n\nFull changelog: a...b" | ||
| 702 | + ); | ||
| 703 | + assert_eq!(bullets(&[], None), ""); | ||
| 704 | + } | ||
| 705 | +} | ||
crates/forge-web/src/ci/schedule.rsmodified+25 -16
| @@ -284,6 +284,15 @@ fn plan_jobs(cfg: &CiConfig) -> forge_core::Result<Vec<PlannedJob>> { | |||
| 284 | } | 284 | } |
| 285 | 285 | ||
| 286 | /// Reads and parses `.forge/ci.toml` at `commit` from the repo `repo_id`. | 286 | /// Reads and parses `.forge/ci.toml` at `commit` from the repo `repo_id`. |
| 287 | +/// The workflow at `commit`, when it is a valid file. Used by the release hook, which reads the | ||
| 288 | +/// config the run itself was made from. | ||
| 289 | +pub(super) async fn config_at(state: &AppState, repo_id: &str, commit: &str) -> Option<CiConfig> { | ||
| 290 | + match load(state, repo_id, commit).await { | ||
| 291 | + Loaded::Valid(config) => Some(config), | ||
| 292 | + Loaded::Missing | Loaded::Invalid(_) => None, | ||
| 293 | + } | ||
| 294 | +} | ||
| 295 | + | ||
| 287 | async fn load(state: &AppState, repo_id: &str, commit: &str) -> Loaded { | 296 | async fn load(state: &AppState, repo_id: &str, commit: &str) -> Loaded { |
| 288 | let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, repo_id) { | 297 | let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, repo_id) { |
| 289 | Ok(path) => path, | 298 | Ok(path) => path, |
| @@ -368,7 +377,7 @@ where | |||
| 368 | } | 377 | } |
| 369 | 378 | ||
| 370 | #[cfg(test)] | 379 | #[cfg(test)] |
| 371 | -mod tests { | 380 | +pub(super) mod tests { |
| 372 | use std::path::{Path, PathBuf}; | 381 | use std::path::{Path, PathBuf}; |
| 373 | use std::sync::Arc; | 382 | use std::sync::Arc; |
| 374 | use std::time::Duration; | 383 | use std::time::Duration; |
| @@ -386,7 +395,7 @@ mod tests { | |||
| 386 | use crate::post_update::after_ref_update; | 395 | use crate::post_update::after_ref_update; |
| 387 | use crate::test_support::test_state; | 396 | use crate::test_support::test_state; |
| 388 | 397 | ||
| 389 | - const ZERO: &str = "0000000000000000000000000000000000000000"; | 398 | + pub(in crate::ci) const ZERO: &str = "0000000000000000000000000000000000000000"; |
| 390 | 399 | ||
| 391 | const CONFIG: &str = r#" | 400 | const CONFIG: &str = r#" |
| 392 | [on] | 401 | [on] |
| @@ -412,7 +421,7 @@ image = "alpine:3" | |||
| 412 | run = "make" | 421 | run = "make" |
| 413 | "#; | 422 | "#; |
| 414 | 423 | ||
| 415 | - const CONFIG_TAGS: &str = r#" | 424 | + pub(in crate::ci) const CONFIG_TAGS: &str = r#" |
| 416 | [on] | 425 | [on] |
| 417 | push = [] | 426 | push = [] |
| 418 | tags = ["v*"] | 427 | tags = ["v*"] |
| @@ -441,7 +450,7 @@ image = "alpine:3" | |||
| 441 | run = "make" | 450 | run = "make" |
| 442 | "#; | 451 | "#; |
| 443 | 452 | ||
| 444 | - fn git(dir: &Path, args: &[&str]) -> String { | 453 | + pub(in crate::ci) fn git(dir: &Path, args: &[&str]) -> String { |
| 445 | let out = std::process::Command::new("git") | 454 | let out = std::process::Command::new("git") |
| 446 | .arg("-C") | 455 | .arg("-C") |
| 447 | .arg(dir) | 456 | .arg(dir) |
| @@ -460,16 +469,16 @@ run = "make" | |||
| 460 | String::from_utf8_lossy(&out.stdout).trim().to_string() | 469 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 461 | } | 470 | } |
| 462 | 471 | ||
| 463 | - struct Fixture { | 472 | + pub(in crate::ci) struct Fixture { |
| 464 | - _tmp: TempDir, | 473 | + pub(in crate::ci) _tmp: TempDir, |
| 465 | - state: AppState, | 474 | + pub(in crate::ci) state: AppState, |
| 466 | - repo: Repo, | 475 | + pub(in crate::ci) repo: Repo, |
| 467 | - owner: User, | 476 | + pub(in crate::ci) owner: User, |
| 468 | - bare: PathBuf, | 477 | + pub(in crate::ci) bare: PathBuf, |
| 469 | - work: PathBuf, | 478 | + pub(in crate::ci) work: PathBuf, |
| 470 | } | 479 | } |
| 471 | 480 | ||
| 472 | - async fn fixture() -> Fixture { | 481 | + pub(in crate::ci) async fn fixture() -> Fixture { |
| 473 | let tmp = tempfile::tempdir().expect("tempdir"); | 482 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 474 | let state = test_state(tmp.path()).await; | 483 | let state = test_state(tmp.path()).await; |
| 475 | let owner = state | 484 | let owner = state |
| @@ -499,7 +508,7 @@ run = "make" | |||
| 499 | } | 508 | } |
| 500 | 509 | ||
| 501 | /// Commits `files` in the work tree and returns the new commit. | 510 | /// Commits `files` in the work tree and returns the new commit. |
| 502 | - fn commit(work: &Path, files: &[(&str, &str)]) -> String { | 511 | + pub(in crate::ci) fn commit(work: &Path, files: &[(&str, &str)]) -> String { |
| 503 | for (path, text) in files { | 512 | for (path, text) in files { |
| 504 | let full = work.join(path); | 513 | let full = work.join(path); |
| 505 | if let Some(parent) = full.parent() { | 514 | if let Some(parent) = full.parent() { |
| @@ -513,7 +522,7 @@ run = "make" | |||
| 513 | } | 522 | } |
| 514 | 523 | ||
| 515 | /// Makes `oid` the tip of `refname` in the bare repo. Fetch runs no hooks, unlike a push. | 524 | /// Makes `oid` the tip of `refname` in the bare repo. Fetch runs no hooks, unlike a push. |
| 516 | - fn land(fx: &Fixture, oid: &str, refname: &str) { | 525 | + pub(in crate::ci) fn land(fx: &Fixture, oid: &str, refname: &str) { |
| 517 | let work = fx.work.to_str().expect("utf8 path"); | 526 | let work = fx.work.to_str().expect("utf8 path"); |
| 518 | git( | 527 | git( |
| 519 | &fx.bare, | 528 | &fx.bare, |
| @@ -522,7 +531,7 @@ run = "make" | |||
| 522 | } | 531 | } |
| 523 | 532 | ||
| 524 | /// Commits `files`, lands them on `refname`, and runs the post-update hook for the update. | 533 | /// Commits `files`, lands them on `refname`, and runs the post-update hook for the update. |
| 525 | - async fn push(fx: &Fixture, files: &[(&str, &str)], refname: &str) -> String { | 534 | + pub(in crate::ci) async fn push(fx: &Fixture, files: &[(&str, &str)], refname: &str) -> String { |
| 526 | let oid = commit(&fx.work, files); | 535 | let oid = commit(&fx.work, files); |
| 527 | land(fx, &oid, refname); | 536 | land(fx, &oid, refname); |
| 528 | after_ref_update(&fx.state, &fx.repo, &fx.owner.id, refname, ZERO, &oid) | 537 | after_ref_update(&fx.state, &fx.repo, &fx.owner.id, refname, ZERO, &oid) |
| @@ -539,7 +548,7 @@ run = "make" | |||
| 539 | jobs.iter().find(|j| j.name == name).map(|j| j.state) | 548 | jobs.iter().find(|j| j.name == name).map(|j| j.state) |
| 540 | } | 549 | } |
| 541 | 550 | ||
| 542 | - async fn runs_total(fx: &Fixture) -> u64 { | 551 | + pub(in crate::ci) async fn runs_total(fx: &Fixture) -> u64 { |
| 543 | fx.state | 552 | fx.state |
| 544 | .store | 553 | .store |
| 545 | .list_runs(&fx.repo.id, 1, 50) | 554 | .list_runs(&fx.repo.id, 1, 50) |
crates/forge-web/src/i18n/releases_ci.rsmodified+36 -4
| @@ -67,6 +67,7 @@ pub enum K { | |||
| 67 | RelSaved, | 67 | RelSaved, |
| 68 | RelDeleted, | 68 | RelDeleted, |
| 69 | RelAssetUploaded, | 69 | RelAssetUploaded, |
| 70 | + RelAssetReplaced, | ||
| 70 | RelAssetDeleted, | 71 | RelAssetDeleted, |
| 71 | RelAssetTooLarge, | 72 | RelAssetTooLarge, |
| 72 | RelAssetExists, | 73 | RelAssetExists, |
| @@ -79,7 +80,6 @@ pub enum K { | |||
| 79 | // Release form errors. | 80 | // Release form errors. |
| 80 | RelErrTagName, | 81 | RelErrTagName, |
| 81 | RelErrReleaseExists, | 82 | RelErrReleaseExists, |
| 82 | - RelErrChooseBranch, | ||
| 83 | 83 | ||
| 84 | // Release pages. | 84 | // Release pages. |
| 85 | Releases, | 85 | Releases, |
| @@ -112,6 +112,12 @@ pub enum K { | |||
| 112 | UploadAsset, | 112 | UploadAsset, |
| 113 | DeleteReleaseHelp, | 113 | DeleteReleaseHelp, |
| 114 | YesDeleteRelease, | 114 | YesDeleteRelease, |
| 115 | + EditTagHelp, | ||
| 116 | + EditTargetLabel, | ||
| 117 | + CurrentCommit, | ||
| 118 | + TargetMoveHelp, | ||
| 119 | + TargetLockedHelp, | ||
| 120 | + ReplaceAsset, | ||
| 115 | } | 121 | } |
| 116 | 122 | ||
| 117 | pub fn t(lang: Lang, key: K) -> &'static str { | 123 | pub fn t(lang: Lang, key: K) -> &'static str { |
| @@ -239,6 +245,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 239 | (RelDeleted, Tr) => "Sürüm silindi. Etiket korundu.", | 245 | (RelDeleted, Tr) => "Sürüm silindi. Etiket korundu.", |
| 240 | (RelAssetUploaded, En) => "Asset uploaded.", | 246 | (RelAssetUploaded, En) => "Asset uploaded.", |
| 241 | (RelAssetUploaded, Tr) => "Dosya yüklendi.", | 247 | (RelAssetUploaded, Tr) => "Dosya yüklendi.", |
| 248 | + (RelAssetReplaced, En) => "Asset replaced. Downloads now serve the new file.", | ||
| 249 | + (RelAssetReplaced, Tr) => "Dosya değiştirildi. İndirmeler artık yeni dosyayı sunar.", | ||
| 242 | (RelAssetDeleted, En) => "Asset deleted.", | 250 | (RelAssetDeleted, En) => "Asset deleted.", |
| 243 | (RelAssetDeleted, Tr) => "Dosya silindi.", | 251 | (RelAssetDeleted, Tr) => "Dosya silindi.", |
| 244 | (RelAssetTooLarge, En) => { | 252 | (RelAssetTooLarge, En) => { |
| @@ -286,8 +294,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 286 | (RelErrReleaseExists, Tr) => { | 294 | (RelErrReleaseExists, Tr) => { |
| 287 | "Bu etiket için zaten bir sürüm var. Bunun yerine o sürümü düzenleyin." | 295 | "Bu etiket için zaten bir sürüm var. Bunun yerine o sürümü düzenleyin." |
| 288 | } | 296 | } |
| 289 | - (RelErrChooseBranch, En) => "Choose a branch to create the tag on.", | ||
| 290 | - (RelErrChooseBranch, Tr) => "Etiketin oluşturulacağı bir dal seçin.", | ||
| 291 | 297 | ||
| 292 | (Releases, En) => "Releases", | 298 | (Releases, En) => "Releases", |
| 293 | (Releases, Tr) => "Sürümler", | 299 | (Releases, Tr) => "Sürümler", |
| @@ -355,6 +361,26 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 355 | (DeleteReleaseHelp, Tr) => "Sürümü ve dosyalarını siler. Git etiketi korunur.", | 361 | (DeleteReleaseHelp, Tr) => "Sürümü ve dosyalarını siler. Git etiketi korunur.", |
| 356 | (YesDeleteRelease, En) => "Yes, delete this release", | 362 | (YesDeleteRelease, En) => "Yes, delete this release", |
| 357 | (YesDeleteRelease, Tr) => "Evet, bu sürümü sil", | 363 | (YesDeleteRelease, Tr) => "Evet, bu sürümü sil", |
| 364 | + (EditTagHelp, En) => { | ||
| 365 | + "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." | ||
| 366 | + } | ||
| 367 | + (EditTagHelp, Tr) => { | ||
| 368 | + "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." | ||
| 369 | + } | ||
| 370 | + (EditTargetLabel, En) => "Move tag to branch (optional)", | ||
| 371 | + (EditTargetLabel, Tr) => "Etiketi dala taşı (isteğe bağlı)", | ||
| 372 | + (CurrentCommit, En) => "Keep the current commit", | ||
| 373 | + (CurrentCommit, Tr) => "Mevcut commit'i koru", | ||
| 374 | + (TargetMoveHelp, En) => "The tag can only move while the release is a draft.", | ||
| 375 | + (TargetMoveHelp, Tr) => "Etiket yalnızca sürüm taslakken taşınabilir.", | ||
| 376 | + (TargetLockedHelp, En) => { | ||
| 377 | + "Published releases keep their commit. To point at another commit, enter a new tag." | ||
| 378 | + } | ||
| 379 | + (TargetLockedHelp, Tr) => { | ||
| 380 | + "Yayımlanmış sürümler commit'lerini korur. Başka bir commit'i göstermek için yeni bir etiket girin." | ||
| 381 | + } | ||
| 382 | + (ReplaceAsset, En) => "Replace", | ||
| 383 | + (ReplaceAsset, Tr) => "Değiştir", | ||
| 358 | } | 384 | } |
| 359 | } | 385 | } |
| 360 | 386 | ||
| @@ -496,6 +522,7 @@ mod tests { | |||
| 496 | K::RelSaved, | 522 | K::RelSaved, |
| 497 | K::RelDeleted, | 523 | K::RelDeleted, |
| 498 | K::RelAssetUploaded, | 524 | K::RelAssetUploaded, |
| 525 | + K::RelAssetReplaced, | ||
| 499 | K::RelAssetDeleted, | 526 | K::RelAssetDeleted, |
| 500 | K::RelAssetTooLarge, | 527 | K::RelAssetTooLarge, |
| 501 | K::RelAssetExists, | 528 | K::RelAssetExists, |
| @@ -506,7 +533,6 @@ mod tests { | |||
| 506 | K::RelAssetEmpty, | 533 | K::RelAssetEmpty, |
| 507 | K::RelErrTagName, | 534 | K::RelErrTagName, |
| 508 | K::RelErrReleaseExists, | 535 | K::RelErrReleaseExists, |
| 509 | - K::RelErrChooseBranch, | ||
| 510 | K::Releases, | 536 | K::Releases, |
| 511 | K::NewRelease, | 537 | K::NewRelease, |
| 512 | K::EditRelease, | 538 | K::EditRelease, |
| @@ -537,6 +563,12 @@ mod tests { | |||
| 537 | K::UploadAsset, | 563 | K::UploadAsset, |
| 538 | K::DeleteReleaseHelp, | 564 | K::DeleteReleaseHelp, |
| 539 | K::YesDeleteRelease, | 565 | K::YesDeleteRelease, |
| 566 | + K::EditTagHelp, | ||
| 567 | + K::EditTargetLabel, | ||
| 568 | + K::CurrentCommit, | ||
| 569 | + K::TargetMoveHelp, | ||
| 570 | + K::TargetLockedHelp, | ||
| 571 | + K::ReplaceAsset, | ||
| 540 | ]; | 572 | ]; |
| 541 | 573 | ||
| 542 | #[test] | 574 | #[test] |
crates/forge-web/src/main.rsmodified+1 -0
| @@ -37,6 +37,7 @@ mod pages; | |||
| 37 | mod post_update; | 37 | mod post_update; |
| 38 | mod pulls_sync; | 38 | mod pulls_sync; |
| 39 | mod raw; | 39 | mod raw; |
| 40 | +mod release_ops; | ||
| 40 | mod render; | 41 | mod render; |
| 41 | mod replication; | 42 | mod replication; |
| 42 | mod self_update; | 43 | mod self_update; |
crates/forge-web/src/pages/releases.rsmodified+281 -306
| @@ -4,17 +4,16 @@ | |||
| 4 | //! | 4 | //! |
| 5 | //! A release names a git tag. When the tag does not exist yet it is created as a lightweight tag | 5 | //! A release names a git tag. When the tag does not exist yet it is created as a lightweight tag |
| 6 | //! at the head of the chosen branch, through `after_ref_update`. Deleting a release keeps the tag. | 6 | //! at the head of the chosen branch, through `after_ref_update`. Deleting a release keeps the tag. |
| 7 | -//! Asset bytes are streamed to and from the blob store (see `blobs.rs`). Downloads are served as | 7 | +//! Asset bytes are streamed to and from the blob store (see `blobs.rs`). An upload under a name the |
| 8 | +//! release already has replaces that asset in place; the edit page offers this as a Replace control. Downloads are served as | ||
| 8 | //! attachments with `nosniff`, and each completed start counts one download. | 9 | //! attachments with `nosniff`, and each completed start counts one download. |
| 9 | 10 | ||
| 10 | use forge_core::releases::{ | 11 | use forge_core::releases::{ |
| 11 | - MAX_BODY_CHARS, MAX_TITLE_CHARS, NewAsset, NewRelease, Release, ReleaseAsset, ReleaseEdit, | 12 | + MAX_BODY_CHARS, MAX_TITLE_CHARS, Release, ReleaseAsset, valid_asset_name, |
| 12 | - clean_content_type, valid_asset_name, | ||
| 13 | }; | 13 | }; |
| 14 | -use forge_core::webhooks::WebhookEvent; | ||
| 15 | use forge_core::{Action, Denied, Repo as CoreRepo, User, authorize}; | 14 | use forge_core::{Action, Denied, Repo as CoreRepo, User, authorize}; |
| 16 | use forge_git::browse::RefKind; | 15 | use forge_git::browse::RefKind; |
| 17 | -use forge_git::tags::{create_lightweight_tag, valid_tag_name}; | 16 | +use forge_git::tags::valid_tag_name; |
| 18 | use futures_util::TryStreamExt; | 17 | use futures_util::TryStreamExt; |
| 19 | use http::header::{CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_TYPE}; | 18 | use http::header::{CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_TYPE}; |
| 20 | use http_body::Frame; | 19 | use http_body::Frame; |
| @@ -30,7 +29,7 @@ use topcoat::router::{Body, HeaderName, HeaderValue, StatusCode, page, path_para | |||
| 30 | use topcoat::view::{Unescaped, View, component, view}; | 29 | use topcoat::view::{Unescaped, View, component, view}; |
| 31 | 30 | ||
| 32 | use crate::auth::require_csrf; | 31 | use crate::auth::require_csrf; |
| 33 | -use crate::blobs::{BlobWriter, asset_key}; | 32 | +use crate::blobs::asset_key; |
| 34 | use crate::i18n::{ | 33 | use crate::i18n::{ |
| 35 | self, Key, Lang, | 34 | self, Key, Lang, |
| 36 | releases_ci::{self as g, K}, | 35 | releases_ci::{self as g, K}, |
| @@ -39,11 +38,10 @@ use crate::pages::refs::load_refs; | |||
| 39 | use crate::pages::repo::repo_head; | 38 | use crate::pages::repo::repo_head; |
| 40 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; | 39 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; |
| 41 | use crate::pages::repo_mirrors::stamp_in_tz; | 40 | use crate::pages::repo_mirrors::stamp_in_tz; |
| 42 | -use crate::post_update::after_ref_update; | 41 | +use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError}; |
| 43 | use crate::render::markdown::render_markdown; | 42 | use crate::render::markdown::render_markdown; |
| 44 | use crate::state::AppState; | 43 | use crate::state::AppState; |
| 45 | -use crate::views::{alert, enc, shell, user_facing_message, user_link}; | 44 | +use crate::views::{alert, enc, shell, user_link}; |
| 46 | -use crate::webhooks::emit::{Sender, emit}; | ||
| 47 | 45 | ||
| 48 | path_param!(owner); | 46 | path_param!(owner); |
| 49 | path_param!(repo); | 47 | path_param!(repo); |
| @@ -54,16 +52,13 @@ path_param!(name); | |||
| 54 | 52 | ||
| 55 | /// Multipart framing allowed on top of the file itself when checking `Content-Length`. | 53 | /// Multipart framing allowed on top of the file itself when checking `Content-Length`. |
| 56 | const MULTIPART_OVERHEAD: u64 = 64 * 1024; | 54 | const MULTIPART_OVERHEAD: u64 = 64 * 1024; |
| 57 | -/// The all-zero object id that means "no ref yet" in ref updates. | ||
| 58 | -fn zero_oid(len: usize) -> String { | ||
| 59 | - "0".repeat(len) | ||
| 60 | -} | ||
| 61 | 55 | ||
| 62 | /// Notice words (the only text a `?notice=` query can show), their text and whether they are errors. | 56 | /// Notice words (the only text a `?notice=` query can show), their text and whether they are errors. |
| 63 | -const NOTICES: [(&str, K, bool); 11] = [ | 57 | +const NOTICES: [(&str, K, bool); 12] = [ |
| 64 | ("saved", K::RelSaved, false), | 58 | ("saved", K::RelSaved, false), |
| 65 | ("deleted", K::RelDeleted, false), | 59 | ("deleted", K::RelDeleted, false), |
| 66 | ("asset-uploaded", K::RelAssetUploaded, false), | 60 | ("asset-uploaded", K::RelAssetUploaded, false), |
| 61 | + ("asset-replaced", K::RelAssetReplaced, false), | ||
| 67 | ("asset-deleted", K::RelAssetDeleted, false), | 62 | ("asset-deleted", K::RelAssetDeleted, false), |
| 68 | ("asset-too-large", K::RelAssetTooLarge, true), | 63 | ("asset-too-large", K::RelAssetTooLarge, true), |
| 69 | ("asset-exists", K::RelAssetExists, true), | 64 | ("asset-exists", K::RelAssetExists, true), |
| @@ -286,12 +281,16 @@ struct CreateForm { | |||
| 286 | draft: Option<String>, | 281 | draft: Option<String>, |
| 287 | } | 282 | } |
| 288 | 283 | ||
| 289 | -/// The edit-release form fields. | 284 | +/// The edit-release form fields. `tag` and `target` are the optional retag fields. |
| 290 | #[derive(Deserialize)] | 285 | #[derive(Deserialize)] |
| 291 | struct EditForm { | 286 | struct EditForm { |
| 292 | #[serde(default)] | 287 | #[serde(default)] |
| 293 | csrf: String, | 288 | csrf: String, |
| 294 | #[serde(default)] | 289 | #[serde(default)] |
| 290 | + tag: String, | ||
| 291 | + #[serde(default)] | ||
| 292 | + target: String, | ||
| 293 | + #[serde(default)] | ||
| 295 | title: String, | 294 | title: String, |
| 296 | #[serde(default)] | 295 | #[serde(default)] |
| 297 | body: String, | 296 | body: String, |
| @@ -342,11 +341,13 @@ async fn release_form( | |||
| 342 | csrf: String, | 341 | csrf: String, |
| 343 | lang: Lang, | 342 | lang: Lang, |
| 344 | is_new: bool, | 343 | is_new: bool, |
| 344 | + move_target: bool, | ||
| 345 | draft: FormDraft, | 345 | draft: FormDraft, |
| 346 | branches: Vec<String>, | 346 | branches: Vec<String>, |
| 347 | submit: &'static str, | 347 | submit: &'static str, |
| 348 | ) -> Result<impl View> { | 348 | ) -> Result<impl View> { |
| 349 | let tag_hint = g::t(lang, K::TagHint); | 349 | let tag_hint = g::t(lang, K::TagHint); |
| 350 | + let edit_tag_help = g::t(lang, K::EditTagHelp); | ||
| 350 | Ok(view! { | 351 | Ok(view! { |
| 351 | <form method="post" action=(action.as_str()) class="stack release-form"> | 352 | <form method="post" action=(action.as_str()) class="stack release-form"> |
| 352 | if let Some(message) = draft.error { | 353 | if let Some(message) = draft.error { |
| @@ -368,7 +369,25 @@ async fn release_form( | |||
| 368 | </select> | 369 | </select> |
| 369 | </label> | 370 | </label> |
| 370 | } else { | 371 | } else { |
| 371 | - <p>(g::t(lang, K::Tag)) ": " <code>(draft.tag.as_str())</code></p> | 372 | + <label> |
| 373 | + <span>(g::t(lang, K::Tag))</span> | ||
| 374 | + <input type="text" name="tag" value=(draft.tag.as_str()) required="required" maxlength="100" autocomplete="off" spellcheck="false"> | ||
| 375 | + </label> | ||
| 376 | + <p class="muted small">(edit_tag_help)</p> | ||
| 377 | + if move_target { | ||
| 378 | + <label> | ||
| 379 | + <span>(g::t(lang, K::EditTargetLabel))</span> | ||
| 380 | + <select name="target"> | ||
| 381 | + <option value="" selected=(draft.target.is_empty())>(g::t(lang, K::CurrentCommit))</option> | ||
| 382 | + for branch in branches.iter() { | ||
| 383 | + <option value=(branch.as_str()) selected=(branch.as_str() == draft.target.as_str())>(branch.as_str())</option> | ||
| 384 | + } | ||
| 385 | + </select> | ||
| 386 | + </label> | ||
| 387 | + <p class="muted small">(g::t(lang, K::TargetMoveHelp))</p> | ||
| 388 | + } else { | ||
| 389 | + <p class="muted small">(g::t(lang, K::TargetLockedHelp))</p> | ||
| 390 | + } | ||
| 372 | } | 391 | } |
| 373 | <label> | 392 | <label> |
| 374 | <span>(g::t(lang, K::Title))</span> | 393 | <span>(g::t(lang, K::Title))</span> |
| @@ -398,6 +417,7 @@ async fn release_form( | |||
| 398 | async fn asset_rows( | 417 | async fn asset_rows( |
| 399 | assets: Vec<AssetLink>, | 418 | assets: Vec<AssetLink>, |
| 400 | delete_actions: Vec<String>, | 419 | delete_actions: Vec<String>, |
| 420 | + upload_action: String, | ||
| 401 | csrf: String, | 421 | csrf: String, |
| 402 | lang: Lang, | 422 | lang: Lang, |
| 403 | ) -> Result<impl View> { | 423 | ) -> Result<impl View> { |
| @@ -423,7 +443,13 @@ async fn asset_rows( | |||
| 423 | <td>(asset.size.as_str())</td> | 443 | <td>(asset.size.as_str())</td> |
| 424 | <td>(asset.downloads)</td> | 444 | <td>(asset.downloads)</td> |
| 425 | <td><code class="small">(asset.sha256.as_str())</code></td> | 445 | <td><code class="small">(asset.sha256.as_str())</code></td> |
| 426 | - <td> | 446 | + <td class="asset-actions"> |
| 447 | + <form method="post" action=(upload_action.as_str()) enctype="multipart/form-data" class="inline-form replace-form"> | ||
| 448 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 449 | + <input type="hidden" name="name" value=(asset.name.as_str())> | ||
| 450 | + <input type="file" name="file" required="required" aria-label=(asset.name.as_str())> | ||
| 451 | + <button type="submit">(g::t(lang, K::ReplaceAsset))</button> | ||
| 452 | + </form> | ||
| 427 | <form method="post" action=(action.as_str()) class="inline-form"> | 453 | <form method="post" action=(action.as_str()) class="inline-form"> |
| 428 | <input type="hidden" name="csrf" value=(csrf.as_str())> | 454 | <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 429 | <button type="submit">(i18n::t(lang, Key::Delete))</button> | 455 | <button type="submit">(i18n::t(lang, Key::Delete))</button> |
| @@ -580,7 +606,7 @@ async fn new_form_body( | |||
| 580 | repo_head(head: head) | 606 | repo_head(head: head) |
| 581 | <section class="card"> | 607 | <section class="card"> |
| 582 | <h2>(g::t(lang, K::NewRelease))</h2> | 608 | <h2>(g::t(lang, K::NewRelease))</h2> |
| 583 | - release_form(action: action, csrf: csrf, lang: lang, is_new: true, draft: draft, branches: branches, submit: g::t(lang, K::SaveRelease)) | 609 | + release_form(action: action, csrf: csrf, lang: lang, is_new: true, move_target: true, draft: draft, branches: branches, submit: g::t(lang, K::SaveRelease)) |
| 584 | </section> | 610 | </section> |
| 585 | }) | 611 | }) |
| 586 | } | 612 | } |
| @@ -633,9 +659,6 @@ async fn release_create(cx: &Cx, Form(form): Form<CreateForm>) -> Result<impl Vi | |||
| 633 | }; | 659 | }; |
| 634 | match create_checked(state, &ctx, &user, &draft, lang).await? { | 660 | match create_checked(state, &ctx, &user, &draft, lang).await? { |
| 635 | Ok(release) => { | 661 | Ok(release) => { |
| 636 | - if !release.draft { | ||
| 637 | - emit_release(state, &ctx.repo, &user, "published", &release).await; | ||
| 638 | - } | ||
| 639 | let title = title_of(&ctx); | 662 | let title = title_of(&ctx); |
| 640 | Err(see_other(tag_href(&title, &release.tag)).into()) | 663 | Err(see_other(tag_href(&title, &release.tag)).into()) |
| 641 | } | 664 | } |
| @@ -656,8 +679,8 @@ async fn release_create(cx: &Cx, Form(form): Form<CreateForm>) -> Result<impl Vi | |||
| 656 | } | 679 | } |
| 657 | } | 680 | } |
| 658 | 681 | ||
| 659 | -/// Checks the new-release fields, makes the tag when it is missing, and stores the release. A | 682 | +/// Checks the new-release fields with their form messages, then creates the release through |
| 660 | -/// refusal the form shows is `Err(message)`; storage failures are errors. | 683 | +/// `release_ops`. A refusal the form shows is `Err(message)`; storage failures are errors. |
| 661 | async fn create_checked( | 684 | async fn create_checked( |
| 662 | state: &AppState, | 685 | state: &AppState, |
| 663 | ctx: &RepoCtx, | 686 | ctx: &RepoCtx, |
| @@ -680,84 +703,21 @@ async fn create_checked( | |||
| 680 | { | 703 | { |
| 681 | return Ok(Err(g::t(lang, K::RelErrReleaseExists).to_owned())); | 704 | return Ok(Err(g::t(lang, K::RelErrReleaseExists).to_owned())); |
| 682 | } | 705 | } |
| 683 | - let refs = load_refs(ctx.path.clone()).await?; | 706 | + let input = CreateRelease { |
| 684 | - let existing = refs | 707 | + tag: tag_name.to_owned(), |
| 685 | - .iter() | 708 | + target: Some(draft.target.clone()), |
| 686 | - .find(|r| r.kind == RefKind::Tag && r.name == tag_name) | 709 | + title: draft.title.clone(), |
| 687 | - .map(|r| r.target.clone()); | 710 | + body: draft.body.clone(), |
| 688 | - let target_oid = match existing { | 711 | + draft: draft.draft, |
| 689 | - Some(oid) => oid, | 712 | + prerelease: draft.prerelease, |
| 690 | - None => { | ||
| 691 | - let branch_oid = refs | ||
| 692 | - .iter() | ||
| 693 | - .find(|r| r.kind == RefKind::Branch && r.name == draft.target) | ||
| 694 | - .map(|r| r.target.clone()); | ||
| 695 | - let Some(branch_oid) = branch_oid else { | ||
| 696 | - return Ok(Err(g::t(lang, K::RelErrChooseBranch).to_owned())); | ||
| 697 | - }; | ||
| 698 | - create_lightweight_tag(&state.git, &ctx.path, tag_name, &branch_oid).await?; | ||
| 699 | - let refname = format!("refs/tags/{tag_name}"); | ||
| 700 | - let zero = zero_oid(branch_oid.len()); | ||
| 701 | - if let Err(e) = | ||
| 702 | - after_ref_update(state, &ctx.repo, &user.id, &refname, &zero, &branch_oid).await | ||
| 703 | - { | ||
| 704 | - tracing::error!(error = %e, repo_id = %ctx.repo.id, "releases: post-update for new tag failed"); | ||
| 705 | - } | ||
| 706 | - branch_oid | ||
| 707 | - } | ||
| 708 | }; | 713 | }; |
| 709 | - let created = state | 714 | + match release_ops::create(state, &ctx.repo, user, input).await { |
| 710 | - .store | ||
| 711 | - .create_release(&NewRelease { | ||
| 712 | - repo_id: &ctx.repo.id, | ||
| 713 | - tag: tag_name, | ||
| 714 | - target_oid: &target_oid, | ||
| 715 | - title: &draft.title, | ||
| 716 | - body: &draft.body, | ||
| 717 | - draft: draft.draft, | ||
| 718 | - prerelease: draft.prerelease, | ||
| 719 | - author_id: &user.id, | ||
| 720 | - }) | ||
| 721 | - .await; | ||
| 722 | - match created { | ||
| 723 | Ok(release) => Ok(Ok(release)), | 715 | Ok(release) => Ok(Ok(release)), |
| 724 | - Err(e) => match user_facing_message(&e) { | 716 | + Err(ReleaseError::Internal(e)) => Err(e.into()), |
| 725 | - Some(message) => Ok(Err(message)), | 717 | + Err(e) => Ok(Err(e.message())), |
| 726 | - None => Err(e.into()), | ||
| 727 | - }, | ||
| 728 | } | 718 | } |
| 729 | } | 719 | } |
| 730 | 720 | ||
| 731 | -/// The webhook payload of a release event, sent to every hook that subscribes to `release`. | ||
| 732 | -async fn emit_release( | ||
| 733 | - state: &AppState, | ||
| 734 | - repo: &CoreRepo, | ||
| 735 | - user: &User, | ||
| 736 | - action: &str, | ||
| 737 | - release: &Release, | ||
| 738 | -) { | ||
| 739 | - let payload = serde_json::json!({ | ||
| 740 | - "release": { | ||
| 741 | - "id": release.id, | ||
| 742 | - "tag": release.tag, | ||
| 743 | - "target_oid": release.target_oid, | ||
| 744 | - "name": release.title, | ||
| 745 | - "draft": release.draft, | ||
| 746 | - "prerelease": release.prerelease, | ||
| 747 | - "published_at": release.published_at, | ||
| 748 | - } | ||
| 749 | - }); | ||
| 750 | - emit( | ||
| 751 | - state, | ||
| 752 | - repo, | ||
| 753 | - &Sender::of(user), | ||
| 754 | - WebhookEvent::Release, | ||
| 755 | - action, | ||
| 756 | - payload, | ||
| 757 | - ) | ||
| 758 | - .await; | ||
| 759 | -} | ||
| 760 | - | ||
| 761 | /// The public view of one release: notes, assets and the source archive links. | 721 | /// The public view of one release: notes, assets and the source archive links. |
| 762 | #[page("/{owner}/{repo}/releases/tag/{tag}")] | 722 | #[page("/{owner}/{repo}/releases/tag/{tag}")] |
| 763 | async fn release_tag_page(cx: &Cx) -> Result<impl View> { | 723 | async fn release_tag_page(cx: &Cx) -> Result<impl View> { |
| @@ -881,6 +841,121 @@ async fn release_tag_page(cx: &Cx) -> Result<impl View> { | |||
| 881 | }) | 841 | }) |
| 882 | } | 842 | } |
| 883 | 843 | ||
| 844 | +/// The edit page body below the repo header: the release fields, its assets with replace and | ||
| 845 | +/// delete controls, the upload form and the delete form. Shared by the page and by a refused save, | ||
| 846 | +/// which shows the typed values again. | ||
| 847 | +#[component] | ||
| 848 | +async fn edit_body( | ||
| 849 | + head: RepoHead, | ||
| 850 | + lang: Lang, | ||
| 851 | + notice: Option<(&'static str, bool)>, | ||
| 852 | + view_tag: String, | ||
| 853 | + action: String, | ||
| 854 | + csrf: String, | ||
| 855 | + draft: FormDraft, | ||
| 856 | + branches: Vec<String>, | ||
| 857 | + move_target: bool, | ||
| 858 | + assets: Vec<AssetLink>, | ||
| 859 | + delete_actions: Vec<String>, | ||
| 860 | + upload_action: String, | ||
| 861 | + upload_hint: String, | ||
| 862 | + delete_href: String, | ||
| 863 | +) -> Result<impl View> { | ||
| 864 | + Ok(view! { | ||
| 865 | + repo_head(head: head) | ||
| 866 | + if let Some((text, is_error)) = notice { | ||
| 867 | + if is_error { | ||
| 868 | + alert(message: text) | ||
| 869 | + } else { | ||
| 870 | + <section class="card notice" role="status">(text)</section> | ||
| 871 | + } | ||
| 872 | + } | ||
| 873 | + <section class="card"> | ||
| 874 | + <p class="muted small"><a href=(view_tag.as_str())>(g::t(lang, K::BackToRelease))</a></p> | ||
| 875 | + <h2>(g::t(lang, K::EditRelease))</h2> | ||
| 876 | + release_form(action: action, csrf: csrf.clone(), lang: lang, is_new: false, move_target: move_target, draft: draft, branches: branches, submit: g::t(lang, K::SaveRelease)) | ||
| 877 | + </section> | ||
| 878 | + <section class="card"> | ||
| 879 | + <h2>(g::t(lang, K::Assets))</h2> | ||
| 880 | + <p class="muted small">(upload_hint.as_str())</p> | ||
| 881 | + asset_rows(assets: assets, delete_actions: delete_actions, upload_action: upload_action.clone(), csrf: csrf.clone(), lang: lang) | ||
| 882 | + <form method="post" action=(upload_action.as_str()) enctype="multipart/form-data" class="stack"> | ||
| 883 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 884 | + <label> | ||
| 885 | + <span>(g::t(lang, K::File))</span> | ||
| 886 | + <input type="file" name="file" required="required"> | ||
| 887 | + </label> | ||
| 888 | + <div> | ||
| 889 | + <button type="submit">(g::t(lang, K::UploadAsset))</button> | ||
| 890 | + </div> | ||
| 891 | + </form> | ||
| 892 | + </section> | ||
| 893 | + <section class="card"> | ||
| 894 | + <h2>(g::t(lang, K::DeleteRelease))</h2> | ||
| 895 | + <p class="muted small">(g::t(lang, K::DeleteReleaseHelp))</p> | ||
| 896 | + <form method="post" action=(delete_href.as_str()) class="stack"> | ||
| 897 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 898 | + <label class="inline"> | ||
| 899 | + <input type="checkbox" name="confirm" value="on"> | ||
| 900 | + <span>(g::t(lang, K::YesDeleteRelease))</span> | ||
| 901 | + </label> | ||
| 902 | + <div> | ||
| 903 | + <button type="submit">(g::t(lang, K::DeleteRelease))</button> | ||
| 904 | + </div> | ||
| 905 | + </form> | ||
| 906 | + </section> | ||
| 907 | + }) | ||
| 908 | +} | ||
| 909 | + | ||
| 910 | +/// What the edit page shows, gathered for the page and for a refused save. | ||
| 911 | +struct EditParts { | ||
| 912 | + page_title: String, | ||
| 913 | + head: RepoHead, | ||
| 914 | + branches: Vec<String>, | ||
| 915 | + move_target: bool, | ||
| 916 | + links: Vec<AssetLink>, | ||
| 917 | + delete_actions: Vec<String>, | ||
| 918 | + upload_action: String, | ||
| 919 | + upload_hint: String, | ||
| 920 | + delete_href: String, | ||
| 921 | + view_tag: String, | ||
| 922 | + action: String, | ||
| 923 | +} | ||
| 924 | + | ||
| 925 | +/// Loads the edit page data for `release`. | ||
| 926 | +async fn edit_parts(state: &AppState, ctx: &RepoCtx, release: &Release, lang: Lang) -> Result<EditParts> { | ||
| 927 | + let title = title_of(ctx); | ||
| 928 | + let assets = state.store.list_release_assets(&release.id).await?; | ||
| 929 | + let delete_actions: Vec<String> = assets | ||
| 930 | + .iter() | ||
| 931 | + .map(|a| { | ||
| 932 | + format!( | ||
| 933 | + "/{title}/releases/{}/assets/{}/delete", | ||
| 934 | + enc(&release.id), | ||
| 935 | + enc(&a.id) | ||
| 936 | + ) | ||
| 937 | + }) | ||
| 938 | + .collect(); | ||
| 939 | + let links: Vec<AssetLink> = assets | ||
| 940 | + .iter() | ||
| 941 | + .map(|asset| asset_link(&title, &release.tag, asset)) | ||
| 942 | + .collect(); | ||
| 943 | + let refs = load_refs(ctx.path.clone()).await?; | ||
| 944 | + Ok(EditParts { | ||
| 945 | + page_title: format!("{title} \u{b7} {}", g::edit_title(lang, &release.tag)), | ||
| 946 | + head: ctx.head(state, "releases").await?, | ||
| 947 | + branches: branch_choices(&refs, &ctx.repo.default_branch), | ||
| 948 | + move_target: release.draft, | ||
| 949 | + links, | ||
| 950 | + delete_actions, | ||
| 951 | + upload_action: format!("/{title}/releases/{}/assets", enc(&release.id)), | ||
| 952 | + upload_hint: g::upload_hint(lang, state.config.releases.max_asset_mb), | ||
| 953 | + delete_href: format!("/{title}/releases/{}/delete", enc(&release.id)), | ||
| 954 | + view_tag: tag_href(&title, &release.tag), | ||
| 955 | + action: release_edit_href(&title, &release.id), | ||
| 956 | + }) | ||
| 957 | +} | ||
| 958 | + | ||
| 884 | /// The edit page: the release fields, its assets, and the upload form. | 959 | /// The edit page: the release fields, its assets, and the upload form. |
| 885 | #[page("/{owner}/{repo}/releases/{release_id}/edit")] | 960 | #[page("/{owner}/{repo}/releases/{release_id}/edit")] |
| 886 | async fn release_edit_page(cx: &Cx) -> Result<impl View> { | 961 | async fn release_edit_page(cx: &Cx) -> Result<impl View> { |
| @@ -897,23 +972,6 @@ async fn release_edit_page(cx: &Cx) -> Result<impl View> { | |||
| 897 | if release.repo_id != ctx.repo.id { | 972 | if release.repo_id != ctx.repo.id { |
| 898 | return Err(not_found().into()); | 973 | return Err(not_found().into()); |
| 899 | } | 974 | } |
| 900 | - let title = title_of(&ctx); | ||
| 901 | - let assets = state.store.list_release_assets(&release.id).await?; | ||
| 902 | - let delete_actions: Vec<String> = assets | ||
| 903 | - .iter() | ||
| 904 | - .map(|a| { | ||
| 905 | - format!( | ||
| 906 | - "/{}/releases/{}/assets/{}/delete", | ||
| 907 | - title_of(&ctx), | ||
| 908 | - enc(&release.id), | ||
| 909 | - enc(&a.id) | ||
| 910 | - ) | ||
| 911 | - }) | ||
| 912 | - .collect(); | ||
| 913 | - let links: Vec<AssetLink> = assets | ||
| 914 | - .iter() | ||
| 915 | - .map(|asset| asset_link(&title, &release.tag, asset)) | ||
| 916 | - .collect(); | ||
| 917 | let csrf = match crate::auth::current_user(cx).await? { | 975 | let csrf = match crate::auth::current_user(cx).await? { |
| 918 | Some((_, session)) => session.csrf_token.clone(), | 976 | Some((_, session)) => session.csrf_token.clone(), |
| 919 | None => String::new(), | 977 | None => String::new(), |
| @@ -926,110 +984,72 @@ async fn release_edit_page(cx: &Cx) -> Result<impl View> { | |||
| 926 | draft: release.draft, | 984 | draft: release.draft, |
| 927 | ..FormDraft::default() | 985 | ..FormDraft::default() |
| 928 | }; | 986 | }; |
| 929 | - let refs = load_refs(ctx.path.clone()).await?; | ||
| 930 | - let branches = branch_choices(&refs, &ctx.repo.default_branch); | ||
| 931 | - let head = ctx.head(state, "releases").await?; | ||
| 932 | - let page_title = format!("{title} \u{b7} {}", g::edit_title(lang, &release.tag)); | ||
| 933 | let notice = notice_from_query(cx, lang); | 987 | let notice = notice_from_query(cx, lang); |
| 934 | - let action = release_edit_href(&title, &release.id); | 988 | + let parts = edit_parts(state, &ctx, &release, lang).await?; |
| 935 | - let assets_base = format!("/{title}/releases/{}/assets", enc(&release.id)); | ||
| 936 | - let upload_action = assets_base.clone(); | ||
| 937 | - let upload_hint = g::upload_hint(lang, state.config.releases.max_asset_mb); | ||
| 938 | - let delete_href = format!("/{title}/releases/{}/delete", enc(&release.id)); | ||
| 939 | - let view_tag = tag_href(&title, &release.tag); | ||
| 940 | Ok(view! { | 989 | Ok(view! { |
| 941 | - shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), | 990 | + shell(title: parts.page_title.as_str(), viewer: ctx.viewer.as_ref(), |
| 942 | - repo_head(head: head) | 991 | + edit_body(head: parts.head, lang: lang, notice: notice, view_tag: parts.view_tag, action: parts.action, |
| 943 | - if let Some((text, is_error)) = notice { | 992 | + csrf: csrf, draft: draft, branches: parts.branches, move_target: parts.move_target, |
| 944 | - if is_error { | 993 | + assets: parts.links, delete_actions: parts.delete_actions, upload_action: parts.upload_action, |
| 945 | - alert(message: text) | 994 | + upload_hint: parts.upload_hint, delete_href: parts.delete_href)) |
| 946 | - } else { | ||
| 947 | - <section class="card notice" role="status">(text)</section> | ||
| 948 | - } | ||
| 949 | - } | ||
| 950 | - <section class="card"> | ||
| 951 | - <p class="muted small"><a href=(view_tag.as_str())>(g::t(lang, K::BackToRelease))</a></p> | ||
| 952 | - <h2>(g::t(lang, K::EditRelease))</h2> | ||
| 953 | - release_form(action: action.clone(), csrf: csrf.clone(), lang: lang, is_new: false, draft: draft, branches: branches, submit: g::t(lang, K::SaveRelease)) | ||
| 954 | - </section> | ||
| 955 | - <section class="card"> | ||
| 956 | - <h2>(g::t(lang, K::Assets))</h2> | ||
| 957 | - <p class="muted small">(upload_hint.as_str())</p> | ||
| 958 | - asset_rows(assets: links, delete_actions: delete_actions, csrf: csrf.clone(), lang: lang) | ||
| 959 | - <form method="post" action=(upload_action.as_str()) enctype="multipart/form-data" class="stack"> | ||
| 960 | - <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 961 | - <label> | ||
| 962 | - <span>(g::t(lang, K::File))</span> | ||
| 963 | - <input type="file" name="file" required="required"> | ||
| 964 | - </label> | ||
| 965 | - <div> | ||
| 966 | - <button type="submit">(g::t(lang, K::UploadAsset))</button> | ||
| 967 | - </div> | ||
| 968 | - </form> | ||
| 969 | - </section> | ||
| 970 | - <section class="card"> | ||
| 971 | - <h2>(g::t(lang, K::DeleteRelease))</h2> | ||
| 972 | - <p class="muted small">(g::t(lang, K::DeleteReleaseHelp))</p> | ||
| 973 | - <form method="post" action=(delete_href.as_str()) class="stack"> | ||
| 974 | - <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 975 | - <label class="inline"> | ||
| 976 | - <input type="checkbox" name="confirm" value="on"> | ||
| 977 | - <span>(g::t(lang, K::YesDeleteRelease))</span> | ||
| 978 | - </label> | ||
| 979 | - <div> | ||
| 980 | - <button type="submit">(g::t(lang, K::DeleteRelease))</button> | ||
| 981 | - </div> | ||
| 982 | - </form> | ||
| 983 | - </section> | ||
| 984 | - ) | ||
| 985 | }) | 995 | }) |
| 986 | } | 996 | } |
| 987 | 997 | ||
| 988 | -/// Saves the edited fields. A draft that becomes published is announced as `published`; any other | 998 | +/// Saves the edited fields through `release_ops`. An empty target keeps the commit, and an |
| 989 | -/// change to a published release is `updated`. | 999 | +/// unchanged tag keeps the tag. A refused save shows its message and keeps the typed values. |
| 990 | -#[route(POST "/{owner}/{repo}/releases/{release_id}/edit")] | 1000 | +#[page(POST "/{owner}/{repo}/releases/{release_id}/edit")] |
| 991 | -async fn release_update(cx: &Cx, Form(form): Form<EditForm>) -> Result<Response> { | 1001 | +async fn release_update(cx: &Cx, Form(form): Form<EditForm>) -> Result<impl View> { |
| 992 | let owner = path_param::<Owner>(cx); | 1002 | let owner = path_param::<Owner>(cx); |
| 993 | let name = path_param::<Repo>(cx); | 1003 | let name = path_param::<Repo>(cx); |
| 994 | let id = path_param::<ReleaseId>(cx).to_owned(); | 1004 | let id = path_param::<ReleaseId>(cx).to_owned(); |
| 995 | let ctx = load_repo(cx, owner, name).await?; | 1005 | let ctx = load_repo(cx, owner, name).await?; |
| 996 | - let (user, _) = require_csrf(cx, &form.csrf).await?; | 1006 | + let (user, session) = require_csrf(cx, &form.csrf).await?; |
| 997 | require_write(&ctx)?; | 1007 | require_write(&ctx)?; |
| 1008 | + let lang = i18n::lang(cx, viewer_user(&ctx)); | ||
| 998 | let state = app_context::<AppState>(cx); | 1009 | let state = app_context::<AppState>(cx); |
| 999 | let Some(before) = state.store.release(&id).await? else { | 1010 | let Some(before) = state.store.release(&id).await? else { |
| 1000 | return Err(not_found().into()); | 1011 | return Err(not_found().into()); |
| 1001 | }; | 1012 | }; |
| 1002 | - if before.repo_id != ctx.repo.id { | 1013 | + let draft = FormDraft { |
| 1003 | - return Err(not_found().into()); | 1014 | + tag: form.tag.trim().to_owned(), |
| 1004 | - } | 1015 | + target: form.target.trim().to_owned(), |
| 1005 | - let title_text = form.title.trim().to_owned(); | 1016 | + title: form.title.trim().to_owned(), |
| 1006 | - let body = form.body.trim_end().to_owned(); | 1017 | + body: form.body.trim_end().to_owned(), |
| 1007 | - let lang = i18n::lang(cx, viewer_user(&ctx)); | ||
| 1008 | - if check_title_body(lang, &title_text, &body).is_err() { | ||
| 1009 | - return Err(notice_redirect(&release_edit_href(&title_of(&ctx), &id), "invalid").into()); | ||
| 1010 | - } | ||
| 1011 | - let edit = ReleaseEdit { | ||
| 1012 | - title: &title_text, | ||
| 1013 | - body: &body, | ||
| 1014 | - draft: form.draft.is_some(), | ||
| 1015 | prerelease: form.prerelease.is_some(), | 1018 | prerelease: form.prerelease.is_some(), |
| 1019 | + draft: form.draft.is_some(), | ||
| 1020 | + error: None, | ||
| 1016 | }; | 1021 | }; |
| 1017 | - if !state.store.update_release(&id, &edit).await? { | 1022 | + let edit = EditRelease { |
| 1018 | - return Err(not_found().into()); | 1023 | + title: draft.title.clone(), |
| 1019 | - } | 1024 | + body: draft.body.clone(), |
| 1020 | - let Some(after) = state.store.release(&id).await? else { | 1025 | + draft: draft.draft, |
| 1021 | - return Err(not_found().into()); | 1026 | + prerelease: draft.prerelease, |
| 1022 | - }; | 1027 | + tag: (draft.tag != before.tag).then(|| draft.tag.clone()), |
| 1023 | - let action = match (before.draft, after.draft) { | 1028 | + target: (!draft.target.is_empty()).then(|| draft.target.clone()), |
| 1024 | - (true, false) => Some("published"), | ||
| 1025 | - (true, true) => None, | ||
| 1026 | - (false, _) => Some("updated"), | ||
| 1027 | }; | 1029 | }; |
| 1028 | - if let Some(action) = action { | 1030 | + match release_ops::update(state, &ctx.repo, &user, &before, edit).await { |
| 1029 | - emit_release(state, &ctx.repo, &user, action, &after).await; | 1031 | + Ok(_) => { |
| 1032 | + let href = release_edit_href(&title_of(&ctx), &id); | ||
| 1033 | + Err(notice_redirect(&href, "saved").into()) | ||
| 1034 | + } | ||
| 1035 | + Err(ReleaseError::NotFound) => Err(not_found().into()), | ||
| 1036 | + Err(ReleaseError::Internal(e)) => Err(e.into()), | ||
| 1037 | + Err(e) => { | ||
| 1038 | + let csrf = session.csrf_token.clone(); | ||
| 1039 | + let draft = FormDraft { | ||
| 1040 | + error: Some(e.message()), | ||
| 1041 | + ..draft | ||
| 1042 | + }; | ||
| 1043 | + let parts = edit_parts(state, &ctx, &before, lang).await?; | ||
| 1044 | + Ok(view! { | ||
| 1045 | + shell(title: parts.page_title.as_str(), viewer: ctx.viewer.as_ref(), | ||
| 1046 | + edit_body(head: parts.head, lang: lang, notice: None, view_tag: parts.view_tag, action: parts.action, | ||
| 1047 | + csrf: csrf, draft: draft, branches: parts.branches, move_target: parts.move_target, | ||
| 1048 | + assets: parts.links, delete_actions: parts.delete_actions, upload_action: parts.upload_action, | ||
| 1049 | + upload_hint: parts.upload_hint, delete_href: parts.delete_href)) | ||
| 1050 | + }) | ||
| 1051 | + } | ||
| 1030 | } | 1052 | } |
| 1031 | - let href = release_edit_href(&title_of(&ctx), &id); | ||
| 1032 | - Err(notice_redirect(&href, "saved").into()) | ||
| 1033 | } | 1053 | } |
| 1034 | 1054 | ||
| 1035 | /// Deletes a release and its assets, then their blobs. The git tag is kept. Requires the confirm box. | 1055 | /// Deletes a release and its assets, then their blobs. The git tag is kept. Requires the confirm box. |
| @@ -1050,21 +1070,11 @@ async fn release_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<Response> | |||
| 1050 | let Some(release) = state.store.release(&id).await? else { | 1070 | let Some(release) = state.store.release(&id).await? else { |
| 1051 | return Err(not_found().into()); | 1071 | return Err(not_found().into()); |
| 1052 | }; | 1072 | }; |
| 1053 | - if release.repo_id != ctx.repo.id { | 1073 | + match release_ops::delete(state, &ctx.repo, &user, &release).await { |
| 1054 | - return Err(not_found().into()); | 1074 | + Ok(()) => Err(notice_redirect(&releases_href(&title), "deleted").into()), |
| 1075 | + Err(ReleaseError::Internal(e)) => Err(e.into()), | ||
| 1076 | + Err(_) => Err(not_found().into()), | ||
| 1055 | } | 1077 | } |
| 1056 | - let Some(asset_ids) = state.store.delete_release(&id).await? else { | ||
| 1057 | - return Err(not_found().into()); | ||
| 1058 | - }; | ||
| 1059 | - for asset_id in &asset_ids { | ||
| 1060 | - if let Err(e) = state.blobs.delete(&asset_key(asset_id)).await { | ||
| 1061 | - tracing::error!(error = %e, asset_id, "releases: could not delete an asset blob"); | ||
| 1062 | - } | ||
| 1063 | - } | ||
| 1064 | - if !release.draft { | ||
| 1065 | - emit_release(state, &ctx.repo, &user, "deleted", &release).await; | ||
| 1066 | - } | ||
| 1067 | - Err(notice_redirect(&releases_href(&title), "deleted").into()) | ||
| 1068 | } | 1078 | } |
| 1069 | 1079 | ||
| 1070 | /// Deletes one asset row and its blob. | 1080 | /// Deletes one asset row and its blob. |
| @@ -1072,54 +1082,28 @@ async fn release_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<Response> | |||
| 1072 | async fn asset_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<Response> { | 1082 | async fn asset_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<Response> { |
| 1073 | let owner = path_param::<Owner>(cx); | 1083 | let owner = path_param::<Owner>(cx); |
| 1074 | let name = path_param::<Repo>(cx); | 1084 | let name = path_param::<Repo>(cx); |
| 1075 | - let release = path_param::<ReleaseId>(cx).to_owned(); | 1085 | + let release_id = path_param::<ReleaseId>(cx).to_owned(); |
| 1076 | let asset = path_param::<AssetId>(cx).to_owned(); | 1086 | let asset = path_param::<AssetId>(cx).to_owned(); |
| 1077 | let ctx = load_repo(cx, owner, name).await?; | 1087 | let ctx = load_repo(cx, owner, name).await?; |
| 1078 | require_csrf(cx, &form.csrf).await?; | 1088 | require_csrf(cx, &form.csrf).await?; |
| 1079 | require_write(&ctx)?; | 1089 | require_write(&ctx)?; |
| 1080 | let state = app_context::<AppState>(cx); | 1090 | let state = app_context::<AppState>(cx); |
| 1081 | - let Some(row) = state.store.release_asset_by_id(&asset).await? else { | 1091 | + let Some(release) = state.store.release(&release_id).await? else { |
| 1082 | return Err(not_found().into()); | 1092 | return Err(not_found().into()); |
| 1083 | }; | 1093 | }; |
| 1084 | - if row.release_id != release { | 1094 | + let href = release_edit_href(&title_of(&ctx), &release_id); |
| 1085 | - return Err(not_found().into()); | 1095 | + match release_ops::delete_asset(state, &ctx.repo, &release, &asset).await { |
| 1086 | - } | 1096 | + Ok(()) => Err(notice_redirect(&href, "asset-deleted").into()), |
| 1087 | - let href = release_edit_href(&title_of(&ctx), &release); | 1097 | + Err(ReleaseError::Internal(e)) => Err(e.into()), |
| 1088 | - state.store.delete_release_asset(&row.id).await?; | 1098 | + Err(_) => Err(not_found().into()), |
| 1089 | - if let Err(e) = state.blobs.delete(&asset_key(&row.id)).await { | ||
| 1090 | - tracing::error!(error = %e, asset_id = %row.id, "releases: could not delete an asset blob"); | ||
| 1091 | - } | ||
| 1092 | - Err(notice_redirect(&href, "asset-deleted").into()) | ||
| 1093 | -} | ||
| 1094 | - | ||
| 1095 | -/// Why a streamed upload stopped early. | ||
| 1096 | -enum UploadFailure { | ||
| 1097 | - TooLarge, | ||
| 1098 | - Unreadable, | ||
| 1099 | - Storage(forge_core::Error), | ||
| 1100 | -} | ||
| 1101 | - | ||
| 1102 | -/// Copies one multipart field into the blob writer, enforcing the writer's size limit. | ||
| 1103 | -async fn copy_field( | ||
| 1104 | - field: &mut multer::Field<'_>, | ||
| 1105 | - writer: &mut BlobWriter, | ||
| 1106 | -) -> std::result::Result<(), UploadFailure> { | ||
| 1107 | - loop { | ||
| 1108 | - match field.chunk().await { | ||
| 1109 | - Ok(Some(chunk)) => match writer.push(&chunk).await { | ||
| 1110 | - Ok(()) => {} | ||
| 1111 | - Err(forge_core::Error::Invalid(_)) => return Err(UploadFailure::TooLarge), | ||
| 1112 | - Err(e) => return Err(UploadFailure::Storage(e)), | ||
| 1113 | - }, | ||
| 1114 | - Ok(None) => return Ok(()), | ||
| 1115 | - Err(_) => return Err(UploadFailure::Unreadable), | ||
| 1116 | - } | ||
| 1117 | } | 1099 | } |
| 1118 | } | 1100 | } |
| 1119 | 1101 | ||
| 1120 | /// Uploads one asset. The body is read as a stream: the `csrf` field must come first, then the | 1102 | /// Uploads one asset. The body is read as a stream: the `csrf` field must come first, then the |
| 1121 | -/// `file` field. The file goes to a temporary blob while its sha256 is computed, and is | 1103 | +/// `file` field. An optional `name` field, sent before `file`, stores the file under that name |
| 1122 | -/// published under `assets/<id>` only when it is complete and the row is stored. | 1104 | +/// instead of its local name, so a Replace control can swap an asset whatever the file is called. |
| 1105 | +/// The file goes to a temporary blob while its sha256 is computed, and is published under | ||
| 1106 | +/// `assets/<id>` only when it is complete and the row is stored. | ||
| 1123 | #[route(POST "/{owner}/{repo}/releases/{release_id}/assets")] | 1107 | #[route(POST "/{owner}/{repo}/releases/{release_id}/assets")] |
| 1124 | async fn asset_upload(cx: &Cx, body: Body) -> Result<Response> { | 1108 | async fn asset_upload(cx: &Cx, body: Body) -> Result<Response> { |
| 1125 | let owner = path_param::<Owner>(cx); | 1109 | let owner = path_param::<Owner>(cx); |
| @@ -1156,6 +1140,7 @@ async fn asset_upload(cx: &Cx, body: Body) -> Result<Response> { | |||
| 1156 | 1140 | ||
| 1157 | let mut multipart = multer::Multipart::new(body.into_data_stream(), boundary); | 1141 | let mut multipart = multer::Multipart::new(body.into_data_stream(), boundary); |
| 1158 | let mut uploader: Option<User> = None; | 1142 | let mut uploader: Option<User> = None; |
| 1143 | + let mut name_override: Option<String> = None; | ||
| 1159 | let mut outcome: &'static str = "asset-empty"; | 1144 | let mut outcome: &'static str = "asset-empty"; |
| 1160 | loop { | 1145 | loop { |
| 1161 | let mut field = match multipart.next_field().await { | 1146 | let mut field = match multipart.next_field().await { |
| @@ -1173,11 +1158,26 @@ async fn asset_upload(cx: &Cx, body: Body) -> Result<Response> { | |||
| 1173 | require_write(&ctx)?; | 1158 | require_write(&ctx)?; |
| 1174 | uploader = Some(user); | 1159 | uploader = Some(user); |
| 1175 | } | 1160 | } |
| 1161 | + Some("name") => { | ||
| 1162 | + let value = field.text().await.unwrap_or_default(); | ||
| 1163 | + if !value.is_empty() { | ||
| 1164 | + name_override = Some(value); | ||
| 1165 | + } | ||
| 1166 | + } | ||
| 1176 | Some("file") => { | 1167 | Some("file") => { |
| 1177 | let Some(user) = uploader.as_ref() else { | 1168 | let Some(user) = uploader.as_ref() else { |
| 1178 | return Err(forbidden().into()); | 1169 | return Err(forbidden().into()); |
| 1179 | }; | 1170 | }; |
| 1180 | - outcome = store_upload(state, &release.id, user, &mut field, max_bytes).await?; | 1171 | + outcome = store_upload( |
| 1172 | + state, | ||
| 1173 | + &ctx.repo, | ||
| 1174 | + &release, | ||
| 1175 | + user, | ||
| 1176 | + name_override.as_deref(), | ||
| 1177 | + &mut field, | ||
| 1178 | + max_bytes, | ||
| 1179 | + ) | ||
| 1180 | + .await?; | ||
| 1181 | break; | 1181 | break; |
| 1182 | } | 1182 | } |
| 1183 | _ => { | 1183 | _ => { |
| @@ -1188,12 +1188,16 @@ async fn asset_upload(cx: &Cx, body: Body) -> Result<Response> { | |||
| 1188 | Err(notice_redirect(&href, outcome).into()) | 1188 | Err(notice_redirect(&href, outcome).into()) |
| 1189 | } | 1189 | } |
| 1190 | 1190 | ||
| 1191 | -/// Streams one `file` field into a blob and adds its asset row. Returns the notice word for the | 1191 | +/// Streams one `file` field into `release_ops::put_asset`, which replaces a file of the same name. |
| 1192 | -/// outcome. Storage failures are errors; everything the client can cause is a notice. | 1192 | +/// `name_override` replaces the file's own name when given. Returns the notice word for the |
| 1193 | +/// outcome: `asset-replaced` when an older file of that name was swapped out. Storage failures are | ||
| 1194 | +/// errors; everything the client can cause is a notice. | ||
| 1193 | async fn store_upload( | 1195 | async fn store_upload( |
| 1194 | state: &AppState, | 1196 | state: &AppState, |
| 1195 | - release_id: &str, | 1197 | + repo: &CoreRepo, |
| 1198 | + release: &Release, | ||
| 1196 | user: &User, | 1199 | user: &User, |
| 1200 | + name_override: Option<&str>, | ||
| 1197 | field: &mut multer::Field<'_>, | 1201 | field: &mut multer::Field<'_>, |
| 1198 | max_bytes: u64, | 1202 | max_bytes: u64, |
| 1199 | ) -> Result<&'static str> { | 1203 | ) -> Result<&'static str> { |
| @@ -1201,61 +1205,32 @@ async fn store_upload( | |||
| 1201 | if file_name.is_empty() { | 1205 | if file_name.is_empty() { |
| 1202 | return Ok("asset-empty"); | 1206 | return Ok("asset-empty"); |
| 1203 | } | 1207 | } |
| 1204 | - if !valid_asset_name(&file_name) { | 1208 | + let name = name_override.map_or(file_name, str::to_owned); |
| 1209 | + if !valid_asset_name(&name) { | ||
| 1205 | return Ok("asset-name"); | 1210 | return Ok("asset-name"); |
| 1206 | } | 1211 | } |
| 1207 | - if state | ||
| 1208 | - .store | ||
| 1209 | - .release_asset(release_id, &file_name) | ||
| 1210 | - .await? | ||
| 1211 | - .is_some() | ||
| 1212 | - { | ||
| 1213 | - return Ok("asset-exists"); | ||
| 1214 | - } | ||
| 1215 | let mime = field.content_type().map(|m| m.to_string()); | 1212 | let mime = field.content_type().map(|m| m.to_string()); |
| 1216 | - let content_type = clean_content_type(mime.as_deref().and_then(|m| m.split(';').next())); | 1213 | + let content_type = mime.as_deref().and_then(|m| m.split(';').next()); |
| 1217 | - let asset_id = ulid::Ulid::generate().to_string(); | 1214 | + let stream = (&mut *field).map_err(std::io::Error::other); |
| 1218 | - let key = asset_key(&asset_id); | 1215 | + match release_ops::put_asset( |
| 1219 | - let mut writer = state.blobs.begin(&key, max_bytes).await?; | 1216 | + state, |
| 1220 | - match copy_field(field, &mut writer).await { | 1217 | + repo, |
| 1221 | - Ok(()) => {} | 1218 | + release, |
| 1222 | - Err(UploadFailure::TooLarge) => { | 1219 | + user, |
| 1223 | - writer.abort().await; | 1220 | + &name, |
| 1224 | - return Ok("asset-too-large"); | 1221 | + content_type, |
| 1225 | - } | 1222 | + stream, |
| 1226 | - Err(UploadFailure::Unreadable) => { | 1223 | + max_bytes, |
| 1227 | - writer.abort().await; | 1224 | + ) |
| 1228 | - return Ok("asset-invalid"); | 1225 | + .await |
| 1229 | - } | 1226 | + { |
| 1230 | - Err(UploadFailure::Storage(e)) => { | 1227 | + Ok((_, true)) => Ok("asset-replaced"), |
| 1231 | - writer.abort().await; | 1228 | + Ok((_, false)) => Ok("asset-uploaded"), |
| 1232 | - return Err(e.into()); | 1229 | + Err(ReleaseError::TooLarge) => Ok("asset-too-large"), |
| 1233 | - } | 1230 | + Err(ReleaseError::Conflict(_)) => Ok("asset-exists"), |
| 1234 | - } | 1231 | + Err(ReleaseError::Invalid(_)) => Ok("asset-invalid"), |
| 1235 | - let (size, sha256) = writer.finish().await?; | 1232 | + Err(ReleaseError::NotFound) => Err(not_found().into()), |
| 1236 | - let added = state | 1233 | + Err(ReleaseError::Internal(e)) => Err(e.into()), |
| 1237 | - .store | ||
| 1238 | - .add_asset(&NewAsset { | ||
| 1239 | - id: &asset_id, | ||
| 1240 | - release_id, | ||
| 1241 | - name: &file_name, | ||
| 1242 | - size, | ||
| 1243 | - sha256: &sha256, | ||
| 1244 | - content_type: &content_type, | ||
| 1245 | - uploader_id: &user.id, | ||
| 1246 | - }) | ||
| 1247 | - .await; | ||
| 1248 | - match added { | ||
| 1249 | - Ok(_) => Ok("asset-uploaded"), | ||
| 1250 | - Err(e) => { | ||
| 1251 | - if let Err(del) = state.blobs.delete(&key).await { | ||
| 1252 | - tracing::error!(error = %del, "releases: could not remove an unlinked blob"); | ||
| 1253 | - } | ||
| 1254 | - match user_facing_message(&e) { | ||
| 1255 | - Some(_) => Ok("asset-exists"), | ||
| 1256 | - None => Err(e.into()), | ||
| 1257 | - } | ||
| 1258 | - } | ||
| 1259 | } | 1234 | } |
| 1260 | } | 1235 | } |
| 1261 | 1236 | ||
crates/forge-web/src/pages/releases_tests.rsmodified+470 -1
| @@ -4,12 +4,15 @@ | |||
| 4 | use std::path::{Path, PathBuf}; | 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::sync::Arc; | 5 | use std::sync::Arc; |
| 6 | 6 | ||
| 7 | +use forge_core::releases::Release; | ||
| 7 | use forge_core::{Repo, Role, Store, User, Visibility}; | 8 | use forge_core::{Repo, Role, Store, User, Visibility}; |
| 8 | use forge_git::repo::{init_bare, repo_path}; | 9 | use forge_git::repo::{init_bare, repo_path}; |
| 9 | use topcoat::router::request::Request; | 10 | use topcoat::router::request::Request; |
| 10 | use topcoat::router::{Body, HeaderMap, Router, to_bytes}; | 11 | use topcoat::router::{Body, HeaderMap, Router, to_bytes}; |
| 11 | 12 | ||
| 12 | use crate::auth::SESSION_COOKIE; | 13 | use crate::auth::SESSION_COOKIE; |
| 14 | +use crate::blobs::asset_key; | ||
| 15 | +use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError}; | ||
| 13 | use crate::test_support::{app_router, create_session, test_state}; | 16 | use crate::test_support::{app_router, create_session, test_state}; |
| 14 | 17 | ||
| 15 | const CSRF: &str = "releases-test-csrf"; | 18 | const CSRF: &str = "releases-test-csrf"; |
| @@ -506,7 +509,9 @@ async fn an_upload_over_the_size_cap_is_refused_and_leaves_no_blob() { | |||
| 506 | let fx = fixture(Some(1)).await; | 509 | let fx = fixture(Some(1)).await; |
| 507 | let rel = fx.release("v1.0", false).await; | 510 | let rel = fx.release("v1.0", false).await; |
| 508 | let big = vec![7u8; 1024 * 1024 + 4096]; | 511 | let big = vec![7u8; 1024 * 1024 + 4096]; |
| 509 | - let reply = fx.upload(&rel.id, "big.bin", &big, &fx.tahinli_cookie).await; | 512 | + let reply = fx |
| 513 | + .upload(&rel.id, "big.bin", &big, &fx.tahinli_cookie) | ||
| 514 | + .await; | ||
| 510 | assert_eq!(reply.status, 303); | 515 | assert_eq!(reply.status, 303); |
| 511 | assert!( | 516 | assert!( |
| 512 | reply | 517 | reply |
| @@ -588,3 +593,467 @@ async fn the_latest_release_card_shows_on_the_repo_home() { | |||
| 588 | "the tabs link to releases" | 593 | "the tabs link to releases" |
| 589 | ); | 594 | ); |
| 590 | } | 595 | } |
| 596 | + | ||
| 597 | +/// The release's own fields, unchanged, with no tag change. | ||
| 598 | +fn keep(rel: &Release) -> EditRelease { | ||
| 599 | + EditRelease { | ||
| 600 | + title: rel.title.clone(), | ||
| 601 | + body: rel.body.clone(), | ||
| 602 | + draft: rel.draft, | ||
| 603 | + prerelease: rel.prerelease, | ||
| 604 | + tag: None, | ||
| 605 | + target: None, | ||
| 606 | + } | ||
| 607 | +} | ||
| 608 | + | ||
| 609 | +/// Adds a commit on top of `main` and points branch `next` at it. Returns the new commit. | ||
| 610 | +fn second_commit(fx: &Fixture) -> String { | ||
| 611 | + let tree = git(&fx.bare, &["rev-parse", "refs/heads/main^{tree}"]); | ||
| 612 | + let next = git( | ||
| 613 | + &fx.bare, | ||
| 614 | + &["commit-tree", &tree, "-p", &fx.main_tip(), "-m", "two"], | ||
| 615 | + ); | ||
| 616 | + git(&fx.bare, &["update-ref", "refs/heads/next", &next]); | ||
| 617 | + next | ||
| 618 | +} | ||
| 619 | + | ||
| 620 | +#[tokio::test] | ||
| 621 | +async fn a_second_upload_under_the_same_name_replaces_the_file() { | ||
| 622 | + let fx = fixture(None).await; | ||
| 623 | + let rel = fx.release("v1.0", false).await; | ||
| 624 | + let first = fx | ||
| 625 | + .upload(&rel.id, "app.bin", b"first", &fx.tahinli_cookie) | ||
| 626 | + .await; | ||
| 627 | + assert_eq!(first.status, 303); | ||
| 628 | + let before = fx | ||
| 629 | + .store | ||
| 630 | + .release_asset(&rel.id, "app.bin") | ||
| 631 | + .await | ||
| 632 | + .expect("read") | ||
| 633 | + .expect("row"); | ||
| 634 | + fx.store | ||
| 635 | + .count_asset_download(&before.id) | ||
| 636 | + .await | ||
| 637 | + .expect("count"); | ||
| 638 | + | ||
| 639 | + let second = fx | ||
| 640 | + .upload(&rel.id, "app.bin", b"second bytes", &fx.tahinli_cookie) | ||
| 641 | + .await; | ||
| 642 | + assert!( | ||
| 643 | + second | ||
| 644 | + .location | ||
| 645 | + .unwrap_or_default() | ||
| 646 | + .contains("notice=asset-replaced"), | ||
| 647 | + "a same-name upload replaces instead of refusing" | ||
| 648 | + ); | ||
| 649 | + let assets = fx.store.list_release_assets(&rel.id).await.expect("assets"); | ||
| 650 | + assert_eq!(assets.len(), 1, "still one asset of that name"); | ||
| 651 | + let after = &assets[0]; | ||
| 652 | + assert_ne!(after.id, before.id, "the new file has its own blob"); | ||
| 653 | + assert_eq!(after.size, 12); | ||
| 654 | + assert_eq!(after.download_count, 1, "the download counter survives"); | ||
| 655 | + assert!( | ||
| 656 | + fx.state | ||
| 657 | + .blobs | ||
| 658 | + .read(&asset_key(&before.id)) | ||
| 659 | + .await | ||
| 660 | + .expect("read") | ||
| 661 | + .is_none(), | ||
| 662 | + "the replaced blob is deleted" | ||
| 663 | + ); | ||
| 664 | + let got = send( | ||
| 665 | + &fx.app, | ||
| 666 | + "GET", | ||
| 667 | + "/tahinli/proj/releases/download/v1.0/app.bin", | ||
| 668 | + None, | ||
| 669 | + None, | ||
| 670 | + Vec::new(), | ||
| 671 | + ) | ||
| 672 | + .await; | ||
| 673 | + assert_eq!(got.body, b"second bytes"); | ||
| 674 | +} | ||
| 675 | + | ||
| 676 | +#[tokio::test] | ||
| 677 | +async fn a_refused_replacement_keeps_the_old_file() { | ||
| 678 | + let fx = fixture(Some(1)).await; | ||
| 679 | + let rel = fx.release("v1.0", false).await; | ||
| 680 | + fx.upload(&rel.id, "app.bin", b"keep me", &fx.tahinli_cookie) | ||
| 681 | + .await; | ||
| 682 | + let big = vec![7u8; 1024 * 1024 + 4096]; | ||
| 683 | + let reply = fx | ||
| 684 | + .upload(&rel.id, "app.bin", &big, &fx.tahinli_cookie) | ||
| 685 | + .await; | ||
| 686 | + assert!( | ||
| 687 | + reply | ||
| 688 | + .location | ||
| 689 | + .unwrap_or_default() | ||
| 690 | + .contains("notice=asset-too-large") | ||
| 691 | + ); | ||
| 692 | + let row = fx | ||
| 693 | + .store | ||
| 694 | + .release_asset(&rel.id, "app.bin") | ||
| 695 | + .await | ||
| 696 | + .expect("read") | ||
| 697 | + .expect("row"); | ||
| 698 | + assert_eq!(row.size, 7); | ||
| 699 | + let got = send( | ||
| 700 | + &fx.app, | ||
| 701 | + "GET", | ||
| 702 | + "/tahinli/proj/releases/download/v1.0/app.bin", | ||
| 703 | + None, | ||
| 704 | + None, | ||
| 705 | + Vec::new(), | ||
| 706 | + ) | ||
| 707 | + .await; | ||
| 708 | + assert_eq!(got.body, b"keep me"); | ||
| 709 | +} | ||
| 710 | + | ||
| 711 | +#[tokio::test] | ||
| 712 | +async fn a_published_release_moves_to_a_new_tag_and_keeps_the_old_git_tag() { | ||
| 713 | + let fx = fixture(None).await; | ||
| 714 | + git(&fx.bare, &["tag", "v1.0", "refs/heads/main"]); | ||
| 715 | + let rel = fx.release("v1.0", false).await; | ||
| 716 | + let edit = EditRelease { | ||
| 717 | + tag: Some("v1.1".to_owned()), | ||
| 718 | + ..keep(&rel) | ||
| 719 | + }; | ||
| 720 | + let moved = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &rel, edit) | ||
| 721 | + .await | ||
| 722 | + .expect("retag"); | ||
| 723 | + assert_eq!(moved.tag, "v1.1"); | ||
| 724 | + assert_eq!(moved.target_oid, fx.main_tip()); | ||
| 725 | + assert_eq!( | ||
| 726 | + fx.tag_target("v1.1").as_deref(), | ||
| 727 | + Some(fx.main_tip().as_str()) | ||
| 728 | + ); | ||
| 729 | + assert!(fx.tag_target("v1.0").is_some(), "the old git tag is kept"); | ||
| 730 | + assert!( | ||
| 731 | + fx.store | ||
| 732 | + .release_by_tag(&fx.repo.id, "v1.0") | ||
| 733 | + .await | ||
| 734 | + .expect("read") | ||
| 735 | + .is_none() | ||
| 736 | + ); | ||
| 737 | +} | ||
| 738 | + | ||
| 739 | +#[tokio::test] | ||
| 740 | +async fn a_published_tag_cannot_be_moved_in_place_but_a_draft_can() { | ||
| 741 | + let fx = fixture(None).await; | ||
| 742 | + git(&fx.bare, &["tag", "v2.0", "refs/heads/main"]); | ||
| 743 | + let next = second_commit(&fx); | ||
| 744 | + let published = fx.release("v2.0", false).await; | ||
| 745 | + let move_published = EditRelease { | ||
| 746 | + target: Some("next".to_owned()), | ||
| 747 | + ..keep(&published) | ||
| 748 | + }; | ||
| 749 | + let refused = | ||
| 750 | + release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &published, move_published).await; | ||
| 751 | + assert!( | ||
| 752 | + matches!(refused, Err(ReleaseError::Invalid(_))), | ||
| 753 | + "{refused:?}" | ||
| 754 | + ); | ||
| 755 | + assert_eq!( | ||
| 756 | + fx.tag_target("v2.0").as_deref(), | ||
| 757 | + Some(fx.main_tip().as_str()) | ||
| 758 | + ); | ||
| 759 | + | ||
| 760 | + let draft = fx | ||
| 761 | + .store | ||
| 762 | + .create_release(&forge_core::releases::NewRelease { | ||
| 763 | + repo_id: &fx.repo.id, | ||
| 764 | + tag: "v3.0", | ||
| 765 | + target_oid: &fx.main_tip(), | ||
| 766 | + title: "draft", | ||
| 767 | + body: "", | ||
| 768 | + draft: true, | ||
| 769 | + prerelease: false, | ||
| 770 | + author_id: &fx.tahinli.id, | ||
| 771 | + }) | ||
| 772 | + .await | ||
| 773 | + .expect("draft"); | ||
| 774 | + git(&fx.bare, &["tag", "v3.0", "refs/heads/main"]); | ||
| 775 | + let move_draft = EditRelease { | ||
| 776 | + target: Some("next".to_owned()), | ||
| 777 | + ..keep(&draft) | ||
| 778 | + }; | ||
| 779 | + let moved = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, move_draft) | ||
| 780 | + .await | ||
| 781 | + .expect("draft moves"); | ||
| 782 | + assert_eq!(moved.target_oid, next); | ||
| 783 | + assert_eq!(fx.tag_target("v3.0"), Some(next)); | ||
| 784 | +} | ||
| 785 | + | ||
| 786 | +#[tokio::test] | ||
| 787 | +async fn retagging_adopts_an_existing_tag_and_refuses_clashes() { | ||
| 788 | + let fx = fixture(None).await; | ||
| 789 | + git(&fx.bare, &["tag", "v0.9", "refs/heads/main"]); | ||
| 790 | + let next = second_commit(&fx); | ||
| 791 | + let draft = fx.release("v5", true).await; | ||
| 792 | + | ||
| 793 | + let clash_target = EditRelease { | ||
| 794 | + tag: Some("v0.9".to_owned()), | ||
| 795 | + target: Some("next".to_owned()), | ||
| 796 | + ..keep(&draft) | ||
| 797 | + }; | ||
| 798 | + let refused = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, clash_target).await; | ||
| 799 | + assert!( | ||
| 800 | + matches!(refused, Err(ReleaseError::Invalid(_))), | ||
| 801 | + "{refused:?}" | ||
| 802 | + ); | ||
| 803 | + | ||
| 804 | + let adopt = EditRelease { | ||
| 805 | + tag: Some("v0.9".to_owned()), | ||
| 806 | + ..keep(&draft) | ||
| 807 | + }; | ||
| 808 | + let adopted = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, adopt) | ||
| 809 | + .await | ||
| 810 | + .expect("adopt"); | ||
| 811 | + assert_eq!(adopted.tag, "v0.9"); | ||
| 812 | + assert_eq!(adopted.target_oid, fx.main_tip()); | ||
| 813 | + assert_ne!(adopted.target_oid, next); | ||
| 814 | + | ||
| 815 | + let other = fx.release("v6", false).await; | ||
| 816 | + let taken = EditRelease { | ||
| 817 | + tag: Some("v0.9".to_owned()), | ||
| 818 | + ..keep(&other) | ||
| 819 | + }; | ||
| 820 | + let clash = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &other, taken).await; | ||
| 821 | + assert!(matches!(clash, Err(ReleaseError::Conflict(_))), "{clash:?}"); | ||
| 822 | + | ||
| 823 | + let bad_name = EditRelease { | ||
| 824 | + tag: Some("a/b".to_owned()), | ||
| 825 | + ..keep(&other) | ||
| 826 | + }; | ||
| 827 | + let invalid = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &other, bad_name).await; | ||
| 828 | + assert!( | ||
| 829 | + matches!(invalid, Err(ReleaseError::Invalid(_))), | ||
| 830 | + "{invalid:?}" | ||
| 831 | + ); | ||
| 832 | +} | ||
| 833 | + | ||
| 834 | +#[tokio::test] | ||
| 835 | +async fn create_refuses_a_bad_tag_before_touching_git() { | ||
| 836 | + let fx = fixture(None).await; | ||
| 837 | + let input = CreateRelease { | ||
| 838 | + tag: "a/b".to_owned(), | ||
| 839 | + target: Some("main".to_owned()), | ||
| 840 | + title: "x".to_owned(), | ||
| 841 | + body: String::new(), | ||
| 842 | + draft: false, | ||
| 843 | + prerelease: false, | ||
| 844 | + }; | ||
| 845 | + let refused = release_ops::create(&fx.state, &fx.repo, &fx.tahinli, input).await; | ||
| 846 | + assert!( | ||
| 847 | + matches!(refused, Err(ReleaseError::Invalid(_))), | ||
| 848 | + "{refused:?}" | ||
| 849 | + ); | ||
| 850 | + assert!(fx.tag_target("a/b").is_none()); | ||
| 851 | +} | ||
| 852 | + | ||
| 853 | +#[tokio::test] | ||
| 854 | +async fn create_takes_a_commit_id_as_its_target_and_refuses_a_missing_one() { | ||
| 855 | + let fx = fixture(None).await; | ||
| 856 | + let tip = fx.main_tip(); | ||
| 857 | + let made = release_ops::create( | ||
| 858 | + &fx.state, | ||
| 859 | + &fx.repo, | ||
| 860 | + &fx.tahinli, | ||
| 861 | + CreateRelease { | ||
| 862 | + tag: "v7".to_owned(), | ||
| 863 | + target: Some(tip.clone()), | ||
| 864 | + title: "by sha".to_owned(), | ||
| 865 | + body: String::new(), | ||
| 866 | + draft: false, | ||
| 867 | + prerelease: false, | ||
| 868 | + }, | ||
| 869 | + ) | ||
| 870 | + .await | ||
| 871 | + .expect("a commit id works as a target"); | ||
| 872 | + assert_eq!(made.target_oid, tip); | ||
| 873 | + assert_eq!(fx.tag_target("v7").as_deref(), Some(tip.as_str())); | ||
| 874 | + | ||
| 875 | + let missing = release_ops::create( | ||
| 876 | + &fx.state, | ||
| 877 | + &fx.repo, | ||
| 878 | + &fx.tahinli, | ||
| 879 | + CreateRelease { | ||
| 880 | + tag: "v8".to_owned(), | ||
| 881 | + target: Some("1111111111111111111111111111111111111111".to_owned()), | ||
| 882 | + title: "missing".to_owned(), | ||
| 883 | + body: String::new(), | ||
| 884 | + draft: false, | ||
| 885 | + prerelease: false, | ||
| 886 | + }, | ||
| 887 | + ) | ||
| 888 | + .await; | ||
| 889 | + assert!( | ||
| 890 | + matches!(missing, Err(ReleaseError::Invalid(_))), | ||
| 891 | + "{missing:?}" | ||
| 892 | + ); | ||
| 893 | + assert!(fx.tag_target("v8").is_none()); | ||
| 894 | +} | ||
| 895 | + | ||
| 896 | +#[tokio::test] | ||
| 897 | +async fn the_edit_page_shows_tag_and_target_controls_and_hides_the_target_once_published() { | ||
| 898 | + let fx = fixture(None).await; | ||
| 899 | + let draft = fx.release("v1.0", true).await; | ||
| 900 | + let published = fx.release("v2.0", false).await; | ||
| 901 | + | ||
| 902 | + let page = send( | ||
| 903 | + &fx.app, | ||
| 904 | + "GET", | ||
| 905 | + &format!("/tahinli/proj/releases/{}/edit", draft.id), | ||
| 906 | + Some(&fx.tahinli_cookie), | ||
| 907 | + None, | ||
| 908 | + Vec::new(), | ||
| 909 | + ) | ||
| 910 | + .await; | ||
| 911 | + assert_eq!(page.status, 200, "body: {}", page.text()); | ||
| 912 | + let html = page.text(); | ||
| 913 | + assert!(html.contains("name=\"tag\" value=\"v1.0\""), "{html}"); | ||
| 914 | + assert!(html.contains("name=\"target\""), "a draft shows the target"); | ||
| 915 | + | ||
| 916 | + let page = send( | ||
| 917 | + &fx.app, | ||
| 918 | + "GET", | ||
| 919 | + &format!("/tahinli/proj/releases/{}/edit", published.id), | ||
| 920 | + Some(&fx.tahinli_cookie), | ||
| 921 | + None, | ||
| 922 | + Vec::new(), | ||
| 923 | + ) | ||
| 924 | + .await; | ||
| 925 | + let html = page.text(); | ||
| 926 | + assert!(html.contains("name=\"tag\" value=\"v2.0\""), "{html}"); | ||
| 927 | + assert!(!html.contains("name=\"target\""), "published hides the target"); | ||
| 928 | + assert!(html.contains("Published releases keep their commit"), "{html}"); | ||
| 929 | +} | ||
| 930 | + | ||
| 931 | +#[tokio::test] | ||
| 932 | +async fn a_published_release_can_be_retagged_through_the_form_and_keeps_its_commit() { | ||
| 933 | + let fx = fixture(None).await; | ||
| 934 | + git(&fx.bare, &["tag", "v2.0", "refs/heads/main"]); | ||
| 935 | + let published = fx.release("v2.0", false).await; | ||
| 936 | + let reply = send( | ||
| 937 | + &fx.app, | ||
| 938 | + "POST", | ||
| 939 | + &format!("/tahinli/proj/releases/{}/edit", published.id), | ||
| 940 | + Some(&fx.tahinli_cookie), | ||
| 941 | + Some(FORM_TYPE), | ||
| 942 | + form(&[ | ||
| 943 | + ("csrf", CSRF), | ||
| 944 | + ("tag", "v2.1"), | ||
| 945 | + ("target", ""), | ||
| 946 | + ("title", "Release v2.0"), | ||
| 947 | + ("body", "notes"), | ||
| 948 | + ]), | ||
| 949 | + ) | ||
| 950 | + .await; | ||
| 951 | + assert_eq!(reply.status, 303, "body: {}", reply.text()); | ||
| 952 | + assert!( | ||
| 953 | + reply | ||
| 954 | + .location | ||
| 955 | + .unwrap_or_default() | ||
| 956 | + .contains("notice=saved") | ||
| 957 | + ); | ||
| 958 | + let moved = fx | ||
| 959 | + .store | ||
| 960 | + .release(&published.id) | ||
| 961 | + .await | ||
| 962 | + .expect("read") | ||
| 963 | + .expect("row"); | ||
| 964 | + assert_eq!(moved.tag, "v2.1"); | ||
| 965 | + assert_eq!(fx.tag_target("v2.1"), Some(fx.main_tip())); | ||
| 966 | + assert_eq!(fx.tag_target("v2.0"), Some(fx.main_tip()), "old git tag kept"); | ||
| 967 | +} | ||
| 968 | + | ||
| 969 | +#[tokio::test] | ||
| 970 | +async fn a_published_target_move_is_refused_on_the_page_and_the_typed_values_stay() { | ||
| 971 | + let fx = fixture(None).await; | ||
| 972 | + git(&fx.bare, &["tag", "v2.0", "refs/heads/main"]); | ||
| 973 | + second_commit(&fx); | ||
| 974 | + let published = fx.release("v2.0", false).await; | ||
| 975 | + let reply = send( | ||
| 976 | + &fx.app, | ||
| 977 | + "POST", | ||
| 978 | + &format!("/tahinli/proj/releases/{}/edit", published.id), | ||
| 979 | + Some(&fx.tahinli_cookie), | ||
| 980 | + Some(FORM_TYPE), | ||
| 981 | + form(&[ | ||
| 982 | + ("csrf", CSRF), | ||
| 983 | + ("tag", "v2.0"), | ||
| 984 | + ("target", "next"), | ||
| 985 | + ("title", "Typed title"), | ||
| 986 | + ("body", "notes"), | ||
| 987 | + ]), | ||
| 988 | + ) | ||
| 989 | + .await; | ||
| 990 | + assert_eq!(reply.status, 200, "a refused save re-renders: {}", reply.text()); | ||
| 991 | + let html = reply.text(); | ||
| 992 | + assert!(html.contains("pick a new tag"), "{html}"); | ||
| 993 | + assert!(html.contains("Typed title"), "the typed title stays: {html}"); | ||
| 994 | + assert_eq!(fx.tag_target("v2.0"), Some(fx.main_tip())); | ||
| 995 | +} | ||
| 996 | + | ||
| 997 | +#[tokio::test] | ||
| 998 | +async fn replace_keeps_the_asset_name_whatever_the_new_file_is_called() { | ||
| 999 | + let fx = fixture(None).await; | ||
| 1000 | + let rel = fx.release("v1.0", false).await; | ||
| 1001 | + let first = fx | ||
| 1002 | + .upload(&rel.id, "app.bin", b"first", &fx.tahinli_cookie) | ||
| 1003 | + .await; | ||
| 1004 | + assert_eq!(first.status, 303); | ||
| 1005 | + | ||
| 1006 | + let page = send( | ||
| 1007 | + &fx.app, | ||
| 1008 | + "GET", | ||
| 1009 | + &format!("/tahinli/proj/releases/{}/edit", rel.id), | ||
| 1010 | + Some(&fx.tahinli_cookie), | ||
| 1011 | + None, | ||
| 1012 | + Vec::new(), | ||
| 1013 | + ) | ||
| 1014 | + .await; | ||
| 1015 | + assert!( | ||
| 1016 | + page.text().contains("name=\"name\" value=\"app.bin\""), | ||
| 1017 | + "each asset has a replace form" | ||
| 1018 | + ); | ||
| 1019 | + | ||
| 1020 | + let (content_type, body) = crate::pages::settings_profile::tests::multipart(&[ | ||
| 1021 | + ("csrf", None, CSRF.as_bytes()), | ||
| 1022 | + ("name", None, "app.bin".as_bytes()), | ||
| 1023 | + ( | ||
| 1024 | + "file", | ||
| 1025 | + Some(("renamed-build.zip", "application/octet-stream")), | ||
| 1026 | + "second bytes".as_bytes(), | ||
| 1027 | + ), | ||
| 1028 | + ]); | ||
| 1029 | + let reply = send( | ||
| 1030 | + &fx.app, | ||
| 1031 | + "POST", | ||
| 1032 | + &format!("/tahinli/proj/releases/{}/assets", rel.id), | ||
| 1033 | + Some(&fx.tahinli_cookie), | ||
| 1034 | + Some(&content_type), | ||
| 1035 | + body, | ||
| 1036 | + ) | ||
| 1037 | + .await; | ||
| 1038 | + assert_eq!(reply.status, 303, "body: {}", reply.text()); | ||
| 1039 | + assert!( | ||
| 1040 | + reply | ||
| 1041 | + .location | ||
| 1042 | + .unwrap_or_default() | ||
| 1043 | + .contains("notice=asset-replaced") | ||
| 1044 | + ); | ||
| 1045 | + let assets = fx.store.list_release_assets(&rel.id).await.expect("assets"); | ||
| 1046 | + assert_eq!(assets.len(), 1, "still one asset"); | ||
| 1047 | + assert_eq!(assets[0].name, "app.bin"); | ||
| 1048 | + assert_eq!(assets[0].size, 12); | ||
| 1049 | + let got = send( | ||
| 1050 | + &fx.app, | ||
| 1051 | + "GET", | ||
| 1052 | + "/tahinli/proj/releases/download/v1.0/app.bin", | ||
| 1053 | + None, | ||
| 1054 | + None, | ||
| 1055 | + Vec::new(), | ||
| 1056 | + ) | ||
| 1057 | + .await; | ||
| 1058 | + assert_eq!(got.body, b"second bytes"); | ||
| 1059 | +} | ||
crates/forge-web/src/pages/settings_security.rsmodified+1 -0
| @@ -1039,6 +1039,7 @@ mod tests { | |||
| 1039 | webhooks: Default::default(), | 1039 | webhooks: Default::default(), |
| 1040 | backup: Default::default(), | 1040 | backup: Default::default(), |
| 1041 | releases: Default::default(), | 1041 | releases: Default::default(), |
| 1042 | + storage: Default::default(), | ||
| 1042 | replication: Default::default(), | 1043 | replication: Default::default(), |
| 1043 | lfs: Default::default(), | 1044 | lfs: Default::default(), |
| 1044 | ci: Default::default(), | 1045 | ci: Default::default(), |
crates/forge-web/src/release_ops.rsadded+527 -0
| @@ -0,0 +1,527 @@ | |||
| 1 | +//! Release operations shared by the web form, the REST API and CI auto-release. Each function | ||
| 2 | +//! checks the rules every caller needs (names, limits, that the release belongs to the repo), does | ||
| 3 | +//! the git work for tags, stores the row and emits the release webhooks. Callers only translate | ||
| 4 | +//! their input and output; pages keep their own form messages and redirects. | ||
| 5 | +//! | ||
| 6 | +//! A release names a git tag. A missing tag is created as a lightweight tag through | ||
| 7 | +//! `after_ref_update`; an existing tag is adopted as it is. Git tags are never deleted, and the tag | ||
| 8 | +//! of a published release is never moved in place. | ||
| 9 | + | ||
| 10 | +use std::io; | ||
| 11 | +use std::path::{Path, PathBuf}; | ||
| 12 | + | ||
| 13 | +use bytes::Bytes; | ||
| 14 | +use forge_core::releases::{ | ||
| 15 | + MAX_BODY_CHARS, MAX_TITLE_CHARS, NewAsset, NewRelease, Release, ReleaseAsset, ReleaseEdit, | ||
| 16 | + clean_content_type, valid_asset_name, | ||
| 17 | +}; | ||
| 18 | +use forge_core::webhooks::WebhookEvent; | ||
| 19 | +use forge_core::{Repo, User}; | ||
| 20 | +use forge_git::browse::{self, RefInfo, RefKind}; | ||
| 21 | +use forge_git::repo::repo_path; | ||
| 22 | +use forge_git::tags::{ | ||
| 23 | + commit_exists, create_lightweight_tag, move_lightweight_tag, valid_tag_name, | ||
| 24 | +}; | ||
| 25 | +use futures_util::{Stream, StreamExt}; | ||
| 26 | +use http::StatusCode; | ||
| 27 | + | ||
| 28 | +use crate::blobs::asset_key; | ||
| 29 | +use crate::post_update::after_ref_update; | ||
| 30 | +use crate::state::AppState; | ||
| 31 | +use crate::webhooks::emit::{Sender, emit}; | ||
| 32 | + | ||
| 33 | +/// Why a release operation failed. `NotFound` also covers a release or asset that belongs to a | ||
| 34 | +/// different repo, so callers cannot probe other repos through these functions. | ||
| 35 | +#[derive(Debug)] | ||
| 36 | +pub enum ReleaseError { | ||
| 37 | + NotFound, | ||
| 38 | + Conflict(String), | ||
| 39 | + Invalid(String), | ||
| 40 | + TooLarge, | ||
| 41 | + Internal(forge_core::Error), | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +impl ReleaseError { | ||
| 45 | + /// The message to show. Internal errors show no detail; the caller logs them. | ||
| 46 | + pub fn message(&self) -> String { | ||
| 47 | + match self { | ||
| 48 | + Self::NotFound => "not found".to_owned(), | ||
| 49 | + Self::Conflict(message) | Self::Invalid(message) => message.clone(), | ||
| 50 | + Self::TooLarge => "the file is larger than the upload limit".to_owned(), | ||
| 51 | + Self::Internal(_) => "something went wrong".to_owned(), | ||
| 52 | + } | ||
| 53 | + } | ||
| 54 | + | ||
| 55 | + /// The HTTP status an API answers with. | ||
| 56 | + pub fn status(&self) -> StatusCode { | ||
| 57 | + match self { | ||
| 58 | + Self::NotFound => StatusCode::NOT_FOUND, | ||
| 59 | + Self::Conflict(_) => StatusCode::CONFLICT, | ||
| 60 | + Self::Invalid(_) => StatusCode::UNPROCESSABLE_ENTITY, | ||
| 61 | + Self::TooLarge => StatusCode::PAYLOAD_TOO_LARGE, | ||
| 62 | + Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, | ||
| 63 | + } | ||
| 64 | + } | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +impl std::fmt::Display for ReleaseError { | ||
| 68 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 69 | + f.write_str(&self.message()) | ||
| 70 | + } | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +impl From<forge_core::Error> for ReleaseError { | ||
| 74 | + fn from(e: forge_core::Error) -> Self { | ||
| 75 | + match e { | ||
| 76 | + forge_core::Error::NotFound => Self::NotFound, | ||
| 77 | + forge_core::Error::Conflict(message) => Self::Conflict(message), | ||
| 78 | + forge_core::Error::Invalid(message) | forge_core::Error::InvalidName(message) => { | ||
| 79 | + Self::Invalid(message) | ||
| 80 | + } | ||
| 81 | + other => Self::Internal(other), | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +impl From<forge_git::error::Error> for ReleaseError { | ||
| 87 | + fn from(e: forge_git::error::Error) -> Self { | ||
| 88 | + match e { | ||
| 89 | + forge_git::error::Error::InvalidInput(message) => Self::Invalid(message), | ||
| 90 | + forge_git::error::Error::RefMoved(_) => { | ||
| 91 | + Self::Conflict("the tag moved while it was being changed; try again".to_owned()) | ||
| 92 | + } | ||
| 93 | + other => Self::Internal(other.into()), | ||
| 94 | + } | ||
| 95 | + } | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +/// Input for [`create`]. `target` is a branch name or a commit id. It is used only when the tag | ||
| 99 | +/// does not exist yet; an empty or missing target means the repo's default branch. | ||
| 100 | +#[derive(Debug, Clone)] | ||
| 101 | +pub struct CreateRelease { | ||
| 102 | + pub tag: String, | ||
| 103 | + pub target: Option<String>, | ||
| 104 | + pub title: String, | ||
| 105 | + pub body: String, | ||
| 106 | + pub draft: bool, | ||
| 107 | + pub prerelease: bool, | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// Input for [`update`]. `tag` retags the release: an existing git tag is adopted (and `target` | ||
| 111 | +/// must name its commit or be empty), a missing one is created at `target`, or at the old commit | ||
| 112 | +/// when `target` is empty. `target` on its own moves the tag of a draft. A published release keeps | ||
| 113 | +/// its tag, so it must pick a new one. | ||
| 114 | +#[derive(Debug, Clone)] | ||
| 115 | +pub struct EditRelease { | ||
| 116 | + pub title: String, | ||
| 117 | + pub body: String, | ||
| 118 | + pub draft: bool, | ||
| 119 | + pub prerelease: bool, | ||
| 120 | + pub tag: Option<String>, | ||
| 121 | + pub target: Option<String>, | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// The on-disk path of a repo. | ||
| 125 | +fn path_of(state: &AppState, repo: &Repo) -> Result<PathBuf, ReleaseError> { | ||
| 126 | + Ok(repo_path(&state.config.data_dir, &repo.id)?) | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +/// Every ref of a repo. Git runs on a blocking thread. | ||
| 130 | +async fn refs_of(path: PathBuf) -> Result<Vec<RefInfo>, ReleaseError> { | ||
| 131 | + let refs = tokio::task::spawn_blocking(move || browse::list_refs(&path)) | ||
| 132 | + .await | ||
| 133 | + .map_err(|e| ReleaseError::Internal(forge_core::Error::Git(e.to_string())))?; | ||
| 134 | + Ok(refs?) | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +/// The commit a tag names, if the tag exists. | ||
| 138 | +fn tag_oid(refs: &[RefInfo], tag: &str) -> Option<String> { | ||
| 139 | + refs.iter() | ||
| 140 | + .find(|r| r.kind == RefKind::Tag && r.name == tag) | ||
| 141 | + .map(|r| r.target.clone()) | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +/// The commit a target names: a branch of the repo, or a full commit id that exists. | ||
| 145 | +async fn resolve_target( | ||
| 146 | + state: &AppState, | ||
| 147 | + path: &Path, | ||
| 148 | + refs: &[RefInfo], | ||
| 149 | + target: &str, | ||
| 150 | +) -> Result<String, ReleaseError> { | ||
| 151 | + if let Some(branch) = refs | ||
| 152 | + .iter() | ||
| 153 | + .find(|r| r.kind == RefKind::Branch && r.name == target) | ||
| 154 | + { | ||
| 155 | + return Ok(branch.target.clone()); | ||
| 156 | + } | ||
| 157 | + if commit_exists(&state.git, path, target).await { | ||
| 158 | + return Ok(target.to_owned()); | ||
| 159 | + } | ||
| 160 | + Err(ReleaseError::Invalid(format!( | ||
| 161 | + "no branch or commit named {target:?}" | ||
| 162 | + ))) | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +/// The zero object id, which git reads as "no ref yet". | ||
| 166 | +fn zero_oid(len: usize) -> String { | ||
| 167 | + "0".repeat(len) | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +/// Tells the ref hooks, webhooks, CI and mirrors that a tag moved from `old` to `new`. | ||
| 171 | +async fn fire_tag_hook( | ||
| 172 | + state: &AppState, | ||
| 173 | + repo: &Repo, | ||
| 174 | + actor: &User, | ||
| 175 | + tag: &str, | ||
| 176 | + old: &str, | ||
| 177 | + new: &str, | ||
| 178 | +) { | ||
| 179 | + let refname = format!("refs/tags/{tag}"); | ||
| 180 | + if let Err(e) = after_ref_update(state, repo, &actor.id, &refname, old, new).await { | ||
| 181 | + tracing::error!(error = %e, repo_id = %repo.id, "releases: post-update for a tag failed"); | ||
| 182 | + } | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +/// Rejects a title or notes that are out of bounds. | ||
| 186 | +fn check_fields(title: &str, body: &str) -> Result<(), ReleaseError> { | ||
| 187 | + if title.is_empty() || title.chars().count() > MAX_TITLE_CHARS { | ||
| 188 | + return Err(ReleaseError::Invalid(format!( | ||
| 189 | + "the title must be 1 to {MAX_TITLE_CHARS} characters" | ||
| 190 | + ))); | ||
| 191 | + } | ||
| 192 | + if body.chars().count() > MAX_BODY_CHARS { | ||
| 193 | + return Err(ReleaseError::Invalid(format!( | ||
| 194 | + "the notes must be at most {MAX_BODY_CHARS} characters" | ||
| 195 | + ))); | ||
| 196 | + } | ||
| 197 | + Ok(()) | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +/// `NotFound` when the release belongs to another repo. | ||
| 201 | +fn ensure_same_repo(repo: &Repo, release: &Release) -> Result<(), ReleaseError> { | ||
| 202 | + if release.repo_id == repo.id { | ||
| 203 | + Ok(()) | ||
| 204 | + } else { | ||
| 205 | + Err(ReleaseError::NotFound) | ||
| 206 | + } | ||
| 207 | +} | ||
| 208 | + | ||
| 209 | +/// The webhook payload of a release event, sent to every hook that subscribes to `release`. | ||
| 210 | +async fn emit_release(state: &AppState, repo: &Repo, user: &User, action: &str, release: &Release) { | ||
| 211 | + let payload = serde_json::json!({ | ||
| 212 | + "release": { | ||
| 213 | + "id": release.id, | ||
| 214 | + "tag": release.tag, | ||
| 215 | + "target_oid": release.target_oid, | ||
| 216 | + "name": release.title, | ||
| 217 | + "draft": release.draft, | ||
| 218 | + "prerelease": release.prerelease, | ||
| 219 | + "published_at": release.published_at, | ||
| 220 | + } | ||
| 221 | + }); | ||
| 222 | + emit( | ||
| 223 | + state, | ||
| 224 | + repo, | ||
| 225 | + &Sender::of(user), | ||
| 226 | + WebhookEvent::Release, | ||
| 227 | + action, | ||
| 228 | + payload, | ||
| 229 | + ) | ||
| 230 | + .await; | ||
| 231 | +} | ||
| 232 | + | ||
| 233 | +/// Creates a release. An existing tag is adopted as it is; a missing one is created as a | ||
| 234 | +/// lightweight tag at `target`. A second release on the same tag is `Conflict`. A published | ||
| 235 | +/// release emits `published`. | ||
| 236 | +pub async fn create( | ||
| 237 | + state: &AppState, | ||
| 238 | + repo: &Repo, | ||
| 239 | + actor: &User, | ||
| 240 | + input: CreateRelease, | ||
| 241 | +) -> Result<Release, ReleaseError> { | ||
| 242 | + if !valid_tag_name(&input.tag) { | ||
| 243 | + return Err(ReleaseError::Invalid( | ||
| 244 | + "the tag name may only use letters, digits and . _ - +".to_owned(), | ||
| 245 | + )); | ||
| 246 | + } | ||
| 247 | + check_fields(&input.title, &input.body)?; | ||
| 248 | + if state | ||
| 249 | + .store | ||
| 250 | + .release_by_tag(&repo.id, &input.tag) | ||
| 251 | + .await? | ||
| 252 | + .is_some() | ||
| 253 | + { | ||
| 254 | + return Err(ReleaseError::Conflict( | ||
| 255 | + "a release already exists for this tag".to_owned(), | ||
| 256 | + )); | ||
| 257 | + } | ||
| 258 | + let path = path_of(state, repo)?; | ||
| 259 | + let refs = refs_of(path.clone()).await?; | ||
| 260 | + let target_oid = match tag_oid(&refs, &input.tag) { | ||
| 261 | + Some(oid) => oid, | ||
| 262 | + None => { | ||
| 263 | + let target = input | ||
| 264 | + .target | ||
| 265 | + .as_deref() | ||
| 266 | + .filter(|t| !t.is_empty()) | ||
| 267 | + .unwrap_or(&repo.default_branch); | ||
| 268 | + let oid = resolve_target(state, &path, &refs, target).await?; | ||
| 269 | + create_lightweight_tag(&state.git, &path, &input.tag, &oid).await?; | ||
| 270 | + fire_tag_hook(state, repo, actor, &input.tag, &zero_oid(oid.len()), &oid).await; | ||
| 271 | + oid | ||
| 272 | + } | ||
| 273 | + }; | ||
| 274 | + let created = state | ||
| 275 | + .store | ||
| 276 | + .create_release(&NewRelease { | ||
| 277 | + repo_id: &repo.id, | ||
| 278 | + tag: &input.tag, | ||
| 279 | + target_oid: &target_oid, | ||
| 280 | + title: &input.title, | ||
| 281 | + body: &input.body, | ||
| 282 | + draft: input.draft, | ||
| 283 | + prerelease: input.prerelease, | ||
| 284 | + author_id: &actor.id, | ||
| 285 | + }) | ||
| 286 | + .await?; | ||
| 287 | + if !created.draft { | ||
| 288 | + emit_release(state, repo, actor, "published", &created).await; | ||
| 289 | + } | ||
| 290 | + Ok(created) | ||
| 291 | +} | ||
| 292 | + | ||
| 293 | +/// Saves a release. The fields change in place. The tag rules are in [`EditRelease`]. A draft | ||
| 294 | +/// that becomes published emits `published`; any other change to a published release emits | ||
| 295 | +/// `updated`. | ||
| 296 | +pub async fn update( | ||
| 297 | + state: &AppState, | ||
| 298 | + repo: &Repo, | ||
| 299 | + actor: &User, | ||
| 300 | + release: &Release, | ||
| 301 | + edit: EditRelease, | ||
| 302 | +) -> Result<Release, ReleaseError> { | ||
| 303 | + ensure_same_repo(repo, release)?; | ||
| 304 | + check_fields(&edit.title, &edit.body)?; | ||
| 305 | + let new_tag = edit.tag.clone().unwrap_or_else(|| release.tag.clone()); | ||
| 306 | + let retag = new_tag != release.tag; | ||
| 307 | + if retag && !valid_tag_name(&new_tag) { | ||
| 308 | + return Err(ReleaseError::Invalid( | ||
| 309 | + "the tag name may only use letters, digits and . _ - +".to_owned(), | ||
| 310 | + )); | ||
| 311 | + } | ||
| 312 | + let wanted = edit.target.as_deref().filter(|t| !t.is_empty()); | ||
| 313 | + let path = path_of(state, repo)?; | ||
| 314 | + let refs = refs_of(path.clone()).await?; | ||
| 315 | + let mut target_oid = release.target_oid.clone(); | ||
| 316 | + | ||
| 317 | + if retag { | ||
| 318 | + if state | ||
| 319 | + .store | ||
| 320 | + .release_by_tag(&repo.id, &new_tag) | ||
| 321 | + .await? | ||
| 322 | + .is_some() | ||
| 323 | + { | ||
| 324 | + return Err(ReleaseError::Conflict( | ||
| 325 | + "a release already exists for this tag".to_owned(), | ||
| 326 | + )); | ||
| 327 | + } | ||
| 328 | + match tag_oid(&refs, &new_tag) { | ||
| 329 | + Some(existing) => { | ||
| 330 | + if let Some(target) = wanted | ||
| 331 | + && resolve_target(state, &path, &refs, target).await? != existing | ||
| 332 | + { | ||
| 333 | + return Err(ReleaseError::Invalid(format!( | ||
| 334 | + "the tag {new_tag} already exists at another commit" | ||
| 335 | + ))); | ||
| 336 | + } | ||
| 337 | + target_oid = existing; | ||
| 338 | + } | ||
| 339 | + None => { | ||
| 340 | + let oid = match wanted { | ||
| 341 | + Some(target) => resolve_target(state, &path, &refs, target).await?, | ||
| 342 | + None => release.target_oid.clone(), | ||
| 343 | + }; | ||
| 344 | + create_lightweight_tag(&state.git, &path, &new_tag, &oid).await?; | ||
| 345 | + fire_tag_hook(state, repo, actor, &new_tag, &zero_oid(oid.len()), &oid).await; | ||
| 346 | + target_oid = oid; | ||
| 347 | + } | ||
| 348 | + } | ||
| 349 | + } else if let Some(target) = wanted { | ||
| 350 | + if !release.draft { | ||
| 351 | + return Err(ReleaseError::Invalid( | ||
| 352 | + "published release tags can't be moved; pick a new tag".to_owned(), | ||
| 353 | + )); | ||
| 354 | + } | ||
| 355 | + let oid = resolve_target(state, &path, &refs, target).await?; | ||
| 356 | + match tag_oid(&refs, &release.tag) { | ||
| 357 | + Some(current) if current == oid => {} | ||
| 358 | + Some(current) => { | ||
| 359 | + move_lightweight_tag(&state.git, &path, &release.tag, &oid, ¤t).await?; | ||
| 360 | + fire_tag_hook(state, repo, actor, &release.tag, ¤t, &oid).await; | ||
| 361 | + } | ||
| 362 | + None => { | ||
| 363 | + create_lightweight_tag(&state.git, &path, &release.tag, &oid).await?; | ||
| 364 | + fire_tag_hook(state, repo, actor, &release.tag, &zero_oid(oid.len()), &oid).await; | ||
| 365 | + } | ||
| 366 | + } | ||
| 367 | + target_oid = oid; | ||
| 368 | + } | ||
| 369 | + | ||
| 370 | + if (retag || target_oid != release.target_oid) | ||
| 371 | + && !state | ||
| 372 | + .store | ||
| 373 | + .set_release_tag(&release.id, &new_tag, &target_oid) | ||
| 374 | + .await? | ||
| 375 | + { | ||
| 376 | + return Err(ReleaseError::NotFound); | ||
| 377 | + } | ||
| 378 | + let fields = ReleaseEdit { | ||
| 379 | + title: &edit.title, | ||
| 380 | + body: &edit.body, | ||
| 381 | + draft: edit.draft, | ||
| 382 | + prerelease: edit.prerelease, | ||
| 383 | + }; | ||
| 384 | + if !state.store.update_release(&release.id, &fields).await? { | ||
| 385 | + return Err(ReleaseError::NotFound); | ||
| 386 | + } | ||
| 387 | + let after = state | ||
| 388 | + .store | ||
| 389 | + .release(&release.id) | ||
| 390 | + .await? | ||
| 391 | + .ok_or(ReleaseError::NotFound)?; | ||
| 392 | + let action = match (release.draft, after.draft) { | ||
| 393 | + (true, false) => Some("published"), | ||
| 394 | + (true, true) => None, | ||
| 395 | + (false, _) => Some("updated"), | ||
| 396 | + }; | ||
| 397 | + if let Some(action) = action { | ||
| 398 | + emit_release(state, repo, actor, action, &after).await; | ||
| 399 | + } | ||
| 400 | + Ok(after) | ||
| 401 | +} | ||
| 402 | + | ||
| 403 | +/// Deletes a release and its assets, then their blobs. The git tag is kept. A published release | ||
| 404 | +/// emits `deleted`. | ||
| 405 | +pub async fn delete( | ||
| 406 | + state: &AppState, | ||
| 407 | + repo: &Repo, | ||
| 408 | + actor: &User, | ||
| 409 | + release: &Release, | ||
| 410 | +) -> Result<(), ReleaseError> { | ||
| 411 | + ensure_same_repo(repo, release)?; | ||
| 412 | + let Some(asset_ids) = state.store.delete_release(&release.id).await? else { | ||
| 413 | + return Err(ReleaseError::NotFound); | ||
| 414 | + }; | ||
| 415 | + for asset_id in &asset_ids { | ||
| 416 | + if let Err(e) = state.blobs.delete(&asset_key(asset_id)).await { | ||
| 417 | + tracing::error!(error = %e, asset_id, "releases: could not delete an asset blob"); | ||
| 418 | + } | ||
| 419 | + } | ||
| 420 | + if !release.draft { | ||
| 421 | + emit_release(state, repo, actor, "deleted", release).await; | ||
| 422 | + } | ||
| 423 | + Ok(()) | ||
| 424 | +} | ||
| 425 | + | ||
| 426 | +/// Deletes one asset of a release and its blob. `NotFound` when the asset is not on this release. | ||
| 427 | +pub async fn delete_asset( | ||
| 428 | + state: &AppState, | ||
| 429 | + repo: &Repo, | ||
| 430 | + release: &Release, | ||
| 431 | + asset_id: &str, | ||
| 432 | +) -> Result<(), ReleaseError> { | ||
| 433 | + ensure_same_repo(repo, release)?; | ||
| 434 | + let Some(row) = state.store.release_asset_by_id(asset_id).await? else { | ||
| 435 | + return Err(ReleaseError::NotFound); | ||
| 436 | + }; | ||
| 437 | + if row.release_id != release.id { | ||
| 438 | + return Err(ReleaseError::NotFound); | ||
| 439 | + } | ||
| 440 | + if !state.store.delete_release_asset(&row.id).await? { | ||
| 441 | + return Err(ReleaseError::NotFound); | ||
| 442 | + } | ||
| 443 | + if let Err(e) = state.blobs.delete(&asset_key(&row.id)).await { | ||
| 444 | + tracing::error!(error = %e, asset_id = %row.id, "releases: could not delete an asset blob"); | ||
| 445 | + } | ||
| 446 | + Ok(()) | ||
| 447 | +} | ||
| 448 | + | ||
| 449 | +/// Stores a file as an asset of `release`. The bytes are streamed into a fresh blob, so a refused | ||
| 450 | +/// or broken upload leaves nothing behind. A name the release already has is replaced: the row | ||
| 451 | +/// takes the new file and keeps its name and download count, and the old blob is deleted after | ||
| 452 | +/// the row is swapped. Returns the asset and whether it replaced an older file. | ||
| 453 | +#[allow(clippy::too_many_arguments)] // the signature is the one the callers share | ||
| 454 | +pub async fn put_asset( | ||
| 455 | + state: &AppState, | ||
| 456 | + repo: &Repo, | ||
| 457 | + release: &Release, | ||
| 458 | + uploader: &User, | ||
| 459 | + name: &str, | ||
| 460 | + content_type: Option<&str>, | ||
| 461 | + mut stream: impl Stream<Item = io::Result<Bytes>> + Unpin, | ||
| 462 | + max_bytes: u64, | ||
| 463 | +) -> Result<(ReleaseAsset, bool), ReleaseError> { | ||
| 464 | + ensure_same_repo(repo, release)?; | ||
| 465 | + if !valid_asset_name(name) { | ||
| 466 | + return Err(ReleaseError::Invalid( | ||
| 467 | + "the file name may only use letters, digits and . _ - +".to_owned(), | ||
| 468 | + )); | ||
| 469 | + } | ||
| 470 | + let content_type = clean_content_type(content_type); | ||
| 471 | + let blob_id = ulid::Ulid::generate().to_string(); | ||
| 472 | + let key = asset_key(&blob_id); | ||
| 473 | + let mut writer = state.blobs.begin(&key, max_bytes).await?; | ||
| 474 | + while let Some(chunk) = stream.next().await { | ||
| 475 | + let chunk = match chunk { | ||
| 476 | + Ok(chunk) => chunk, | ||
| 477 | + Err(_) => { | ||
| 478 | + writer.abort().await; | ||
| 479 | + return Err(ReleaseError::Invalid( | ||
| 480 | + "the upload could not be read".to_owned(), | ||
| 481 | + )); | ||
| 482 | + } | ||
| 483 | + }; | ||
| 484 | + if let Err(e) = writer.push(&chunk).await { | ||
| 485 | + writer.abort().await; | ||
| 486 | + return Err(match e { | ||
| 487 | + forge_core::Error::Invalid(_) => ReleaseError::TooLarge, | ||
| 488 | + other => other.into(), | ||
| 489 | + }); | ||
| 490 | + } | ||
| 491 | + } | ||
| 492 | + let (size, sha256) = writer.finish().await?; | ||
| 493 | + | ||
| 494 | + let previous = state | ||
| 495 | + .store | ||
| 496 | + .release_asset(&release.id, name) | ||
| 497 | + .await? | ||
| 498 | + .map(|asset| asset.id); | ||
| 499 | + let new = NewAsset { | ||
| 500 | + id: &blob_id, | ||
| 501 | + release_id: &release.id, | ||
| 502 | + name, | ||
| 503 | + size, | ||
| 504 | + sha256: &sha256, | ||
| 505 | + content_type: &content_type, | ||
| 506 | + uploader_id: &uploader.id, | ||
| 507 | + }; | ||
| 508 | + let stored = match &previous { | ||
| 509 | + None => state.store.add_asset(&new).await, | ||
| 510 | + Some(old_id) => state.store.replace_asset(old_id, &new).await, | ||
| 511 | + }; | ||
| 512 | + let stored = match stored { | ||
| 513 | + Ok(stored) => stored, | ||
| 514 | + Err(e) => { | ||
| 515 | + if let Err(del) = state.blobs.delete(&key).await { | ||
| 516 | + tracing::error!(error = %del, "releases: could not remove an unlinked blob"); | ||
| 517 | + } | ||
| 518 | + return Err(e.into()); | ||
| 519 | + } | ||
| 520 | + }; | ||
| 521 | + if let Some(old_id) = &previous | ||
| 522 | + && let Err(e) = state.blobs.delete(&asset_key(old_id)).await | ||
| 523 | + { | ||
| 524 | + tracing::error!(error = %e, asset_id = %old_id, "releases: could not delete a replaced blob"); | ||
| 525 | + } | ||
| 526 | + Ok((stored, previous.is_some())) | ||
| 527 | +} | ||
crates/forge-web/src/test_support.rsmodified+1 -0
| @@ -45,6 +45,7 @@ pub fn test_config(dir: &Path) -> Config { | |||
| 45 | webhooks: Default::default(), | 45 | webhooks: Default::default(), |
| 46 | backup: Default::default(), | 46 | backup: Default::default(), |
| 47 | releases: Default::default(), | 47 | releases: Default::default(), |
| 48 | + storage: Default::default(), | ||
| 48 | replication: Default::default(), | 49 | replication: Default::default(), |
| 49 | lfs: Default::default(), | 50 | lfs: Default::default(), |
| 50 | ci: Default::default(), | 51 | ci: Default::default(), |
docs/api.mdmodified+169 -1
| @@ -31,7 +31,7 @@ Errors are JSON: `{"error": "message"}`. | |||
| 31 | | 401 | No token, an unknown or expired token, or an anonymous caller who cannot use the repo. | | 31 | | 401 | No token, an unknown or expired token, or an anonymous caller who cannot use the repo. | |
| 32 | | 403 | The token lacks the `repo` scope, or the user has read-only access and tried to write. | | 32 | | 403 | The token lacks the `repo` scope, or the user has read-only access and tried to write. | |
| 33 | | 404 | The repo or the commit does not exist, or the signed-in user cannot see the repo. | | 33 | | 404 | The repo or the commit does not exist, or the signed-in user cannot see the repo. | |
| 34 | -| 413 | The request body is larger than 16 KiB. | | 34 | +| 413 | The request body is too large: over 16 KiB for statuses, over 64 KiB for release JSON, or an asset over `releases.max_asset_mb`. | |
| 35 | | 422 | A field has an invalid value, or `sha` is not a full commit id. | | 35 | | 422 | A field has an invalid value, or `sha` is not a full commit id. | |
| 36 | | 429 | Too many failed authentication attempts from this IP. | | 36 | | 429 | Too many failed authentication attempts from this IP. | |
| 37 | 37 | ||
| @@ -129,3 +129,171 @@ Response, `200 OK`: | |||
| 129 | 129 | ||
| 130 | `statuses` is ordered by `context`. The list is empty and `state` is `null` when nothing has | 130 | `statuses` is ordered by `context`. The list is empty and `state` is `null` when nothing has |
| 131 | reported on the commit. | 131 | reported on the commit. |
| 132 | + | ||
| 133 | +## Releases | ||
| 134 | + | ||
| 135 | +A release names a git tag and carries notes and files. Scripts and CI jobs can manage releases | ||
| 136 | +with a token. The same release can instead be published from a tag run with no script: see the | ||
| 137 | +declarative `[release]` table in `docs/ci.md`. | ||
| 138 | + | ||
| 139 | +| Method | Path | Access | Answers | | ||
| 140 | +| --- | --- | --- | --- | | ||
| 141 | +| `GET` | `/api/v1/repos/{owner}/{repo}/releases` | public, or a token with read access | `200`, the list, newest first | | ||
| 142 | +| `GET` | `/api/v1/repos/{owner}/{repo}/releases/tags/{tag}` | public, or a token with read access | `200`, one release | | ||
| 143 | +| `POST` | `/api/v1/repos/{owner}/{repo}/releases` | write | `201`, the new release | | ||
| 144 | +| `PATCH` | `/api/v1/repos/{owner}/{repo}/releases/{id}` | write | `200`, the release | | ||
| 145 | +| `DELETE` | `/api/v1/repos/{owner}/{repo}/releases/{id}` | write | `204` | | ||
| 146 | +| `PUT` | `/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}` | write | `201` when new, `200` when it replaces a file of that name | | ||
| 147 | +| `DELETE` | `/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}` | write | `204` | | ||
| 148 | + | ||
| 149 | +In the asset routes `{asset}` is the file name for `PUT` and the asset `id` (from the release JSON) | ||
| 150 | +for `DELETE`. | ||
| 151 | + | ||
| 152 | +Drafts are visible only to callers with write access: they are left out of the list, and fetching | ||
| 153 | +one by tag gets `404` for anyone else. A release `{id}` must belong to the repo in the path; | ||
| 154 | +another repo's id gets `404`. | ||
| 155 | + | ||
| 156 | +A release has these fields: | ||
| 157 | + | ||
| 158 | +| Field | Notes | | ||
| 159 | +| --- | --- | | ||
| 160 | +| `tag` | A git tag name: letters, digits and `. _ - +`. | | ||
| 161 | +| `target` | The commit the tag names. Set when the release is made. | | ||
| 162 | +| `title` | 1 to 200 characters. Defaults to the tag on create. | | ||
| 163 | +| `body` | Notes, at most 64 KiB of text. Defaults to empty. | | ||
| 164 | +| `draft` | A draft is hidden from readers until it is published. Defaults to `false`. | | ||
| 165 | +| `prerelease` | Defaults to `false`. | | ||
| 166 | + | ||
| 167 | +### Release JSON | ||
| 168 | + | ||
| 169 | +```json | ||
| 170 | +{ | ||
| 171 | + "id": "01J...", | ||
| 172 | + "tag": "v1.2.0", | ||
| 173 | + "target": "0123...", | ||
| 174 | + "title": "v1.2.0", | ||
| 175 | + "body": "Built by CI", | ||
| 176 | + "draft": false, | ||
| 177 | + "prerelease": false, | ||
| 178 | + "author": "tahinli", | ||
| 179 | + "created_at": "2026-10-19T10:00:00Z", | ||
| 180 | + "published_at": "2026-10-19T10:00:00Z", | ||
| 181 | + "html_url": "http://127.0.0.1:7660/tahinli/demo/releases/tag/v1.2.0", | ||
| 182 | + "assets": [ | ||
| 183 | + { | ||
| 184 | + "id": "01J...", | ||
| 185 | + "name": "forge-linux-x86_64.tar.gz", | ||
| 186 | + "size": 1048576, | ||
| 187 | + "sha256": "9f86...", | ||
| 188 | + "content_type": "application/gzip", | ||
| 189 | + "download_count": 3, | ||
| 190 | + "created_at": "2026-10-19T10:01:00Z", | ||
| 191 | + "download_url": "http://127.0.0.1:7660/tahinli/demo/releases/download/v1.2.0/forge-linux-x86_64.tar.gz" | ||
| 192 | + } | ||
| 193 | + ] | ||
| 194 | +} | ||
| 195 | +``` | ||
| 196 | + | ||
| 197 | +`published_at` is `null` for a draft. `download_url` is the web download route, so it works with | ||
| 198 | +the same visibility rules as the release page. | ||
| 199 | + | ||
| 200 | +### Create a release | ||
| 201 | + | ||
| 202 | +`POST /api/v1/repos/{owner}/{repo}/releases` takes JSON. Only `tag` is required. `target` is a | ||
| 203 | +branch name or a full commit id; it is used only when the tag does not exist yet, and it defaults | ||
| 204 | +to the default branch. An existing tag is adopted as it is. A second release for the same tag | ||
| 205 | +gets `409`. | ||
| 206 | + | ||
| 207 | +```sh | ||
| 208 | +curl -X POST http://127.0.0.1:7660/api/v1/repos/tahinli/demo/releases \ | ||
| 209 | + -H "Authorization: Bearer $FORGE_TOKEN" \ | ||
| 210 | + -H "Content-Type: application/json" \ | ||
| 211 | + -d '{"tag": "v1.2.0", "target": "main", "title": "Version 1.2", "body": "Fixes.", "draft": true}' | ||
| 212 | +``` | ||
| 213 | + | ||
| 214 | +### Edit a release | ||
| 215 | + | ||
| 216 | +`PATCH .../releases/{id}` changes only the fields it sends. Omitted fields keep their values. | ||
| 217 | +`tag` renames the release. A published release keeps its tag, so it must pick a new one; a draft | ||
| 218 | +can also move its tag with `target`. | ||
| 219 | + | ||
| 220 | +```sh | ||
| 221 | +curl -X PATCH http://127.0.0.1:7660/api/v1/repos/tahinli/demo/releases/$ID \ | ||
| 222 | + -H "Authorization: Bearer $FORGE_TOKEN" \ | ||
| 223 | + -H "Content-Type: application/json" \ | ||
| 224 | + -d '{"draft": false}' | ||
| 225 | +``` | ||
| 226 | + | ||
| 227 | +### Get releases | ||
| 228 | + | ||
| 229 | +```sh | ||
| 230 | +curl http://127.0.0.1:7660/api/v1/repos/tahinli/demo/releases/tags/v1.2.0 | ||
| 231 | +``` | ||
| 232 | + | ||
| 233 | +### Upload an asset | ||
| 234 | + | ||
| 235 | +`PUT .../releases/{id}/assets/{asset}` sends the file as the raw request body. The body is | ||
| 236 | +streamed to storage, so large files are not held in memory. `Content-Type` is stored as the | ||
| 237 | +asset's content type; a missing one is stored as `application/octet-stream`. The name may use | ||
| 238 | +letters, digits and `. _ - +`. An upload over `releases.max_asset_mb` gets `413`. Uploading the | ||
| 239 | +same name again replaces the file and keeps its download count. | ||
| 240 | + | ||
| 241 | +```sh | ||
| 242 | +curl -X PUT http://127.0.0.1:7660/api/v1/repos/tahinli/demo/releases/$ID/assets/forge-linux-x86_64.tar.gz \ | ||
| 243 | + -H "Authorization: Bearer $FORGE_TOKEN" \ | ||
| 244 | + -H "Content-Type: application/gzip" \ | ||
| 245 | + --data-binary @dist/forge-linux-x86_64.tar.gz | ||
| 246 | +``` | ||
| 247 | + | ||
| 248 | +### Delete an asset or a release | ||
| 249 | + | ||
| 250 | +```sh | ||
| 251 | +curl -X DELETE http://127.0.0.1:7660/api/v1/repos/tahinli/demo/releases/$ID/assets/$ASSET_ID \ | ||
| 252 | + -H "Authorization: Bearer $FORGE_TOKEN" | ||
| 253 | + | ||
| 254 | +curl -X DELETE http://127.0.0.1:7660/api/v1/repos/tahinli/demo/releases/$ID \ | ||
| 255 | + -H "Authorization: Bearer $FORGE_TOKEN" | ||
| 256 | +``` | ||
| 257 | + | ||
| 258 | +Deleting a release removes its files. The git tag is kept. | ||
| 259 | + | ||
| 260 | +### CI job script | ||
| 261 | + | ||
| 262 | +A job that builds artifacts and publishes them as a release. The token is a repo secret named | ||
| 263 | +`FORGE_TOKEN` with the `repo` scope, and the job exposes it as an environment variable. The | ||
| 264 | +release is created as a draft, the files are uploaded, and only then is it published, so readers | ||
| 265 | +never see a half-filled release. The script needs `curl` and `jq`. | ||
| 266 | + | ||
| 267 | +```sh | ||
| 268 | +#!/bin/sh | ||
| 269 | +set -eu | ||
| 270 | + | ||
| 271 | +BASE="http://127.0.0.1:7660/api/v1/repos/tahinli/demo" | ||
| 272 | +AUTH="Authorization: Bearer $FORGE_TOKEN" | ||
| 273 | +TAG="v1.2.0" | ||
| 274 | +SHA="$(git rev-parse HEAD)" | ||
| 275 | + | ||
| 276 | +cargo build --release | ||
| 277 | +mkdir -p dist | ||
| 278 | +cp target/release/forge dist/forge-linux-x86_64 | ||
| 279 | +tar -C dist -czf dist/forge-linux-x86_64.tar.gz forge-linux-x86_64 | ||
| 280 | + | ||
| 281 | +# 1. Create the release as a draft on this commit. | ||
| 282 | +ID="$(curl -fsS -X POST "$BASE/releases" -H "$AUTH" -H "Content-Type: application/json" \ | ||
| 283 | + -d "{\"tag\": \"$TAG\", \"target\": \"$SHA\", \"draft\": true}" | jq -r .id)" | ||
| 284 | + | ||
| 285 | +# 2. Upload each file. A re-run replaces files of the same name. | ||
| 286 | +for file in dist/forge-linux-x86_64.tar.gz; do | ||
| 287 | + curl -fsS -X PUT "$BASE/releases/$ID/assets/$(basename "$file")" -H "$AUTH" \ | ||
| 288 | + -H "Content-Type: application/octet-stream" --data-binary "@$file" > /dev/null | ||
| 289 | +done | ||
| 290 | + | ||
| 291 | +# 3. Publish. | ||
| 292 | +curl -fsS -X PATCH "$BASE/releases/$ID" -H "$AUTH" -H "Content-Type: application/json" \ | ||
| 293 | + -d '{"draft": false}' > /dev/null | ||
| 294 | +echo "published $TAG" | ||
| 295 | +``` | ||
| 296 | + | ||
| 297 | +If the job runs on the tag itself, the tag already exists and `target` is ignored. A simpler | ||
| 298 | +alternative needs no script at all: a `[release]` table in `ci.toml` publishes the release from | ||
| 299 | +a tag run and attaches the selected artifacts. See `docs/ci.md`, "Releases". | ||
docs/backup.mdmodified+21 -1
| @@ -303,13 +303,33 @@ Follow `docs/architecture.md` §8.5. The steps below are specific to the standby | |||
| 303 | 303 | ||
| 304 | ## Release assets | 304 | ## Release assets |
| 305 | 305 | ||
| 306 | -Release asset bytes live in `<data_dir>/blobs/assets/<asset id>`, outside the database and the repos. The database rows that point at them are in every backup set, so a restore without the blobs leaves downloads returning 404. Keep the blobs in step with the sets: | 306 | +Release asset bytes live in `<data_dir>/blobs/assets/<asset id>`, outside the database and the repos. The database rows that point at them are in every backup set, so a restore without the blobs leaves downloads returning 404. Keep the blobs in step with the sets. This applies to the default `fs` backend; with `backend = "s3"` see "Blob storage backends" below: |
| 307 | 307 | ||
| 308 | - Blobs are immutable. An asset is written once under its id and never rewritten, only added or deleted. The writer streams to a temporary file and renames it into place when complete, so a copy taken at any moment never holds half of an asset that is listed in the database. | 308 | - Blobs are immutable. An asset is written once under its id and never rewritten, only added or deleted. The writer streams to a temporary file and renames it into place when complete, so a copy taken at any moment never holds half of an asset that is listed in the database. |
| 309 | - Copy the directory with a plain `rsync -a --delete <data_dir>/blobs/ <backup target>/blobs/`. Do it after each backup set, or on the same schedule. Copying during an upload is safe: the in-flight file is a temporary name that rsync may skip or copy, and the row that references it is written only after the rename. | 309 | - Copy the directory with a plain `rsync -a --delete <data_dir>/blobs/ <backup target>/blobs/`. Do it after each backup set, or on the same schedule. Copying during an upload is safe: the in-flight file is a temporary name that rsync may skip or copy, and the row that references it is written only after the rename. |
| 310 | - On restore, copy `blobs/` back into the new `data_dir` before starting the server. A row whose blob is missing is harmless to the server but its download returns 404; check the release pages after a drill. | 310 | - On restore, copy `blobs/` back into the new `data_dir` before starting the server. A row whose blob is missing is harmless to the server but its download returns 404; check the release pages after a drill. |
| 311 | - Deleting a release or a repo deletes its blobs at once. The blob directory has no other index, so it can be checked against the database with a `SELECT id FROM release_assets` list. | 311 | - Deleting a release or a repo deletes its blobs at once. The blob directory has no other index, so it can be checked against the database with a `SELECT id FROM release_assets` list. |
| 312 | 312 | ||
| 313 | +### Blob storage backends | ||
| 314 | + | ||
| 315 | +`[storage]` chooses where release assets and CI artifacts are kept. The default, `backend = "fs"`, is the directory described above. With `backend = "r2"` (Cloudflare R2, see below) or `backend = "s3"` (AWS S3, MinIO, Garage, or any other S3-compatible store) the bytes live in a bucket instead, and `<data_dir>/blobs` is no longer used: | ||
| 316 | + | ||
| 317 | +- **Credentials:** the secret access key is read from `secret_access_key_file` at startup. Keep that file mode 0600, owned by the forge user, and out of the repository. A missing file or a missing required field stops the server with a config error. | ||
| 318 | +- **Backing up the bucket:** do not `rsync` anything. Enable **bucket versioning**, so an overwritten or deleted key keeps its previous version, and add a lifecycle rule that expires noncurrent versions only after the longest backup retention you need. Then replicate the bucket to a second store, or to a second region, with the provider's replication feature or `rclone sync` from a cron job. Replication is asynchronous, so a disaster can lose the newest uploads; this is the same window as the database snapshot interval. | ||
| 319 | +- **Restore:** point `[storage.s3]` (or `[storage.r2]`) at the restored bucket, or at the replica, before starting the server. Check a release download after a drill, as above. Keys are `assets/<id>` and `ci/<id>`, under `prefix` if one is set. | ||
| 320 | +- **Object lock:** if the bucket has object lock in governance or compliance mode, deleted blobs are kept until the retention period ends. Use it when deletes must be recoverable. | ||
| 321 | +- **Limits:** a rename of a finished upload is a server-side copy followed by a delete. S3 caps a single copy at 5 GiB, so keep `[releases] max_asset_mb` and `[ci] max_artifact_mb` below that. | ||
| 322 | + | ||
| 323 | +#### Cloudflare R2 | ||
| 324 | + | ||
| 325 | +`backend = "r2"` takes `account_id`, `bucket`, `access_key_id`, `secret_access_key_file`, and optionally `jurisdiction` (`"eu"` or `"fedramp"`) and `prefix`. There is no endpoint or region to set: forge derives `https://<account_id>.r2.cloudflarestorage.com` (with the jurisdiction in the host when set) and signs as `auto`. Create an R2 API token with object read and write on the one bucket, and use its access key id and secret. | ||
| 326 | + | ||
| 327 | +- **R2 has no bucket versioning**, so it cannot be the immutable copy on its own. An overwritten or deleted key is gone. Pick one of these, or both: | ||
| 328 | + - **Bucket lock rules** (R2 object lifecycle and lock rules) that keep deleted or overwritten objects for the retention you need. Set the rule on the bucket before the first upload, and test it with a delete in a scratch bucket. | ||
| 329 | + - **A periodic copy outside Cloudflare**, such as `rclone sync` from a cron job to the standby host or to another provider. A copy is asynchronous, so the newest uploads can be lost in a disaster, as with the database snapshot interval. A copy that is only ever synced (never versioned) has the same overwrite problem, so keep the source's lock rules or take dated copies. | ||
| 330 | +- **Egress is free**, so R2 suits release downloads: release assets can be served from the bucket without paying per-gigabyte transfer fees. Storage and operations are billed, so keep an eye on the bucket size. | ||
| 331 | +- **Restore** works as for `s3`: point `[storage.r2]` at the restored or replica bucket, and check one release download after a drill. | ||
| 332 | + | ||
| 313 | ## LFS objects | 333 | ## LFS objects |
| 314 | 334 | ||
| 315 | Git LFS object bytes live in `<data_dir>/lfs/<oid[0..2]>/<oid[2..4]>/<oid>`, outside the database and the repos. The `lfs_objects` rows that link them to repos are in every backup set. Copy the directory with the same `rsync` step as release blobs, after each backup set or on the same schedule: | 335 | Git LFS object bytes live in `<data_dir>/lfs/<oid[0..2]>/<oid[2..4]>/<oid>`, outside the database and the repos. The `lfs_objects` rows that link them to repos are in every backup set. Copy the directory with the same `rsync` step as release blobs, after each backup set or on the same schedule: |
docs/ci.mdmodified+75 -0
| @@ -102,6 +102,81 @@ Artifacts are stored under the flattened name: `dist/forge` is stored as `dist_f | |||
| 102 | - Jobs whose `needs` fail or are skipped are marked `skipped`. A skipped job gets the status | 102 | - Jobs whose `needs` fail or are skipped are marked `skipped`. A skipped job gets the status |
| 103 | `ci/<job>` = `error` with the description `skipped`. | 103 | `ci/<job>` = `error` with the description `skipped`. |
| 104 | 104 | ||
| 105 | +### Releases | ||
| 106 | + | ||
| 107 | +A `[release]` table publishes a release from a tag run. It needs at least one glob in `[on] tags`. | ||
| 108 | + | ||
| 109 | +When a tag push matches `on.tags` and **every job in the run succeeds**, the forge creates the | ||
| 110 | +release for that tag and attaches the selected artifacts. If a release for that tag already exists, | ||
| 111 | +for example one you made by hand, the forge updates it: the existing title and notes are kept, and | ||
| 112 | +the selected artifacts are attached, replacing any asset with the same name. A run where any job | ||
| 113 | +fails or is skipped creates no release. The job needs no token and no `curl`. | ||
| 114 | + | ||
| 115 | +For scripted control, use the REST API with a personal access token stored as a repo secret. See | ||
| 116 | +[api.md](api.md). | ||
| 117 | + | ||
| 118 | +| Key | Type | Default | Meaning | | ||
| 119 | +|--------------|------------------------|-----------|---------| | ||
| 120 | +| `assets` | array of string | `[]` | `"<job>:<glob>"` entries. The glob matches that job's **flattened** artifact names (see below). Max 32. A job named here must exist and declare `artifacts`. | | ||
| 121 | +| `prerelease` | `"auto"`, `true`, `false` | `"auto"` | `"auto"` marks the release a prerelease when its tag contains `-`, e.g. `v1.2.0-rc1`. | | ||
| 122 | +| `draft` | bool | `false` | Create the release as a draft. | | ||
| 123 | +| `notes` | `"commits"` or `"none"` | `"commits"` | `"commits"` writes one line per commit since the previous release tag. `"none"` writes no notes. | | ||
| 124 | +| `title` | string | `"{tag}"` | Release title. `{tag}` is replaced by the tag name. It is the only placeholder. 1 to 200 characters after trimming, no control characters. | | ||
| 125 | + | ||
| 126 | +Asset globs follow the [glob rules](#triggers-and-glob-rules). Artifact names are flattened, so the | ||
| 127 | +glob cannot contain `/`. `dist/forge-linux-x86_64` is stored as `dist_forge-linux-x86_64`, so it is | ||
| 128 | +selected with `build:dist_forge-*`. A `[release]` table with no `assets` creates a release with notes | ||
| 129 | +only. | ||
| 130 | + | ||
| 131 | +The notes list at most 200 commits, newest first, and end with a `Full changelog: <previous>...<tag>` | ||
| 132 | +line when a previous tag is known. The previous tag is the newest other published release whose | ||
| 133 | +commit is an ancestor of the tag, or else the closest git tag reachable from it. If the release is | ||
| 134 | +made, the release is attributed to the run's actor. A system run, such as a mirror update, falls back | ||
| 135 | +to the repo owner, and to the ghost account when the owner is an organization. | ||
| 136 | + | ||
| 137 | +The outcome is written as a `[forge] Published release <tag> with N assets.` line at the end of the | ||
| 138 | +log of the run's last job. A failed asset is listed on that line, and the release still stands. | ||
| 139 | + | ||
| 140 | +Example. The `build` job packages binaries into `dist/`, and `test` must also pass before any release | ||
| 141 | +is made: | ||
| 142 | + | ||
| 143 | +```toml | ||
| 144 | +name = "release" | ||
| 145 | + | ||
| 146 | +[on] | ||
| 147 | +tags = ["v*"] | ||
| 148 | + | ||
| 149 | +[jobs.test] | ||
| 150 | +image = "docker.io/library/rust:1" | ||
| 151 | +run = "cargo test --workspace" | ||
| 152 | + | ||
| 153 | +[jobs.build] | ||
| 154 | +image = "docker.io/library/rust:1" | ||
| 155 | +needs = ["test"] | ||
| 156 | +run = """ | ||
| 157 | +cargo build --release | ||
| 158 | +mkdir -p dist | ||
| 159 | +cp target/release/forge dist/forge-linux-x86_64 | ||
| 160 | +cp target/release/forge-runner dist/forge-runner-linux-x86_64 | ||
| 161 | +cd dist && sha256sum forge-linux-x86_64 forge-runner-linux-x86_64 > SHA256SUMS | ||
| 162 | +""" | ||
| 163 | +artifacts = ["dist/*"] | ||
| 164 | + | ||
| 165 | +[release] | ||
| 166 | +assets = [ | ||
| 167 | + "build:dist_forge-linux-*", | ||
| 168 | + "build:dist_forge-runner-linux-*", | ||
| 169 | + "build:dist_SHA256SUMS", | ||
| 170 | +] | ||
| 171 | +prerelease = "auto" | ||
| 172 | +draft = false | ||
| 173 | +notes = "commits" | ||
| 174 | +title = "forge {tag}" | ||
| 175 | +``` | ||
| 176 | + | ||
| 177 | +With this file, pushing `v1.2.0-rc1` creates a prerelease titled `forge v1.2.0-rc1` with the three | ||
| 178 | +files attached. The `dist_` prefix comes from flattening `dist/`. | ||
| 179 | + | ||
| 105 | ### Commit statuses | 180 | ### Commit statuses |
| 106 | 181 | ||
| 107 | Every job reports one status on the commit it ran on. Its context is `ci/<job name>`. A run whose | 182 | Every job reports one status on the commit it ran on. Its context is `ci/<job name>`. A run whose |
style/main.scssmodified+9 -0
| @@ -3553,6 +3553,15 @@ span.reaction { | |||
| 3553 | word-break: break-all; | 3553 | word-break: break-all; |
| 3554 | } | 3554 | } |
| 3555 | 3555 | ||
| 3556 | +.release-assets .asset-actions { | ||
| 3557 | + white-space: nowrap; | ||
| 3558 | +} | ||
| 3559 | + | ||
| 3560 | +.release-assets .replace-form input[type="file"] { | ||
| 3561 | + max-width: 180px; | ||
| 3562 | + vertical-align: middle; | ||
| 3563 | +} | ||
| 3564 | + | ||
| 3556 | .badge.latest { | 3565 | .badge.latest { |
| 3557 | background: var(--public-bg); | 3566 | background: var(--public-bg); |
| 3558 | color: var(--public-text); | 3567 | color: var(--public-text); |