forge
Explore
Log in

Don't you dare go Hollow

CI auto-releases, releases REST API, asset replace, retag, R2/S3 storage

Browse files at this commit

51b2bbf0cf834e6d5e45fdae8b5bd2c4ed34bdb7Ahmet Kaan GümüşParent: 9261c0f
  • feat
    • CI auto-releases, releases REST API, asset replace, retag, R2/S3 storage
Show full message
✨ feat: CI auto-releases, releases REST API, asset replace, retag, R2/S3 storage

- `[release]` in .forge/ci.toml: successful tag runs publish the release,
  attach matching job artifacts and write commit notes since the last release
- token-authenticated /api/v1/repos/{owner}/{repo}/releases API with streamed uploads
- same-name uploads replace assets in place; per-asset Replace control
- edit a release's tag and target (target moves only while draft)
- release_ops layer shared by pages, API and CI
- `[storage]` backend: fs (default), r2 (native config) or s3
- fix: asset delete now checks the release belongs to the repo in the URL

28 changed files +4543 -341

Cargo.lockmodified+53 -2
@@ -1011,6 +1011,16 @@ dependencies = [
10111011 "libc",
10121012 ]
10131013
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+
10141024 [[package]]
10151025 name = "crc32c"
10161026 version = "0.6.8"
@@ -4157,6 +4167,16 @@ version = "0.9.2"
41574167 source = "registry+https://github.com/rust-lang/crates.io-index"
41584168 checksum = "8863b587001c1b9a8a4e36008cebc6b3612cb1226fe2de94858e06092687b608"
41594169
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+
41604180 [[package]]
41614181 name = "md5"
41624182 version = "0.8.1"
@@ -4328,7 +4348,7 @@ dependencies = [
43284348 "httparse",
43294349 "memchr",
43304350 "mime",
4331- "spin",
4351+ "spin 0.9.9",
43324352 "version_check",
43334353 ]
43344354
@@ -4503,17 +4523,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
45034523 checksum = "f1796bc93603f78c5760a69f2d58badc9618d22adade0a95385bb2adbae4eb94"
45044524 dependencies = [
45054525 "async-trait",
4526+ "aws-lc-rs",
4527+ "base64 0.23.1",
45064528 "bytes",
45074529 "chrono",
4530+ "crc-fast",
4531+ "form_urlencoded",
45084532 "futures-channel",
45094533 "futures-core",
45104534 "futures-util",
45114535 "http",
4536+ "http-body-util",
45124537 "humantime",
4538+ "hyper",
45134539 "itertools 0.15.0",
4540+ "md-5",
45144541 "nix 0.31.3",
45154542 "parking_lot",
45164543 "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",
45174551 "thiserror 2.0.21",
45184552 "tokio",
45194553 "tracing",
@@ -5016,7 +5050,7 @@ checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb"
50165050 dependencies = [
50175051 "base64 0.23.1",
50185052 "indexmap",
5019- "quick-xml",
5053+ "quick-xml 0.42.0",
50205054 "serde",
50215055 "time",
50225056 ]
@@ -5324,6 +5358,16 @@ version = "2.0.1"
53245358 source = "registry+https://github.com/rust-lang/crates.io-index"
53255359 checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
53265360
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+
53275371 [[package]]
53285372 name = "quick-xml"
53295373 version = "0.42.0"
@@ -5614,6 +5658,7 @@ dependencies = [
56145658 "bytes",
56155659 "futures-core",
56165660 "futures-util",
5661+ "h2",
56175662 "http",
56185663 "http-body",
56195664 "http-body-util",
@@ -6458,6 +6503,12 @@ version = "0.9.9"
64586503 source = "registry+https://github.com/rust-lang/crates.io-index"
64596504 checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
64606505
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+
64616512 [[package]]
64626513 name = "spki"
64636514 version = "0.8.1"
Cargo.tomlmodified+1 -1
@@ -68,7 +68,7 @@ chacha20poly1305 = "0.11.0"
6868
6969 # storage
7070 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"] }
7272 multer = "3.1.0"
7373
7474 # outgoing mail (forge-web): SMTP over rustls, no native TLS
config/forge.example.tomlmodified+39 -0
@@ -52,6 +52,45 @@ trusted_proxies = []
5252 # Largest accepted release asset, in MiB.
5353 # max_asset_mb = 512
5454
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+
5594 # Standby replication (see docs/backup.md). Empty target disables it. When target is set,
5695 # identity_file and known_hosts_file are required.
5796 # [replication]
crates/forge-ci/src/config.rsmodified+391 -0
@@ -33,6 +33,10 @@ pub const MAX_WORKFLOW_NAME_CHARS: usize = 40;
3333 pub const MAX_CACHE_ENTRIES: usize = 8;
3434 /// Longest `cache` entry, in characters.
3535 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;
3640
3741 /// A parsed and validated workflow.
3842 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -47,6 +51,83 @@ pub struct CiConfig {
4751 /// The `[jobs.<name>]` tables, keyed by job name.
4852 #[serde(default)]
4953 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,
50131 }
51132
52133 /// The `[on]` table.
@@ -142,6 +223,12 @@ impl CiConfig {
142223 }
143224 }
144225
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+
145232 /// Job names in dependency order. Ties are broken by name, so the order is stable.
146233 /// Jobs in a cycle, or with unknown needs, are left out. [`parse_config`] rejects both.
147234 pub fn job_order(&self) -> Vec<&str> {
@@ -192,6 +279,9 @@ impl CiConfig {
192279 for (name, job) in &self.jobs {
193280 validate_job(name, job, &self.jobs)?;
194281 }
282+ if let Some(release) = &self.release {
283+ validate_release(release, &self.on, &self.jobs)?;
284+ }
195285 let order = self.job_order();
196286 if order.len() != self.jobs.len() {
197287 let job = self
@@ -206,6 +296,37 @@ impl CiConfig {
206296 }
207297 }
208298
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+
209330 fn matches_any(globs: &[String], value: &str) -> bool {
210331 globs
211332 .iter()
@@ -368,6 +489,79 @@ fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> {
368489 Ok(())
369490 }
370491
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+
371565 fn validate_job(
372566 name: &str,
373567 job: &JobSpec,
@@ -889,4 +1083,201 @@ artifacts = ["target/release/forge"]
8891083 ConfigError::Toml(_)
8901084 ));
8911085 }
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+ }
8921283 }
crates/forge-ci/src/error.rsmodified+12 -0
@@ -71,6 +71,18 @@ pub enum ConfigError {
7171 #[error("job {job:?}: duplicate cache path {path:?}")]
7272 DuplicateCachePath { job: String, path: String },
7373
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+
7486 #[error("invalid {kind} glob {pattern:?}: {reason}")]
7587 InvalidTriggerGlob {
7688 kind: &'static str,
crates/forge-core/src/config.rsmodified+401 -1
@@ -81,6 +81,9 @@ pub struct Config {
8181 /// Release asset limits, from the `[releases]` section.
8282 #[serde(default)]
8383 pub releases: ReleasesConfig,
84+ /// Where release assets and CI artifacts are stored, from the `[storage]` section.
85+ #[serde(default)]
86+ pub storage: StorageConfig,
8487 /// Standby replication, from the `[replication]` section. An empty `target` disables it.
8588 #[serde(default)]
8689 pub replication: ReplicationConfig,
@@ -358,6 +361,168 @@ impl Default for ReleasesConfig {
358361 }
359362 }
360363
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+
361526 /// Scheduled backups, from the `[backup]` section. See `docs/backup.md`.
362527 #[derive(Debug, Clone, Deserialize)]
363528 #[serde(deny_unknown_fields, default)]
@@ -455,6 +620,7 @@ impl Config {
455620 config.backup.validate()?;
456621 config.replication.validate()?;
457622 config.self_update.validate()?;
623+ config.storage.validate()?;
458624 Ok(config)
459625 }
460626 }
@@ -627,7 +793,10 @@ mod tests {
627793 let base = format!("{DEV_DEFAULTS}\n[self_update]\nenabled = true\n");
628794 for repo in ["", "forge", "a/b/c", "/forge", "owner/"] {
629795 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+ );
631800 }
632801 std::fs::write(&path, format!("{base}repo = \"Tahinli/forge\"\n")).unwrap();
633802 let cfg = Config::load(&path).unwrap();
@@ -662,4 +831,235 @@ mod tests {
662831 std::fs::write(&path, format!("{DEV_DEFAULTS}\n[backup]\nbogus = 1\n")).unwrap();
663832 assert!(matches!(Config::load(&path), Err(Error::Config(_))));
664833 }
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+ }
6651065 }
crates/forge-core/src/releases.rsmodified+1 -1
@@ -59,7 +59,7 @@ pub struct NewRelease<'a> {
5959 pub author_id: &'a str,
6060 }
6161
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`.
6363 #[derive(Debug, Clone, Copy)]
6464 pub struct ReleaseEdit<'a> {
6565 pub title: &'a str,
crates/forge-core/src/store/releases.rsmodified+146 -1
@@ -281,6 +281,52 @@ impl Store {
281281 .ok_or_else(missing_row)
282282 }
283283
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+
284330 /// Deletes one asset row. Returns false when it is already gone.
285331 pub async fn delete_release_asset(&self, id: &str) -> Result<bool> {
286332 let conn = self.inner.conn.lock().await;
@@ -328,7 +374,10 @@ mod tests {
328374 async fn store_with_repo() -> (tempfile::TempDir, Store, String, String) {
329375 let dir = tempfile::tempdir().unwrap();
330376 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();
332381 let repo = store
333382 .create_repo(&user.id, "proj", "", crate::Visibility::Public, "main")
334383 .await
@@ -444,6 +493,102 @@ mod tests {
444493 assert_eq!(store.delete_release(&rel.id).await.unwrap(), None);
445494 }
446495
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+
447592 #[test]
448593 fn asset_names_and_content_types_are_cleaned() {
449594 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(
4747 .await
4848 }
4949
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+
50130 #[cfg(test)]
51131 mod tests {
52132 use super::valid_tag_name;
crates/forge-web/src/api/mod.rsmodified+1 -0
@@ -4,6 +4,7 @@
44 //! `{"error": "..."}` with a matching status code. Anonymous callers get 401 whenever they cannot
55 //! use a repo, the same as git, so missing and hidden repos look identical to them.
66
7+pub mod releases;
78 pub mod statuses;
89
910 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,
2-//! so an S3 backend can replace it later without touching the pages.
1+//! Blob storage for release assets and CI artifacts. A thin wrapper over object_store, backed by
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.
36 //!
47 //! Keys are `assets/<asset id>`. Writes stream through object_store's multipart upload, which
58 //! assembles the object in a temporary file and renames it into place on `finish`. Every chunk
@@ -10,10 +13,13 @@ use std::path::Path;
1013 use std::sync::Arc;
1114
1215 use bytes::Bytes;
16+use forge_core::config::{R2Config, S3Config, StorageBackend, StorageConfig};
1317 use forge_core::{Error, Result};
1418 use futures_util::{StreamExt, TryStreamExt, stream::BoxStream};
19+use object_store::aws::AmazonS3Builder;
1520 use object_store::local::LocalFileSystem;
1621 use object_store::path::Path as ObjectPath;
22+use object_store::prefix::PrefixStore;
1723 use object_store::{ObjectStore, ObjectStoreExt, WriteMultipart};
1824 use sha2::{Digest, Sha256};
1925
@@ -34,6 +40,20 @@ where
3440 Error::Io(std::io::Error::other(e))
3541 }
3642
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+
3757 /// The blob store rooted at `<data_dir>/blobs`. Cheap to clone.
3858 #[derive(Clone)]
3959 pub struct BlobStore {
@@ -47,15 +67,84 @@ pub struct BlobRead {
4767 }
4868
4969 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+
5079 /// Opens the store at `root`, creating the directory if needed.
5180 pub fn open(root: &Path) -> Result<Self> {
5281 std::fs::create_dir_all(root)?;
5382 let fs = LocalFileSystem::new_with_prefix(root).map_err(storage_err)?;
54- Ok(Self {
55- store: Arc::new(fs),
83+ Ok(Self::from_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,
56118 })
57119 }
58120
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+
59148 /// Starts a write of `key`. The bytes are not visible under `key` until `finish`.
60149 pub async fn begin(&self, key: &str, max_bytes: u64) -> Result<BlobWriter> {
61150 let upload = self
@@ -141,3 +230,114 @@ impl BlobWriter {
141230 let _ = self.writer.abort().await;
142231 }
143232 }
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<()> {
8989 Arc::new(crate::mail::LogMailer::new(data_dir.join("mail-log")))
9090 }
9191 };
92+ let blobs = crate::blobs::BlobStore::from_config(&config.storage, &data_dir)?;
9293 let state = AppState {
9394 config: Arc::new(config),
9495 store,
@@ -101,7 +102,7 @@ pub async fn serve(config: Config) -> forge_core::Result<()> {
101102 throttle: Arc::new(crate::throttle::Throttle::default()),
102103 webhook_waker: Arc::new(Notify::new()),
103104 mirror_waker: Arc::new(Notify::new()),
104- blobs: crate::blobs::BlobStore::open(&data_dir.join("blobs"))?,
105+ blobs,
105106 replication: Arc::new(crate::replication::ReplicationQueue::default()),
106107 ci_waker: Arc::new(Notify::new()),
107108 mailer,
crates/forge-web/src/ci/api.rsmodified+6 -1
@@ -12,7 +12,7 @@ use forge_ci::proto::{
1212 FinishRequest, HeartbeatResponse, JobAssignment, Outcome, RegisterRequest, RegisterResponse,
1313 };
1414 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};
1616 use futures_util::StreamExt;
1717 use http::header::HeaderValue;
1818 use serde_json::json;
@@ -774,6 +774,11 @@ async fn finish_job(
774774 }
775775 // A run that just went green may deploy the forge itself.
776776 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+ }
777782 Ok(run.state.as_str())
778783 }
779784
crates/forge-web/src/ci/mod.rsmodified+1 -0
@@ -13,6 +13,7 @@ use crate::state::AppState;
1313 pub mod api;
1414 pub mod live;
1515 pub mod reaper;
16+pub mod release;
1617 pub mod schedule;
1718
1819 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>> {
284284 }
285285
286286 /// 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+
287296 async fn load(state: &AppState, repo_id: &str, commit: &str) -> Loaded {
288297 let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, repo_id) {
289298 Ok(path) => path,
@@ -368,7 +377,7 @@ where
368377 }
369378
370379 #[cfg(test)]
371-mod tests {
380+pub(super) mod tests {
372381 use std::path::{Path, PathBuf};
373382 use std::sync::Arc;
374383 use std::time::Duration;
@@ -386,7 +395,7 @@ mod tests {
386395 use crate::post_update::after_ref_update;
387396 use crate::test_support::test_state;
388397
389- const ZERO: &str = "0000000000000000000000000000000000000000";
398+ pub(in crate::ci) const ZERO: &str = "0000000000000000000000000000000000000000";
390399
391400 const CONFIG: &str = r#"
392401 [on]
@@ -412,7 +421,7 @@ image = "alpine:3"
412421 run = "make"
413422 "#;
414423
415- const CONFIG_TAGS: &str = r#"
424+ pub(in crate::ci) const CONFIG_TAGS: &str = r#"
416425 [on]
417426 push = []
418427 tags = ["v*"]
@@ -441,7 +450,7 @@ image = "alpine:3"
441450 run = "make"
442451 "#;
443452
444- fn git(dir: &Path, args: &[&str]) -> String {
453+ pub(in crate::ci) fn git(dir: &Path, args: &[&str]) -> String {
445454 let out = std::process::Command::new("git")
446455 .arg("-C")
447456 .arg(dir)
@@ -460,16 +469,16 @@ run = "make"
460469 String::from_utf8_lossy(&out.stdout).trim().to_string()
461470 }
462471
463- struct Fixture {
464- _tmp: TempDir,
465- state: AppState,
466- repo: Repo,
467- owner: User,
468- bare: PathBuf,
469- work: PathBuf,
472+ pub(in crate::ci) struct Fixture {
473+ pub(in crate::ci) _tmp: TempDir,
474+ pub(in crate::ci) state: AppState,
475+ pub(in crate::ci) repo: Repo,
476+ pub(in crate::ci) owner: User,
477+ pub(in crate::ci) bare: PathBuf,
478+ pub(in crate::ci) work: PathBuf,
470479 }
471480
472- async fn fixture() -> Fixture {
481+ pub(in crate::ci) async fn fixture() -> Fixture {
473482 let tmp = tempfile::tempdir().expect("tempdir");
474483 let state = test_state(tmp.path()).await;
475484 let owner = state
@@ -499,7 +508,7 @@ run = "make"
499508 }
500509
501510 /// 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 {
503512 for (path, text) in files {
504513 let full = work.join(path);
505514 if let Some(parent) = full.parent() {
@@ -513,7 +522,7 @@ run = "make"
513522 }
514523
515524 /// 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) {
517526 let work = fx.work.to_str().expect("utf8 path");
518527 git(
519528 &fx.bare,
@@ -522,7 +531,7 @@ run = "make"
522531 }
523532
524533 /// 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 {
526535 let oid = commit(&fx.work, files);
527536 land(fx, &oid, refname);
528537 after_ref_update(&fx.state, &fx.repo, &fx.owner.id, refname, ZERO, &oid)
@@ -539,7 +548,7 @@ run = "make"
539548 jobs.iter().find(|j| j.name == name).map(|j| j.state)
540549 }
541550
542- async fn runs_total(fx: &Fixture) -> u64 {
551+ pub(in crate::ci) async fn runs_total(fx: &Fixture) -> u64 {
543552 fx.state
544553 .store
545554 .list_runs(&fx.repo.id, 1, 50)
crates/forge-web/src/i18n/releases_ci.rsmodified+36 -4
@@ -67,6 +67,7 @@ pub enum K {
6767 RelSaved,
6868 RelDeleted,
6969 RelAssetUploaded,
70+ RelAssetReplaced,
7071 RelAssetDeleted,
7172 RelAssetTooLarge,
7273 RelAssetExists,
@@ -79,7 +80,6 @@ pub enum K {
7980 // Release form errors.
8081 RelErrTagName,
8182 RelErrReleaseExists,
82- RelErrChooseBranch,
8383
8484 // Release pages.
8585 Releases,
@@ -112,6 +112,12 @@ pub enum K {
112112 UploadAsset,
113113 DeleteReleaseHelp,
114114 YesDeleteRelease,
115+ EditTagHelp,
116+ EditTargetLabel,
117+ CurrentCommit,
118+ TargetMoveHelp,
119+ TargetLockedHelp,
120+ ReplaceAsset,
115121 }
116122
117123 pub fn t(lang: Lang, key: K) -> &'static str {
@@ -239,6 +245,8 @@ pub fn t(lang: Lang, key: K) -> &'static str {
239245 (RelDeleted, Tr) => "Sürüm silindi. Etiket korundu.",
240246 (RelAssetUploaded, En) => "Asset uploaded.",
241247 (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.",
242250 (RelAssetDeleted, En) => "Asset deleted.",
243251 (RelAssetDeleted, Tr) => "Dosya silindi.",
244252 (RelAssetTooLarge, En) => {
@@ -286,8 +294,6 @@ pub fn t(lang: Lang, key: K) -> &'static str {
286294 (RelErrReleaseExists, Tr) => {
287295 "Bu etiket için zaten bir sürüm var. Bunun yerine o sürümü düzenleyin."
288296 }
289- (RelErrChooseBranch, En) => "Choose a branch to create the tag on.",
290- (RelErrChooseBranch, Tr) => "Etiketin oluşturulacağı bir dal seçin.",
291297
292298 (Releases, En) => "Releases",
293299 (Releases, Tr) => "Sürümler",
@@ -355,6 +361,26 @@ pub fn t(lang: Lang, key: K) -> &'static str {
355361 (DeleteReleaseHelp, Tr) => "Sürümü ve dosyalarını siler. Git etiketi korunur.",
356362 (YesDeleteRelease, En) => "Yes, delete this release",
357363 (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",
358384 }
359385 }
360386
@@ -496,6 +522,7 @@ mod tests {
496522 K::RelSaved,
497523 K::RelDeleted,
498524 K::RelAssetUploaded,
525+ K::RelAssetReplaced,
499526 K::RelAssetDeleted,
500527 K::RelAssetTooLarge,
501528 K::RelAssetExists,
@@ -506,7 +533,6 @@ mod tests {
506533 K::RelAssetEmpty,
507534 K::RelErrTagName,
508535 K::RelErrReleaseExists,
509- K::RelErrChooseBranch,
510536 K::Releases,
511537 K::NewRelease,
512538 K::EditRelease,
@@ -537,6 +563,12 @@ mod tests {
537563 K::UploadAsset,
538564 K::DeleteReleaseHelp,
539565 K::YesDeleteRelease,
566+ K::EditTagHelp,
567+ K::EditTargetLabel,
568+ K::CurrentCommit,
569+ K::TargetMoveHelp,
570+ K::TargetLockedHelp,
571+ K::ReplaceAsset,
540572 ];
541573
542574 #[test]
crates/forge-web/src/main.rsmodified+1 -0
@@ -37,6 +37,7 @@ mod pages;
3737 mod post_update;
3838 mod pulls_sync;
3939 mod raw;
40+mod release_ops;
4041 mod render;
4142 mod replication;
4243 mod self_update;
crates/forge-web/src/pages/releases.rsmodified+281 -306
@@ -4,17 +4,16 @@
44 //!
55 //! A release names a git tag. When the tag does not exist yet it is created as a lightweight tag
66 //! 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
89 //! attachments with `nosniff`, and each completed start counts one download.
910
1011 use forge_core::releases::{
11- MAX_BODY_CHARS, MAX_TITLE_CHARS, NewAsset, NewRelease, Release, ReleaseAsset, ReleaseEdit,
12- clean_content_type, valid_asset_name,
12+ MAX_BODY_CHARS, MAX_TITLE_CHARS, Release, ReleaseAsset, valid_asset_name,
1313 };
14-use forge_core::webhooks::WebhookEvent;
1514 use forge_core::{Action, Denied, Repo as CoreRepo, User, authorize};
1615 use forge_git::browse::RefKind;
17-use forge_git::tags::{create_lightweight_tag, valid_tag_name};
16+use forge_git::tags::valid_tag_name;
1817 use futures_util::TryStreamExt;
1918 use http::header::{CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_TYPE};
2019 use http_body::Frame;
@@ -30,7 +29,7 @@ use topcoat::router::{Body, HeaderName, HeaderValue, StatusCode, page, path_para
3029 use topcoat::view::{Unescaped, View, component, view};
3130
3231 use crate::auth::require_csrf;
33-use crate::blobs::{BlobWriter, asset_key};
32+use crate::blobs::asset_key;
3433 use crate::i18n::{
3534 self, Key, Lang,
3635 releases_ci::{self as g, K},
@@ -39,11 +38,10 @@ use crate::pages::refs::load_refs;
3938 use crate::pages::repo::repo_head;
4039 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
4140 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};
4342 use crate::render::markdown::render_markdown;
4443 use crate::state::AppState;
45-use crate::views::{alert, enc, shell, user_facing_message, user_link};
46-use crate::webhooks::emit::{Sender, emit};
44+use crate::views::{alert, enc, shell, user_link};
4745
4846 path_param!(owner);
4947 path_param!(repo);
@@ -54,16 +52,13 @@ path_param!(name);
5452
5553 /// Multipart framing allowed on top of the file itself when checking `Content-Length`.
5654 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-}
6155
6256 /// 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] = [
6458 ("saved", K::RelSaved, false),
6559 ("deleted", K::RelDeleted, false),
6660 ("asset-uploaded", K::RelAssetUploaded, false),
61+ ("asset-replaced", K::RelAssetReplaced, false),
6762 ("asset-deleted", K::RelAssetDeleted, false),
6863 ("asset-too-large", K::RelAssetTooLarge, true),
6964 ("asset-exists", K::RelAssetExists, true),
@@ -286,12 +281,16 @@ struct CreateForm {
286281 draft: Option<String>,
287282 }
288283
289-/// The edit-release form fields.
284+/// The edit-release form fields. `tag` and `target` are the optional retag fields.
290285 #[derive(Deserialize)]
291286 struct EditForm {
292287 #[serde(default)]
293288 csrf: String,
294289 #[serde(default)]
290+ tag: String,
291+ #[serde(default)]
292+ target: String,
293+ #[serde(default)]
295294 title: String,
296295 #[serde(default)]
297296 body: String,
@@ -342,11 +341,13 @@ async fn release_form(
342341 csrf: String,
343342 lang: Lang,
344343 is_new: bool,
344+ move_target: bool,
345345 draft: FormDraft,
346346 branches: Vec<String>,
347347 submit: &'static str,
348348 ) -> Result<impl View> {
349349 let tag_hint = g::t(lang, K::TagHint);
350+ let edit_tag_help = g::t(lang, K::EditTagHelp);
350351 Ok(view! {
351352 <form method="post" action=(action.as_str()) class="stack release-form">
352353 if let Some(message) = draft.error {
@@ -368,7 +369,25 @@ async fn release_form(
368369 </select>
369370 </label>
370371 } 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+ }
372391 }
373392 <label>
374393 <span>(g::t(lang, K::Title))</span>
@@ -398,6 +417,7 @@ async fn release_form(
398417 async fn asset_rows(
399418 assets: Vec<AssetLink>,
400419 delete_actions: Vec<String>,
420+ upload_action: String,
401421 csrf: String,
402422 lang: Lang,
403423 ) -> Result<impl View> {
@@ -423,7 +443,13 @@ async fn asset_rows(
423443 <td>(asset.size.as_str())</td>
424444 <td>(asset.downloads)</td>
425445 <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>
427453 <form method="post" action=(action.as_str()) class="inline-form">
428454 <input type="hidden" name="csrf" value=(csrf.as_str())>
429455 <button type="submit">(i18n::t(lang, Key::Delete))</button>
@@ -580,7 +606,7 @@ async fn new_form_body(
580606 repo_head(head: head)
581607 <section class="card">
582608 <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))
584610 </section>
585611 })
586612 }
@@ -633,9 +659,6 @@ async fn release_create(cx: &Cx, Form(form): Form<CreateForm>) -> Result<impl Vi
633659 };
634660 match create_checked(state, &ctx, &user, &draft, lang).await? {
635661 Ok(release) => {
636- if !release.draft {
637- emit_release(state, &ctx.repo, &user, "published", &release).await;
638- }
639662 let title = title_of(&ctx);
640663 Err(see_other(tag_href(&title, &release.tag)).into())
641664 }
@@ -656,8 +679,8 @@ async fn release_create(cx: &Cx, Form(form): Form<CreateForm>) -> Result<impl Vi
656679 }
657680 }
658681
659-/// Checks the new-release fields, makes the tag when it is missing, and stores the release. A
660-/// refusal the form shows is `Err(message)`; storage failures are errors.
682+/// Checks the new-release fields with their form messages, then creates the release through
683+/// `release_ops`. A refusal the form shows is `Err(message)`; storage failures are errors.
661684 async fn create_checked(
662685 state: &AppState,
663686 ctx: &RepoCtx,
@@ -680,84 +703,21 @@ async fn create_checked(
680703 {
681704 return Ok(Err(g::t(lang, K::RelErrReleaseExists).to_owned()));
682705 }
683- let refs = load_refs(ctx.path.clone()).await?;
684- let existing = refs
685- .iter()
686- .find(|r| r.kind == RefKind::Tag && r.name == tag_name)
687- .map(|r| r.target.clone());
688- let target_oid = match existing {
689- Some(oid) => oid,
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- }
706+ let input = CreateRelease {
707+ tag: tag_name.to_owned(),
708+ target: Some(draft.target.clone()),
709+ title: draft.title.clone(),
710+ body: draft.body.clone(),
711+ draft: draft.draft,
712+ prerelease: draft.prerelease,
708713 };
709- let created = state
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 {
714+ match release_ops::create(state, &ctx.repo, user, input).await {
723715 Ok(release) => Ok(Ok(release)),
724- Err(e) => match user_facing_message(&e) {
725- Some(message) => Ok(Err(message)),
726- None => Err(e.into()),
727- },
716+ Err(ReleaseError::Internal(e)) => Err(e.into()),
717+ Err(e) => Ok(Err(e.message())),
728718 }
729719 }
730720
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-
761721 /// The public view of one release: notes, assets and the source archive links.
762722 #[page("/{owner}/{repo}/releases/tag/{tag}")]
763723 async fn release_tag_page(cx: &Cx) -> Result<impl View> {
@@ -881,6 +841,121 @@ async fn release_tag_page(cx: &Cx) -> Result<impl View> {
881841 })
882842 }
883843
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+
884959 /// The edit page: the release fields, its assets, and the upload form.
885960 #[page("/{owner}/{repo}/releases/{release_id}/edit")]
886961 async fn release_edit_page(cx: &Cx) -> Result<impl View> {
@@ -897,23 +972,6 @@ async fn release_edit_page(cx: &Cx) -> Result<impl View> {
897972 if release.repo_id != ctx.repo.id {
898973 return Err(not_found().into());
899974 }
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();
917975 let csrf = match crate::auth::current_user(cx).await? {
918976 Some((_, session)) => session.csrf_token.clone(),
919977 None => String::new(),
@@ -926,110 +984,72 @@ async fn release_edit_page(cx: &Cx) -> Result<impl View> {
926984 draft: release.draft,
927985 ..FormDraft::default()
928986 };
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));
933987 let notice = notice_from_query(cx, lang);
934- let action = release_edit_href(&title, &release.id);
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);
988+ let parts = edit_parts(state, &ctx, &release, lang).await?;
940989 Ok(view! {
941- shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),
942- repo_head(head: head)
943- if let Some((text, is_error)) = notice {
944- if is_error {
945- alert(message: text)
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- )
990+ shell(title: parts.page_title.as_str(), viewer: ctx.viewer.as_ref(),
991+ edit_body(head: parts.head, lang: lang, notice: notice, view_tag: parts.view_tag, action: parts.action,
992+ csrf: csrf, draft: draft, branches: parts.branches, move_target: parts.move_target,
993+ assets: parts.links, delete_actions: parts.delete_actions, upload_action: parts.upload_action,
994+ upload_hint: parts.upload_hint, delete_href: parts.delete_href))
985995 })
986996 }
987997
988-/// Saves the edited fields. A draft that becomes published is announced as `published`; any other
989-/// change to a published release is `updated`.
990-#[route(POST "/{owner}/{repo}/releases/{release_id}/edit")]
991-async fn release_update(cx: &Cx, Form(form): Form<EditForm>) -> Result<Response> {
998+/// Saves the edited fields through `release_ops`. An empty target keeps the commit, and an
999+/// unchanged tag keeps the tag. A refused save shows its message and keeps the typed values.
1000+#[page(POST "/{owner}/{repo}/releases/{release_id}/edit")]
1001+async fn release_update(cx: &Cx, Form(form): Form<EditForm>) -> Result<impl View> {
9921002 let owner = path_param::<Owner>(cx);
9931003 let name = path_param::<Repo>(cx);
9941004 let id = path_param::<ReleaseId>(cx).to_owned();
9951005 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?;
9971007 require_write(&ctx)?;
1008+ let lang = i18n::lang(cx, viewer_user(&ctx));
9981009 let state = app_context::<AppState>(cx);
9991010 let Some(before) = state.store.release(&id).await? else {
10001011 return Err(not_found().into());
10011012 };
1002- if before.repo_id != ctx.repo.id {
1003- return Err(not_found().into());
1004- }
1005- let title_text = form.title.trim().to_owned();
1006- let 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(),
1013+ let draft = FormDraft {
1014+ tag: form.tag.trim().to_owned(),
1015+ target: form.target.trim().to_owned(),
1016+ title: form.title.trim().to_owned(),
1017+ body: form.body.trim_end().to_owned(),
10151018 prerelease: form.prerelease.is_some(),
1019+ draft: form.draft.is_some(),
1020+ error: None,
10161021 };
1017- if !state.store.update_release(&id, &edit).await? {
1018- return Err(not_found().into());
1019- }
1020- let Some(after) = state.store.release(&id).await? else {
1021- return Err(not_found().into());
1022- };
1023- let action = match (before.draft, after.draft) {
1024- (true, false) => Some("published"),
1025- (true, true) => None,
1026- (false, _) => Some("updated"),
1022+ let edit = EditRelease {
1023+ title: draft.title.clone(),
1024+ body: draft.body.clone(),
1025+ draft: draft.draft,
1026+ prerelease: draft.prerelease,
1027+ tag: (draft.tag != before.tag).then(|| draft.tag.clone()),
1028+ target: (!draft.target.is_empty()).then(|| draft.target.clone()),
10271029 };
1028- if let Some(action) = action {
1029- emit_release(state, &ctx.repo, &user, action, &after).await;
1030+ match release_ops::update(state, &ctx.repo, &user, &before, edit).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+ }
10301052 }
1031- let href = release_edit_href(&title_of(&ctx), &id);
1032- Err(notice_redirect(&href, "saved").into())
10331053 }
10341054
10351055 /// 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>
10501070 let Some(release) = state.store.release(&id).await? else {
10511071 return Err(not_found().into());
10521072 };
1053- if release.repo_id != ctx.repo.id {
1054- return Err(not_found().into());
1073+ match release_ops::delete(state, &ctx.repo, &user, &release).await {
1074+ Ok(()) => Err(notice_redirect(&releases_href(&title), "deleted").into()),
1075+ Err(ReleaseError::Internal(e)) => Err(e.into()),
1076+ Err(_) => Err(not_found().into()),
10551077 }
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())
10681078 }
10691079
10701080 /// Deletes one asset row and its blob.
@@ -1072,54 +1082,28 @@ async fn release_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<Response>
10721082 async fn asset_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<Response> {
10731083 let owner = path_param::<Owner>(cx);
10741084 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();
10761086 let asset = path_param::<AssetId>(cx).to_owned();
10771087 let ctx = load_repo(cx, owner, name).await?;
10781088 require_csrf(cx, &form.csrf).await?;
10791089 require_write(&ctx)?;
10801090 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 {
10821092 return Err(not_found().into());
10831093 };
1084- if row.release_id != release {
1085- return Err(not_found().into());
1086- }
1087- let href = release_edit_href(&title_of(&ctx), &release);
1088- state.store.delete_release_asset(&row.id).await?;
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- }
1094+ let href = release_edit_href(&title_of(&ctx), &release_id);
1095+ match release_ops::delete_asset(state, &ctx.repo, &release, &asset).await {
1096+ Ok(()) => Err(notice_redirect(&href, "asset-deleted").into()),
1097+ Err(ReleaseError::Internal(e)) => Err(e.into()),
1098+ Err(_) => Err(not_found().into()),
11171099 }
11181100 }
11191101
11201102 /// 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
1122-/// published under `assets/<id>` only when it is complete and the row is stored.
1103+/// `file` field. An optional `name` field, sent before `file`, stores the file under that name
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.
11231107 #[route(POST "/{owner}/{repo}/releases/{release_id}/assets")]
11241108 async fn asset_upload(cx: &Cx, body: Body) -> Result<Response> {
11251109 let owner = path_param::<Owner>(cx);
@@ -1156,6 +1140,7 @@ async fn asset_upload(cx: &Cx, body: Body) -> Result<Response> {
11561140
11571141 let mut multipart = multer::Multipart::new(body.into_data_stream(), boundary);
11581142 let mut uploader: Option<User> = None;
1143+ let mut name_override: Option<String> = None;
11591144 let mut outcome: &'static str = "asset-empty";
11601145 loop {
11611146 let mut field = match multipart.next_field().await {
@@ -1173,11 +1158,26 @@ async fn asset_upload(cx: &Cx, body: Body) -> Result<Response> {
11731158 require_write(&ctx)?;
11741159 uploader = Some(user);
11751160 }
1161+ Some("name") => {
1162+ let value = field.text().await.unwrap_or_default();
1163+ if !value.is_empty() {
1164+ name_override = Some(value);
1165+ }
1166+ }
11761167 Some("file") => {
11771168 let Some(user) = uploader.as_ref() else {
11781169 return Err(forbidden().into());
11791170 };
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?;
11811181 break;
11821182 }
11831183 _ => {
@@ -1188,12 +1188,16 @@ async fn asset_upload(cx: &Cx, body: Body) -> Result<Response> {
11881188 Err(notice_redirect(&href, outcome).into())
11891189 }
11901190
1191-/// Streams one `file` field into a blob and adds its asset row. Returns the notice word for the
1192-/// outcome. Storage failures are errors; everything the client can cause is a notice.
1191+/// Streams one `file` field into `release_ops::put_asset`, which replaces a file of the same name.
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.
11931195 async fn store_upload(
11941196 state: &AppState,
1195- release_id: &str,
1197+ repo: &CoreRepo,
1198+ release: &Release,
11961199 user: &User,
1200+ name_override: Option<&str>,
11971201 field: &mut multer::Field<'_>,
11981202 max_bytes: u64,
11991203 ) -> Result<&'static str> {
@@ -1201,61 +1205,32 @@ async fn store_upload(
12011205 if file_name.is_empty() {
12021206 return Ok("asset-empty");
12031207 }
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) {
12051210 return Ok("asset-name");
12061211 }
1207- if state
1208- .store
1209- .release_asset(release_id, &file_name)
1210- .await?
1211- .is_some()
1212- {
1213- return Ok("asset-exists");
1214- }
12151212 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()));
1217- let asset_id = ulid::Ulid::generate().to_string();
1218- let key = asset_key(&asset_id);
1219- let mut writer = state.blobs.begin(&key, max_bytes).await?;
1220- match copy_field(field, &mut writer).await {
1221- Ok(()) => {}
1222- Err(UploadFailure::TooLarge) => {
1223- writer.abort().await;
1224- return Ok("asset-too-large");
1225- }
1226- Err(UploadFailure::Unreadable) => {
1227- writer.abort().await;
1228- return Ok("asset-invalid");
1229- }
1230- Err(UploadFailure::Storage(e)) => {
1231- writer.abort().await;
1232- return Err(e.into());
1233- }
1234- }
1235- let (size, sha256) = writer.finish().await?;
1236- let added = state
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- }
1213+ let content_type = mime.as_deref().and_then(|m| m.split(';').next());
1214+ let stream = (&mut *field).map_err(std::io::Error::other);
1215+ match release_ops::put_asset(
1216+ state,
1217+ repo,
1218+ release,
1219+ user,
1220+ &name,
1221+ content_type,
1222+ stream,
1223+ max_bytes,
1224+ )
1225+ .await
1226+ {
1227+ Ok((_, true)) => Ok("asset-replaced"),
1228+ Ok((_, false)) => Ok("asset-uploaded"),
1229+ Err(ReleaseError::TooLarge) => Ok("asset-too-large"),
1230+ Err(ReleaseError::Conflict(_)) => Ok("asset-exists"),
1231+ Err(ReleaseError::Invalid(_)) => Ok("asset-invalid"),
1232+ Err(ReleaseError::NotFound) => Err(not_found().into()),
1233+ Err(ReleaseError::Internal(e)) => Err(e.into()),
12591234 }
12601235 }
12611236
crates/forge-web/src/pages/releases_tests.rsmodified+470 -1
@@ -4,12 +4,15 @@
44 use std::path::{Path, PathBuf};
55 use std::sync::Arc;
66
7+use forge_core::releases::Release;
78 use forge_core::{Repo, Role, Store, User, Visibility};
89 use forge_git::repo::{init_bare, repo_path};
910 use topcoat::router::request::Request;
1011 use topcoat::router::{Body, HeaderMap, Router, to_bytes};
1112
1213 use crate::auth::SESSION_COOKIE;
14+use crate::blobs::asset_key;
15+use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError};
1316 use crate::test_support::{app_router, create_session, test_state};
1417
1518 const CSRF: &str = "releases-test-csrf";
@@ -506,7 +509,9 @@ async fn an_upload_over_the_size_cap_is_refused_and_leaves_no_blob() {
506509 let fx = fixture(Some(1)).await;
507510 let rel = fx.release("v1.0", false).await;
508511 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;
510515 assert_eq!(reply.status, 303);
511516 assert!(
512517 reply
@@ -588,3 +593,467 @@ async fn the_latest_release_card_shows_on_the_repo_home() {
588593 "the tabs link to releases"
589594 );
590595 }
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 {
10391039 webhooks: Default::default(),
10401040 backup: Default::default(),
10411041 releases: Default::default(),
1042+ storage: Default::default(),
10421043 replication: Default::default(),
10431044 lfs: Default::default(),
10441045 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, &current).await?;
360+ fire_tag_hook(state, repo, actor, &release.tag, &current, &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 {
4545 webhooks: Default::default(),
4646 backup: Default::default(),
4747 releases: Default::default(),
48+ storage: Default::default(),
4849 replication: Default::default(),
4950 lfs: Default::default(),
5051 ci: Default::default(),
docs/api.mdmodified+169 -1
@@ -31,7 +31,7 @@ Errors are JSON: `{"error": "message"}`.
3131 | 401 | No token, an unknown or expired token, or an anonymous caller who cannot use the repo. |
3232 | 403 | The token lacks the `repo` scope, or the user has read-only access and tried to write. |
3333 | 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`. |
3535 | 422 | A field has an invalid value, or `sha` is not a full commit id. |
3636 | 429 | Too many failed authentication attempts from this IP. |
3737
@@ -129,3 +129,171 @@ Response, `200 OK`:
129129
130130 `statuses` is ordered by `context`. The list is empty and `state` is `null` when nothing has
131131 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
303303
304304 ## Release assets
305305
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:
307307
308308 - 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.
309309 - 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.
310310 - 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.
311311 - 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.
312312
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+
313333 ## LFS objects
314334
315335 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
102102 - Jobs whose `needs` fail or are skipped are marked `skipped`. A skipped job gets the status
103103 `ci/<job>` = `error` with the description `skipped`.
104104
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+
105180 ### Commit statuses
106181
107182 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 {
35533553 word-break: break-all;
35543554 }
35553555
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+
35563565 .badge.latest {
35573566 background: var(--public-bg);
35583567 color: var(--public-text);