forge
Explore
Log in

Don't you dare go Hollow

Forge-web-app drops dead code, duplicated helpers and stale comments

Browse files at this commit

2e748ef70e9a18af72120071b8fe1179fab1932cAhmet Kaan GümüşParent: 68935b0
  • refactor
    • forge-web-app drops dead code, duplicated helpers and stale comments
    • fixes: nice_max no longer overflows on huge runner rates, runner log seqs saturate, disabled alert categories clear their alerts, LFS over SSH gets a direction-scoped token, ci-job is a reserved name so no user is locked out of git over HTTP, and other verified fixes
Show full message
♻️ refactor: forge-web-app drops dead code, duplicated helpers and stale comments; fixes: nice_max no longer overflows on huge runner rates, runner log seqs saturate, disabled alert categories clear their alerts, LFS over SSH gets a direction-scoped token, ci-job is a reserved name so no user is locked out of git over HTTP, and other verified fixes

78 changed files +1598 -2440

crates/forge-core/src/names.rsmodified+1 -0
@@ -28,6 +28,7 @@ pub const RESERVED: &[&str] = &[
28 "orgs",28 "orgs",
29 "raw",29 "raw",
30 "git",30 "git",
31+ "ci-job",
31 "internal",32 "internal",
32 "help",33 "help",
33 "about",34 "about",
crates/forge-core/src/store/mod.rsmodified+13 -0
@@ -745,6 +745,19 @@ impl Store {
745 }745 }
746 }746 }
747 747
748+ pub async fn user_roles(
749+ &self,
750+ repo: &Repo,
751+ user: Option<&User>,
752+ ) -> Result<(Option<Role>, Option<Role>)> {
753+ let Some(user) = user else {
754+ return Ok((None, None));
755+ };
756+ let collaborator = self.collaborator_role(&repo.id, &user.id).await?;
757+ let org = self.org_repo_role(&repo.owner_id, &user.id, &repo.id).await?;
758+ Ok((collaborator, org))
759+ }
760+
748 /// Adds or replaces a collaborator's role on a repo.761 /// Adds or replaces a collaborator's role on a repo.
749 pub async fn set_collaborator(&self, repo_id: &str, user_id: &str, role: Role) -> Result<()> {762 pub async fn set_collaborator(&self, repo_id: &str, user_id: &str, role: Role) -> Result<()> {
750 let conn = self.inner.conn.lock().await;763 let conn = self.inner.conn.lock().await;
crates/forge-core/src/time.rsmodified+47 -2
@@ -3,7 +3,9 @@
3 use std::time::Duration;3 use std::time::Duration;
4 4
5 use time::{5 use time::{
6- OffsetDateTime, SignedDuration, format_description::FormatItem, macros::format_description,6+ OffsetDateTime, SignedDuration,
7+ format_description::{FormatItem, well_known::Rfc3339},
8+ macros::format_description,
7 };9 };
8 10
9 const FORMAT: &[FormatItem<'static>] =11 const FORMAT: &[FormatItem<'static>] =
@@ -19,6 +21,16 @@ pub fn now_stamp() -> String {
19 format_stamp(OffsetDateTime::now_utc())21 format_stamp(OffsetDateTime::now_utc())
20 }22 }
21 23
24+pub fn unix_now() -> u64 {
25+ std::time::SystemTime::now()
26+ .duration_since(std::time::UNIX_EPOCH)
27+ .map_or(0, |d| d.as_secs())
28+}
29+
30+pub fn now_unix() -> i64 {
31+ i64::try_from(unix_now()).unwrap_or(0)
32+}
33+
22 /// The stamp for `now + after`, in the same format as [`now_stamp`].34 /// The stamp for `now + after`, in the same format as [`now_stamp`].
23 /// Saturates at the maximum representable time instead of panicking.35 /// Saturates at the maximum representable time instead of panicking.
24 pub fn stamp_after(after: Duration) -> String {36 pub fn stamp_after(after: Duration) -> String {
@@ -43,15 +55,48 @@ pub fn stamp_from_unix(unix: i64) -> Option<String> {
43 55
44 /// Unix seconds for a stamp written by [`now_stamp`]. `None` when the text is not a stamp.56 /// Unix seconds for a stamp written by [`now_stamp`]. `None` when the text is not a stamp.
45 pub fn stamp_to_unix(stamp: &str) -> Option<i64> {57 pub fn stamp_to_unix(stamp: &str) -> Option<i64> {
46- OffsetDateTime::parse(stamp, &time::format_description::well_known::Rfc3339)58+ OffsetDateTime::parse(stamp, &Rfc3339)
47 .ok()59 .ok()
48 .map(OffsetDateTime::unix_timestamp)60 .map(OffsetDateTime::unix_timestamp)
49 }61 }
50 62
63+/// The shortest sleep, so a due time that has already passed does not spin a worker loop.
64+const MIN_SLEEP: Duration = Duration::from_secs(1);
65+
66+/// How long a worker sleeps: until `next_due` (an RFC 3339 stamp), clamped to
67+/// `MIN_SLEEP..=backstop`. `None` (nothing due) or an unparsable stamp gives `backstop`.
68+pub fn sleep_until(next_due: Option<&str>, now: OffsetDateTime, backstop: Duration) -> Duration {
69+ let Some(due) = next_due.and_then(|s| OffsetDateTime::parse(s, &Rfc3339).ok()) else {
70+ return backstop;
71+ };
72+ let until = Duration::try_from(due - now).unwrap_or(Duration::ZERO);
73+ until.clamp(MIN_SLEEP, backstop)
74+}
75+
51 #[cfg(test)]76 #[cfg(test)]
52 mod tests {77 mod tests {
53 use super::*;78 use super::*;
54 79
80+ #[test]
81+ fn sleep_stops_at_the_next_due_time_and_is_clamped() {
82+ use time::macros::datetime;
83+
84+ let backstop = Duration::from_secs(900);
85+ let now = datetime!(2026-10-15 12:00:00 UTC);
86+ let stamp = |t: OffsetDateTime| t.format(&Rfc3339).expect("stamp");
87+ assert_eq!(sleep_until(None, now, backstop), backstop);
88+ let in_10s = stamp(now + SignedDuration::seconds(10));
89+ assert_eq!(
90+ sleep_until(Some(&in_10s), now, backstop),
91+ Duration::from_secs(10)
92+ );
93+ let in_1h = stamp(now + SignedDuration::hours(1));
94+ assert_eq!(sleep_until(Some(&in_1h), now, backstop), backstop);
95+ let past = stamp(now - SignedDuration::seconds(5));
96+ assert_eq!(sleep_until(Some(&past), now, backstop), MIN_SLEEP);
97+ assert_eq!(sleep_until(Some("soon"), now, backstop), backstop);
98+ }
99+
55 fn is_valid_stamp(s: &str) -> bool {100 fn is_valid_stamp(s: &str) -> bool {
56 let b = s.as_bytes();101 let b = s.as_bytes();
57 b.len() == 30102 b.len() == 30
crates/forge-core/src/token.rsmodified+15 -0
@@ -39,6 +39,21 @@ pub fn hash_token(token: &str) -> String {
39 hex::encode(Sha256::digest(token.as_bytes()))39 hex::encode(Sha256::digest(token.as_bytes()))
40 }40 }
41 41
42+pub fn sha256_reader(mut reader: impl std::io::Read) -> std::io::Result<(u64, String)> {
43+ let mut hasher = Sha256::new();
44+ let mut buf = vec![0u8; 64 * 1024];
45+ let mut total = 0u64;
46+ loop {
47+ let n = reader.read(&mut buf)?;
48+ if n == 0 {
49+ break;
50+ }
51+ hasher.update(&buf[..n]);
52+ total += n as u64;
53+ }
54+ Ok((total, hex::encode(hasher.finalize())))
55+}
56+
42 /// Constant-time byte comparison.57 /// Constant-time byte comparison.
43 pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {58 pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
44 a.ct_eq(b).into()59 a.ct_eq(b).into()
crates/forge-git/src/history.rsmodified+26 -0
@@ -289,6 +289,32 @@ pub async fn count(env: &GitEnv, repo: &Path, commit: &str, path: Option<&str>)
289 .map_err(|_| Error::Failed(format!("unexpected rev-list count: {:?}", text.trim())))289 .map_err(|_| Error::Failed(format!("unexpected rev-list count: {:?}", text.trim())))
290 }290 }
291 291
292+pub async fn count_new_commits(
293+ env: &GitEnv,
294+ repo: &Path,
295+ old: Option<&str>,
296+ new: &str,
297+) -> Result<u64> {
298+ validate_oid(new)?;
299+ let exclude;
300+ let mut revs = vec![new];
301+ if let Some(old) = old {
302+ validate_oid(old)?;
303+ exclude = format!("^{old}");
304+ revs.push(&exclude);
305+ }
306+ let out = git(env, "rev-list")
307+ .git_dir(repo)
308+ .arg("--count")
309+ .user_revs(&revs)?
310+ .output()
311+ .await?;
312+ let text = String::from_utf8_lossy(&out);
313+ text.trim()
314+ .parse::<u64>()
315+ .map_err(|_| Error::Failed(format!("unexpected rev-list count: {:?}", text.trim())))
316+}
317+
292 pub async fn new_commits(318 pub async fn new_commits(
293 env: &GitEnv,319 env: &GitEnv,
294 repo: &Path,320 repo: &Path,
crates/forge-git/src/repo.rsmodified+2 -7
@@ -2,6 +2,8 @@
2 2
3 use std::path::{Path, PathBuf};3 use std::path::{Path, PathBuf};
4 4
5+use forge_core::time::unix_now;
6+
5 use crate::command::{GitCommand, GitEnv};7 use crate::command::{GitCommand, GitEnv};
6 use crate::error::{Error, Result};8 use crate::error::{Error, Result};
7 9
@@ -43,13 +45,6 @@ pub struct TrashEntry {
43 pub wiki: bool,45 pub wiki: bool,
44 }46 }
45 47
46-fn unix_now() -> u64 {
47- std::time::SystemTime::now()
48- .duration_since(std::time::UNIX_EPOCH)
49- .map(|d| d.as_secs())
50- .unwrap_or(0)
51-}
52-
53 /// Renames the bare repo for `repo_id` into `data_dir/trash/<id>-<unix_ts>.git` and returns the48 /// Renames the bare repo for `repo_id` into `data_dir/trash/<id>-<unix_ts>.git` and returns the
54 /// new path. A rename stays on one filesystem, so nothing is copied and nothing is deleted.49 /// new path. A rename stays on one filesystem, so nothing is copied and nothing is deleted.
55 /// Fails without touching anything when the repo directory is missing or the target exists.50 /// Fails without touching anything when the repo directory is missing or the target exists.
crates/forge-web-account/src/pages/admin_live_tests.rsmodified+1 -1
@@ -270,7 +270,7 @@ async fn backups_replication_health_and_server_send_for_their_changes() {
270 270
271 crate::alerts::raise(271 crate::alerts::raise(
272 &fx.state,272 &fx.state,
273- "runner_offline",273+ crate::alerts::AlertTopic::RunnerOffline,
274 "runner-offline:tahinli-ci",274 "runner-offline:tahinli-ci",
275 "tahinli-ci",275 "tahinli-ci",
276 "silent for an hour",276 "silent for an hour",
crates/forge-web-account/src/pages/settings_security.rsmodified+4 -4
@@ -19,7 +19,7 @@ use topcoat::view::{View, component, view};
19 19
20 use crate::audit::{self, Actor, Target};20 use crate::audit::{self, Actor, Target};
21 use crate::auth::{21 use crate::auth::{
22- hash_password_async, logout, require_csrf, require_user, two_factor_enabled, unix_now,22+ hash_password_async, logout, require_csrf, require_user, two_factor_enabled,
23 verify_password_async, verify_second_factor,23 verify_password_async, verify_second_factor,
24 };24 };
25 use crate::i18n::packages::{self as pk, K as PK};25 use crate::i18n::packages::{self as pk, K as PK};
@@ -906,7 +906,7 @@ async fn two_factor_confirm(cx: &Cx, Form(form): Form<EnrollForm>) -> Result<imp
906 match totp::verify(906 match totp::verify(
907 &shared,907 &shared,
908 form.code.trim(),908 form.code.trim(),
909- totp::step_for(unix_now()),909+ totp::step_for(forge_core::time::unix_now()),
910 totp_state.last_step,910 totp_state.last_step,
911 ) {911 ) {
912 Some(step) => {912 Some(step) => {
@@ -1228,7 +1228,7 @@ mod tests {
1228 }1228 }
1229 1229
1230 fn now_code(shared: &[u8]) -> String {1230 fn now_code(shared: &[u8]) -> String {
1231- totp::code_at(shared, totp::step_for(crate::auth::unix_now()))1231+ totp::code_at(shared, totp::step_for(forge_core::time::unix_now()))
1232 }1232 }
1233 1233
1234 /// Turns two-factor on directly in the store. Returns the shared secret.1234 /// Turns two-factor on directly in the store. Returns the shared secret.
@@ -1698,7 +1698,7 @@ mod tests {
1698 1698
1699 // The confirm step already used the current code, so disabling takes the next step's1699 // The confirm step already used the current code, so disabling takes the next step's
1700 // code. Reusing the current one would be refused as a replay.1700 // code. Reusing the current one would be refused as a replay.
1701- let next = totp::code_at(&shared, totp::step_for(crate::auth::unix_now()) + 1);1701+ let next = totp::code_at(&shared, totp::step_for(forge_core::time::unix_now()) + 1);
1702 let disable = format!("csrf={CSRF}&current_password={PASSWORD}&code={next}");1702 let disable = format!("csrf={CSRF}&current_password={PASSWORD}&code={next}");
1703 let reply = send(1703 let reply = send(
1704 &fx.router,1704 &fx.router,
crates/forge-web-app/build.rsmodified+1 -1
@@ -177,7 +177,7 @@ fn swatch_rules(css: &mut String) {
177 /// chips.177 /// chips.
178 fn accents_scss() -> String {178 fn accents_scss() -> String {
179 let mut css = String::from(179 let mut css = String::from(
180- "/* Generated by crates/forge-web/build.rs from forge-web-base/src/accent_palette.rs. Edit that file. */\n",180+ "/* Generated by crates/forge-web-app/build.rs from forge-web-base/src/accent_palette.rs. Edit that file. */\n",
181 );181 );
182 assert_eq!(PALETTES[0].id, DEFAULT, "the default palette comes first");182 assert_eq!(PALETTES[0].id, DEFAULT, "the default palette comes first");
183 assert_eq!(BASES[0].id, BASE_DEFAULT, "the default base comes first");183 assert_eq!(BASES[0].id, BASE_DEFAULT, "the default base comes first");
crates/forge-web-app/src/admin_client.rsmodified+3 -10
@@ -191,17 +191,10 @@ mod tests {
191 }191 }
192 192
193 #[tokio::test]193 #[tokio::test]
194- async fn no_socket_means_no_server() {194+ async fn no_server_without_a_live_socket() {
195 let dir = tempfile::tempdir().expect("tempdir");195 let dir = tempfile::tempdir().expect("tempdir");
196- let config = crate::test_support::test_config(dir.path());196+ let config = test_config(dir.path());
197 assert!(running_server(&config).await.expect("probe").is_none());197 assert!(running_server(&config).await.expect("probe").is_none());
198- }
199-
200- #[tokio::test]
201- async fn stale_socket_means_no_server() {
202- let dir = tempfile::tempdir().expect("tempdir");
203- let config = crate::test_support::test_config(dir.path());
204- // A socket file with no listener behind it, left by a crashed server.
205 let listener =198 let listener =
206 std::os::unix::net::UnixListener::bind(dir.path().join(SOCKET_FILE)).expect("bind");199 std::os::unix::net::UnixListener::bind(dir.path().join(SOCKET_FILE)).expect("bind");
207 drop(listener);200 drop(listener);
@@ -209,7 +202,7 @@ mod tests {
209 }202 }
210 203
211 /// Serves the internal router on a real unix socket, as boot does, and talks to it through204 /// Serves the internal router on a real unix socket, as boot does, and talks to it through
212- /// the client. Checks the answer, a refusal with the wrong token, and the no-server path.205+ /// the client. Checks the answer and a refusal with the wrong token.
213 #[tokio::test]206 #[tokio::test]
214 async fn client_talks_to_the_server_over_the_socket() {207 async fn client_talks_to_the_server_over_the_socket() {
215 let dir = tempfile::tempdir().expect("tempdir");208 let dir = tempfile::tempdir().expect("tempdir");
crates/forge-web-app/src/advisories/scan.rsmodified+4 -10
@@ -126,23 +126,17 @@ pub fn collect_dependencies(
126 }126 }
127 let text = match read_text_blob(repo, commit, &path, MAX_LOCKFILE_BYTES) {127 let text = match read_text_blob(repo, commit, &path, MAX_LOCKFILE_BYTES) {
128 Ok(Some(text)) => text,128 Ok(Some(text)) => text,
129- Ok(None) => continue,129+ Ok(None) => {
130- Err(e) => {130+ return Err(format!("{path}: not UTF-8 text or over the size limit"));
131- tracing::warn!(error = %e, path = %path, "advisories: lockfile unreadable");
132- continue;
133 }131 }
132+ Err(e) => return Err(format!("{path}: {e}")),
134 };133 };
135 let parsed = match entry.name.as_str() {134 let parsed = match entry.name.as_str() {
136 "Cargo.lock" => parse_cargo_lock(&text, &path),135 "Cargo.lock" => parse_cargo_lock(&text, &path),
137 "package-lock.json" => parse_package_lock(&text, &path),136 "package-lock.json" => parse_package_lock(&text, &path),
138 _ => Ok(parse_go_sum(&text, &path)),137 _ => Ok(parse_go_sum(&text, &path)),
139 };138 };
140- match parsed {139+ found.extend(parsed.map_err(|e| format!("{path}: {e}"))?);
141- Ok(deps) => found.extend(deps),
142- Err(e) => {
143- tracing::warn!(error = %e, path = %path, "advisories: lockfile skipped")
144- }
145- }
146 }140 }
147 EntryKind::Symlink | EntryKind::Submodule => {}141 EntryKind::Symlink | EntryKind::Submodule => {}
148 }142 }
crates/forge-web-app/src/alerts.rsmodified+103 -50
@@ -36,27 +36,79 @@ fn started() -> i64 {
36 *STARTED.get_or_init(now_unix)36 *STARTED.get_or_init(now_unix)
37 }37 }
38 38
39-fn kind_of(topic: &str) -> AlertKind {39+#[derive(Clone, Copy, PartialEq, Eq)]
40- match topic {40+pub enum AlertTopic {
41- "runner_offline" => AlertKind::RunnerOffline,41+ RunnerOffline,
42- "backup_failed" | "backup_verify_failed" | "backup_overdue" | "fsck_failed" => {42+ BackupFailed,
43- AlertKind::Backup43+ BackupVerifyFailed,
44+ BackupOverdue,
45+ FsckFailed,
46+ DiskLow,
47+ CiKilled,
48+ SelfUpdateRestart,
49+ SelfUpdateFailed,
50+ Replication,
51+}
52+
53+impl AlertTopic {
54+ const ALL: [Self; 10] = [
55+ Self::RunnerOffline,
56+ Self::BackupFailed,
57+ Self::BackupVerifyFailed,
58+ Self::BackupOverdue,
59+ Self::FsckFailed,
60+ Self::DiskLow,
61+ Self::CiKilled,
62+ Self::SelfUpdateRestart,
63+ Self::SelfUpdateFailed,
64+ Self::Replication,
65+ ];
66+
67+ fn as_str(self) -> &'static str {
68+ match self {
69+ Self::RunnerOffline => "runner_offline",
70+ Self::BackupFailed => "backup_failed",
71+ Self::BackupVerifyFailed => "backup_verify_failed",
72+ Self::BackupOverdue => "backup_overdue",
73+ Self::FsckFailed => "fsck_failed",
74+ Self::DiskLow => "disk_low",
75+ Self::CiKilled => "ci_killed",
76+ Self::SelfUpdateRestart => "self_update_restart",
77+ Self::SelfUpdateFailed => "self_update_failed",
78+ Self::Replication => "replication",
79+ }
80+ }
81+
82+ fn parse(stored: &str) -> Option<Self> {
83+ Self::ALL.into_iter().find(|t| t.as_str() == stored)
84+ }
85+
86+ fn kind(self) -> AlertKind {
87+ match self {
88+ Self::RunnerOffline => AlertKind::RunnerOffline,
89+ Self::BackupFailed | Self::BackupVerifyFailed | Self::BackupOverdue | Self::FsckFailed => {
90+ AlertKind::Backup
91+ }
92+ Self::DiskLow => AlertKind::Disk,
93+ Self::CiKilled => AlertKind::CiKilled,
94+ Self::SelfUpdateRestart | Self::SelfUpdateFailed => AlertKind::SelfUpdate,
95+ Self::Replication => AlertKind::Replication,
44 }96 }
45- "disk_low" => AlertKind::Disk,
46- "ci_killed" => AlertKind::CiKilled,
47- "self_update_restart" | "self_update_failed" => AlertKind::SelfUpdate,
48- _ => AlertKind::Replication,
49 }97 }
50 }98 }
51 99
52 /// Raises the alert `key` of `topic`. The admins hear about it once, until it resolves.100 /// Raises the alert `key` of `topic`. The admins hear about it once, until it resolves.
53-pub async fn raise(state: &AppState, topic: &str, key: &str, subject: &str, detail: &str) {101+pub async fn raise(state: &AppState, topic: AlertTopic, key: &str, subject: &str, detail: &str) {
54- if !state.live().alerts.kind_enabled(kind_of(topic)) {102+ if !state.live().alerts.kind_enabled(topic.kind()) {
55 return;103 return;
56 }104 }
57- match state.store.raise_alert(key, topic, subject, detail).await {105+ match state
106+ .store
107+ .raise_alert(key, topic.as_str(), subject, detail)
108+ .await
109+ {
58 Ok(true) => {110 Ok(true) => {
59- if topic == "runner_offline" {111+ if topic == AlertTopic::RunnerOffline {
60 OFFLINE_ACTIVE.store(true, Ordering::Relaxed);112 OFFLINE_ACTIVE.store(true, Ordering::Relaxed);
61 }113 }
62 deliver(state, key, topic, subject, detail, false).await;114 deliver(state, key, topic, subject, detail, false).await;
@@ -71,9 +123,12 @@ pub async fn resolve(state: &AppState, key: &str) {
71 match state.store.resolve_alert(key).await {123 match state.store.resolve_alert(key).await {
72 Ok(Some(alert)) => {124 Ok(Some(alert)) => {
73 crate::live::admin().bump(&crate::live::Topic::AdminHealth);125 crate::live::admin().bump(&crate::live::Topic::AdminHealth);
74- let kind = kind_of(&alert.kind);126+ let Some(topic) = AlertTopic::parse(&alert.kind) else {
75- if state.live().alerts.kind_enabled(kind) {127+ tracing::error!(key, kind = %alert.kind, "alerts: resolved an unknown topic");
76- deliver(state, key, &alert.kind, &alert.subject, &alert.detail, true).await;128+ return;
129+ };
130+ if state.live().alerts.kind_enabled(topic.kind()) {
131+ deliver(state, key, topic, &alert.subject, &alert.detail, true).await;
77 }132 }
78 }133 }
79 Ok(None) => {}134 Ok(None) => {}
@@ -82,13 +137,13 @@ pub async fn resolve(state: &AppState, key: &str) {
82 }137 }
83 138
84 /// Tells the admins that something happened, once per `key`.139 /// Tells the admins that something happened, once per `key`.
85-pub async fn event(state: &AppState, topic: &str, key: &str, subject: &str, detail: &str) {140+pub async fn event(state: &AppState, topic: AlertTopic, key: &str, subject: &str, detail: &str) {
86- if !state.live().alerts.kind_enabled(kind_of(topic)) {141+ if !state.live().alerts.kind_enabled(topic.kind()) {
87 return;142 return;
88 }143 }
89 match state144 match state
90 .store145 .store
91- .record_alert_event(key, topic, subject, detail)146+ .record_alert_event(key, topic.as_str(), subject, detail)
92 .await147 .await
93 {148 {
94 Ok(true) => deliver(state, key, topic, subject, detail, false).await,149 Ok(true) => deliver(state, key, topic, subject, detail, false).await,
@@ -101,7 +156,7 @@ pub async fn event(state: &AppState, topic: &str, key: &str, subject: &str, deta
101 async fn deliver(156 async fn deliver(
102 state: &AppState,157 state: &AppState,
103 key: &str,158 key: &str,
104- topic: &str,159+ topic: AlertTopic,
105 subject: &str,160 subject: &str,
106 detail: &str,161 detail: &str,
107 resolved: bool,162 resolved: bool,
@@ -121,7 +176,7 @@ async fn deliver(
121 for admin in admins.into_iter().filter(|u| !u.is_org()) {176 for admin in admins.into_iter().filter(|u| !u.is_org()) {
122 if let Err(e) = state177 if let Err(e) = state
123 .store178 .store
124- .add_admin_notice(&admin.id, key, topic, subject, detail, resolved)179+ .add_admin_notice(&admin.id, key, topic.as_str(), subject, detail, resolved)
125 .await180 .await
126 {181 {
127 tracing::error!(error = %e, key, "alerts: writing an inbox row failed");182 tracing::error!(error = %e, key, "alerts: writing an inbox row failed");
@@ -151,10 +206,10 @@ async fn deliver(
151 }206 }
152 }207 }
153 let lang = i18n::resolve(Some(admin.language.as_str()), &http::HeaderMap::new());208 let lang = i18n::resolve(Some(admin.language.as_str()), &http::HeaderMap::new());
154- let title = text::title(lang, topic, subject, resolved);209+ let title = text::title(lang, topic.as_str(), subject, resolved);
155 let body = text::mail_body(210 let body = text::mail_body(
156 lang,211 lang,
157- &text::body(lang, topic, subject, detail, resolved),212+ &text::body(lang, topic.as_str(), subject, detail, resolved),
158 &format!("{base}/admin/health"),213 &format!("{base}/admin/health"),
159 &format!("{base}/admin/server?tab=alerts"),214 &format!("{base}/admin/server?tab=alerts"),
160 );215 );
@@ -221,7 +276,7 @@ pub async fn job_ended(
221 let detail = format!("job {} of run {}", job.name, job.run_id);276 let detail = format!("job {} of run {}", job.name, job.run_id);
222 event(277 event(
223 state,278 state,
224- "ci_killed",279+ AlertTopic::CiKilled,
225 &format!("ci_killed:{}", job.run_id),280 &format!("ci_killed:{}", job.run_id),
226 &runner,281 &runner,
227 &detail,282 &detail,
@@ -239,11 +294,11 @@ pub async fn backup_finished(state: &AppState, outcome: Result<(), &str>) {
239 }294 }
240 Err(error) => {295 Err(error) => {
241 let topic = if error.contains("failed verification") {296 let topic = if error.contains("failed verification") {
242- "backup_verify_failed"297+ AlertTopic::BackupVerifyFailed
243 } else {298 } else {
244- "backup_failed"299+ AlertTopic::BackupFailed
245 };300 };
246- raise(state, topic, topic, "", error).await;301+ raise(state, topic, topic.as_str(), "", error).await;
247 }302 }
248 }303 }
249 }304 }
@@ -252,7 +307,7 @@ pub async fn backup_finished(state: &AppState, outcome: Result<(), &str>) {
252 pub async fn fsck_finished(state: &AppState, outcome: Result<(), &str>) {307 pub async fn fsck_finished(state: &AppState, outcome: Result<(), &str>) {
253 match outcome {308 match outcome {
254 Ok(()) => resolve(state, "fsck_failed").await,309 Ok(()) => resolve(state, "fsck_failed").await,
255- Err(error) => raise(state, "fsck_failed", "fsck_failed", "", error).await,310+ Err(error) => raise(state, AlertTopic::FsckFailed, "fsck_failed", "", error).await,
256 }311 }
257 }312 }
258 313
@@ -260,7 +315,7 @@ pub async fn fsck_finished(state: &AppState, outcome: Result<(), &str>) {
260 pub async fn self_update_deployed(state: &AppState, version: &str) {315 pub async fn self_update_deployed(state: &AppState, version: &str) {
261 raise(316 raise(
262 state,317 state,
263- "self_update_restart",318+ AlertTopic::SelfUpdateRestart,
264 "self_update_restart",319 "self_update_restart",
265 version,320 version,
266 "",321 "",
@@ -272,7 +327,7 @@ pub async fn self_update_deployed(state: &AppState, version: &str) {
272 pub async fn self_update_failed(state: &AppState, run_id: &str, error: &str) {327 pub async fn self_update_failed(state: &AppState, run_id: &str, error: &str) {
273 event(328 event(
274 state,329 state,
275- "self_update_failed",330+ AlertTopic::SelfUpdateFailed,
276 &format!("self_update_failed:{run_id}"),331 &format!("self_update_failed:{run_id}"),
277 "",332 "",
278 error,333 error,
@@ -297,7 +352,7 @@ pub async fn on_boot(state: &AppState) {
297 deliver(352 deliver(
298 state,353 state,
299 "self_update_restart",354 "self_update_restart",
300- "self_update_restart",355+ AlertTopic::SelfUpdateRestart,
301 &version,356 &version,
302 "",357 "",
303 true,358 true,
@@ -311,12 +366,7 @@ pub async fn on_boot(state: &AppState) {
311 366
312 /// Raises an alert for each runner silent for longer than the configured minutes and resolves the367 /// Raises an alert for each runner silent for longer than the configured minutes and resolves the
313 /// ones that are not any more. Runs on every CI reaper pass: one query.368 /// ones that are not any more. Runs on every CI reaper pass: one query.
314-pub async fn check_runners(state: &AppState) {369+pub async fn check_runners(state: &AppState, now: i64) {
315- check_runners_at(state, now_unix()).await;
316-}
317-
318-/// [`check_runners`] with an explicit clock.
319-pub async fn check_runners_at(state: &AppState, now: i64) {
320 let live = state.live();370 let live = state.live();
321 let cfg = &live.alerts;371 let cfg = &live.alerts;
322 let runners = match state.store.list_runners().await {372 let runners = match state.store.list_runners().await {
@@ -347,7 +397,7 @@ pub async fn check_runners_at(state: &AppState, now: i64) {
347 let key = format!("runner_offline:{}", runner.id);397 let key = format!("runner_offline:{}", runner.id);
348 offline.insert(key.clone());398 offline.insert(key.clone());
349 let since = seen.map_or_else(String::new, |t| forge_core::tz::format_in_tz(t, "UTC"));399 let since = seen.map_or_else(String::new, |t| forge_core::tz::format_in_tz(t, "UTC"));
350- raise(state, "runner_offline", &key, &runner.name, &since).await;400+ raise(state, AlertTopic::RunnerOffline, &key, &runner.name, &since).await;
351 }401 }
352 // Whatever is active but no longer offline (back, disabled or deleted) is resolved.402 // Whatever is active but no longer offline (back, disabled or deleted) is resolved.
353 match state.store.active_alert_keys("runner_offline").await {403 match state.store.active_alert_keys("runner_offline").await {
@@ -388,6 +438,7 @@ async fn check_disk(state: &AppState) {
388 let live = state.live();438 let live = state.live();
389 let cfg = &live.alerts;439 let cfg = &live.alerts;
390 if !cfg.kind_enabled(AlertKind::Disk) {440 if !cfg.kind_enabled(AlertKind::Disk) {
441+ resolve(state, "disk_low").await;
391 return;442 return;
392 }443 }
393 let dir = live.data_dir.clone();444 let dir = live.data_dir.clone();
@@ -410,7 +461,7 @@ async fn check_disk(state: &AppState) {
410 );461 );
411 raise(462 raise(
412 state,463 state,
413- "disk_low",464+ AlertTopic::DiskLow,
414 "disk_low",465 "disk_low",
415 &dir.to_string_lossy(),466 &dir.to_string_lossy(),
416 &detail,467 &detail,
@@ -424,6 +475,7 @@ async fn check_disk(state: &AppState) {
424 async fn check_backup_overdue(state: &AppState, now: i64) {475 async fn check_backup_overdue(state: &AppState, now: i64) {
425 let live = state.live();476 let live = state.live();
426 if !live.backup.enabled() || !live.alerts.kind_enabled(AlertKind::Backup) {477 if !live.backup.enabled() || !live.alerts.kind_enabled(AlertKind::Backup) {
478+ resolve(state, "backup_overdue").await;
427 return;479 return;
428 }480 }
429 let last_ok = match state.store.last_ok(RunKind::Backup).await {481 let last_ok = match state.store.last_ok(RunKind::Backup).await {
@@ -439,7 +491,7 @@ async fn check_backup_overdue(state: &AppState, now: i64) {
439 || "never".to_owned(),491 || "never".to_owned(),
440 |t| forge_core::tz::format_in_tz(t, "UTC"),492 |t| forge_core::tz::format_in_tz(t, "UTC"),
441 );493 );
442- raise(state, "backup_overdue", "backup_overdue", "", &detail).await;494+ raise(state, AlertTopic::BackupOverdue, "backup_overdue", "", &detail).await;
443 } else {495 } else {
444 resolve(state, "backup_overdue").await;496 resolve(state, "backup_overdue").await;
445 }497 }
@@ -448,6 +500,7 @@ async fn check_backup_overdue(state: &AppState, now: i64) {
448 async fn check_replication(state: &AppState, now: i64) {500 async fn check_replication(state: &AppState, now: i64) {
449 let live = state.live();501 let live = state.live();
450 if !live.replication.enabled() || !live.alerts.kind_enabled(AlertKind::Replication) {502 if !live.replication.enabled() || !live.alerts.kind_enabled(AlertKind::Replication) {
503+ resolve(state, "replication").await;
451 return;504 return;
452 }505 }
453 let rows = match state.store.list_replication_status().await {506 let rows = match state.store.list_replication_status().await {
@@ -474,7 +527,7 @@ async fn check_replication(state: &AppState, now: i64) {
474 }527 }
475 }528 }
476 match problem {529 match problem {
477- Some(detail) => raise(state, "replication", "replication", "", &detail).await,530+ Some(detail) => raise(state, AlertTopic::Replication, "replication", "", &detail).await,
478 None => resolve(state, "replication").await,531 None => resolve(state, "replication").await,
479 }532 }
480 }533 }
@@ -533,8 +586,8 @@ mod tests {
533 let tahinli = admin(&state, "tahinli", true).await;586 let tahinli = admin(&state, "tahinli", true).await;
534 let second = admin(&state, "tahinli2", false).await;587 let second = admin(&state, "tahinli2", false).await;
535 588
536- raise(&state, "disk_low", "disk_low", "/data", "4% free").await;589+ raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "4% free").await;
537- raise(&state, "disk_low", "disk_low", "/data", "3% free").await;590+ raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "3% free").await;
538 assert_eq!(inbox(&state, &tahinli).await.len(), 1, "deduplicated");591 assert_eq!(inbox(&state, &tahinli).await.len(), 1, "deduplicated");
539 assert_eq!(inbox(&state, &second).await.len(), 1);592 assert_eq!(inbox(&state, &second).await.len(), 1);
540 assert_eq!(state.store.active_alerts().await.unwrap().len(), 1);593 assert_eq!(state.store.active_alerts().await.unwrap().len(), 1);
@@ -553,7 +606,7 @@ mod tests {
553 assert_eq!(queued_mail(&state).await, 2);606 assert_eq!(queued_mail(&state).await, 2);
554 assert_eq!(state.store.unread_count(&tahinli).await.unwrap(), 2);607 assert_eq!(state.store.unread_count(&tahinli).await.unwrap(), 2);
555 608
556- raise(&state, "disk_low", "disk_low", "/data", "2% free").await;609+ raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "2% free").await;
557 assert_eq!(610 assert_eq!(
558 inbox(&state, &tahinli).await.len(),611 inbox(&state, &tahinli).await.len(),
559 3,612 3,
@@ -569,19 +622,19 @@ mod tests {
569 let mut config = (*state.config).clone();622 let mut config = (*state.config).clone();
570 config.alerts.on_disk = false;623 config.alerts.on_disk = false;
571 state.set_config(config.clone());624 state.set_config(config.clone());
572- raise(&state, "disk_low", "disk_low", "/data", "4% free").await;625+ raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "4% free").await;
573 assert!(inbox(&state, &tahinli).await.is_empty());626 assert!(inbox(&state, &tahinli).await.is_empty());
574 627
575 config.alerts.on_disk = true;628 config.alerts.on_disk = true;
576 config.alerts.email = false;629 config.alerts.email = false;
577 state.set_config(config.clone());630 state.set_config(config.clone());
578- raise(&state, "disk_low", "disk_low", "/data", "4% free").await;631+ raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "4% free").await;
579 assert_eq!(inbox(&state, &tahinli).await.len(), 1);632 assert_eq!(inbox(&state, &tahinli).await.len(), 1);
580 assert_eq!(queued_mail(&state).await, 0);633 assert_eq!(queued_mail(&state).await, 0);
581 634
582 config.alerts.enabled = false;635 config.alerts.enabled = false;
583 state.set_config(config);636 state.set_config(config);
584- raise(&state, "backup_failed", "backup_failed", "", "boom").await;637+ raise(&state, AlertTopic::BackupFailed, "backup_failed", "", "boom").await;
585 assert_eq!(638 assert_eq!(
586 inbox(&state, &tahinli).await.len(),639 inbox(&state, &tahinli).await.len(),
587 1,640 1,
@@ -608,12 +661,12 @@ mod tests {
608 state.store.runner_by_secret(&secret).await.unwrap();661 state.store.runner_by_secret(&secret).await.unwrap();
609 662
610 let now = now_unix();663 let now = now_unix();
611- check_runners_at(&state, now).await;664+ check_runners(&state, now).await;
612 assert!(inbox(&state, &tahinli).await.is_empty(), "fresh heartbeat");665 assert!(inbox(&state, &tahinli).await.is_empty(), "fresh heartbeat");
613 666
614 // Eleven minutes of silence on a fake clock (the default is ten).667 // Eleven minutes of silence on a fake clock (the default is ten).
615- check_runners_at(&state, now + 11 * 60).await;668+ check_runners(&state, now + 11 * 60).await;
616- check_runners_at(&state, now + 12 * 60).await;669+ check_runners(&state, now + 12 * 60).await;
617 let rows = inbox(&state, &tahinli).await;670 let rows = inbox(&state, &tahinli).await;
618 assert_eq!(rows.len(), 1, "told once");671 assert_eq!(rows.len(), 1, "told once");
619 assert_eq!(rows[0].subject, "tahinli-ci");672 assert_eq!(rows[0].subject, "tahinli-ci");
crates/forge-web-app/src/api/gitea.rsmodified+156 -168
@@ -222,6 +222,10 @@ fn internal(e: impl std::fmt::Display) -> Refusal {
222 api::internal(e)222 api::internal(e)
223 }223 }
224 224
225+fn respond(result: Result<Response, Refusal>) -> topcoat::Result<Response> {
226+ Ok(result.unwrap_or_else(|res| *res))
227+}
228+
225 #[route(GET "/api/v1/version")]229 #[route(GET "/api/v1/version")]
226 async fn version_route(cx: &Cx) -> topcoat::Result<Response> {230 async fn version_route(cx: &Cx) -> topcoat::Result<Response> {
227 Ok(api::json(231 Ok(api::json(
@@ -480,7 +484,7 @@ fn filter_of(cx: &Cx, pg: &Paging) -> Result<IssueFilter, Refusal> {
480 Ok(IssueFilter {484 Ok(IssueFilter {
481 state: state_filter(cx)?,485 state: state_filter(cx)?,
482 sort: IssueSort::Oldest,486 sort: IssueSort::Oldest,
483- page: pg.page as u32,487+ page: u32::try_from(pg.page).unwrap_or(u32::MAX),
484 per_page: pg.limit as u32,488 per_page: pg.limit as u32,
485 ..IssueFilter::default()489 ..IssueFilter::default()
486 })490 })
@@ -565,34 +569,31 @@ fn comment_json(
565 569
566 #[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/comments")]570 #[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/comments")]
567 async fn issue_comments(cx: &Cx) -> topcoat::Result<Response> {571 async fn issue_comments(cx: &Cx) -> topcoat::Result<Response> {
572+ respond(issue_comments_inner(cx).await)
573+}
574+
575+async fn issue_comments_inner(cx: &Cx) -> Result<Response, Refusal> {
568 let state = context::<AppState>(cx);576 let state = context::<AppState>(cx);
569- let ctx = match read_ctx(cx).await {577+ let ctx = read_ctx(cx).await?;
570- Ok(ctx) => ctx,578+ let issue = issue_row(state, &ctx.repo, index(cx)).await?;
571- Err(res) => return Ok(*res),579+ let all = state
572- };580+ .store
573- let result: Result<Response, Refusal> = async {581+ .list_comments(&issue.id)
574- let issue = issue_row(state, &ctx.repo, index(cx)).await?;582+ .await
575- let all = state583+ .map_err(internal)?;
576- .store584+ let numbered: Vec<(usize, Comment)> = all.into_iter().enumerate().collect();
577- .list_comments(&issue.id)585+ let pg = paging(cx, DEFAULT_PAGE);
578- .await586+ let (page, total) = slice(numbered, &pg);
579- .map_err(internal)?;587+ let authors = names(
580- let numbered: Vec<(usize, Comment)> = all.into_iter().enumerate().collect();588+ state,
581- let pg = paging(cx, DEFAULT_PAGE);589+ page.iter().map(|(_, c)| c.author_id.clone()).collect(),
582- let (page, total) = slice(numbered, &pg);590+ )
583- let authors = names(591+ .await?;
584- state,592+ let items = page
585- page.iter().map(|(_, c)| c.author_id.clone()).collect(),593+ .iter()
586- )594+ .map(|(pos, c)| comment_json(&ctx, issue.number, *pos, c, &authors))
587- .await?;595+ .collect();
588- let items = page596+ Ok(page_response(cx, items, total, &pg))
589- .iter()
590- .map(|(pos, c)| comment_json(&ctx, issue.number, *pos, c, &authors))
591- .collect();
592- Ok(page_response(cx, items, total, &pg))
593- }
594- .await;
595- Ok(result.unwrap_or_else(|res| *res))
596 }597 }
597 598
598 /// Reactions of one target as the Gitea list. Forge keeps the first ten users per emoji.599 /// Reactions of one target as the Gitea list. Forge keeps the first ten users per emoji.
@@ -611,12 +612,16 @@ async fn reactions_json(
611 let mut out = Vec::new();612 let mut out = Vec::new();
612 for summary in map.get(target_id).into_iter().flatten() {613 for summary in map.get(target_id).into_iter().flatten() {
613 for username in &summary.users {614 for username in &summary.users {
614- let id = match state.store.user_by_username(username).await {615+ let Some(user) = state
615- Ok(Some(user)) => user.id,616+ .store
616- _ => continue,617+ .user_by_username(username)
618+ .await
619+ .map_err(internal)?
620+ else {
621+ continue;
617 };622 };
618 out.push(json!({623 out.push(json!({
619- "user": user_json(&ctx.base, &id, username),624+ "user": user_json(&ctx.base, &user.id, username),
620 "reaction": summary.reaction.name(),625 "reaction": summary.reaction.name(),
621 "created_at": created_at,626 "created_at": created_at,
622 }));627 }));
@@ -627,63 +632,56 @@ async fn reactions_json(
627 632
628 #[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/reactions")]633 #[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/reactions")]
629 async fn issue_reactions(cx: &Cx) -> topcoat::Result<Response> {634 async fn issue_reactions(cx: &Cx) -> topcoat::Result<Response> {
635+ respond(issue_reactions_inner(cx).await)
636+}
637+
638+async fn issue_reactions_inner(cx: &Cx) -> Result<Response, Refusal> {
630 let state = context::<AppState>(cx);639 let state = context::<AppState>(cx);
631- let ctx = match read_ctx(cx).await {640+ let ctx = read_ctx(cx).await?;
632- Ok(ctx) => ctx,641+ let issue = issue_row(state, &ctx.repo, index(cx)).await?;
633- Err(res) => return Ok(*res),642+ let all = reactions_json(
634- };643+ state,
635- let result: Result<Response, Refusal> = async {644+ &ctx,
636- let issue = issue_row(state, &ctx.repo, index(cx)).await?;645+ ReactionTarget::Issue,
637- let all = reactions_json(646+ &issue.id,
638- state,647+ &issue.created_at,
639- &ctx,648+ )
640- ReactionTarget::Issue,649+ .await?;
641- &issue.id,650+ let pg = paging(cx, 1000);
642- &issue.created_at,651+ let (page, total) = slice(all, &pg);
643- )652+ Ok(page_response(cx, page, total, &pg))
644- .await?;
645- let pg = paging(cx, 1000);
646- let (page, total) = slice(all, &pg);
647- Ok(page_response(cx, page, total, &pg))
648- }
649- .await;
650- Ok(result.unwrap_or_else(|res| *res))
651 }653 }
652 654
653 #[route(GET "/api/v1/repos/{owner}/{repo}/issues/comments/{id}/reactions")]655 #[route(GET "/api/v1/repos/{owner}/{repo}/issues/comments/{id}/reactions")]
654 async fn comment_reactions(cx: &Cx) -> topcoat::Result<Response> {656 async fn comment_reactions(cx: &Cx) -> topcoat::Result<Response> {
657+ respond(comment_reactions_inner(cx).await)
658+}
659+
660+async fn comment_reactions_inner(cx: &Cx) -> Result<Response, Refusal> {
655 let state = context::<AppState>(cx);661 let state = context::<AppState>(cx);
656- let ctx = match read_ctx(cx).await {662+ let ctx = read_ctx(cx).await?;
657- Ok(ctx) => ctx,663+ let id: i64 = id(cx).parse().map_err(|_| bad("invalid comment id"))?;
658- Err(res) => return Ok(*res),664+ let (number, position) = split_comment_id(id).ok_or_else(|| not_found("comment not found"))?;
659- };665+ let issue = issue_row(state, &ctx.repo, &number.to_string()).await?;
660- let result: Result<Response, Refusal> = async {666+ let all = state
661- let id: i64 = id(cx).parse().map_err(|_| bad("invalid comment id"))?;667+ .store
662- let (number, position) =668+ .list_comments(&issue.id)
663- split_comment_id(id).ok_or_else(|| not_found("comment not found"))?;669+ .await
664- let issue = issue_row(state, &ctx.repo, &number.to_string()).await?;670+ .map_err(internal)?;
665- let all = state671+ let comment = all
666- .store672+ .get(position)
667- .list_comments(&issue.id)673+ .ok_or_else(|| not_found("comment not found"))?;
668- .await674+ let items = reactions_json(
669- .map_err(internal)?;675+ state,
670- let comment = all676+ &ctx,
671- .get(position)677+ ReactionTarget::Comment,
672- .ok_or_else(|| not_found("comment not found"))?;678+ &comment.id,
673- let items = reactions_json(679+ &comment.created_at,
674- state,680+ )
675- &ctx,681+ .await?;
676- ReactionTarget::Comment,682+ let pg = paging(cx, 1000);
677- &comment.id,683+ let (page, total) = slice(items, &pg);
678- &comment.created_at,684+ Ok(page_response(cx, page, total, &pg))
679- )
680- .await?;
681- let pg = paging(cx, 1000);
682- let (page, total) = slice(items, &pg);
683- Ok(page_response(cx, page, total, &pg))
684- }
685- .await;
686- Ok(result.unwrap_or_else(|res| *res))
687 }685 }
688 686
689 fn pr_branch(687 fn pr_branch(
@@ -794,36 +792,33 @@ async fn pull_json(
794 792
795 #[route(GET "/api/v1/repos/{owner}/{repo}/pulls")]793 #[route(GET "/api/v1/repos/{owner}/{repo}/pulls")]
796 async fn list_pulls_route(cx: &Cx) -> topcoat::Result<Response> {794 async fn list_pulls_route(cx: &Cx) -> topcoat::Result<Response> {
795+ respond(list_pulls_inner(cx).await)
796+}
797+
798+async fn list_pulls_inner(cx: &Cx) -> Result<Response, Refusal> {
797 let state = context::<AppState>(cx);799 let state = context::<AppState>(cx);
798- let ctx = match read_ctx(cx).await {800+ let ctx = read_ctx(cx).await?;
799- Ok(ctx) => ctx,801+ let pg = paging(cx, DEFAULT_PAGE);
800- Err(res) => return Ok(*res),802+ let filter = filter_of(cx, &pg)?;
801- };803+ let (rows, total) = state
802- let result: Result<Response, Refusal> = async {804+ .store
803- let pg = paging(cx, DEFAULT_PAGE);805+ .list_pulls(&ctx.repo.id, &filter)
804- let filter = filter_of(cx, &pg)?;806+ .await
805- let (rows, total) = state807+ .map_err(internal)?;
808+ let milestones = milestone_map(state, &ctx.repo).await?;
809+ let mut out = Vec::with_capacity(rows.len());
810+ for item in &rows {
811+ let Some(pull) = state
806 .store812 .store
807- .list_pulls(&ctx.repo.id, &filter)813+ .pull_by_number(&ctx.repo.id, item.issue.number)
808 .await814 .await
809- .map_err(internal)?;815+ .map_err(internal)?
810- let milestones = milestone_map(state, &ctx.repo).await?;816+ else {
811- let mut out = Vec::with_capacity(rows.len());817+ continue;
812- for item in &rows {818+ };
813- let Some(pull) = state819+ out.push(pull_json(state, &ctx, item, &pull, &milestones).await?);
814- .store
815- .pull_by_number(&ctx.repo.id, item.issue.number)
816- .await
817- .map_err(internal)?
818- else {
819- continue;
820- };
821- out.push(pull_json(state, &ctx, item, &pull, &milestones).await?);
822- }
823- Ok(page_response(cx, out, total as usize, &pg))
824 }820 }
825- .await;821+ Ok(page_response(cx, out, total as usize, &pg))
826- Ok(result.unwrap_or_else(|res| *res))
827 }822 }
828 823
829 /// The review state as Forgejo's uploader reads it (`CHANGES_REQUESTED`, `COMMENTED`). The Go SDK824 /// The review state as Forgejo's uploader reads it (`CHANGES_REQUESTED`, `COMMENTED`). The Go SDK
@@ -884,32 +879,29 @@ async fn review_comments(state: &AppState, issue_id: &str) -> Result<Vec<ReviewC
884 879
885 #[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews")]880 #[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews")]
886 async fn pull_reviews(cx: &Cx) -> topcoat::Result<Response> {881 async fn pull_reviews(cx: &Cx) -> topcoat::Result<Response> {
882+ respond(pull_reviews_inner(cx).await)
883+}
884+
885+async fn pull_reviews_inner(cx: &Cx) -> Result<Response, Refusal> {
887 let state = context::<AppState>(cx);886 let state = context::<AppState>(cx);
888- let ctx = match read_ctx(cx).await {887+ let ctx = read_ctx(cx).await?;
889- Ok(ctx) => ctx,888+ let issue = pull_issue(state, &ctx.repo, index(cx)).await?;
890- Err(res) => return Ok(*res),889+ let reviews = state
891- };890+ .store
892- let result: Result<Response, Refusal> = async {891+ .list_reviews(&issue.id)
893- let issue = pull_issue(state, &ctx.repo, index(cx)).await?;892+ .await
894- let reviews = state893+ .map_err(internal)?;
895- .store894+ let comments = review_comments(state, &issue.id).await?;
896- .list_reviews(&issue.id)895+ let pg = paging(cx, DEFAULT_PAGE);
897- .await896+ let (page, total) = slice(reviews, &pg);
898- .map_err(internal)?;897+ let items = page
899- let comments = review_comments(state, &issue.id).await?;898+ .iter()
900- let pg = paging(cx, DEFAULT_PAGE);899+ .map(|r| {
901- let (page, total) = slice(reviews, &pg);900+ let count = comments.iter().filter(|c| c.review_id == r.id).count();
902- let items = page901+ review_json(&ctx, issue.number, r, count)
903- .iter()902+ })
904- .map(|r| {903+ .collect();
905- let count = comments.iter().filter(|c| c.review_id == r.id).count();904+ Ok(page_response(cx, items, total, &pg))
906- review_json(&ctx, issue.number, r, count)
907- })
908- .collect();
909- Ok(page_response(cx, items, total, &pg))
910- }
911- .await;
912- Ok(result.unwrap_or_else(|res| *res))
913 }905 }
914 906
915 /// The issue row of a number that must be a pull request.907 /// The issue row of a number that must be a pull request.
@@ -958,40 +950,36 @@ fn review_comment_json(ctx: &Ctx, number: i64, c: &ReviewComment) -> Value {
958 950
959 #[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews/{review_id}/comments")]951 #[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews/{review_id}/comments")]
960 async fn pull_review_comments(cx: &Cx) -> topcoat::Result<Response> {952 async fn pull_review_comments(cx: &Cx) -> topcoat::Result<Response> {
953+ respond(pull_review_comments_inner(cx).await)
954+}
955+
956+async fn pull_review_comments_inner(cx: &Cx) -> Result<Response, Refusal> {
961 let state = context::<AppState>(cx);957 let state = context::<AppState>(cx);
962- let ctx = match read_ctx(cx).await {958+ let ctx = read_ctx(cx).await?;
963- Ok(ctx) => ctx,959+ let issue = pull_issue(state, &ctx.repo, index(cx)).await?;
964- Err(res) => return Ok(*res),960+ let raw = review_id(cx);
961+ let reviews = state
962+ .store
963+ .list_reviews(&issue.id)
964+ .await
965+ .map_err(internal)?;
966+ let review = reviews
967+ .iter()
968+ .find(|r| r.id == raw || (is_numeric(raw) && raw.parse() == Ok(numeric_id(&r.id))))
969+ .ok_or_else(|| not_found("review not found"))?;
970+ let own: Vec<ReviewComment> = review_comments(state, &issue.id)
971+ .await?
972+ .into_iter()
973+ .filter(|c| c.review_id == review.id)
974+ .collect();
975+ let items = own
976+ .iter()
977+ .map(|c| review_comment_json(&ctx, issue.number, c))
978+ .collect::<Vec<_>>();
979+ let total = items.len();
980+ let pg = Paging {
981+ page: 1,
982+ limit: total.max(1),
965 };983 };
966- let result: Result<Response, Refusal> = async {984+ Ok(page_response(cx, items, total, &pg))
967- let issue = pull_issue(state, &ctx.repo, index(cx)).await?;
968- let raw = review_id(cx);
969- let reviews = state
970- .store
971- .list_reviews(&issue.id)
972- .await
973- .map_err(internal)?;
974- let review = reviews
975- .iter()
976- .find(|r| r.id == raw || (is_numeric(raw) && raw.parse() == Ok(numeric_id(&r.id))))
977- .ok_or_else(|| not_found("review not found"))?;
978- let own: Vec<ReviewComment> = review_comments(state, &issue.id)
979- .await?
980- .into_iter()
981- .filter(|c| c.review_id == review.id)
982- .collect();
983- let items = own
984- .iter()
985- .map(|c| review_comment_json(&ctx, issue.number, c))
986- .collect::<Vec<_>>();
987- let total = items.len();
988- // Review comments are not paged by the downloader; return them whole.
989- let pg = Paging {
990- page: 1,
991- limit: total.max(1),
992- };
993- Ok(page_response(cx, items, total, &pg))
994- }
995- .await;
996- Ok(result.unwrap_or_else(|res| *res))
997 }985 }
crates/forge-web-app/src/api/mod.rsmodified+37 -19
@@ -18,7 +18,7 @@ use forge_core::{Action, Denied, Repo, User, authorize, token::hash_token};
18 use forge_git::browse;18 use forge_git::browse;
19 use http::HeaderMap;19 use http::HeaderMap;
20 use http::header::{AUTHORIZATION, CONTENT_TYPE, HeaderValue, RETRY_AFTER, WWW_AUTHENTICATE};20 use http::header::{AUTHORIZATION, CONTENT_TYPE, HeaderValue, RETRY_AFTER, WWW_AUTHENTICATE};
21-use serde_json::{Value, json};21+use serde_json::json;
22 use topcoat::router::StatusCode;22 use topcoat::router::StatusCode;
23 use topcoat::router::response::Response;23 use topcoat::router::response::Response;
24 24
@@ -31,9 +31,10 @@ pub const REPO_SCOPE: &str = "repo";
31 /// A failed step. The response is boxed, as in git_http, to keep `Result` small.31 /// A failed step. The response is boxed, as in git_http, to keep `Result` small.
32 pub type Refusal = Box<Response>;32 pub type Refusal = Box<Response>;
33 33
34-/// Builds a JSON response with the given status.34+pub fn json<T: serde::Serialize + ?Sized>(status: StatusCode, value: &T) -> Response {
35-pub fn json(status: StatusCode, value: &Value) -> Response {35+ let mut res = Response::new(topcoat::router::Body::from(
36- let mut res = Response::new(topcoat::router::Body::from(value.to_string()));36+ serde_json::to_string(value).unwrap_or_default(),
37+ ));
37 *res.status_mut() = status;38 *res.status_mut() = status;
38 res.headers_mut().insert(39 res.headers_mut().insert(
39 CONTENT_TYPE,40 CONTENT_TYPE,
@@ -185,25 +186,29 @@ pub async fn load_repo(
185 Ok(None) => return Err(refused(actor, Denied::NotFound)),186 Ok(None) => return Err(refused(actor, Denied::NotFound)),
186 Err(e) => return Err(internal(e)),187 Err(e) => return Err(internal(e)),
187 };188 };
188- let (role, org_role) = match actor {189+ let (role, org_role) = state
189- Some(user) => (190+ .store
190- state191+ .user_roles(&repo, actor)
191- .store192+ .await
192- .collaborator_role(&repo.id, &user.id)193+ .map_err(internal)?;
193- .await
194- .map_err(internal)?,
195- state
196- .store
197- .org_repo_role(&repo.owner_id, &user.id, &repo.id)
198- .await
199- .map_err(internal)?,
200- ),
201- None => (None, None),
202- };
203 authorize(actor, &repo, role, org_role, action).map_err(|denied| refused(actor, denied))?;194 authorize(actor, &repo, role, org_role, action).map_err(|denied| refused(actor, denied))?;
204 Ok(repo)195 Ok(repo)
205 }196 }
206 197
198+pub async fn load_writer(
199+ state: &AppState,
200+ ip: IpAddr,
201+ headers: &HeaderMap,
202+ owner: &str,
203+ name: &str,
204+) -> Result<(Repo, User), Refusal> {
205+ let Some(user) = authenticate(state, ip, headers).await? else {
206+ return Err(Box::new(unauthorized()));
207+ };
208+ let repo = load_repo(state, Some(&user), owner, name, Action::Write).await?;
209+ Ok((repo, user))
210+}
211+
207 /// On-disk path of a repo's bare directory.212 /// On-disk path of a repo's bare directory.
208 pub fn repo_dir(state: &AppState, repo: &Repo) -> Result<PathBuf, Refusal> {213 pub fn repo_dir(state: &AppState, repo: &Repo) -> Result<PathBuf, Refusal> {
209 forge_git::repo::repo_path(&state.config.data_dir, &repo.id).map_err(internal)214 forge_git::repo::repo_path(&state.config.data_dir, &repo.id).map_err(internal)
@@ -237,6 +242,19 @@ pub async fn read_body(body: topcoat::router::Body, limit: usize) -> Result<Vec<
237 })242 })
238 }243 }
239 244
245+pub async fn json_body<T: serde::de::DeserializeOwned>(
246+ body: topcoat::router::Body,
247+ limit: usize,
248+) -> Result<T, Refusal> {
249+ let bytes = read_body(body, limit).await?;
250+ serde_json::from_slice(&bytes).map_err(|e| {
251+ Box::new(error(
252+ StatusCode::BAD_REQUEST,
253+ &format!("invalid JSON body: {e}"),
254+ ))
255+ })
256+}
257+
240 #[cfg(test)]258 #[cfg(test)]
241 mod tests {259 mod tests {
242 use super::*;260 use super::*;
crates/forge-web-app/src/api/packages.rsmodified+14 -16
@@ -128,6 +128,16 @@ async fn owner_of(cx: &Cx) -> Result<User, Refusal> {
128 }128 }
129 }129 }
130 130
131+async fn writer(cx: &Cx) -> Result<User, Refusal> {
132+ match caller(cx, true).await? {
133+ Some(user) => Ok(user),
134+ None => Err(Box::new(cargo_error(
135+ StatusCode::UNAUTHORIZED,
136+ "authentication required",
137+ ))),
138+ }
139+}
140+
131 #[route(GET "/api/packages/{owner}/cargo/config.json")]141 #[route(GET "/api/packages/{owner}/cargo/config.json")]
132 async fn config(cx: &Cx) -> topcoat::Result<Response> {142 async fn config(cx: &Cx) -> topcoat::Result<Response> {
133 let state = context::<AppState>(cx);143 let state = context::<AppState>(cx);
@@ -218,14 +228,8 @@ async fn download(cx: &Cx) -> topcoat::Result<Response> {
218 #[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/new")]228 #[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/new")]
219 async fn publish(cx: &Cx, body: Body) -> topcoat::Result<Response> {229 async fn publish(cx: &Cx, body: Body) -> topcoat::Result<Response> {
220 let state = context::<AppState>(cx);230 let state = context::<AppState>(cx);
221- let actor = match caller(cx, true).await {231+ let actor = match writer(cx).await {
222- Ok(Some(actor)) => actor,232+ Ok(actor) => actor,
223- Ok(None) => {
224- return Ok(cargo_error(
225- StatusCode::UNAUTHORIZED,
226- "authentication required",
227- ));
228- }
229 Err(res) => return Ok(*res),233 Err(res) => return Ok(*res),
230 };234 };
231 let owner = match owner_of(cx).await {235 let owner = match owner_of(cx).await {
@@ -263,14 +267,8 @@ async fn unyank(cx: &Cx) -> topcoat::Result<Response> {
263 267
264 async fn set_yank(cx: &Cx, yanked: bool) -> topcoat::Result<Response> {268 async fn set_yank(cx: &Cx, yanked: bool) -> topcoat::Result<Response> {
265 let state = context::<AppState>(cx);269 let state = context::<AppState>(cx);
266- let actor = match caller(cx, true).await {270+ let actor = match writer(cx).await {
267- Ok(Some(actor)) => actor,271+ Ok(actor) => actor,
268- Ok(None) => {
269- return Ok(cargo_error(
270- StatusCode::UNAUTHORIZED,
271- "authentication required",
272- ));
273- }
274 Err(res) => return Ok(*res),272 Err(res) => return Ok(*res),
275 };273 };
276 let owner = match owner_of(cx).await {274 let owner = match owner_of(cx).await {
crates/forge-web-app/src/api/releases.rsmodified+59 -75
@@ -8,7 +8,7 @@
8 use std::io;8 use std::io;
9 9
10 use forge_core::releases::{Release, ReleaseAsset};10 use forge_core::releases::{Release, ReleaseAsset};
11-use forge_core::{Action, Repo as CoreRepo, User};11+use forge_core::{Action, Repo as CoreRepo};
12 use futures_util::StreamExt;12 use futures_util::StreamExt;
13 use http::header::CONTENT_TYPE;13 use http::header::CONTENT_TYPE;
14 use serde::Deserialize;14 use serde::Deserialize;
@@ -132,22 +132,21 @@ async fn get_release_by_tag(cx: &Cx) -> topcoat::Result<Response> {
132 #[route(POST "/api/v1/repos/{owner}/{repo}/releases")]132 #[route(POST "/api/v1/repos/{owner}/{repo}/releases")]
133 async fn create_release(cx: &Cx, body: Body) -> topcoat::Result<Response> {133 async fn create_release(cx: &Cx, body: Body) -> topcoat::Result<Response> {
134 let state = context::<AppState>(cx);134 let state = context::<AppState>(cx);
135- let (repo, user) = match write_context(cx).await {135+ let (repo, user) = match api::load_writer(
136+ state,
137+ client_ip(cx),
138+ headers(cx),
139+ owner(cx),
140+ repo(cx),
141+ )
142+ .await
143+ {
136 Ok(found) => found,144 Ok(found) => found,
137 Err(res) => return Ok(*res),145 Err(res) => return Ok(*res),
138 };146 };
139- let bytes = match api::read_body(body, MAX_JSON_BYTES).await {147+ let input: CreateBody = match api::json_body(body, MAX_JSON_BYTES).await {
140- Ok(bytes) => bytes,
141- Err(res) => return Ok(*res),
142- };
143- let input: CreateBody = match serde_json::from_slice(&bytes) {
144 Ok(input) => input,148 Ok(input) => input,
145- Err(e) => {149+ Err(res) => return Ok(*res),
146- return Ok(api::error(
147- StatusCode::BAD_REQUEST,
148- &format!("invalid JSON body: {e}"),
149- ));
150- }
151 };150 };
152 let title = input.title.unwrap_or_else(|| input.tag.clone());151 let title = input.title.unwrap_or_else(|| input.tag.clone());
153 let created = release_ops::create(152 let created = release_ops::create(
@@ -177,7 +176,15 @@ async fn create_release(cx: &Cx, body: Body) -> topcoat::Result<Response> {
177 #[route(PATCH "/api/v1/repos/{owner}/{repo}/releases/{id}")]176 #[route(PATCH "/api/v1/repos/{owner}/{repo}/releases/{id}")]
178 async fn edit_release(cx: &Cx, body: Body) -> topcoat::Result<Response> {177 async fn edit_release(cx: &Cx, body: Body) -> topcoat::Result<Response> {
179 let state = context::<AppState>(cx);178 let state = context::<AppState>(cx);
180- let (repo, user) = match write_context(cx).await {179+ let (repo, user) = match api::load_writer(
180+ state,
181+ client_ip(cx),
182+ headers(cx),
183+ owner(cx),
184+ repo(cx),
185+ )
186+ .await
187+ {
181 Ok(found) => found,188 Ok(found) => found,
182 Err(res) => return Ok(*res),189 Err(res) => return Ok(*res),
183 };190 };
@@ -185,18 +192,9 @@ async fn edit_release(cx: &Cx, body: Body) -> topcoat::Result<Response> {
185 Ok(release) => release,192 Ok(release) => release,
186 Err(res) => return Ok(*res),193 Err(res) => return Ok(*res),
187 };194 };
188- let bytes = match api::read_body(body, MAX_JSON_BYTES).await {195+ let patch: PatchBody = match api::json_body(body, MAX_JSON_BYTES).await {
189- Ok(bytes) => bytes,
190- Err(res) => return Ok(*res),
191- };
192- let patch: PatchBody = match serde_json::from_slice(&bytes) {
193 Ok(patch) => patch,196 Ok(patch) => patch,
194- Err(e) => {197+ Err(res) => return Ok(*res),
195- return Ok(api::error(
196- StatusCode::BAD_REQUEST,
197- &format!("invalid JSON body: {e}"),
198- ));
199- }
200 };198 };
201 let edit = EditRelease {199 let edit = EditRelease {
202 title: patch.title.unwrap_or_else(|| release.title.clone()),200 title: patch.title.unwrap_or_else(|| release.title.clone()),
@@ -219,7 +217,15 @@ async fn edit_release(cx: &Cx, body: Body) -> topcoat::Result<Response> {
219 #[route(DELETE "/api/v1/repos/{owner}/{repo}/releases/{id}")]217 #[route(DELETE "/api/v1/repos/{owner}/{repo}/releases/{id}")]
220 async fn delete_release(cx: &Cx) -> topcoat::Result<Response> {218 async fn delete_release(cx: &Cx) -> topcoat::Result<Response> {
221 let state = context::<AppState>(cx);219 let state = context::<AppState>(cx);
222- let (repo, user) = match write_context(cx).await {220+ let (repo, user) = match api::load_writer(
221+ state,
222+ client_ip(cx),
223+ headers(cx),
224+ owner(cx),
225+ repo(cx),
226+ )
227+ .await
228+ {
223 Ok(found) => found,229 Ok(found) => found,
224 Err(res) => return Ok(*res),230 Err(res) => return Ok(*res),
225 };231 };
@@ -237,7 +243,15 @@ async fn delete_release(cx: &Cx) -> topcoat::Result<Response> {
237 #[route(PUT "/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}")]243 #[route(PUT "/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}")]
238 async fn upload_asset(cx: &Cx, body: Body) -> topcoat::Result<Response> {244 async fn upload_asset(cx: &Cx, body: Body) -> topcoat::Result<Response> {
239 let state = context::<AppState>(cx);245 let state = context::<AppState>(cx);
240- let (repo, user) = match write_context(cx).await {246+ let (repo, user) = match api::load_writer(
247+ state,
248+ client_ip(cx),
249+ headers(cx),
250+ owner(cx),
251+ repo(cx),
252+ )
253+ .await
254+ {
241 Ok(found) => found,255 Ok(found) => found,
242 Err(res) => return Ok(*res),256 Err(res) => return Ok(*res),
243 };257 };
@@ -288,7 +302,15 @@ async fn upload_asset(cx: &Cx, body: Body) -> topcoat::Result<Response> {
288 #[route(DELETE "/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}")]302 #[route(DELETE "/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}")]
289 async fn delete_asset(cx: &Cx) -> topcoat::Result<Response> {303 async fn delete_asset(cx: &Cx) -> topcoat::Result<Response> {
290 let state = context::<AppState>(cx);304 let state = context::<AppState>(cx);
291- let (repo, _user) = match write_context(cx).await {305+ let (repo, _user) = match api::load_writer(
306+ state,
307+ client_ip(cx),
308+ headers(cx),
309+ owner(cx),
310+ repo(cx),
311+ )
312+ .await
313+ {
292 Ok(found) => found,314 Ok(found) => found,
293 Err(res) => return Ok(*res),315 Err(res) => return Ok(*res),
294 };316 };
@@ -321,7 +343,7 @@ async fn read_context(cx: &Cx) -> Result<(CoreRepo, bool), Refusal> {
321 let state = context::<AppState>(cx);343 let state = context::<AppState>(cx);
322 let actor = api::authenticate(state, client_ip(cx), headers(cx)).await?;344 let actor = api::authenticate(state, client_ip(cx), headers(cx)).await?;
323 let repo = api::load_repo(state, actor.as_ref(), owner(cx), repo(cx), Action::Read).await?;345 let repo = api::load_repo(state, actor.as_ref(), owner(cx), repo(cx), Action::Read).await?;
324- let can_write = api::load_repo(346+ let can_write = match api::load_repo(
325 state,347 state,
326 actor.as_ref(),348 actor.as_ref(),
327 owner(cx),349 owner(cx),
@@ -329,21 +351,14 @@ async fn read_context(cx: &Cx) -> Result<(CoreRepo, bool), Refusal> {
329 Action::Write,351 Action::Write,
330 )352 )
331 .await353 .await
332- .is_ok();354+ {
355+ Ok(_) => true,
356+ Err(res) if res.status() == StatusCode::INTERNAL_SERVER_ERROR => return Err(res),
357+ Err(_) => false,
358+ };
333 Ok((repo, can_write))359 Ok((repo, can_write))
334 }360 }
335 361
336-/// Authenticates a required caller with write access and loads the repo.
337-async fn write_context(cx: &Cx) -> Result<(CoreRepo, User), Refusal> {
338- let state = context::<AppState>(cx);
339- let actor = api::authenticate(state, client_ip(cx), headers(cx)).await?;
340- let repo = api::load_repo(state, actor.as_ref(), owner(cx), repo(cx), Action::Write).await?;
341- match actor {
342- Some(user) => Ok((repo, user)),
343- None => Err(Box::new(api::unauthorized())),
344- }
345-}
346-
347 /// The release with this id, which must belong to `repo`. Anything else is a 404, so ids from362 /// The release with this id, which must belong to `repo`. Anything else is a 404, so ids from
348 /// other repos cannot be probed. `id` is the forge id or the integer shown as `id` in the JSON.363 /// other repos cannot be probed. `id` is the forge id or the integer shown as `id` in the JSON.
349 /// Callers of this function already have write access, or check drafts themselves.364 /// Callers of this function already have write access, or check drafts themselves.
@@ -453,40 +468,23 @@ fn no_content() -> Response {
453 468
454 #[cfg(test)]469 #[cfg(test)]
455 mod tests {470 mod tests {
456- use std::path::{Path, PathBuf};471+ use std::path::PathBuf;
457 472
458 use forge_core::releases::NewRelease;473 use forge_core::releases::NewRelease;
459- use forge_core::token::{generate_token, hash_token};
460 use forge_core::{Role, Store, User, Visibility};474 use forge_core::{Role, Store, User, Visibility};
461 use forge_git::repo::{init_bare, repo_path};475 use forge_git::repo::{init_bare, repo_path};
462 use http::header::{AUTHORIZATION, CONTENT_TYPE};476 use http::header::{AUTHORIZATION, CONTENT_TYPE};
463 use topcoat::router::request::Request;477 use topcoat::router::request::Request;
464 use topcoat::router::{Body, Router, to_bytes};478 use topcoat::router::{Body, Router, to_bytes};
465 479
480+ use crate::test_support::fixture::git;
481+ use crate::test_support::http::{bearer, token_for};
466 use crate::test_support::{app_router, test_state};482 use crate::test_support::{app_router, test_state};
467 483
468 const OWNER: &str = "tahinli";484 const OWNER: &str = "tahinli";
469 const REPO: &str = "proj";485 const REPO: &str = "proj";
470 const MIB: u64 = 1024 * 1024;486 const MIB: u64 = 1024 * 1024;
471 487
472- fn git(dir: &Path, args: &[&str]) -> String {
473- let out = std::process::Command::new("git")
474- .current_dir(dir)
475- .args(args)
476- .env("GIT_AUTHOR_NAME", "test")
477- .env("GIT_AUTHOR_EMAIL", "test@example.com")
478- .env("GIT_COMMITTER_NAME", "test")
479- .env("GIT_COMMITTER_EMAIL", "test@example.com")
480- .output()
481- .expect("git runs");
482- assert!(
483- out.status.success(),
484- "git {args:?} failed: {}",
485- String::from_utf8_lossy(&out.stderr)
486- );
487- String::from_utf8_lossy(&out.stdout).trim().to_owned()
488- }
489-
490 struct Fixture {488 struct Fixture {
491 _tmp: tempfile::TempDir,489 _tmp: tempfile::TempDir,
492 router: Router,490 router: Router,
@@ -555,20 +553,6 @@ mod tests {
555 }553 }
556 }554 }
557 555
558- async fn token_for(store: &Store, user_id: &str, scopes: &[&str]) -> String {
559- let raw = generate_token();
560- let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect();
561- store
562- .create_token(user_id, "test", &hash_token(&raw), &scopes, None)
563- .await
564- .expect("token");
565- raw
566- }
567-
568- fn bearer(raw: &str) -> String {
569- format!("Bearer {raw}")
570- }
571-
572 /// Sends one request through the router: `(status, json body)`.556 /// Sends one request through the router: `(status, json body)`.
573 async fn send(557 async fn send(
574 router: &Router,558 router: &Router,
crates/forge-web-app/src/api/statuses.rsmodified+14 -37
@@ -36,33 +36,24 @@ struct ReportBody {
36 #[route(POST "/api/v1/repos/{owner}/{repo}/statuses/{sha}")]36 #[route(POST "/api/v1/repos/{owner}/{repo}/statuses/{sha}")]
37 async fn report_status(cx: &Cx, body: Body) -> topcoat::Result<Response> {37 async fn report_status(cx: &Cx, body: Body) -> topcoat::Result<Response> {
38 let state = context::<AppState>(cx);38 let state = context::<AppState>(cx);
39- let actor = match api::authenticate(state, client_ip(cx), headers(cx)).await {39+ let (repo, user) = match api::load_writer(
40- Ok(actor) => actor,40+ state,
41- Err(res) => return Ok(*res),41+ client_ip(cx),
42- };42+ headers(cx),
43- let repo = match api::load_repo(state, actor.as_ref(), owner(cx), repo(cx), Action::Write).await43+ owner(cx),
44+ repo(cx),
45+ )
46+ .await
44 {47 {
45- Ok(repo) => repo,48+ Ok(found) => found,
46 Err(res) => return Ok(*res),49 Err(res) => return Ok(*res),
47 };50 };
48- let Some(user) = actor else {
49- return Ok(api::unauthorized());
50- };
51 let Some(sha) = api::normalize_sha(sha(cx)) else {51 let Some(sha) = api::normalize_sha(sha(cx)) else {
52 return Ok(not_a_full_sha());52 return Ok(not_a_full_sha());
53 };53 };
54- let bytes = match api::read_body(body, MAX_BODY_BYTES).await {54+ let report: ReportBody = match api::json_body(body, MAX_BODY_BYTES).await {
55- Ok(bytes) => bytes,
56- Err(res) => return Ok(*res),
57- };
58- let report: ReportBody = match serde_json::from_slice(&bytes) {
59 Ok(report) => report,55 Ok(report) => report,
60- Err(e) => {56+ Err(res) => return Ok(*res),
61- return Ok(api::error(
62- StatusCode::BAD_REQUEST,
63- &format!("invalid JSON body: {e}"),
64- ));
65- }
66 };57 };
67 let Some(status_state) = StatusState::parse(&report.state) else {58 let Some(status_state) = StatusState::parse(&report.state) else {
68 return Ok(api::error(59 return Ok(api::error(
@@ -171,14 +162,15 @@ fn commit_not_found() -> Response {
171 162
172 #[cfg(test)]163 #[cfg(test)]
173 mod tests {164 mod tests {
174- use forge_core::token::{generate_token, hash_token};165+ use forge_core::token::generate_token;
175- use forge_core::{Role, Store, Visibility};166+ use forge_core::{Role, Visibility};
176 use http::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE};167 use http::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE};
177 use topcoat::router::request::Request;168 use topcoat::router::request::Request;
178 use topcoat::router::{Body, Router, to_bytes};169 use topcoat::router::{Body, Router, to_bytes};
179 170
180 use crate::auth::SESSION_COOKIE;171 use crate::auth::SESSION_COOKIE;
181 use crate::test_support::fixture::{Fixture, OWNER, REPO};172 use crate::test_support::fixture::{Fixture, OWNER, REPO};
173+ use crate::test_support::http::{bearer, token_for};
182 174
183 /// Sends one request through the router: `(status, json body)`.175 /// Sends one request through the router: `(status, json body)`.
184 async fn send(176 async fn send(
@@ -209,21 +201,6 @@ mod tests {
209 (status, json)201 (status, json)
210 }202 }
211 203
212- /// A personal access token for `user_id` with the given scopes. Returns the raw token.
213- async fn token_for(store: &Store, user_id: &str, scopes: &[&str]) -> String {
214- let raw = generate_token();
215- let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect();
216- store
217- .create_token(user_id, "test", &hash_token(&raw), &scopes, None)
218- .await
219- .expect("token");
220- raw
221- }
222-
223- fn bearer(raw: &str) -> String {
224- format!("Bearer {raw}")
225- }
226-
227 struct Setup {204 struct Setup {
228 fx: Fixture,205 fx: Fixture,
229 reader_token: String,206 reader_token: String,
crates/forge-web-app/src/auth.rsmodified+1 -67
@@ -1,13 +1,8 @@
1-//! Session cookie, current user, CSRF checks and login redirect helpers.
2-//!
3-//! The browser holds the raw session token in `__Host-forge_session`. The database
4-//! stores only `hash_token(token)`, so a leaked DB row cannot be replayed as a cookie.
5-
6 use std::sync::{Arc, OnceLock};1 use std::sync::{Arc, OnceLock};
7 use std::time::Duration;2 use std::time::Duration;
8 3
9 use forge_core::password::{hash_password, verify_password};4 use forge_core::password::{hash_password, verify_password};
10-use forge_core::time::stamp_after;5+use forge_core::time::{stamp_after, unix_now};
11 use forge_core::token::{constant_time_eq, hash_token, random_b64url};6 use forge_core::token::{constant_time_eq, hash_token, random_b64url};
12 use forge_core::{Session, Store, User, secret, totp};7 use forge_core::{Session, Store, User, secret, totp};
13 use tokio::sync::Semaphore;8 use tokio::sync::Semaphore;
@@ -20,35 +15,21 @@ use topcoat::router::request::{headers, uri};
20 use crate::client_ip::client_addr;15 use crate::client_ip::client_addr;
21 use crate::state::AppState;16 use crate::state::AppState;
22 17
23-/// Logical cookie name. `override_prefix_host()` stores it as `__Host-forge_session`.
24 pub const SESSION_COOKIE: &str = "forge_session";18 pub const SESSION_COOKIE: &str = "forge_session";
25-/// Lifetime of a web session, both in the database and on the cookie.
26 pub const SESSION_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);19 pub const SESSION_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);
27 20
28-/// Logical name of the pre-session CSRF cookie, used by `/login` and `/setup` before any
29-/// session exists. Stored as `__Host-forge_precsrf`.
30 pub const PRE_CSRF_COOKIE: &str = "forge_precsrf";21 pub const PRE_CSRF_COOKIE: &str = "forge_precsrf";
31-/// Lifetime of the pre-session CSRF cookie.
32 const PRE_CSRF_TTL: Duration = Duration::from_secs(60 * 60);22 const PRE_CSRF_TTL: Duration = Duration::from_secs(60 * 60);
33 23
34-/// Logical name of the pending-login cookie set between the password and the second factor.
35-/// Stored as `__Host-forge_2fa`. Its value is sealed with the instance key.
36 pub const PENDING_2FA_COOKIE: &str = "forge_2fa";24 pub const PENDING_2FA_COOKIE: &str = "forge_2fa";
37-/// How long a password-verified login may wait for its second factor.
38 pub const PENDING_2FA_TTL: Duration = Duration::from_secs(5 * 60);25 pub const PENDING_2FA_TTL: Duration = Duration::from_secs(5 * 60);
39 26
40-/// Maximum accepted length of a `next` redirect target.
41 const MAX_NEXT_LEN: usize = 2048;27 const MAX_NEXT_LEN: usize = 2048;
42 28
43-/// Cookie jar that forces the `__Host-` prefix (Secure, Path=/, no Domain).
44 fn session_jar(cx: &Cx) -> impl Cookies + '_ {29 fn session_jar(cx: &Cx) -> impl Cookies + '_ {
45 cookies(cx).override_prefix_host()30 cookies(cx).override_prefix_host()
46 }31 }
47 32
48-/// Resolves the signed-in user from the session cookie.
49-///
50-/// Returns `None` when there is no cookie, the session is unknown or expired, or its
51-/// user no longer exists. Every successful lookup refreshes `last_seen`.
52 pub async fn current_user(cx: &Cx) -> forge_core::Result<Option<(User, Session)>> {33 pub async fn current_user(cx: &Cx) -> forge_core::Result<Option<(User, Session)>> {
53 let Some(cookie) = session_jar(cx).get(SESSION_COOKIE) else {34 let Some(cookie) = session_jar(cx).get(SESSION_COOKIE) else {
54 return Ok(None);35 return Ok(None);
@@ -60,7 +41,6 @@ pub async fn current_user(cx: &Cx) -> forge_core::Result<Option<(User, Session)>
60 else {41 else {
61 return Ok(None);42 return Ok(None);
62 };43 };
63- // An organization never signs in, even if a session row names one.
64 let Some(user) = store44 let Some(user) = store
65 .user_by_id(&session.user_id)45 .user_by_id(&session.user_id)
66 .await?46 .await?
@@ -73,7 +53,6 @@ pub async fn current_user(cx: &Cx) -> forge_core::Result<Option<(User, Session)>
73 Ok(Some((user, session)))53 Ok(Some((user, session)))
74 }54 }
75 55
76-/// Creates a session for `user` and sets the session cookie on the response.
77 pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {56 pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {
78 let store = &context::<AppState>(cx).store;57 let store = &context::<AppState>(cx).store;
79 let token = random_b64url();58 let token = random_b64url();
@@ -88,7 +67,6 @@ pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {
88 Some(&addr),67 Some(&addr),
89 )68 )
90 .await?;69 .await?;
91- // A new sign-in shows up in the user's session list in their other open tabs.
92 context::<AppState>(cx)70 context::<AppState>(cx)
93 .live71 .live
94 .bump(&crate::live::Topic::Account(user.id.clone()));72 .bump(&crate::live::Topic::Account(user.id.clone()));
@@ -105,27 +83,19 @@ pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {
105 Ok(session)83 Ok(session)
106 }84 }
107 85
108-/// Deletes the session row and clears the cookie.
109 pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> {86 pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> {
110 let state = context::<AppState>(cx);87 let state = context::<AppState>(cx);
111 state.store.delete_session(&session.id).await?;88 state.store.delete_session(&session.id).await?;
112- // The user's other tabs may show this session (a page that now leaves for the login page).
113 crate::live::bump_account(state, &session.user_id);89 crate::live::bump_account(state, &session.user_id);
114 session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/"));90 session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/"));
115 Ok(())91 Ok(())
116 }92 }
117 93
118-/// Constant-time comparison of the submitted CSRF token with the session's token.
119 pub fn check_csrf(session: &Session, submitted: &str) -> bool {94 pub fn check_csrf(session: &Session, submitted: &str) -> bool {
120- // An empty stored token must never match, even an empty submission.
121 !session.csrf_token.is_empty()95 !session.csrf_token.is_empty()
122 && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes())96 && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes())
123 }97 }
124 98
125-/// Returns the pre-session CSRF token for a form, issuing one when the browser has none.
126-///
127-/// The existing cookie is reused so that two open login tabs keep working. The same value
128-/// goes into a hidden `precsrf` field; the POST must echo it back.
129 pub fn pre_csrf_token(cx: &Cx) -> String {99 pub fn pre_csrf_token(cx: &Cx) -> String {
130 if let Some(cookie) = session_jar(cx).get(PRE_CSRF_COOKIE) {100 if let Some(cookie) = session_jar(cx).get(PRE_CSRF_COOKIE) {
131 let value = cookie.value();101 let value = cookie.value();
@@ -138,7 +108,6 @@ pub fn pre_csrf_token(cx: &Cx) -> String {
138 token108 token
139 }109 }
140 110
141-/// True only when the submitted `precsrf` equals the cookie, compared in constant time.
142 pub fn check_pre_csrf(cx: &Cx, submitted: &str) -> bool {111 pub fn check_pre_csrf(cx: &Cx, submitted: &str) -> bool {
143 let Some(cookie) = session_jar(cx).get(PRE_CSRF_COOKIE) else {112 let Some(cookie) = session_jar(cx).get(PRE_CSRF_COOKIE) else {
144 return false;113 return false;
@@ -146,7 +115,6 @@ pub fn check_pre_csrf(cx: &Cx, submitted: &str) -> bool {
146 !cookie.value().is_empty() && constant_time_eq(cookie.value().as_bytes(), submitted.as_bytes())115 !cookie.value().is_empty() && constant_time_eq(cookie.value().as_bytes(), submitted.as_bytes())
147 }116 }
148 117
149-/// Removes the pre-session CSRF cookie. Called after a successful login or setup.
150 pub fn clear_pre_csrf(cx: &Cx) {118 pub fn clear_pre_csrf(cx: &Cx) {
151 session_jar(cx).remove(Cookie::build((PRE_CSRF_COOKIE, "")).path("/"));119 session_jar(cx).remove(Cookie::build((PRE_CSRF_COOKIE, "")).path("/"));
152 }120 }
@@ -163,17 +131,13 @@ fn pre_csrf_cookie(token: String) -> Cookie<'static> {
163 .build()131 .build()
164 }132 }
165 133
166-/// Argon2 runs at once, server-wide. Each hash or verify allocates about 19 MiB, so a burst of
167-/// logins would otherwise pile that memory up on the blocking pool.
168 const MAX_CONCURRENT_PASSWORD_HASHES: usize = 4;134 const MAX_CONCURRENT_PASSWORD_HASHES: usize = 4;
169 135
170-/// Permits for argon2 work. A permit is held until the hash or verify finishes.
171 fn password_slots() -> &'static Arc<Semaphore> {136 fn password_slots() -> &'static Arc<Semaphore> {
172 static SLOTS: OnceLock<Arc<Semaphore>> = OnceLock::new();137 static SLOTS: OnceLock<Arc<Semaphore>> = OnceLock::new();
173 SLOTS.get_or_init(|| Arc::new(Semaphore::new(MAX_CONCURRENT_PASSWORD_HASHES)))138 SLOTS.get_or_init(|| Arc::new(Semaphore::new(MAX_CONCURRENT_PASSWORD_HASHES)))
174 }139 }
175 140
176-/// Hashes a password with argon2 on the blocking pool, keeping the async runtime free.
177 pub async fn hash_password_async(password: String) -> forge_core::Result<String> {141 pub async fn hash_password_async(password: String) -> forge_core::Result<String> {
178 let _permit = password_slots()142 let _permit = password_slots()
179 .acquire()143 .acquire()
@@ -184,7 +148,6 @@ pub async fn hash_password_async(password: String) -> forge_core::Result<String>
184 .map_err(|_| forge_core::Error::Crypto("password hashing task failed".into()))?148 .map_err(|_| forge_core::Error::Crypto("password hashing task failed".into()))?
185 }149 }
186 150
187-/// Verifies a password with argon2 on the blocking pool.
188 pub async fn verify_password_async(password: String, hash: String) -> forge_core::Result<bool> {151 pub async fn verify_password_async(password: String, hash: String) -> forge_core::Result<bool> {
189 let _permit = password_slots()152 let _permit = password_slots()
190 .acquire()153 .acquire()
@@ -195,7 +158,6 @@ pub async fn verify_password_async(password: String, hash: String) -> forge_core
195 .map_err(|_| forge_core::Error::Crypto("password verification task failed".into()))158 .map_err(|_| forge_core::Error::Crypto("password verification task failed".into()))
196 }159 }
197 160
198-/// Returns the signed-in user, or a 303 redirect to `/login?next=<current path>`.
199 pub async fn require_user(cx: &Cx) -> Result<(User, Session)> {161 pub async fn require_user(cx: &Cx) -> Result<(User, Session)> {
200 match current_user(cx).await? {162 match current_user(cx).await? {
201 Some(viewer) => Ok(viewer),163 Some(viewer) => Ok(viewer),
@@ -207,7 +169,6 @@ pub async fn require_user(cx: &Cx) -> Result<(User, Session)> {
207 }169 }
208 }170 }
209 171
210-/// Requires a signed-in user and a valid `csrf` form field. Returns 403 on a bad token.
211 pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<(User, Session)> {172 pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<(User, Session)> {
212 let (user, session) = require_user(cx).await?;173 let (user, session) = require_user(cx).await?;
213 if check_csrf(&session, submitted) {174 if check_csrf(&session, submitted) {
@@ -217,21 +178,11 @@ pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<(User, Session)> {
217 }178 }
218 }179 }
219 180
220-/// A login that has passed its password and waits for the second factor.
221 pub struct PendingLogin {181 pub struct PendingLogin {
222 pub user_id: String,182 pub user_id: String,
223 pub next: String,183 pub next: String,
224 }184 }
225 185
226-/// Seconds since the Unix epoch, or 0 if the clock is before it.
227-pub fn unix_now() -> u64 {
228- std::time::SystemTime::now()
229- .duration_since(std::time::UNIX_EPOCH)
230- .map_or(0, |d| d.as_secs())
231-}
232-
233-/// Sets the pending-login cookie. Its payload is `expires|user_id|next`, sealed so the browser
234-/// cannot change the user or the expiry.
235 pub fn set_pending_login(186 pub fn set_pending_login(
236 cx: &Cx,187 cx: &Cx,
237 key: &[u8; 32],188 key: &[u8; 32],
@@ -253,8 +204,6 @@ pub fn set_pending_login(
253 Ok(())204 Ok(())
254 }205 }
255 206
256-/// The pending login from the cookie, or `None` when the cookie is missing, tampered with,
257-/// malformed or past its expiry.
258 pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option<PendingLogin> {207 pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option<PendingLogin> {
259 let cookie = session_jar(cx).get(PENDING_2FA_COOKIE)?;208 let cookie = session_jar(cx).get(PENDING_2FA_COOKIE)?;
260 let plain = secret::open(key, cookie.value()).ok()?;209 let plain = secret::open(key, cookie.value()).ok()?;
@@ -272,12 +221,10 @@ pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option<PendingLogin> {
272 })221 })
273 }222 }
274 223
275-/// Removes the pending-login cookie.
276 pub fn clear_pending_login(cx: &Cx) {224 pub fn clear_pending_login(cx: &Cx) {
277 session_jar(cx).remove(Cookie::build((PENDING_2FA_COOKIE, "")).path("/"));225 session_jar(cx).remove(Cookie::build((PENDING_2FA_COOKIE, "")).path("/"));
278 }226 }
279 227
280-/// True when the user has confirmed two-factor authentication.
281 pub async fn two_factor_enabled(store: &Store, user_id: &str) -> forge_core::Result<bool> {228 pub async fn two_factor_enabled(store: &Store, user_id: &str) -> forge_core::Result<bool> {
282 Ok(store229 Ok(store
283 .totp_state(user_id)230 .totp_state(user_id)
@@ -285,9 +232,6 @@ pub async fn two_factor_enabled(store: &Store, user_id: &str) -> forge_core::Res
285 .is_some_and(|state| state.enabled))232 .is_some_and(|state| state.enabled))
286 }233 }
287 234
288-/// Checks a second-factor input for a user with two-factor on. A six-digit input is a TOTP
289-/// code, checked with replay protection. Anything else is a recovery code, which is used up
290-/// on success. Returns false for any wrong or spent input.
291 pub async fn verify_second_factor(235 pub async fn verify_second_factor(
292 store: &Store,236 store: &Store,
293 key: &[u8; 32],237 key: &[u8; 32],
@@ -295,7 +239,6 @@ pub async fn verify_second_factor(
295 input: &str,239 input: &str,
296 ) -> forge_core::Result<bool> {240 ) -> forge_core::Result<bool> {
297 let input = input.trim();241 let input = input.trim();
298- // An organization has no second factor and never passes one.
299 if store242 if store
300 .user_by_id(user_id)243 .user_by_id(user_id)
301 .await?244 .await?
@@ -325,10 +268,6 @@ pub async fn verify_second_factor(
325 .await268 .await
326 }269 }
327 270
328-/// Returns `next` only when it is a same-site relative path; otherwise `/`.
329-///
330-/// Accepts a single leading `/`, rejects `//` and `/\` (protocol-relative or browser
331-/// backslash tricks), rejects control characters and caps the length.
332 pub fn safe_next(next: Option<&str>) -> &str {271 pub fn safe_next(next: Option<&str>) -> &str {
333 match next {272 match next {
334 Some(n) if is_local_path(n) => n,273 Some(n) if is_local_path(n) => n,
@@ -344,7 +283,6 @@ fn is_local_path(path: &str) -> bool {
344 && path.chars().all(|c| !c.is_control())283 && path.chars().all(|c| !c.is_control())
345 }284 }
346 285
347-/// Percent-encodes everything except unreserved characters and `/`.
348 pub fn percent_encode(input: &str) -> String {286 pub fn percent_encode(input: &str) -> String {
349 let mut out = String::with_capacity(input.len());287 let mut out = String::with_capacity(input.len());
350 for b in input.bytes() {288 for b in input.bytes() {
@@ -358,7 +296,6 @@ pub fn percent_encode(input: &str) -> String {
358 out296 out
359 }297 }
360 298
361-/// The request's `User-Agent`, truncated to 512 characters.
362 pub fn user_agent(cx: &Cx) -> Option<String> {299 pub fn user_agent(cx: &Cx) -> Option<String> {
363 headers(cx)300 headers(cx)
364 .get(http::header::USER_AGENT)301 .get(http::header::USER_AGENT)
@@ -437,8 +374,6 @@ mod tests {
437 assert_eq!(percent_encode("/a b"), "/a%20b");374 assert_eq!(percent_encode("/a b"), "/a%20b");
438 }375 }
439 376
440- /// An organization has no second factor and never passes one, even with a valid TOTP code or
441- /// a recovery code on its row. A person with the same setup does pass.
442 #[tokio::test]377 #[tokio::test]
443 async fn an_org_never_passes_a_second_factor() {378 async fn an_org_never_passes_a_second_factor() {
444 let dir = tempfile::tempdir().unwrap();379 let dir = tempfile::tempdir().unwrap();
@@ -471,7 +406,6 @@ mod tests {
471 .await406 .await
472 .unwrap()407 .unwrap()
473 );408 );
474- // The same setup on a person works, so the refusal is the org rule.
475 assert!(409 assert!(
476 verify_second_factor(&store, &key, &tahinli.id, "aaaa-bbbb")410 verify_second_factor(&store, &key, &tahinli.id, "aaaa-bbbb")
477 .await411 .await
crates/forge-web-app/src/automerge.rsmodified+2 -6
@@ -63,7 +63,7 @@ async fn evaluate_logged(state: &AppState, repo: &Repo, pr: &PullRequest) {
63 /// The merge runs as the user who enabled auto-merge, and only while that user still has Write on63 /// The merge runs as the user who enabled auto-merge, and only while that user still has Write on
64 /// the repo; otherwise auto-merge is switched off with a timeline notice. A merge the repository64 /// the repo; otherwise auto-merge is switched off with a timeline notice. A merge the repository
65 /// refuses (a conflict, a moved base) also switches it off, so it never retries forever.65 /// refuses (a conflict, a moved base) also switches it off, so it never retries forever.
66-pub async fn evaluate(state: &AppState, repo: &Repo, pr: &PullRequest) -> forge_core::Result<bool> {66+async fn evaluate(state: &AppState, repo: &Repo, pr: &PullRequest) -> forge_core::Result<bool> {
67 let Some(auto) = pr.auto_merge.as_ref() else {67 let Some(auto) = pr.auto_merge.as_ref() else {
68 return Ok(false);68 return Ok(false);
69 };69 };
@@ -87,11 +87,7 @@ pub async fn evaluate(state: &AppState, repo: &Repo, pr: &PullRequest) -> forge_
87 .await?;87 .await?;
88 return Ok(false);88 return Ok(false);
89 };89 };
90- let collaborator = state.store.collaborator_role(&repo.id, &user.id).await?;90+ let (collaborator, org) = state.store.user_roles(repo, Some(&user)).await?;
91- let org = state
92- .store
93- .org_repo_role(&repo.owner_id, &user.id, &repo.id)
94- .await?;
95 if authorize(Some(&user), repo, collaborator, org, Action::Write).is_err() {91 if authorize(Some(&user), repo, collaborator, org, Action::Write).is_err() {
96 state92 state
97 .store93 .store
crates/forge-web-app/src/backup/mod.rsmodified+11 -27
@@ -14,11 +14,11 @@ pub mod scheduler;
14 mod verify;14 mod verify;
15 15
16 use std::fs::{DirBuilder, File};16 use std::fs::{DirBuilder, File};
17-use std::io::Read;
18 use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};17 use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
19 use std::path::{Path, PathBuf};18 use std::path::{Path, PathBuf};
20 19
21 use forge_core::{Error, Result, Store};20 use forge_core::{Error, Result, Store};
21+use forge_core::token::sha256_reader;
22 use forge_git::GitEnv;22 use forge_git::GitEnv;
23 use serde::{Deserialize, Serialize};23 use serde::{Deserialize, Serialize};
24 use sha2::{Digest, Sha256};24 use sha2::{Digest, Sha256};
@@ -36,7 +36,6 @@ pub const DB_FILE: &str = "db/forge.db";
36 pub const KEY_FILE: &str = "keys/forge.key";36 pub const KEY_FILE: &str = "keys/forge.key";
37 const BACKUP_DIR_PREFIX: &str = "forge-backup-";37 const BACKUP_DIR_PREFIX: &str = "forge-backup-";
38 const PARTIAL_PREFIX: &str = ".partial-";38 const PARTIAL_PREFIX: &str = ".partial-";
39-const COPY_BUF: usize = 64 * 1024;
40 39
41 /// What a backup set contains.40 /// What a backup set contains.
42 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]41 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -190,44 +189,29 @@ fn fsync_dir(path: &Path) -> Result<()> {
190 189
191 /// Streams the file through sha256. Returns its size and lowercase hex digest.190 /// Streams the file through sha256. Returns its size and lowercase hex digest.
192 fn hash_file(path: &Path) -> Result<(u64, String)> {191 fn hash_file(path: &Path) -> Result<(u64, String)> {
193- let mut f = File::open(path).map_err(io_err)?;192+ sha256_reader(File::open(path).map_err(io_err)?).map_err(io_err)
194- let mut hasher = Sha256::new();
195- let mut buf = vec![0u8; COPY_BUF];
196- let mut total = 0u64;
197- loop {
198- let n = f.read(&mut buf).map_err(io_err)?;
199- if n == 0 {
200- break;
201- }
202- hasher.update(&buf[..n]);
203- total += n as u64;
204- }
205- Ok((total, hex::encode(hasher.finalize())))
206 }193 }
207 194
208 /// `20260102T030405Z`, the UTC stamp used in set names.195 /// `20260102T030405Z`, the UTC stamp used in set names.
209 fn name_stamp(t: time::OffsetDateTime) -> String {196 fn name_stamp(t: time::OffsetDateTime) -> String {
210- format!(197+ stamp(t, "", "")
211- "{:04}{:02}{:02}T{:02}{:02}{:02}Z",
212- t.year(),
213- u8::from(t.month()),
214- t.day(),
215- t.hour(),
216- t.minute(),
217- t.second()
218- )
219 }198 }
220 199
221-/// RFC 3339 UTC, used in the manifest.
222 fn manifest_stamp(t: time::OffsetDateTime) -> String {200 fn manifest_stamp(t: time::OffsetDateTime) -> String {
201+ stamp(t, "-", ":")
202+}
203+
204+fn stamp(t: time::OffsetDateTime, date_sep: &str, time_sep: &str) -> String {
223 format!(205 format!(
224- "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",206+ "{:04}{d}{:02}{d}{:02}T{:02}{s}{:02}{s}{:02}Z",
225 t.year(),207 t.year(),
226 u8::from(t.month()),208 u8::from(t.month()),
227 t.day(),209 t.day(),
228 t.hour(),210 t.hour(),
229 t.minute(),211 t.minute(),
230- t.second()212+ t.second(),
213+ d = date_sep,
214+ s = time_sep,
231 )215 )
232 }216 }
233 217
crates/forge-web-app/src/backup/restore.rsmodified+83 -165
@@ -106,22 +106,11 @@ pub async fn restore_backup(
106 init_bare(&git, &path, &default_branch).await?;106 init_bare(&git, &path, &default_branch).await?;
107 dirs_to_lock.push(path.clone());107 dirs_to_lock.push(path.clone());
108 108
109- match &entry.bundle {109+ let bundle = entry.bundle.as_ref().map(|rel| set.join(rel));
110- Some(rel) => {110+ if bundle.is_some() {
111- let bundle = set.join(rel);111+ repos += 1;
112- let bundle_str = bundle112+ } else {
113- .to_str()113+ empty_repos += 1;
114- .ok_or_else(|| Error::Invalid("bundle path is not UTF-8".into()))?;
115- GitCommand::new(&git, "fetch")
116- .git_dir(&path)
117- .arg("--quiet")
118- .user_arg(bundle_str)?
119- .user_arg("+refs/*:refs/*")?
120- .status()
121- .await?;
122- repos += 1;
123- }
124- None => empty_repos += 1,
125 }114 }
126 115
127 let head = format!("refs/heads/{default_branch}");116 let head = format!("refs/heads/{default_branch}");
@@ -131,50 +120,28 @@ pub async fn restore_backup(
131 .user_arg(&head)?120 .user_arg(&head)?
132 .status()121 .status()
133 .await?;122 .await?;
123+ restore_git(
124+ &git,
125+ &path,
126+ bundle.as_deref(),
127+ &entry.refs_sha256,
128+ &format!("repo {}", entry.id),
129+ )
130+ .await?;
134 131
135- let refs = forge_git::backup::refs_checksum(&git, &path).await?;
136- if refs != entry.refs_sha256 {
137- return Err(Error::Conflict(format!(
138- "repo {}: refs after restore ({refs}) do not match the manifest ({})",
139- entry.id, entry.refs_sha256
140- )));
141- }
142- GitCommand::new(&git, "fsck")
143- .git_dir(&path)
144- .arg("--full")
145- .status()
146- .await?;
147-
148- // The wiki comes back the same way as the repo, from its own bundle, if the set has one.
149 if let Some(wiki) = &entry.wiki {132 if let Some(wiki) = &entry.wiki {
150 let wiki_repo = forge_git::repo::wiki_path(&target, &entry.id)?;133 let wiki_repo = forge_git::repo::wiki_path(&target, &entry.id)?;
151 init_bare(&git, &wiki_repo, forge_git::wiki::WIKI_BRANCH).await?;134 init_bare(&git, &wiki_repo, forge_git::wiki::WIKI_BRANCH).await?;
152 dirs_to_lock.push(wiki_repo.clone());135 dirs_to_lock.push(wiki_repo.clone());
153- if let Some(rel) = &wiki.bundle {136+ let bundle = wiki.bundle.as_ref().map(|rel| set.join(rel));
154- let bundle = set.join(rel);137+ restore_git(
155- let bundle_str = bundle138+ &git,
156- .to_str()139+ &wiki_repo,
157- .ok_or_else(|| Error::Invalid("bundle path is not UTF-8".into()))?;140+ bundle.as_deref(),
158- GitCommand::new(&git, "fetch")141+ &wiki.refs_sha256,
159- .git_dir(&wiki_repo)142+ &format!("repo {} wiki", entry.id),
160- .arg("--quiet")143+ )
161- .user_arg(bundle_str)?144+ .await?;
162- .user_arg("+refs/*:refs/*")?
163- .status()
164- .await?;
165- }
166- let refs = forge_git::backup::refs_checksum(&git, &wiki_repo).await?;
167- if refs != wiki.refs_sha256 {
168- return Err(Error::Conflict(format!(
169- "repo {} wiki: refs after restore ({refs}) do not match the manifest ({})",
170- entry.id, wiki.refs_sha256
171- )));
172- }
173- GitCommand::new(&git, "fsck")
174- .git_dir(&wiki_repo)
175- .arg("--full")
176- .status()
177- .await?;
178 }145 }
179 }146 }
180 drop(store);147 drop(store);
@@ -214,6 +181,39 @@ pub async fn restore_backup(
214 })181 })
215 }182 }
216 183
184+async fn restore_git(
185+ git: &GitEnv,
186+ dir: &Path,
187+ bundle: Option<&Path>,
188+ expected_refs: &str,
189+ label: &str,
190+) -> Result<()> {
191+ if let Some(bundle) = bundle {
192+ let bundle_str = bundle
193+ .to_str()
194+ .ok_or_else(|| Error::Invalid("bundle path is not UTF-8".into()))?;
195+ GitCommand::new(git, "fetch")
196+ .git_dir(dir)
197+ .arg("--quiet")
198+ .user_arg(bundle_str)?
199+ .user_arg("+refs/*:refs/*")?
200+ .status()
201+ .await?;
202+ }
203+ let refs = forge_git::backup::refs_checksum(git, dir).await?;
204+ if refs != expected_refs {
205+ return Err(Error::Conflict(format!(
206+ "{label}: refs after restore ({refs}) do not match the manifest ({expected_refs})"
207+ )));
208+ }
209+ GitCommand::new(git, "fsck")
210+ .git_dir(dir)
211+ .arg("--full")
212+ .status()
213+ .await?;
214+ Ok(())
215+}
216+
217 /// The target must not be inside the set, and must be missing or an empty directory.217 /// The target must not be inside the set, and must be missing or an empty directory.
218 fn check_target(set: &Path, target: &Path) -> Result<()> {218 fn check_target(set: &Path, target: &Path) -> Result<()> {
219 if target.starts_with(set) {219 if target.starts_with(set) {
@@ -299,30 +299,34 @@ fn lock_down_dirs(target: &Path, repo_dirs: &[PathBuf]) -> Result<()> {
299 #[cfg(test)]299 #[cfg(test)]
300 mod tests {300 mod tests {
301 use super::*;301 use super::*;
302- use crate::backup::{BackupOptions, BackupSource, create_backup};302+ use crate::backup::BackupOptions;
303- use forge_core::model::Visibility;303+ use crate::backup::create_backup;
304+ use crate::backup::tests::{Fixture, fixture, git_in, opts};
304 use std::os::unix::fs::PermissionsExt;305 use std::os::unix::fs::PermissionsExt;
305 use std::process::Command;306 use std::process::Command;
306 307
307- struct Source {308+ async fn source() -> Fixture {
308- dir: tempfile::TempDir,309+ let fx = fixture().await;
309- data_dir: PathBuf,310+ let tahinli = fx
310- source: BackupSource,311+ .source
311- demo_id: String,312+ .store
312- empty_id: String,313+ .user_by_username("tahinli")
314+ .await
315+ .expect("query")
316+ .expect("user");
317+ fx.source
318+ .store
319+ .create_issue(&fx.demo_id, &tahinli.id, "First issue", "body")
320+ .await
321+ .expect("issue");
322+ let key = fx.data_dir.join("forge.key");
323+ std::fs::write(&key, [7u8; 32]).expect("key");
324+ std::fs::set_permissions(&key, std::fs::Permissions::from_mode(0o600)).expect("key mode");
325+ fx
313 }326 }
314 327
315- fn git_in(dir: &Path, args: &[&str]) {328+ fn git_bin() -> PathBuf {
316- let out = Command::new("git")329+ PathBuf::from("git")
317- .current_dir(dir)
318- .env("GIT_AUTHOR_NAME", "t")
319- .env("GIT_AUTHOR_EMAIL", "t@example.invalid")
320- .env("GIT_COMMITTER_NAME", "t")
321- .env("GIT_COMMITTER_EMAIL", "t@example.invalid")
322- .args(args)
323- .output()
324- .expect("run git");
325- assert!(out.status.success(), "git {args:?}: {out:?}");
326 }330 }
327 331
328 fn git_out(dir: &Path, args: &[&str]) -> String {332 fn git_out(dir: &Path, args: &[&str]) -> String {
@@ -335,92 +339,6 @@ mod tests {
335 String::from_utf8(out.stdout).expect("utf8")339 String::from_utf8(out.stdout).expect("utf8")
336 }340 }
337 341
338- /// A data dir with a user, an issue, a repo with commits/branch/tag, and an empty repo.
339- async fn source() -> Source {
340- let dir = tempfile::tempdir().expect("tempdir");
341- let data_dir = dir.path().join("data");
342- std::fs::create_dir_all(&data_dir).expect("data dir");
343- let store = Store::open(&data_dir.join("forge.db")).await.expect("open");
344- let tahinli = store
345- .create_user("Tahinli", None, "hash", false)
346- .await
347- .expect("user");
348- let git = GitEnv {
349- git_bin: "git".into(),
350- data_dir: data_dir.clone(),
351- };
352- let demo = store
353- .create_repo(&tahinli.id, "demo", "", Visibility::Private, "main")
354- .await
355- .expect("demo");
356- let demo_path = repo_path(&data_dir, &demo.id).expect("path");
357- let work = dir.path().join("work");
358- std::fs::create_dir_all(&work).expect("work");
359- git_in(&work, &["init", "-q", "-b", "main"]);
360- git_in(&work, &["commit", "-q", "--allow-empty", "-m", "one"]);
361- git_in(&work, &["commit", "-q", "--allow-empty", "-m", "two"]);
362- git_in(&work, &["branch", "feature"]);
363- git_in(&work, &["tag", "v1"]);
364- std::fs::create_dir_all(demo_path.parent().expect("parent")).expect("mkdir");
365- let dest = demo_path.to_str().expect("utf8").to_string();
366- git_in(
367- dir.path(),
368- &[
369- "clone",
370- "-q",
371- "--bare",
372- "--no-hardlinks",
373- work.to_str().expect("utf8"),
374- &dest,
375- ],
376- );
377- let empty = store
378- .create_repo(&tahinli.id, "empty", "", Visibility::Private, "main")
379- .await
380- .expect("empty");
381- init_bare(
382- &git,
383- &repo_path(&data_dir, &empty.id).expect("path"),
384- "main",
385- )
386- .await
387- .expect("init empty");
388- store
389- .create_issue(&demo.id, &tahinli.id, "First issue", "body")
390- .await
391- .expect("issue");
392- std::fs::write(data_dir.join("forge.key"), [7u8; 32]).expect("key");
393- std::fs::set_permissions(
394- data_dir.join("forge.key"),
395- std::fs::Permissions::from_mode(0o600),
396- )
397- .expect("key mode");
398-
399- Source {
400- source: BackupSource {
401- store,
402- git,
403- base_url: "https://forge.example.invalid".into(),
404- },
405- data_dir,
406- demo_id: demo.id,
407- empty_id: empty.id,
408- dir,
409- }
410- }
411-
412- fn git_bin() -> PathBuf {
413- PathBuf::from("git")
414- }
415-
416- fn opts(out: &Path, include_key: bool) -> BackupOptions {
417- BackupOptions {
418- out: out.to_path_buf(),
419- include_key,
420- scope: Scope::All,
421- }
422- }
423-
424 fn for_each_ref(dir: &Path) -> String {342 fn for_each_ref(dir: &Path) -> String {
425 git_out(dir, &["for-each-ref", "--format=%(objectname) %(refname)"])343 git_out(dir, &["for-each-ref", "--format=%(objectname) %(refname)"])
426 }344 }
@@ -429,7 +347,7 @@ mod tests {
429 async fn round_trip_restores_store_repos_hooks_and_config() {347 async fn round_trip_restores_store_repos_hooks_and_config() {
430 let src = source().await;348 let src = source().await;
431 let out = src.dir.path().join("out");349 let out = src.dir.path().join("out");
432- let summary = create_backup(&src.source, &opts(&out, true))350+ let summary = create_backup(&src.source, &opts(&out, true, Scope::All))
433 .await351 .await
434 .expect("backup");352 .expect("backup");
435 let target = src.dir.path().join("fresh");353 let target = src.dir.path().join("fresh");
@@ -517,7 +435,7 @@ mod tests {
517 .expect("commit page");435 .expect("commit page");
518 436
519 let out = src.dir.path().join("out");437 let out = src.dir.path().join("out");
520- let summary = create_backup(&src.source, &opts(&out, true))438+ let summary = create_backup(&src.source, &opts(&out, true, Scope::All))
521 .await439 .await
522 .expect("backup");440 .expect("backup");
523 let manifest = std::fs::read(summary.path.join(MANIFEST_FILE)).expect("manifest");441 let manifest = std::fs::read(summary.path.join(MANIFEST_FILE)).expect("manifest");
@@ -549,7 +467,7 @@ mod tests {
549 async fn restore_refuses_a_non_empty_target() {467 async fn restore_refuses_a_non_empty_target() {
550 let src = source().await;468 let src = source().await;
551 let out = src.dir.path().join("out");469 let out = src.dir.path().join("out");
552- let summary = create_backup(&src.source, &opts(&out, false))470+ let summary = create_backup(&src.source, &opts(&out, false, Scope::All))
553 .await471 .await
554 .expect("backup");472 .expect("backup");
555 let target = src.dir.path().join("busy");473 let target = src.dir.path().join("busy");
@@ -568,7 +486,7 @@ mod tests {
568 async fn restore_refuses_a_tampered_set_and_writes_nothing() {486 async fn restore_refuses_a_tampered_set_and_writes_nothing() {
569 let src = source().await;487 let src = source().await;
570 let out = src.dir.path().join("out");488 let out = src.dir.path().join("out");
571- let summary = create_backup(&src.source, &opts(&out, false))489+ let summary = create_backup(&src.source, &opts(&out, false, Scope::All))
572 .await490 .await
573 .expect("backup");491 .expect("backup");
574 let bundle = summary.path.join(format!("repos/{}.bundle", src.demo_id));492 let bundle = summary.path.join(format!("repos/{}.bundle", src.demo_id));
@@ -590,7 +508,7 @@ mod tests {
590 async fn restore_without_key_warns() {508 async fn restore_without_key_warns() {
591 let src = source().await;509 let src = source().await;
592 let out = src.dir.path().join("out");510 let out = src.dir.path().join("out");
593- let summary = create_backup(&src.source, &opts(&out, false))511+ let summary = create_backup(&src.source, &opts(&out, false, Scope::All))
594 .await512 .await
595 .expect("backup");513 .expect("backup");
596 let target = src.dir.path().join("fresh");514 let target = src.dir.path().join("fresh");
crates/forge-web-app/src/backup/scheduler.rsmodified+18 -33
@@ -214,12 +214,16 @@ pub fn configured_dir(state: &AppState) -> Result<PathBuf> {
214 std::path::absolute(&state.config.backup.dir).map_err(Error::Io)214 std::path::absolute(&state.config.backup.dir).map_err(Error::Io)
215 }215 }
216 216
217-async fn scheduled_backup(state: &AppState) -> Result<BackupSummary> {217+fn full_set_options(state: &AppState) -> Result<BackupOptions> {
218- let opts = BackupOptions {218+ Ok(BackupOptions {
219 out: configured_dir(state)?,219 out: configured_dir(state)?,
220 include_key: false,220 include_key: false,
221 scope: super::Scope::All,221 scope: super::Scope::All,
222- };222+ })
223+}
224+
225+async fn scheduled_backup(state: &AppState) -> Result<BackupSummary> {
226+ let opts = full_set_options(state)?;
223 backup_job(state, RunTrigger::Schedule, opts, true).await227 backup_job(state, RunTrigger::Schedule, opts, true).await
224 }228 }
225 229
@@ -296,23 +300,13 @@ pub async fn fsck_job(state: &AppState, trigger: RunTrigger, full: bool) -> Resu
296 let run_id = state.store.start_run(RunKind::Fsck, trigger).await?;300 let run_id = state.store.start_run(RunKind::Fsck, trigger).await?;
297 runs_changed();301 runs_changed();
298 let outcome = run_fsck(&state.store, &state.git, full).await;302 let outcome = run_fsck(&state.store, &state.git, full).await;
299- match &outcome {303+ let problem: Option<String> = match &outcome {
300- Ok(summary) if summary.is_ok() => crate::alerts::fsck_finished(state, Ok(())).await,304+ Ok(summary) if summary.is_ok() => None,
301- Ok(summary) => crate::alerts::fsck_finished(state, Err(&summary.problems.join("\n"))).await,305+ Ok(summary) => Some(summary.problems.join("\n")),
302- Err(e) => crate::alerts::fsck_finished(state, Err(&e.to_string())).await,306+ Err(e) => Some(e.to_string()),
303- }307+ };
304- match &outcome {308+ crate::alerts::fsck_finished(state, problem.as_deref().map_or(Ok(()), Err)).await;
305- Ok(summary) if summary.is_ok() => {309+ record_finish(state, &run_id, problem.is_none(), None, None, problem.as_deref()).await;
306- record_finish(state, &run_id, true, None, None, None).await;
307- }
308- Ok(summary) => {
309- let text = summary.problems.join("\n");
310- record_finish(state, &run_id, false, None, None, Some(&text)).await;
311- }
312- Err(e) => {
313- record_finish(state, &run_id, false, None, None, Some(&e.to_string())).await;
314- }
315- }
316 outcome310 outcome
317 }311 }
318 312
@@ -346,19 +340,10 @@ pub fn start_manual(state: &AppState, guard: JobGuard) -> Result<()> {
346 tokio::spawn(async move {340 tokio::spawn(async move {
347 let _guard = guard;341 let _guard = guard;
348 let outcome: Result<()> = match kind {342 let outcome: Result<()> = match kind {
349- RunKind::Backup => match configured_dir(&state) {343+ RunKind::Backup => match full_set_options(&state) {
350- Ok(out) => backup_job(344+ Ok(opts) => backup_job(&state, RunTrigger::Manual, opts, true)
351- &state,345+ .await
352- RunTrigger::Manual,346+ .map(|_| ()),
353- BackupOptions {
354- out,
355- include_key: false,
356- scope: super::Scope::All,
357- },
358- true,
359- )
360- .await
361- .map(|_| ()),
362 Err(e) => Err(e),347 Err(e) => Err(e),
363 },348 },
364 RunKind::Fsck => fsck_job(&state, RunTrigger::Manual, false)349 RunKind::Fsck => fsck_job(&state, RunTrigger::Manual, false)
crates/forge-web-app/src/backup/tests.rsmodified+10 -10
@@ -15,16 +15,16 @@ use super::{
15 verify_backup,15 verify_backup,
16 };16 };
17 17
18-struct Fixture {18+pub(super) struct Fixture {
19- dir: tempfile::TempDir,19+ pub(super) dir: tempfile::TempDir,
20- source: BackupSource,20+ pub(super) source: BackupSource,
21- git: GitEnv,21+ pub(super) git: GitEnv,
22- data_dir: PathBuf,22+ pub(super) data_dir: PathBuf,
23- demo_id: String,23+ pub(super) demo_id: String,
24- empty_id: String,24+ pub(super) empty_id: String,
25 }25 }
26 26
27-fn git_in(dir: &Path, args: &[&str]) {27+pub(super) fn git_in(dir: &Path, args: &[&str]) {
28 let out = Command::new("git")28 let out = Command::new("git")
29 .current_dir(dir)29 .current_dir(dir)
30 .env("GIT_AUTHOR_NAME", "t")30 .env("GIT_AUTHOR_NAME", "t")
@@ -39,7 +39,7 @@ fn git_in(dir: &Path, args: &[&str]) {
39 39
40 /// A store with one user, a repo that has commits, a branch and a tag, and an empty repo. The40 /// A store with one user, a repo that has commits, a branch and a tag, and an empty repo. The
41 /// repos are laid out where the server would put them.41 /// repos are laid out where the server would put them.
42-async fn fixture() -> Fixture {42+pub(super) async fn fixture() -> Fixture {
43 let dir = tempfile::tempdir().expect("tempdir");43 let dir = tempfile::tempdir().expect("tempdir");
44 let data_dir = dir.path().join("data");44 let data_dir = dir.path().join("data");
45 std::fs::create_dir_all(&data_dir).expect("data dir");45 std::fs::create_dir_all(&data_dir).expect("data dir");
@@ -105,7 +105,7 @@ async fn fixture() -> Fixture {
105 }105 }
106 }106 }
107 107
108-fn opts(out: &Path, include_key: bool, scope: Scope) -> BackupOptions {108+pub(super) fn opts(out: &Path, include_key: bool, scope: Scope) -> BackupOptions {
109 BackupOptions {109 BackupOptions {
110 out: out.to_path_buf(),110 out: out.to_path_buf(),
111 include_key,111 include_key,
crates/forge-web-app/src/backup/verify.rsmodified+60 -55
@@ -100,49 +100,55 @@ fn check_layout(root: &Path, manifest: &Manifest, problems: &mut Vec<String>) ->
100 if !ids.insert(repo.id.as_str()) {100 if !ids.insert(repo.id.as_str()) {
101 problems.push(format!("repo {} is listed twice", repo.id));101 problems.push(format!("repo {} is listed twice", repo.id));
102 }102 }
103- match &repo.bundle {103+ check_bundle(
104- Some(b) => {104+ problems,
105- if *b != format!("repos/{}.bundle", repo.id) || !listed.contains(b.as_str()) {105+ &listed,
106- problems.push(format!(106+ &repo.id,
107- "repo {}: bundle {b} is not listed as a file",107+ "",
108- repo.id108+ repo.bundle.as_deref(),
109- ));109+ &repo.refs_sha256,
110- }110+ format!("repos/{}.bundle", repo.id),
111- }111+ );
112- None => {112+ if let Some(wiki) = &repo.wiki {
113- if repo.refs_sha256 != empty_sha256() {113+ check_bundle(
114- problems.push(format!(114+ problems,
115- "repo {} has no bundle but its refs are not empty",115+ &listed,
116- repo.id116+ &repo.id,
117- ));117+ "wiki ",
118- }118+ wiki.bundle.as_deref(),
119+ &wiki.refs_sha256,
120+ format!("repos/{}.wiki.bundle", repo.id),
121+ );
122+ }
123+ }
124+ Ok(())
125+}
126+
127+fn check_bundle(
128+ problems: &mut Vec<String>,
129+ listed: &BTreeSet<&str>,
130+ repo_id: &str,
131+ label: &str,
132+ bundle: Option<&str>,
133+ refs_sha256: &str,
134+ expected_path: String,
135+) {
136+ match bundle {
137+ Some(b) => {
138+ if b != expected_path || !listed.contains(b) {
139+ problems.push(format!(
140+ "repo {repo_id}: {label}bundle {b} is not listed as a file"
141+ ));
119 }142 }
120 }143 }
121- // The wiki, when the set has one, follows the same rules under its own file name.144+ None => {
122- if let Some(wiki) = &repo.wiki {145+ if refs_sha256 != empty_sha256() {
123- match &wiki.bundle {146+ problems.push(format!(
124- Some(b) => {147+ "repo {repo_id} has no {label}bundle but its {label}refs are not empty"
125- if *b != format!("repos/{}.wiki.bundle", repo.id)148+ ));
126- || !listed.contains(b.as_str())
127- {
128- problems.push(format!(
129- "repo {}: wiki bundle {b} is not listed as a file",
130- repo.id
131- ));
132- }
133- }
134- None => {
135- if wiki.refs_sha256 != empty_sha256() {
136- problems.push(format!(
137- "repo {} has no wiki bundle but its wiki refs are not empty",
138- repo.id
139- ));
140- }
141- }
142 }149 }
143 }150 }
144 }151 }
145- Ok(())
146 }152 }
147 153
148 /// Collects regular files under `dir` as paths relative to `root`. Unexpected directories and154 /// Collects regular files under `dir` as paths relative to `root`. Unexpected directories and
@@ -259,28 +265,28 @@ async fn check_bundles(
259 git: &GitEnv,265 git: &GitEnv,
260 problems: &mut Vec<String>,266 problems: &mut Vec<String>,
261 ) -> Result<usize> {267 ) -> Result<usize> {
262- let bundles: Vec<(usize, &super::RepoEntry, &str)> = manifest268+ let mut bundles: Vec<(String, &str, &str)> = Vec::new();
263- .repos269+ for repo in &manifest.repos {
264- .iter()270+ if let Some(b) = &repo.bundle {
265- .enumerate()271+ bundles.push((format!("repo {}", repo.id), b, &repo.refs_sha256));
266- .filter_map(|(i, r)| r.bundle.as_deref().map(|b| (i, r, b)))272+ }
267- .collect();273+ if let Some(wiki) = &repo.wiki
274+ && let Some(b) = &wiki.bundle
275+ {
276+ bundles.push((format!("repo {} wiki", repo.id), b, &wiki.refs_sha256));
277+ }
278+ }
268 if bundles.is_empty() {279 if bundles.is_empty() {
269 return Ok(0);280 return Ok(0);
270 }281 }
271 let parent = root282 let parent = root
272 .parent()283 .parent()
273 .ok_or_else(|| Error::Invalid("the backup set has no parent directory".into()))?;284 .ok_or_else(|| Error::Invalid("the backup set has no parent directory".into()))?;
274- let suffix = format!(285+ let scratch_root: PathBuf = parent.join(format!(".partial-verify-{}", super::unique_suffix()));
275- "{}-{}",
276- std::process::id(),
277- time::OffsetDateTime::now_utc().unix_timestamp_nanos()
278- );
279- let scratch_root: PathBuf = parent.join(format!(".partial-verify-{suffix}"));
280 create_private_dir(&scratch_root)?;286 create_private_dir(&scratch_root)?;
281 287
282 let mut passed = 0;288 let mut passed = 0;
283- for (idx, repo, bundle) in bundles {289+ for (idx, (name, bundle, expected)) in bundles.into_iter().enumerate() {
284 let scratch = scratch_root.join(format!("{idx}.git"));290 let scratch = scratch_root.join(format!("{idx}.git"));
285 let outcome = async {291 let outcome = async {
286 forge_git::repo::init_bare(git, &scratch, "main").await?;292 forge_git::repo::init_bare(git, &scratch, "main").await?;
@@ -288,12 +294,11 @@ async fn check_bundles(
288 }294 }
289 .await;295 .await;
290 match outcome {296 match outcome {
291- Ok(imported) if imported == repo.refs_sha256 => passed += 1,297+ Ok(imported) if imported == expected => passed += 1,
292 Ok(imported) => problems.push(format!(298 Ok(imported) => problems.push(format!(
293- "repo {}: bundle refs {imported} do not match the manifest {}",299+ "{name}: bundle refs {imported} do not match the manifest {expected}"
294- repo.id, repo.refs_sha256
295 )),300 )),
296- Err(e) => problems.push(format!("repo {}: bundle failed verification: {e}", repo.id)),301+ Err(e) => problems.push(format!("{name}: bundle failed verification: {e}")),
297 }302 }
298 }303 }
299 if let Err(e) = std::fs::remove_dir_all(&scratch_root) {304 if let Err(e) = std::fs::remove_dir_all(&scratch_root) {
crates/forge-web-app/src/ci/api.rsmodified+91 -144
@@ -18,6 +18,7 @@ use forge_core::Error as CoreError;
18 use forge_core::ci::{18 use forge_core::ci::{
19 CiJob, CiRun, CiRunner, JobState, MemoryOffer, QueueSkips, RestartMode, RunState, RunnerReport,19 CiJob, CiRun, CiRunner, JobState, MemoryOffer, QueueSkips, RestartMode, RunState, RunnerReport,
20 };20 };
21+use forge_core::pulls::PullRequest;
21 use futures_util::StreamExt;22 use futures_util::StreamExt;
22 use http::header::HeaderValue;23 use http::header::HeaderValue;
23 use serde_json::json;24 use serde_json::json;
@@ -62,6 +63,7 @@ const MAX_LABELS: usize = 32;
62 /// Text appended once when the log cap is reached.63 /// Text appended once when the log cap is reached.
63 const TRUNCATED_MARKER: &[u8] = b"\n[log truncated]\n";64 const TRUNCATED_MARKER: &[u8] = b"\n[log truncated]\n";
64 const MIB: u64 = 1024 * 1024;65 const MIB: u64 = 1024 * 1024;
66+static LOG_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
65 67
66 /// Bearer token from the `Authorization` header, or `None`.68 /// Bearer token from the `Authorization` header, or `None`.
67 fn bearer_token(headers: &HeaderMap) -> Option<&str> {69 fn bearer_token(headers: &HeaderMap) -> Option<&str> {
@@ -114,9 +116,8 @@ async fn job_from(state: &AppState, headers: &HeaderMap, job_id: &str) -> Result
114 }116 }
115 }117 }
116 118
117-/// Parses a JSON body of at most [`MAX_JSON_BODY`] bytes.119+async fn json_body<T: serde::de::DeserializeOwned>(body: Body, limit: usize) -> Result<T, Refusal> {
118-async fn json_body<T: serde::de::DeserializeOwned>(body: Body) -> Result<T, Refusal> {120+ let bytes = api::read_body(body, limit).await?;
119- let bytes = api::read_body(body, MAX_JSON_BODY).await?;
120 serde_json::from_slice(&bytes).map_err(|e| {121 serde_json::from_slice(&bytes).map_err(|e| {
121 Box::new(api::error(122 Box::new(api::error(
122 StatusCode::BAD_REQUEST,123 StatusCode::BAD_REQUEST,
@@ -146,17 +147,14 @@ pub fn valid_artifact_name(name: &str) -> bool {
146 #[route(POST "/api/v1/ci/runners/register")]147 #[route(POST "/api/v1/ci/runners/register")]
147 async fn register(cx: &Cx, body: Body) -> topcoat::Result<Response> {148 async fn register(cx: &Cx, body: Body) -> topcoat::Result<Response> {
148 let state = context::<AppState>(cx);149 let state = context::<AppState>(cx);
149- let request: RegisterRequest = match json_body(body).await {150+ let request: RegisterRequest = match json_body(body, MAX_JSON_BODY).await {
150 Ok(request) => request,151 Ok(request) => request,
151 Err(res) => return Ok(*res),152 Err(res) => return Ok(*res),
152 };153 };
153- if !valid_name(&request.name) || request.labels.len() > MAX_LABELS {154+ if !valid_name(&request.name)
154- return Ok(api::error(155+ || request.labels.len() > MAX_LABELS
155- StatusCode::UNPROCESSABLE_ENTITY,156+ || request.labels.iter().any(|label| !valid_name(label))
156- "the runner name or labels are invalid",157+ {
157- ));
158- }
159- if request.labels.iter().any(|label| !valid_name(label)) {
160 return Ok(api::error(158 return Ok(api::error(
161 StatusCode::UNPROCESSABLE_ENTITY,159 StatusCode::UNPROCESSABLE_ENTITY,
162 "the runner name or labels are invalid",160 "the runner name or labels are invalid",
@@ -173,10 +171,7 @@ async fn register(cx: &Cx, body: Body) -> topcoat::Result<Response> {
173 runner_id: runner.id,171 runner_id: runner.id,
174 runner_secret: secret,172 runner_secret: secret,
175 };173 };
176- Ok(api::json(174+ Ok(api::json(StatusCode::CREATED, &body))
177- StatusCode::CREATED,
178- &serde_json::to_value(&body).unwrap_or_default(),
179- ))
180 }175 }
181 Err(CoreError::Invalid(_)) => Ok(api::error(176 Err(CoreError::Invalid(_)) => Ok(api::error(
182 StatusCode::UNAUTHORIZED,177 StatusCode::UNAUTHORIZED,
@@ -239,9 +234,7 @@ async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> {
239 .await;234 .await;
240 let mut res = claim_work(state, &runner, offer).await?;235 let mut res = claim_work(state, &runner, offer).await?;
241 // The override can change during the long poll, so it is read at answer time.236 // The override can change during the long poll, so it is read at answer time.
242- set_concurrency_header(state, &runner.id, &mut res).await;237+ set_claim_headers(state, &runner.id, &mut res).await;
243- set_memory_headers(state, &runner.id, &mut res).await;
244- set_restart_header(state, &runner.id, &mut res).await;
245 // Advertises the binary sha256 when self-update is on and the runner asked for this target.238 // Advertises the binary sha256 when self-update is on and the runner asked for this target.
246 self_update::advertise(state, headers(cx), &mut res);239 self_update::advertise(state, headers(cx), &mut res);
247 Ok(res)240 Ok(res)
@@ -277,8 +270,7 @@ async fn note_report(state: &AppState, runner_id: &str, report: &RunnerReport) {
277 }270 }
278 }271 }
279 272
280-/// Adds the admin's concurrency override to a claim answer. No header means no override.273+async fn set_claim_headers(state: &AppState, runner_id: &str, res: &mut Response) {
281-async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Response) {
282 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {274 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
283 return;275 return;
284 }276 }
@@ -287,36 +279,21 @@ async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Res
287 {279 {
288 res.headers_mut().insert(CONCURRENCY_HEADER, value);280 res.headers_mut().insert(CONCURRENCY_HEADER, value);
289 }281 }
290-}282+ if let Ok(Some(text)) = state
291-283+ .store
292-/// Adds the admin's memory budget and default reservation to a claim answer. No header means no284+ .runner_field_override(runner_id, "limits.memory_budget")
293-/// override. An older runner ignores both.285+ .await
294-async fn set_memory_headers(state: &AppState, runner_id: &str, res: &mut Response) {286+ && let Ok(value) = HeaderValue::from_str(&text)
295- if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {287+ {
296- return;288+ res.headers_mut().insert(MEMORY_BUDGET_HEADER, value);
297- }
298- for (key, header) in [
299- ("limits.memory_budget", MEMORY_BUDGET_HEADER),
300- ("limits.reserve_memory", RESERVE_MEMORY_HEADER),
301- ] {
302- if let Ok(Some(text)) = state.store.runner_field_override(runner_id, key).await
303- && let Ok(value) = HeaderValue::from_str(&text)
304- {
305- res.headers_mut().insert(header, value);
306- }
307 }289 }
308-}290+ if let Ok(Some(text)) = state
309-291+ .store
310-/// The restart an admin asked for, in the wire type. `None` when nothing is pending.292+ .runner_field_override(runner_id, "limits.reserve_memory")
311-async fn pending_restart(state: &AppState, runner_id: &str) -> Option<RestartMode> {293+ .await
312- state.store.runner_restart(runner_id).await.ok().flatten()294+ && let Ok(value) = HeaderValue::from_str(&text)
313-}295+ {
314-296+ res.headers_mut().insert(RESERVE_MEMORY_HEADER, value);
315-/// Adds the pending restart request to a claim answer. Sent on every answer until the runner
316-/// comes back with a new boot id. An older runner ignores the header.
317-async fn set_restart_header(state: &AppState, runner_id: &str, res: &mut Response) {
318- if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
319- return;
320 }297 }
321 if let Some(mode) = pending_restart(state, runner_id).await {298 if let Some(mode) = pending_restart(state, runner_id).await {
322 res.headers_mut()299 res.headers_mut()
@@ -324,6 +301,10 @@ async fn set_restart_header(state: &AppState, runner_id: &str, res: &mut Respons
324 }301 }
325 }302 }
326 303
304+async fn pending_restart(state: &AppState, runner_id: &str) -> Option<RestartMode> {
305+ state.store.runner_restart(runner_id).await.ok().flatten()
306+}
307+
327 /// `POST /api/v1/ci/runners/log`: a batch of the runner's own log lines. Answers the next line308 /// `POST /api/v1/ci/runners/log`: a batch of the runner's own log lines. Answers the next line
328 /// number the forge wants for this boot id, so the runner resends what was lost.309 /// number the forge wants for this boot id, so the runner resends what was lost.
329 #[route(POST "/api/v1/ci/runners/log")]310 #[route(POST "/api/v1/ci/runners/log")]
@@ -333,18 +314,9 @@ async fn runner_log(cx: &Cx, body: Body) -> topcoat::Result<Response> {
333 Ok(runner) => runner,314 Ok(runner) => runner,
334 Err(res) => return Ok(*res),315 Err(res) => return Ok(*res),
335 };316 };
336- let bytes = match api::read_body(body, MAX_LOG_BATCH).await {317+ let batch: RunnerLogBatch = match json_body(body, MAX_LOG_BATCH).await {
337- Ok(bytes) => bytes,
338- Err(res) => return Ok(*res),
339- };
340- let batch: RunnerLogBatch = match serde_json::from_slice(&bytes) {
341 Ok(batch) => batch,318 Ok(batch) => batch,
342- Err(e) => {319+ Err(res) => return Ok(*res),
343- return Ok(api::error(
344- StatusCode::BAD_REQUEST,
345- &format!("invalid JSON body: {e}"),
346- ));
347- }
348 };320 };
349 if batch.boot_id.is_empty() || batch.boot_id.len() > 64 {321 if batch.boot_id.is_empty() || batch.boot_id.len() > 64 {
350 return Ok(api::error(322 return Ok(api::error(
@@ -354,8 +326,7 @@ async fn runner_log(cx: &Cx, body: Body) -> topcoat::Result<Response> {
354 }326 }
355 let next_seq = state.runner_logs.ingest(&runner.id, &batch);327 let next_seq = state.runner_logs.ingest(&runner.id, &batch);
356 state.ci_live.bump_runners();328 state.ci_live.bump_runners();
357- let ack = serde_json::to_value(RunnerLogAck { next_seq }).unwrap_or_default();329+ Ok(api::json(StatusCode::OK, &RunnerLogAck { next_seq }))
358- Ok(api::json(StatusCode::OK, &ack))
359 }330 }
360 331
361 /// `POST /api/v1/ci/runners/metrics`: host usage samples of the runner, for the graphs on its admin332 /// `POST /api/v1/ci/runners/metrics`: host usage samples of the runner, for the graphs on its admin
@@ -367,18 +338,9 @@ async fn runner_metrics(cx: &Cx, body: Body) -> topcoat::Result<Response> {
367 Ok(runner) => runner,338 Ok(runner) => runner,
368 Err(res) => return Ok(*res),339 Err(res) => return Ok(*res),
369 };340 };
370- let bytes = match api::read_body(body, MAX_METRICS_BATCH).await {341+ let batch: RunnerMetricsBatch = match json_body(body, MAX_METRICS_BATCH).await {
371- Ok(bytes) => bytes,
372- Err(res) => return Ok(*res),
373- };
374- let batch: RunnerMetricsBatch = match serde_json::from_slice(&bytes) {
375 Ok(batch) => batch,342 Ok(batch) => batch,
376- Err(e) => {343+ Err(res) => return Ok(*res),
377- return Ok(api::error(
378- StatusCode::BAD_REQUEST,
379- &format!("invalid JSON body: {e}"),
380- ));
381- }
382 };344 };
383 if batch.samples.len() > MAX_METRICS_SAMPLES {345 if batch.samples.len() > MAX_METRICS_SAMPLES {
384 return Ok(api::error(346 return Ok(api::error(
@@ -410,7 +372,7 @@ async fn runner_config_put(cx: &Cx, body: Body) -> topcoat::Result<Response> {
410 Ok(runner) => runner,372 Ok(runner) => runner,
411 Err(res) => return Ok(*res),373 Err(res) => return Ok(*res),
412 };374 };
413- let report: RunnerConfigReport = match json_body(body).await {375+ let report: RunnerConfigReport = match json_body(body, MAX_JSON_BODY).await {
414 Ok(report) => report,376 Ok(report) => report,
415 Err(res) => return Ok(*res),377 Err(res) => return Ok(*res),
416 };378 };
@@ -431,12 +393,11 @@ async fn runner_config_put(cx: &Cx, body: Body) -> topcoat::Result<Response> {
431 }393 }
432 394
433 fn overrides_response(runner: &CiRunner) -> Response {395 fn overrides_response(runner: &CiRunner) -> Response {
434- let reply = RunnerConfigOverrides {
435- overrides: runner.config_overrides.clone(),
436- };
437 api::json(396 api::json(
438 StatusCode::OK,397 StatusCode::OK,
439- &serde_json::to_value(reply).unwrap_or_default(),398+ &RunnerConfigOverrides {
399+ overrides: runner.config_overrides.clone(),
400+ },
440 )401 )
441 }402 }
442 403
@@ -462,7 +423,7 @@ async fn claim_work(
462 return Ok(empty(StatusCode::NO_CONTENT));423 return Ok(empty(StatusCode::NO_CONTENT));
463 }424 }
464 match try_claim(state, runner, offer).await {425 match try_claim(state, runner, offer).await {
465- Ok(Some(assignment)) => return Ok(assignment_response(&assignment)),426+ Ok(Some(assignment)) => return Ok(api::json(StatusCode::OK, &assignment)),
466 Ok(None) => {}427 Ok(None) => {}
467 Err(res) => return Ok(*res),428 Err(res) => return Ok(*res),
468 }429 }
@@ -574,13 +535,6 @@ async fn runner_binary(cx: &Cx) -> topcoat::Result<Response> {
574 }535 }
575 }536 }
576 537
577-fn assignment_response(assignment: &JobAssignment) -> Response {
578- api::json(
579- StatusCode::OK,
580- &serde_json::to_value(assignment).unwrap_or_default(),
581- )
582-}
583-
584 fn empty(status: StatusCode) -> Response {538 fn empty(status: StatusCode) -> Response {
585 let mut res = Response::new(topcoat::router::Body::empty());539 let mut res = Response::new(topcoat::router::Body::empty());
586 *res.status_mut() = status;540 *res.status_mut() = status;
@@ -605,13 +559,30 @@ async fn try_claim(
605 state.ci_live.bump_run(&run.id);559 state.ci_live.bump_run(&run.id);
606 state.ci_live.bump_repo(&run.repo_id);560 state.ci_live.bump_repo(&run.repo_id);
607 state.ci_live.bump_runners();561 state.ci_live.bump_runners();
608- // The next refusal is written again, and this job is written now.
609 state.runner_logs.clear_note(&runner.id);562 state.runner_logs.clear_note(&runner.id);
610 note_runner(563 note_runner(
611 state,564 state,
612 &runner.id,565 &runner.id,
613 &format!("took job {} of run #{}", job.name, run.number),566 &format!("took job {} of run #{}", job.name, run.number),
614 );567 );
568+ let job_id = job.id.clone();
569+ match build_assignment(state, job, run, job_token).await {
570+ Ok(assignment) => Ok(Some(assignment)),
571+ Err(e) => {
572+ if let Err(err) = state.store.requeue_job(&job_id).await {
573+ tracing::warn!(error = %err, job = %job_id, "ci: failed claim not requeued");
574+ }
575+ Err(e)
576+ }
577+ }
578+}
579+
580+async fn build_assignment(
581+ state: &AppState,
582+ job: CiJob,
583+ run: CiRun,
584+ job_token: String,
585+) -> Result<JobAssignment, Refusal> {
615 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;586 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
616 let repo = state587 let repo = state
617 .store588 .store
@@ -619,8 +590,15 @@ async fn try_claim(
619 .await590 .await
620 .map_err(api::internal)?591 .map_err(api::internal)?
621 .ok_or_else(|| api::internal("claimed job belongs to a missing repo"))?;592 .ok_or_else(|| api::internal("claimed job belongs to a missing repo"))?;
622-593+ let pull = match (run.trigger.as_str(), run.pull_number) {
623- let secrets = if is_fork_run(state, &run).await? {594+ ("pull_request", Some(number)) => state
595+ .store
596+ .pull_by_number(&run.repo_id, number)
597+ .await
598+ .map_err(api::internal)?,
599+ _ => None,
600+ };
601+ let secrets = if is_fork_run(&run, pull.as_ref()) {
624 BTreeMap::new()602 BTreeMap::new()
625 } else {603 } else {
626 state604 state
@@ -629,11 +607,9 @@ async fn try_claim(
629 .await607 .await
630 .map_err(api::internal)?608 .map_err(api::internal)?
631 };609 };
632-
633 let (cache_key, cache_restore_keys) =610 let (cache_key, cache_restore_keys) =
634- cache_scopes(state, &run, &repo.default_branch, &spec.cache).await?;611+ cache_scopes(&run, &repo.default_branch, &spec.cache, pull.as_ref());
635-612+ Ok(JobAssignment {
636- Ok(Some(JobAssignment {
637 job_id: job.id,613 job_id: job.id,
638 job_token,614 job_token,
639 repo: format!("{}/{}", repo.owner_name, repo.name),615 repo: format!("{}/{}", repo.owner_name, repo.name),
@@ -652,41 +628,29 @@ async fn try_claim(
652 cache_key,628 cache_key,
653 cache_restore_keys,629 cache_restore_keys,
654 memory_bytes: spec.memory,630 memory_bytes: spec.memory,
655- }))631+ })
656 }632 }
657 633
658-/// The cache scopes of a job's run. A job without `cache` gets none. A pull request run's base634+fn cache_scopes(
659-/// branch comes from its pull request record.
660-async fn cache_scopes(
661- state: &AppState,
662 run: &CiRun,635 run: &CiRun,
663 default_branch: &str,636 default_branch: &str,
664 cache: &[String],637 cache: &[String],
665-) -> Result<(String, Vec<String>), Refusal> {638+ pull: Option<&PullRequest>,
639+) -> (String, Vec<String>) {
666 if cache.is_empty() {640 if cache.is_empty() {
667- return Ok((String::new(), Vec::new()));641+ return (String::new(), Vec::new());
668 }642 }
669- let pull_base = match (run.trigger.as_str(), run.pull_number) {
670- ("pull_request", Some(number)) => state
671- .store
672- .pull_by_number(&run.repo_id, number)
673- .await
674- .map_err(api::internal)?
675- .map(|pull| pull.base_branch),
676- _ => None,
677- };
678 let scope = cache_scope(643 let scope = cache_scope(
679 &run.trigger,644 &run.trigger,
680 &run.git_ref,645 &run.git_ref,
681 run.pull_number,646 run.pull_number,
682- pull_base.as_deref(),647+ pull.map(|pull| pull.base_branch.as_str()),
683 default_branch,648 default_branch,
684 );649 );
685- Ok(match scope {650+ match scope {
686 Some(scope) => (scope.key, scope.restore_keys),651 Some(scope) => (scope.key, scope.restore_keys),
687- // A run whose scope cannot be derived gets no key, so the runner neither restores nor saves.
688 None => (String::new(), Vec::new()),652 None => (String::new(), Vec::new()),
689- })653+ }
690 }654 }
691 655
692 /// The cache scope a run may write, and the read-only scopes it may restore from.656 /// The cache scope a run may write, and the read-only scopes it may restore from.
@@ -740,24 +704,9 @@ fn cache_scope(
740 }704 }
741 }705 }
742 706
743-/// True for a pull-request run whose head is not this repo, or whose pull request is gone. Such707+fn is_fork_run(run: &CiRun, pull: Option<&PullRequest>) -> bool {
744-/// runs get no secrets. Missing data counts as a fork, so the answer errs on the safe side.708+ run.trigger == "pull_request"
745-async fn is_fork_run(state: &AppState, run: &CiRun) -> Result<bool, Refusal> {709+ && pull.is_none_or(|pull| pull.head_repo_id.as_deref() != Some(run.repo_id.as_str()))
746- if run.trigger != "pull_request" {
747- return Ok(false);
748- }
749- let Some(number) = run.pull_number else {
750- return Ok(true);
751- };
752- match state
753- .store
754- .pull_by_number(&run.repo_id, number)
755- .await
756- .map_err(api::internal)?
757- {
758- Some(pull) => Ok(pull.head_repo_id.as_deref() != Some(run.repo_id.as_str())),
759- None => Ok(true),
760- }
761 }710 }
762 711
763 // ---------------------------------------------------------------------------------------------712 // ---------------------------------------------------------------------------------------------
@@ -819,25 +768,19 @@ async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> {
819 }768 }
820 Ok(api::json(769 Ok(api::json(
821 StatusCode::OK,770 StatusCode::OK,
822- &serde_json::to_value(HeartbeatResponse {771+ &HeartbeatResponse {
823 cancel,772 cancel,
824 concurrency,773 concurrency,
825 restart,774 restart,
826- })775+ },
827- .unwrap_or_default(),
828 ))776 ))
829 }777 }
830 Err(e) => Ok(*api::internal(e)),778 Err(e) => Ok(*api::internal(e)),
831 }779 }
832 }780 }
833 781
834-/// Outcome of a log append.
835 enum LogWrite {782 enum LogWrite {
836- /// The chunk is stored (or was dropped by the cap); the size is the new byte count.
837 Stored(u64),783 Stored(u64),
838- /// This exact chunk was already stored: a retry. The size is unchanged.
839- Duplicate(u64),
840- /// The offset does not match the stored size.
841 Mismatch(u64),784 Mismatch(u64),
842 }785 }
843 786
@@ -864,7 +807,7 @@ async fn append_log(cx: &Cx, body: Body) -> topcoat::Result<Response> {
864 Err(res) => return Ok(*res),807 Err(res) => return Ok(*res),
865 };808 };
866 match write_log(state, &job, offset, &chunk).await {809 match write_log(state, &job, offset, &chunk).await {
867- Ok(LogWrite::Stored(size) | LogWrite::Duplicate(size)) => {810+ Ok(LogWrite::Stored(size)) => {
868 Ok(api::json(StatusCode::OK, &json!({ "size": size })))811 Ok(api::json(StatusCode::OK, &json!({ "size": size })))
869 }812 }
870 Ok(LogWrite::Mismatch(size)) => {813 Ok(LogWrite::Mismatch(size)) => {
@@ -887,11 +830,15 @@ async fn write_log(
887 offset: u64,830 offset: u64,
888 chunk: &[u8],831 chunk: &[u8],
889 ) -> Result<LogWrite, Refusal> {832 ) -> Result<LogWrite, Refusal> {
890- let size = u64::try_from(job.log_bytes).unwrap_or(0);833+ let _guard = LOG_LOCK.lock().await;
834+ let size = match state.store.job_by_id(&job.id).await.map_err(api::internal)? {
835+ Some(fresh) => u64::try_from(fresh.log_bytes).unwrap_or(0),
836+ None => return Err(api::internal("log for a job that is gone")),
837+ };
891 let len = chunk.len() as u64;838 let len = chunk.len() as u64;
892 if offset != size {839 if offset != size {
893 return Ok(if offset.checked_add(len) == Some(size) {840 return Ok(if offset.checked_add(len) == Some(size) {
894- LogWrite::Duplicate(size)841+ LogWrite::Stored(size)
895 } else {842 } else {
896 LogWrite::Mismatch(size)843 LogWrite::Mismatch(size)
897 });844 });
@@ -1190,7 +1137,7 @@ async fn finish(cx: &Cx, body: Body) -> topcoat::Result<Response> {
1190 Ok(job) => job,1137 Ok(job) => job,
1191 Err(res) => return Ok(*res),1138 Err(res) => return Ok(*res),
1192 };1139 };
1193- let request: FinishRequest = match json_body(body).await {1140+ let request: FinishRequest = match json_body(body, MAX_JSON_BODY).await {
1194 Ok(request) => request,1141 Ok(request) => request,
1195 Err(res) => return Ok(*res),1142 Err(res) => return Ok(*res),
1196 };1143 };
@@ -1213,7 +1160,7 @@ async fn requeue(cx: &Cx, body: Body) -> topcoat::Result<Response> {
1213 Ok(job) => job,1160 Ok(job) => job,
1214 Err(res) => return Ok(*res),1161 Err(res) => return Ok(*res),
1215 };1162 };
1216- let request: RequeueRequest = match json_body(body).await {1163+ let request: RequeueRequest = match json_body(body, MAX_JSON_BODY).await {
1217 Ok(request) => request,1164 Ok(request) => request,
1218 Err(res) => return Ok(*res),1165 Err(res) => return Ok(*res),
1219 };1166 };
crates/forge-web-app/src/ci/metrics_chart.rsmodified+7 -4
@@ -140,14 +140,16 @@ pub fn nice_max(value: u64) -> u64 {
140 if value <= 1 {140 if value <= 1 {
141 return 1;141 return 1;
142 }142 }
143- let mut unit = 1u64;143+ let value = u128::from(value);
144- while unit.saturating_mul(10) <= value {144+ let mut unit = 1u128;
145+ while unit * 10 <= value {
145 unit *= 10;146 unit *= 10;
146 }147 }
147- [unit, unit * 2, unit * 5 / 2, unit * 5, unit * 10]148+ let nice = [unit, unit * 2, unit * 5 / 2, unit * 5, unit * 10]
148 .into_iter()149 .into_iter()
149 .find(|candidate| *candidate >= value)150 .find(|candidate| *candidate >= value)
150- .unwrap_or(unit * 10)151+ .unwrap_or(unit * 10);
152+ u64::try_from(nice).unwrap_or(u64::MAX)
151 }153 }
152 154
153 /// The largest value of a series over the buckets, as a whole number of bytes per second, at least155 /// The largest value of a series over the buckets, as a whole number of bytes per second, at least
@@ -295,5 +297,6 @@ mod tests {
295 assert_eq!(nice_max(1500), 2000);297 assert_eq!(nice_max(1500), 2000);
296 assert_eq!(nice_max(2400), 2500);298 assert_eq!(nice_max(2400), 2500);
297 assert_eq!(nice_max(3_145_728), 5_000_000);299 assert_eq!(nice_max(3_145_728), 5_000_000);
300+ assert_eq!(nice_max(15_000_000_000_000_000_000), u64::MAX);
298 }301 }
299 }302 }
crates/forge-web-app/src/ci/reaper.rsmodified+4 -10
@@ -44,9 +44,9 @@ async fn run(state: AppState) {
44 loop {44 loop {
45 tick.tick().await;45 tick.tick().await;
46 if booted.elapsed() >= LOST_AFTER {46 if booted.elapsed() >= LOST_AFTER {
47- reap_once(&state).await;47+ reap_before(&state, &stamp_ago(LOST_AFTER)).await;
48 }48 }
49- crate::alerts::check_runners(&state).await;49+ crate::alerts::check_runners(&state, crate::views::now_unix()).await;
50 if Instant::now() >= next_health {50 if Instant::now() >= next_health {
51 crate::live::admin().bump(&crate::live::Topic::AdminHealth);51 crate::live::admin().bump(&crate::live::Topic::AdminHealth);
52 next_health = Instant::now() + HEALTH_EVERY;52 next_health = Instant::now() + HEALTH_EVERY;
@@ -62,14 +62,8 @@ async fn run(state: AppState) {
62 }62 }
63 }63 }
64 64
65-/// Marks lost jobs as Error and syncs the statuses of every run they belong to. Returns how many65+/// Marks running jobs whose heartbeat is older than `older_than` as Error and syncs the statuses of
66-/// jobs were reaped.66+/// every run they belong to. Returns how many jobs were reaped.
67-pub async fn reap_once(state: &AppState) -> usize {
68- reap_before(state, &stamp_ago(LOST_AFTER)).await
69-}
70-
71-/// [`reap_once`] with an explicit cutoff: running jobs whose heartbeat is older than `older_than`
72-/// are lost.
73 pub async fn reap_before(state: &AppState, older_than: &str) -> usize {67 pub async fn reap_before(state: &AppState, older_than: &str) -> usize {
74 let jobs = match state.store.reap_lost_jobs(older_than).await {68 let jobs = match state.store.reap_lost_jobs(older_than).await {
75 Ok(jobs) => jobs,69 Ok(jobs) => jobs,
crates/forge-web-app/src/ci/release.rsmodified+0 -55
@@ -1,16 +1,3 @@
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};1 use forge_ci::config::{Event, ReleaseNotes, ReleaseSpec};
15 use forge_core::ci::{CiJob, CiRun, RunState};2 use forge_core::ci::{CiJob, CiRun, RunState};
16 use forge_core::releases::{MAX_BODY_CHARS, MAX_TITLE_CHARS, Release};3 use forge_core::releases::{MAX_BODY_CHARS, MAX_TITLE_CHARS, Release};
@@ -28,13 +15,9 @@ use crate::release_ops::{self, CreateRelease, ReleaseError};
28 use crate::render::commit_message::CommitMessage;15 use crate::render::commit_message::CommitMessage;
29 use crate::state::AppState;16 use crate::state::AppState;
30 17
31-/// Most commits listed in the notes. Older commits are left out.
32 const MAX_NOTE_COMMITS: usize = 200;18 const MAX_NOTE_COMMITS: usize = 200;
33 const MIB: u64 = 1024 * 1024;19 const MIB: u64 = 1024 * 1024;
34 20
35-/// Runs after a run finished. Does nothing unless the run is a successful tag run and the workflow
36-/// at its commit asks for a release for this tag. Failures are logged and written to the job log;
37-/// they never fail the caller.
38 pub async fn on_run_finished(state: &AppState, run: &CiRun) {21 pub async fn on_run_finished(state: &AppState, run: &CiRun) {
39 if run.state != RunState::Success {22 if run.state != RunState::Success {
40 return;23 return;
@@ -74,7 +57,6 @@ pub async fn on_run_finished(state: &AppState, run: &CiRun) {
74 }57 }
75 }58 }
76 59
77-/// Creates or finds the release, attaches the selected artifacts, and describes the outcome.
78 async fn publish(60 async fn publish(
79 state: &AppState,61 state: &AppState,
80 repo: &Repo,62 repo: &Repo,
@@ -140,7 +122,6 @@ async fn publish(
140 text122 text
141 }123 }
142 124
143-/// The person the release is made as: the run's actor, or the fallback of `status_creator`.
144 async fn actor_of(state: &AppState, repo: &Repo, run: &CiRun) -> Option<User> {125 async fn actor_of(state: &AppState, repo: &Repo, run: &CiRun) -> Option<User> {
145 let id = status_creator(state, repo, &run.actor_id).await?;126 let id = status_creator(state, repo, &run.actor_id).await?;
146 match state.store.user_by_id(&id).await {127 match state.store.user_by_id(&id).await {
@@ -152,8 +133,6 @@ async fn actor_of(state: &AppState, repo: &Repo, run: &CiRun) -> Option<User> {
152 }133 }
153 }134 }
154 135
155-/// The existing release for `tag`, or a new one made from the spec. A release made by another run
156-/// in the meantime (a `Conflict`) is read back instead.
157 async fn release_for(136 async fn release_for(
158 state: &AppState,137 state: &AppState,
159 repo: &Repo,138 repo: &Repo,
@@ -195,10 +174,6 @@ async fn release_for(
195 }174 }
196 }175 }
197 176
198-/// An existing release whose tag now names the run's commit (the tag was deleted and pushed
199-/// again elsewhere) follows it: its target becomes that commit, and notes the forge wrote for the
200-/// old target, unedited, are written again for the new one. Hand-written notes and the title are
201-/// kept. A failure is logged and the release is used as it is.
202 async fn follow_tag(177 async fn follow_tag(
203 state: &AppState,178 state: &AppState,
204 repo: &Repo,179 repo: &Repo,
@@ -229,7 +204,6 @@ async fn follow_tag(
229 }204 }
230 }205 }
231 206
232-/// Stores one artifact as an asset of `release`, replacing an asset with the same name.
233 async fn attach(207 async fn attach(
234 state: &AppState,208 state: &AppState,
235 repo: &Repo,209 repo: &Repo,
@@ -265,8 +239,6 @@ async fn attach(
265 })239 })
266 }240 }
267 241
268-/// The notes for a new release, or an empty string when the spec turns them off. A git failure
269-/// leaves the notes empty and is logged; the release is still made.
270 async fn notes(242 async fn notes(
271 state: &AppState,243 state: &AppState,
272 repo: &Repo,244 repo: &Repo,
@@ -286,9 +258,6 @@ async fn notes(
286 }258 }
287 }259 }
288 260
289-/// The commit list since the previous release. The previous release is the newest other
290-/// published release whose target is an ancestor of this commit. Without one, it is the closest
291-/// git tag reachable from the commit. Without either, the list is capped at the newest commits.
292 async fn changelog(261 async fn changelog(
293 state: &AppState,262 state: &AppState,
294 repo: &Repo,263 repo: &Repo,
@@ -337,7 +306,6 @@ async fn changelog(
337 Ok(bullets(&commits, footer.as_deref()))306 Ok(bullets(&commits, footer.as_deref()))
338 }307 }
339 308
340-/// Note sections in output order. Commit kinds map to them through `section_of`.
341 const SECTIONS: [&str; 7] = [309 const SECTIONS: [&str; 7] = [
342 "Features",310 "Features",
343 "Fixes",311 "Fixes",
@@ -348,7 +316,6 @@ const SECTIONS: [&str; 7] = [
348 "Other",316 "Other",
349 ];317 ];
350 318
351-/// The index in `SECTIONS` for a commit kind. Unknown kinds go to `Other`.
352 fn section_of(kind: &str) -> usize {319 fn section_of(kind: &str) -> usize {
353 match kind {320 match kind {
354 "feat" => 0,321 "feat" => 0,
@@ -361,9 +328,6 @@ fn section_of(kind: &str) -> usize {
361 }328 }
362 }329 }
363 330
364-/// The notes body. When at least one subject is structured, the clauses are grouped under
365-/// `SECTIONS`; otherwise one `- subject (shortsha)` line per commit, newest first. Commits that
366-/// would push the notes past the body limit are left out, and the footer is kept in the count.
367 fn bullets(commits: &[CommitInfo], footer: Option<&str>) -> String {331 fn bullets(commits: &[CommitInfo], footer: Option<&str>) -> String {
368 let footer_len = footer.map_or(0, |f| f.chars().count() + 2);332 let footer_len = footer.map_or(0, |f| f.chars().count() + 2);
369 let structured = commits333 let structured = commits
@@ -377,7 +341,6 @@ fn bullets(commits: &[CommitInfo], footer: Option<&str>) -> String {
377 with_footer(&body, footer)341 with_footer(&body, footer)
378 }342 }
379 343
380-/// One `- subject (shortsha)` line per commit, newest first.
381 fn flat_bullets(commits: &[CommitInfo], footer_len: usize) -> String {344 fn flat_bullets(commits: &[CommitInfo], footer_len: usize) -> String {
382 let mut body = String::new();345 let mut body = String::new();
383 let mut used = 0usize;346 let mut used = 0usize;
@@ -394,8 +357,6 @@ fn flat_bullets(commits: &[CommitInfo], footer_len: usize) -> String {
394 body357 body
395 }358 }
396 359
397-/// Lines grouped under `SECTIONS`, in commit order within each section. A heading costs its
398-/// `### name` line and the blank line after the section, and is counted once per section.
399 fn grouped_bullets(commits: &[CommitInfo], footer_len: usize) -> String {360 fn grouped_bullets(commits: &[CommitInfo], footer_len: usize) -> String {
400 let mut sections: Vec<Vec<String>> = vec![Vec::new(); SECTIONS.len()];361 let mut sections: Vec<Vec<String>> = vec![Vec::new(); SECTIONS.len()];
401 let mut used = 0usize;362 let mut used = 0usize;
@@ -444,7 +405,6 @@ fn grouped_bullets(commits: &[CommitInfo], footer_len: usize) -> String {
444 body405 body
445 }406 }
446 407
447-/// The body without trailing whitespace, then the footer after a blank line.
448 fn with_footer(body: &str, footer: Option<&str>) -> String {408 fn with_footer(body: &str, footer: Option<&str>) -> String {
449 let mut body = body.trim_end().to_owned();409 let mut body = body.trim_end().to_owned();
450 if let Some(footer) = footer {410 if let Some(footer) = footer {
@@ -456,8 +416,6 @@ fn with_footer(body: &str, footer: Option<&str>) -> String {
456 body416 body
457 }417 }
458 418
459-/// Appends one `[forge]` line to the log of `job`. Respects the log size cap. A failure is logged;
460-/// the outcome is not lost, it is also in the tracing output.
461 async fn note(state: &AppState, job: &CiJob, text: &str) {419 async fn note(state: &AppState, job: &CiJob, text: &str) {
462 let line = format!("[forge] {text}\n");420 let line = format!("[forge] {text}\n");
463 let cap = state.live().ci.max_log_mb.saturating_mul(MIB);421 let cap = state.live().ci.max_log_mb.saturating_mul(MIB);
@@ -507,7 +465,6 @@ mod tests {
507 use crate::ci::schedule::tests::{Fixture, ZERO, fixture, git, land, push};465 use crate::ci::schedule::tests::{Fixture, ZERO, fixture, git, land, push};
508 use crate::post_update::after_ref_update;466 use crate::post_update::after_ref_update;
509 467
510- /// A tag release workflow with two jobs. Only `build` feeds the release, through `dist_*`.
511 const RELEASE: &str = r#"468 const RELEASE: &str = r#"
512 [on]469 [on]
513 push = ["main"]470 push = ["main"]
@@ -528,7 +485,6 @@ assets = ["build:dist_*"]
528 title = "forge {tag}"485 title = "forge {tag}"
529 "#;486 "#;
530 487
531- /// Finishes the jobs of `run_id` in order. The job named `failing` fails; the others succeed.
532 async fn finish_all(fx: &Fixture, run_id: &str, failing: Option<&str>) {488 async fn finish_all(fx: &Fixture, run_id: &str, failing: Option<&str>) {
533 loop {489 loop {
534 let jobs = fx.state.store.jobs_for_run(run_id).await.expect("jobs");490 let jobs = fx.state.store.jobs_for_run(run_id).await.expect("jobs");
@@ -569,7 +525,6 @@ title = "forge {tag}"
569 .expect("job")525 .expect("job")
570 }526 }
571 527
572- /// Stores `body` as an artifact of `job`, the way the upload handler does.
573 async fn add_artifact(fx: &Fixture, job: &CiJob, name: &str, body: &[u8]) -> CiArtifact {528 async fn add_artifact(fx: &Fixture, job: &CiJob, name: &str, body: &[u8]) -> CiArtifact {
574 let tmp = format!("ci/tmp/{}", ulid::Ulid::generate());529 let tmp = format!("ci/tmp/{}", ulid::Ulid::generate());
575 let mut writer = fx.state.blobs.begin(&tmp, 1 << 30).await.expect("begin");530 let mut writer = fx.state.blobs.begin(&tmp, 1 << 30).await.expect("begin");
@@ -589,7 +544,6 @@ title = "forge {tag}"
589 artifact544 artifact
590 }545 }
591 546
592- /// Commits an empty change with `message` and returns the commit.
593 fn commit_message(work: &std::path::Path, message: &str) -> String {547 fn commit_message(work: &std::path::Path, message: &str) -> String {
594 git(work, &["commit", "--allow-empty", "-m", message]);548 git(work, &["commit", "--allow-empty", "-m", message]);
595 git(work, &["rev-parse", "HEAD"])549 git(work, &["rev-parse", "HEAD"])
@@ -766,16 +720,10 @@ title = "forge {tag}"
766 assert_eq!(asset_names(&fx, &release).await.len(), 1);720 assert_eq!(asset_names(&fx, &release).await.len(), 1);
767 }721 }
768 722
769- /// Failed runs never publish. Each scenario has its own tag, so its run is number 1, 2 and 3.
770- /// Scenario 1: `docs` fails after the jobs run in order. Scenario 2: `build` finishes green
771- /// while `docs` still runs, then `docs` fails. Scenario 3: `docs` fails fast while `build`
772- /// has not finished, so `build` is cancelled at once (the running-job path is covered in the
773- /// store tests). No release is created in any scenario.
774 #[tokio::test]723 #[tokio::test]
775 async fn failed_runs_create_no_release() {724 async fn failed_runs_create_no_release() {
776 let fx = fixture().await;725 let fx = fixture().await;
777 726
778- // Scenario 1.
779 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await;727 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await;
780 let run = run_of(&fx, 1).await;728 let run = run_of(&fx, 1).await;
781 let build = job_of(&fx, &run, "build").await;729 let build = job_of(&fx, &run, "build").await;
@@ -786,7 +734,6 @@ title = "forge {tag}"
786 on_run_finished(&fx.state, &run).await;734 on_run_finished(&fx.state, &run).await;
787 assert!(release_named(&fx, "v1.0").await.is_none(), "in order");735 assert!(release_named(&fx, "v1.0").await.is_none(), "in order");
788 736
789- // Scenario 2.
790 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v2.0").await;737 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v2.0").await;
791 let run = run_of(&fx, 2).await;738 let run = run_of(&fx, 2).await;
792 let build = job_of(&fx, &run, "build").await;739 let build = job_of(&fx, &run, "build").await;
@@ -813,7 +760,6 @@ title = "forge {tag}"
813 on_run_finished(&fx.state, &after_docs).await;760 on_run_finished(&fx.state, &after_docs).await;
814 assert!(release_named(&fx, "v2.0").await.is_none(), "parallel");761 assert!(release_named(&fx, "v2.0").await.is_none(), "parallel");
815 762
816- // Scenario 3.
817 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v3.0").await;763 push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v3.0").await;
818 let run = run_of(&fx, 3).await;764 let run = run_of(&fx, 3).await;
819 let build = job_of(&fx, &run, "build").await;765 let build = job_of(&fx, &run, "build").await;
@@ -873,7 +819,6 @@ title = "forge {tag}"
873 );819 );
874 }820 }
875 821
876- /// No release exists for the earlier tag, so the notes start from the closest git tag.
877 #[tokio::test]822 #[tokio::test]
878 async fn notes_fall_back_to_the_previous_git_tag() {823 async fn notes_fall_back_to_the_previous_git_tag() {
879 let fx = fixture().await;824 let fx = fixture().await;
crates/forge-web-app/src/ci/runner_log.rsmodified+0 -9
@@ -15,8 +15,6 @@ use forge_ci::proto::{RUNNER_LOG_MAX_TEXT, RunnerLogBatch, truncate_text};
15 const MAX_LINES: usize = 2000;15 const MAX_LINES: usize = 2000;
16 /// Most lines taken from one batch. The rest are left for the runner to resend.16 /// Most lines taken from one batch. The rest are left for the runner to resend.
17 const MAX_BATCH_LINES: usize = 1000;17 const MAX_BATCH_LINES: usize = 1000;
18-/// Longest boot id kept, in bytes.
19-const MAX_BOOT_ID_BYTES: usize = 64;
20 /// The levels a runner may send. Any other level is stored as `info`.18 /// The levels a runner may send. Any other level is stored as `info`.
21 const LEVELS: [&str; 5] = ["error", "warn", "info", "debug", "trace"];19 const LEVELS: [&str; 5] = ["error", "warn", "info", "debug", "trace"];
22 20
@@ -54,9 +52,6 @@ impl RunnerLogs {
54 /// starts a fresh numbering, and the lines already in `lines` are kept. Lines before the52 /// starts a fresh numbering, and the lines already in `lines` are kept. Lines before the
55 /// wanted number are skipped, so a resent batch adds only what is new.53 /// wanted number are skipped, so a resent batch adds only what is new.
56 pub fn ingest(&self, runner_id: &str, batch: &RunnerLogBatch) -> u64 {54 pub fn ingest(&self, runner_id: &str, batch: &RunnerLogBatch) -> u64 {
57- if batch.boot_id.is_empty() || batch.boot_id.len() > MAX_BOOT_ID_BYTES {
58- return self.next_seq(runner_id);
59- }
60 let mut runners = self.lock();55 let mut runners = self.lock();
61 let entry = runners.entry(runner_id.to_owned()).or_default();56 let entry = runners.entry(runner_id.to_owned()).or_default();
62 if entry.boot_id != batch.boot_id {57 if entry.boot_id != batch.boot_id {
@@ -118,10 +113,6 @@ impl RunnerLogs {
118 .unwrap_or_default()113 .unwrap_or_default()
119 }114 }
120 115
121- fn next_seq(&self, runner_id: &str) -> u64 {
122- self.lock().get(runner_id).map_or(0, |entry| entry.next_seq)
123- }
124-
125 fn lock(&self) -> MutexGuard<'_, HashMap<String, PerRunner>> {116 fn lock(&self) -> MutexGuard<'_, HashMap<String, PerRunner>> {
126 // A panic while the lock was held leaves the map usable, so a poisoned lock is taken as is.117 // A panic while the lock was held leaves the map usable, so a poisoned lock is taken as is.
127 self.runners.lock().unwrap_or_else(|e| e.into_inner())118 self.runners.lock().unwrap_or_else(|e| e.into_inner())
crates/forge-web-app/src/ci/runner_metrics.rsmodified+1 -1
@@ -9,7 +9,7 @@ use std::sync::{Mutex, MutexGuard};
9 use forge_ci::proto::{RunnerMetricsBatch, RunnerSample};9 use forge_ci::proto::{RunnerMetricsBatch, RunnerSample};
10 10
11 /// How far back samples are kept, in milliseconds, counted from the newest sample.11 /// How far back samples are kept, in milliseconds, counted from the newest sample.
12-pub const KEEP_MS: i64 = 3_600_000;12+const KEEP_MS: i64 = 3_600_000;
13 /// Most samples kept per runner. The oldest go first.13 /// Most samples kept per runner. The oldest go first.
14 const MAX_SAMPLES: usize = 800;14 const MAX_SAMPLES: usize = 800;
15 15
crates/forge-web-app/src/ci/schedule.rsmodified+106 -139
@@ -9,7 +9,7 @@ use forge_core::authz::{Action, authorize};
9 use forge_core::ci::{CiRun, NewJob, NewRun};9 use forge_core::ci::{CiRun, NewJob, NewRun};
10 use forge_core::store::commit_status::StatusState;10 use forge_core::store::commit_status::StatusState;
11 use forge_core::{PullRequest, Repo};11 use forge_core::{PullRequest, Repo};
12-use forge_git::browse::{peel_to_commit, read_blob, resolve_commit};12+use forge_git::browse::{BlobData, peel_to_commit, read_blob, resolve_commit};
13 use tokio::io::AsyncWriteExt;13 use tokio::io::AsyncWriteExt;
14 14
15 use super::api::fit_to_cap;15 use super::api::fit_to_cap;
@@ -35,21 +35,13 @@ pub(super) enum Loaded {
35 Valid(CiConfig),35 Valid(CiConfig),
36 }36 }
37 37
38-/// What a request should do with the loaded config.38+/// A run to create. `config_error` makes it an Error run. `warnings` are the config's ignored keys,
39-enum Plan {39+/// written to the start of every job log. `cancel_superseded` is `[on] cancel_superseded`.
40- /// No workflow file at this commit.40+struct Planned {
41- Missing,41+ jobs: Vec<PlannedJob>,
42- /// The file is valid but this event does not trigger it.42+ config_error: Option<String>,
43- NotTriggered,43+ warnings: Vec<String>,
44- /// Create a run with these jobs, or an Error run when `config_error` is set. `warnings` are the44+ cancel_superseded: bool,
45- /// config's ignored keys, written to the start of every job log.
46- Run {
47- jobs: Vec<PlannedJob>,
48- config_error: Option<String>,
49- warnings: Vec<String>,
50- /// `[on] cancel_superseded`: a push cancels the older live runs on its branch.
51- cancel_superseded: bool,
52- },
53 }45 }
54 46
55 /// The inputs of one run to create.47 /// The inputs of one run to create.
@@ -83,49 +75,49 @@ pub async fn on_ref_update(
83 } else {75 } else {
84 return;76 return;
85 };77 };
86- let result = async {78+ if let Err(e) = schedule_ref(state, repo, actor_id, trigger, refname, &event, new_oid).await {
87- // An annotated tag's ref names a tag object: the run, its statuses and any release are
88- // for the commit it points at.
89- let Some(commit) = peeled_commit(state, &repo.id, new_oid).await else {
90- return forge_core::Result::Ok(());
91- };
92- let new_oid = commit.as_str();
93- let loaded = load(state, &repo.id, new_oid).await;
94- if let Plan::Run {
95- jobs,
96- config_error,
97- warnings,
98- cancel_superseded,
99- } = plan_for(loaded, &event)?
100- {
101- let run = create(
102- state,
103- Request {
104- repo,
105- trigger,
106- git_ref: refname,
107- commit: new_oid,
108- pull_number: None,
109- actor_id,
110- needs_approval: false,
111- },
112- jobs,
113- config_error.as_deref(),
114- &warnings,
115- )
116- .await?;
117- if cancel_superseded && trigger == "push" {
118- cancel_superseded_runs(state, &run).await?;
119- }
120- }
121- forge_core::Result::Ok(())
122- }
123- .await;
124- if let Err(e) = result {
125 tracing::error!(error = %e, repo_id = %repo.id, refname, "ci: scheduling a push failed");79 tracing::error!(error = %e, repo_id = %repo.id, refname, "ci: scheduling a push failed");
126 }80 }
127 }81 }
128 82
83+async fn schedule_ref(
84+ state: &AppState,
85+ repo: &Repo,
86+ actor_id: &str,
87+ trigger: &'static str,
88+ refname: &str,
89+ event: &Event<'_>,
90+ new_oid: &str,
91+) -> forge_core::Result<()> {
92+ // An annotated tag's ref names a tag object: the run, its statuses and any release are
93+ // for the commit it points at.
94+ let Some(commit) = peeled_commit(state, &repo.id, new_oid).await else {
95+ return Ok(());
96+ };
97+ let loaded = load(state, &repo.id, &commit).await;
98+ let Some(planned) = plan_for(loaded, event)? else {
99+ return Ok(());
100+ };
101+ let run = create(
102+ state,
103+ Request {
104+ repo,
105+ trigger,
106+ git_ref: refname,
107+ commit: &commit,
108+ pull_number: None,
109+ actor_id,
110+ needs_approval: false,
111+ },
112+ &planned,
113+ )
114+ .await?;
115+ if planned.cancel_superseded && trigger == "push" {
116+ cancel_superseded_runs(state, &run).await?;
117+ }
118+ Ok(())
119+}
120+
129 /// A pull request was opened, synchronized (its head moved) or reopened. The config is read at121 /// A pull request was opened, synchronized (its head moved) or reopened. The config is read at
130 /// the head commit. A fork head, or an author without Write on the base repo, creates the run in122 /// the head commit. A fork head, or an author without Write on the base repo, creates the run in
131 /// WaitingApproval: its jobs wait until someone approves it.123 /// WaitingApproval: its jobs wait until someone approves it.
@@ -145,13 +137,7 @@ async fn pull_run(
145 actor_id: &str,137 actor_id: &str,
146 ) -> forge_core::Result<()> {138 ) -> forge_core::Result<()> {
147 let loaded = load(state, &repo.id, &pull.head_oid).await;139 let loaded = load(state, &repo.id, &pull.head_oid).await;
148- let Plan::Run {140+ let Some(planned) = plan_for(loaded, &Event::PullRequest)? else {
149- jobs,
150- config_error,
151- warnings,
152- ..
153- } = plan_for(loaded, &Event::PullRequest)?
154- else {
155 return Ok(());141 return Ok(());
156 };142 };
157 let needs_approval = needs_approval(state, repo, pull).await?;143 let needs_approval = needs_approval(state, repo, pull).await?;
@@ -167,9 +153,7 @@ async fn pull_run(
167 actor_id,153 actor_id,
168 needs_approval,154 needs_approval,
169 },155 },
170- jobs,156+ &planned,
171- config_error.as_deref(),
172- &warnings,
173 )157 )
174 .await?;158 .await?;
175 Ok(())159 Ok(())
@@ -198,37 +182,30 @@ pub async fn manual_run(
198 return Err(forge_core::Error::NotFound);182 return Err(forge_core::Error::NotFound);
199 };183 };
200 let loaded = load(state, &repo.id, &commit).await;184 let loaded = load(state, &repo.id, &commit).await;
201- match plan_for(loaded, &Event::Manual)? {185+ if matches!(loaded, Loaded::Missing) {
202- Plan::Run {186+ return Err(forge_core::Error::Invalid(
203- jobs,
204- config_error,
205- warnings,
206- ..
207- } => {
208- create(
209- state,
210- Request {
211- repo,
212- trigger: "manual",
213- git_ref: &git_ref,
214- commit: &commit,
215- pull_number: None,
216- actor_id,
217- needs_approval: false,
218- },
219- jobs,
220- config_error.as_deref(),
221- &warnings,
222- )
223- .await
224- }
225- Plan::NotTriggered => Err(forge_core::Error::Invalid(
226- "manual runs are not enabled in .forge/ci.toml".into(),
227- )),
228- Plan::Missing => Err(forge_core::Error::Invalid(
229 "this branch has no .forge/ci.toml".into(),187 "this branch has no .forge/ci.toml".into(),
230- )),188+ ));
231 }189 }
190+ let Some(planned) = plan_for(loaded, &Event::Manual)? else {
191+ return Err(forge_core::Error::Invalid(
192+ "manual runs are not enabled in .forge/ci.toml".into(),
193+ ));
194+ };
195+ create(
196+ state,
197+ Request {
198+ repo,
199+ trigger: "manual",
200+ git_ref: &git_ref,
201+ commit: &commit,
202+ pull_number: None,
203+ actor_id,
204+ needs_approval: false,
205+ },
206+ &planned,
207+ )
208+ .await
232 }209 }
233 210
234 /// The head commit of the repo's default branch and the workflow at it. `None` when the branch211 /// The head commit of the repo's default branch and the workflow at it. `None` when the branch
@@ -248,7 +225,7 @@ pub(super) async fn default_head_config(state: &AppState, repo: &Repo) -> Option
248 }225 }
249 226
250 /// The `[on] schedule` entries of the workflow on the repo's default branch. Empty when there is227 /// The `[on] schedule` entries of the workflow on the repo's default branch. Empty when there is
251-/// no valid workflow.228+/// no valid workflow or it cannot be read.
252 pub async fn schedules_of(state: &AppState, repo: &Repo) -> Vec<String> {229 pub async fn schedules_of(state: &AppState, repo: &Repo) -> Vec<String> {
253 match default_head_config(state, repo).await {230 match default_head_config(state, repo).await {
254 Some((_, Loaded::Valid(cfg))) => cfg.on.schedule,231 Some((_, Loaded::Valid(cfg))) => cfg.on.schedule,
@@ -264,13 +241,7 @@ pub(super) async fn scheduled_run(
264 commit: &str,241 commit: &str,
265 loaded: Loaded,242 loaded: Loaded,
266 ) -> forge_core::Result<Option<CiRun>> {243 ) -> forge_core::Result<Option<CiRun>> {
267- let Plan::Run {244+ let Some(planned) = plan_for(loaded, &Event::Schedule)? else {
268- jobs,
269- config_error,
270- warnings,
271- ..
272- } = plan_for(loaded, &Event::Schedule)?
273- else {
274 return Ok(None);245 return Ok(None);
275 };246 };
276 let git_ref = format!("refs/heads/{}", repo.default_branch);247 let git_ref = format!("refs/heads/{}", repo.default_branch);
@@ -286,9 +257,7 @@ pub(super) async fn scheduled_run(
286 actor_id: &repo.owner_id,257 actor_id: &repo.owner_id,
287 needs_approval: false,258 needs_approval: false,
288 },259 },
289- jobs,260+ &planned,
290- config_error.as_deref(),
291- &warnings,
292 )261 )
293 .await?;262 .await?;
294 Ok(Some(run))263 Ok(Some(run))
@@ -310,13 +279,7 @@ pub async fn merge_queue_run(
310 return Ok(None);279 return Ok(None);
311 }280 }
312 let loaded = load(state, &repo.id, commit).await;281 let loaded = load(state, &repo.id, commit).await;
313- let Plan::Run {282+ let Some(planned) = plan_for(loaded, &Event::MergeQueue { branch })? else {
314- jobs,
315- config_error,
316- warnings,
317- ..
318- } = plan_for(loaded, &Event::MergeQueue { branch })?
319- else {
320 return Ok(None);283 return Ok(None);
321 };284 };
322 let run = create(285 let run = create(
@@ -330,9 +293,7 @@ pub async fn merge_queue_run(
330 actor_id,293 actor_id,
331 needs_approval: false,294 needs_approval: false,
332 },295 },
333- jobs,296+ &planned,
334- config_error.as_deref(),
335- &warnings,
336 )297 )
337 .await?;298 .await?;
338 Ok(Some(run))299 Ok(Some(run))
@@ -343,11 +304,12 @@ pub async fn merge_queue_run(
343 async fn create(304 async fn create(
344 state: &AppState,305 state: &AppState,
345 req: Request<'_>,306 req: Request<'_>,
346- jobs: Vec<PlannedJob>,307+ planned: &Planned,
347- config_error: Option<&str>,
348- warnings: &[String],
349 ) -> forge_core::Result<CiRun> {308 ) -> forge_core::Result<CiRun> {
350- let new_jobs: Vec<NewJob<'_>> = jobs309+ let config_error = planned.config_error.as_deref();
310+ let warnings = planned.warnings.as_slice();
311+ let new_jobs: Vec<NewJob<'_>> = planned
312+ .jobs
351 .iter()313 .iter()
352 .map(|(name, spec_json, needs)| NewJob {314 .map(|(name, spec_json, needs)| NewJob {
353 name,315 name,
@@ -476,25 +438,25 @@ async fn note_warnings(
476 }438 }
477 439
478 /// Decides what a request does, given the loaded config and the event.440 /// Decides what a request does, given the loaded config and the event.
479-fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result<Plan> {441+fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result<Option<Planned>> {
480 match loaded {442 match loaded {
481- Loaded::Missing => Ok(Plan::Missing),443+ Loaded::Missing => Ok(None),
482- Loaded::Invalid(message) => Ok(Plan::Run {444+ Loaded::Invalid(message) => Ok(Some(Planned {
483 jobs: Vec::new(),445 jobs: Vec::new(),
484 config_error: Some(message),446 config_error: Some(message),
485 warnings: Vec::new(),447 warnings: Vec::new(),
486 cancel_superseded: false,448 cancel_superseded: false,
487- }),449+ })),
488 Loaded::Valid(cfg) => {450 Loaded::Valid(cfg) => {
489 if !cfg.triggered_by(event) {451 if !cfg.triggered_by(event) {
490- return Ok(Plan::NotTriggered);452+ return Ok(None);
491 }453 }
492- Ok(Plan::Run {454+ Ok(Some(Planned {
493 jobs: plan_jobs(&cfg)?,455 jobs: plan_jobs(&cfg)?,
494 config_error: None,456 config_error: None,
495 warnings: cfg.warnings.clone(),457 warnings: cfg.warnings.clone(),
496 cancel_superseded: cfg.on.cancel_superseded,458 cancel_superseded: cfg.on.cancel_superseded,
497- })459+ }))
498 }460 }
499 }461 }
500 }462 }
@@ -513,7 +475,6 @@ fn plan_jobs(cfg: &CiConfig) -> forge_core::Result<Vec<PlannedJob>> {
513 Ok(jobs)475 Ok(jobs)
514 }476 }
515 477
516-/// Reads and parses `.forge/ci.toml` at `commit` from the repo `repo_id`.
517 /// The workflow at `commit`, when it is a valid file. Used by the release hook, which reads the478 /// The workflow at `commit`, when it is a valid file. Used by the release hook, which reads the
518 /// config the run itself was made from.479 /// config the run itself was made from.
519 pub(super) async fn config_at(state: &AppState, repo_id: &str, commit: &str) -> Option<CiConfig> {480 pub(super) async fn config_at(state: &AppState, repo_id: &str, commit: &str) -> Option<CiConfig> {
@@ -543,22 +504,28 @@ async fn peeled_commit(state: &AppState, repo_id: &str, oid: &str) -> Option<Str
543 }504 }
544 }505 }
545 506
546-async fn load(state: &AppState, repo_id: &str, commit: &str) -> Loaded {507+async fn read_config(
547- let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, repo_id) {508+ state: &AppState,
548- Ok(path) => path,509+ repo_id: &str,
549- Err(e) => {510+ commit: &str,
550- tracing::error!(error = %e, repo_id, "ci: bad repo path");511+) -> forge_core::Result<Option<BlobData>> {
551- return Loaded::Invalid(format!("could not read {CONFIG_PATH}"));512+ let repo_dir = forge_git::repo::repo_path(&state.git.data_dir, repo_id)
552- }513+ .map_err(|e| forge_core::Error::Git(e.to_string()))?;
553- };
554 let (dir, rev) = (repo_dir, commit.to_owned());514 let (dir, rev) = (repo_dir, commit.to_owned());
555- let blob = match blocking(move || read_blob(&dir, &rev, CONFIG_PATH, MAX_CONFIG_BYTES)).await {515+ blocking(move || read_blob(&dir, &rev, CONFIG_PATH, MAX_CONFIG_BYTES)).await
556- Ok(blob) => blob,516+}
517+
518+async fn load(state: &AppState, repo_id: &str, commit: &str) -> Loaded {
519+ match read_config(state, repo_id, commit).await {
520+ Ok(blob) => loaded_from(blob),
557 Err(e) => {521 Err(e) => {
558 tracing::error!(error = %e, repo_id, commit, "ci: reading the workflow failed");522 tracing::error!(error = %e, repo_id, commit, "ci: reading the workflow failed");
559- return Loaded::Invalid(format!("could not read {CONFIG_PATH}"));523+ Loaded::Invalid(format!("could not read {CONFIG_PATH}"))
560 }524 }
561- };525+ }
526+}
527+
528+fn loaded_from(blob: Option<BlobData>) -> Loaded {
562 let Some(blob) = blob else {529 let Some(blob) = blob else {
563 return Loaded::Missing;530 return Loaded::Missing;
564 };531 };
crates/forge-web-app/src/client_ip.rsmodified+12 -19
@@ -36,14 +36,7 @@ pub fn client_addr(cx: &Cx) -> IpAddr {
36 resolve_addr(peer, &forwarded, trusted)36 resolve_addr(peer, &forwarded, trusted)
37 }37 }
38 38
39-/// Pure form of [`client_ip`]: `forwarded` is the combined `X-Forwarded-For` value, or empty.39+/// Pure form of [`client_addr`]: `forwarded` is the combined `X-Forwarded-For` value, or empty.
40-/// Only the tests use the bucketed form; the server takes [`client_ip`], which buckets itself.
41-#[cfg(any(test, feature = "test-support"))]
42-pub fn resolve(peer: Option<IpAddr>, forwarded: &str, trusted: &[IpNet]) -> IpAddr {
43- bucket(resolve_addr(peer, forwarded, trusted))
44-}
45-
46-/// Pure form of [`client_addr`]: the exact client address, normalized but not bucketed.
47 pub fn resolve_addr(peer: Option<IpAddr>, forwarded: &str, trusted: &[IpNet]) -> IpAddr {40 pub fn resolve_addr(peer: Option<IpAddr>, forwarded: &str, trusted: &[IpNet]) -> IpAddr {
48 let Some(peer) = peer.map(normalize) else {41 let Some(peer) = peer.map(normalize) else {
49 return IpAddr::V4(Ipv4Addr::UNSPECIFIED);42 return IpAddr::V4(Ipv4Addr::UNSPECIFIED);
@@ -102,14 +95,14 @@ mod tests {
102 #[test]95 #[test]
103 fn forwarded_for_is_ignored_from_untrusted_peer() {96 fn forwarded_for_is_ignored_from_untrusted_peer() {
104 let trusted = [net("10.0.0.0/8")];97 let trusted = [net("10.0.0.0/8")];
105- let got = resolve(Some(ip("203.0.113.9")), "198.51.100.7", &trusted);98+ let got = resolve_addr(Some(ip("203.0.113.9")), "198.51.100.7", &trusted);
106 assert_eq!(got, ip("203.0.113.9"));99 assert_eq!(got, ip("203.0.113.9"));
107 }100 }
108 101
109 #[test]102 #[test]
110 fn forwarded_for_is_honored_from_trusted_peer() {103 fn forwarded_for_is_honored_from_trusted_peer() {
111 let trusted = [net("127.0.0.1/32")];104 let trusted = [net("127.0.0.1/32")];
112- let got = resolve(Some(ip("127.0.0.1")), "198.51.100.7", &trusted);105+ let got = resolve_addr(Some(ip("127.0.0.1")), "198.51.100.7", &trusted);
113 assert_eq!(got, ip("198.51.100.7"));106 assert_eq!(got, ip("198.51.100.7"));
114 }107 }
115 108
@@ -117,7 +110,7 @@ mod tests {
117 fn right_most_untrusted_entry_wins() {110 fn right_most_untrusted_entry_wins() {
118 let trusted = [net("127.0.0.1/32"), net("10.0.0.0/8")];111 let trusted = [net("127.0.0.1/32"), net("10.0.0.0/8")];
119 // The client may prepend anything; the proxy appends the address it saw.112 // The client may prepend anything; the proxy appends the address it saw.
120- let got = resolve(113+ let got = resolve_addr(
121 Some(ip("127.0.0.1")),114 Some(ip("127.0.0.1")),
122 "1.2.3.4, 198.51.100.7, 10.0.0.5",115 "1.2.3.4, 198.51.100.7, 10.0.0.5",
123 &trusted,116 &trusted,
@@ -129,15 +122,15 @@ mod tests {
129 fn unusable_header_falls_back_to_peer() {122 fn unusable_header_falls_back_to_peer() {
130 let trusted = [net("127.0.0.1/32")];123 let trusted = [net("127.0.0.1/32")];
131 assert_eq!(124 assert_eq!(
132- resolve(Some(ip("127.0.0.1")), "", &trusted),125+ resolve_addr(Some(ip("127.0.0.1")), "", &trusted),
133 ip("127.0.0.1")126 ip("127.0.0.1")
134 );127 );
135 assert_eq!(128 assert_eq!(
136- resolve(Some(ip("127.0.0.1")), "garbage", &trusted),129+ resolve_addr(Some(ip("127.0.0.1")), "garbage", &trusted),
137 ip("127.0.0.1")130 ip("127.0.0.1")
138 );131 );
139 assert_eq!(132 assert_eq!(
140- resolve(Some(ip("127.0.0.1")), "127.0.0.1", &trusted),133+ resolve_addr(Some(ip("127.0.0.1")), "127.0.0.1", &trusted),
141 ip("127.0.0.1")134 ip("127.0.0.1")
142 );135 );
143 }136 }
@@ -145,9 +138,9 @@ mod tests {
145 #[test]138 #[test]
146 fn ipv6_is_bucketed_by_slash_64() {139 fn ipv6_is_bucketed_by_slash_64() {
147 let trusted: [IpNet; 0] = [];140 let trusted: [IpNet; 0] = [];
148- let a = resolve(Some(ip("2001:db8:1:2:aaaa::1")), "", &trusted);141+ let a = bucket(resolve_addr(Some(ip("2001:db8:1:2:aaaa::1")), "", &trusted));
149- let b = resolve(Some(ip("2001:db8:1:2:bbbb::9")), "", &trusted);142+ let b = bucket(resolve_addr(Some(ip("2001:db8:1:2:bbbb::9")), "", &trusted));
150- let c = resolve(Some(ip("2001:db8:1:3::1")), "", &trusted);143+ let c = bucket(resolve_addr(Some(ip("2001:db8:1:3::1")), "", &trusted));
151 assert_eq!(a, b);144 assert_eq!(a, b);
152 assert_ne!(a, c);145 assert_ne!(a, c);
153 assert_eq!(a, ip("2001:db8:1:2::"));146 assert_eq!(a, ip("2001:db8:1:2::"));
@@ -157,7 +150,7 @@ mod tests {
157 fn ipv4_mapped_peer_is_reported_as_ipv4() {150 fn ipv4_mapped_peer_is_reported_as_ipv4() {
158 let trusted: [IpNet; 0] = [];151 let trusted: [IpNet; 0] = [];
159 assert_eq!(152 assert_eq!(
160- resolve(Some(ip("::ffff:192.0.2.5")), "", &trusted),153+ resolve_addr(Some(ip("::ffff:192.0.2.5")), "", &trusted),
161 ip("192.0.2.5")154 ip("192.0.2.5")
162 );155 );
163 }156 }
@@ -165,6 +158,6 @@ mod tests {
165 #[test]158 #[test]
166 fn unknown_peer_maps_to_unspecified() {159 fn unknown_peer_maps_to_unspecified() {
167 let trusted: [IpNet; 0] = [];160 let trusted: [IpNet; 0] = [];
168- assert_eq!(resolve(None, "1.2.3.4", &trusted), ip("0.0.0.0"));161+ assert_eq!(resolve_addr(None, "1.2.3.4", &trusted), ip("0.0.0.0"));
169 }162 }
170 }163 }
crates/forge-web-app/src/exporter.rsmodified+30 -22
@@ -27,14 +27,15 @@ use tokio::sync::watch;
27 27
28 use crate::state::AppState;28 use crate::state::AppState;
29 29
30-/// How long a finished export stays downloadable.30+/// How many days a finished export stays downloadable, for the page text.
31-pub const EXPORT_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60);
32-/// How many days that is, for the page text.
33 pub const EXPORT_TTL_DAYS: u64 = 7;31 pub const EXPORT_TTL_DAYS: u64 = 7;
32+/// How long a finished export stays downloadable.
33+pub const EXPORT_TTL: Duration = Duration::from_secs(EXPORT_TTL_DAYS * 24 * 60 * 60);
34 const PAGE: u32 = 100;34 const PAGE: u32 = 100;
35 35
36 static HUB: LazyLock<Mutex<HashMap<String, watch::Sender<u64>>>> =36 static HUB: LazyLock<Mutex<HashMap<String, watch::Sender<u64>>>> =
37 LazyLock::new(|| Mutex::new(HashMap::new()));37 LazyLock::new(|| Mutex::new(HashMap::new()));
38+static START: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
38 39
39 /// Follows a user's exports. Subscribe before reading their state.40 /// Follows a user's exports. Subscribe before reading their state.
40 pub fn subscribe(user_id: &str) -> watch::Receiver<u64> {41 pub fn subscribe(user_id: &str) -> watch::Receiver<u64> {
@@ -56,7 +57,7 @@ fn bump(user_id: &str) {
56 }57 }
57 }58 }
58 59
59-pub fn export_dir(state: &AppState) -> PathBuf {60+fn export_dir(state: &AppState) -> PathBuf {
60 state.config.data_dir.join("exports")61 state.config.data_dir.join("exports")
61 }62 }
62 63
@@ -64,10 +65,26 @@ pub fn archive_path(state: &AppState, id: &str) -> PathBuf {
64 export_dir(state).join(format!("{id}.tar.gz"))65 export_dir(state).join(format!("{id}.tar.gz"))
65 }66 }
66 67
68+fn partial_path(state: &AppState, id: &str) -> PathBuf {
69+ export_dir(state).join(format!("{id}.tar.part"))
70+}
71+
72+async fn remove_archive(state: &AppState, id: &str) -> std::io::Result<()> {
73+ for path in [archive_path(state, id), partial_path(state, id)] {
74+ match tokio::fs::remove_file(&path).await {
75+ Ok(()) => {}
76+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
77+ Err(e) => return Err(e),
78+ }
79+ }
80+ Ok(())
81+}
82+
67 /// Starts an export for `user` and returns its row. At most one runs per user: a second request83 /// Starts an export for `user` and returns its row. At most one runs per user: a second request
68 /// while one is building returns that one.84 /// while one is building returns that one.
69 pub async fn start(state: &AppState, user: &User) -> forge_core::Result<DataExport> {85 pub async fn start(state: &AppState, user: &User) -> forge_core::Result<DataExport> {
70 sweep_expired(state).await;86 sweep_expired(state).await;
87+ let _guard = START.lock().await;
71 if let Some(running) = state88 if let Some(running) = state
72 .store89 .store
73 .list_exports(&user.id)90 .list_exports(&user.id)
@@ -102,7 +119,7 @@ async fn run(state: &AppState, user: &User, id: &str) {
102 }119 }
103 Err(message) => {120 Err(message) => {
104 tracing::error!(error = %message, export_id = id, "export failed");121 tracing::error!(error = %message, export_id = id, "export failed");
105- let _ = tokio::fs::remove_file(archive_path(state, id)).await;122+ let _ = remove_archive(state, id).await;
106 if let Err(e) = state.store.mark_export_failed(id, &message).await {123 if let Err(e) = state.store.mark_export_failed(id, &message).await {
107 tracing::error!(error = %e, "export: could not record a failure");124 tracing::error!(error = %e, "export: could not record a failure");
108 }125 }
@@ -171,7 +188,7 @@ async fn stage_and_pack(
171 stage_repo(state, repo, &repo_dir).await?;188 stage_repo(state, repo, &repo_dir).await?;
172 }189 }
173 let target = archive_path(state, id);190 let target = archive_path(state, id);
174- let partial = target.with_extension("part");191+ let partial = partial_path(state, id);
175 let (work_buf, partial_buf, name) = (192 let (work_buf, partial_buf, name) = (
176 work.to_path_buf(),193 work.to_path_buf(),
177 partial.clone(),194 partial.clone(),
@@ -230,7 +247,7 @@ fn write_array_item(
230 }247 }
231 248
232 /// The account fields worth taking along. Never the password hash.249 /// The account fields worth taking along. Never the password hash.
233-pub fn profile_json(user: &User) -> Value {250+fn profile_json(user: &User) -> Value {
234 json!({251 json!({
235 "username": user.username,252 "username": user.username,
236 "display_name": user.display_name,253 "display_name": user.display_name,
@@ -389,14 +406,9 @@ pub async fn sweep_expired(state: &AppState) {
389 }406 }
390 };407 };
391 for export in expired {408 for export in expired {
392- let path = archive_path(state, &export.id);409+ if let Err(e) = remove_archive(state, &export.id).await {
393- match tokio::fs::remove_file(&path).await {410+ tracing::warn!(error = %e, "export: could not remove an expired archive");
394- Ok(()) => {}411+ continue;
395- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
396- Err(e) => {
397- tracing::warn!(error = %e, "export: could not remove an expired archive");
398- continue;
399- }
400 }412 }
401 if let Err(e) = state.store.delete_export(&export.id).await {413 if let Err(e) = state.store.delete_export(&export.id).await {
402 tracing::warn!(error = %e, "export: could not delete an expired export row");414 tracing::warn!(error = %e, "export: could not delete an expired export row");
@@ -407,13 +419,9 @@ pub async fn sweep_expired(state: &AppState) {
407 419
408 /// Deletes one export by hand, its archive and its row. A missing archive is not an error.420 /// Deletes one export by hand, its archive and its row. A missing archive is not an error.
409 pub async fn delete_one(state: &AppState, export: &DataExport) -> forge_core::Result<()> {421 pub async fn delete_one(state: &AppState, export: &DataExport) -> forge_core::Result<()> {
410- match tokio::fs::remove_file(archive_path(state, &export.id)).await {422+ if let Err(e) = remove_archive(state, &export.id).await {
411- Ok(()) => {}423+ tracing::warn!(error = %e, "export: could not remove an archive");
412- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}424+ return Err(e.into());
413- Err(e) => {
414- tracing::warn!(error = %e, "export: could not remove an archive");
415- return Err(e.into());
416- }
417 }425 }
418 state.store.delete_export(&export.id).await?;426 state.store.delete_export(&export.id).await?;
419 bump(&export.user_id);427 bump(&export.user_id);
crates/forge-web-app/src/git_http.rsmodified+35 -27
@@ -361,6 +361,7 @@ pub async fn job_token_read(
361 if !username.eq_ignore_ascii_case(JOB_GIT_USERNAME) {361 if !username.eq_ignore_ascii_case(JOB_GIT_USERNAME) {
362 return None;362 return None;
363 }363 }
364+ let (job_id, token) = password.split_once(':')?;
364 let key = throttle::ip_key("git-ip", ip);365 let key = throttle::ip_key("git-ip", ip);
365 let now = Instant::now();366 let now = Instant::now();
366 if let Some(retry) = state.throttle.check(&key, GIT_IP_LIMIT, now) {367 if let Some(retry) = state.throttle.check(&key, GIT_IP_LIMIT, now) {
@@ -378,31 +379,13 @@ pub async fn job_token_read(
378 "CI job tokens are read-only",379 "CI job tokens are read-only",
379 ))));380 ))));
380 }381 }
381- let job_token = match password.split_once(':') {382+ let job_repo_id = match job_repo_id(state, job_id, token).await {
382- Some((job_id, token)) => state383+ Ok(Some(id)) => id,
383- .store384+ Ok(None) => {
384- .job_by_token(job_id, token)385+ state.throttle.record_failure(&key, now);
385- .await386+ return Some(Err(job_unauthorized()));
386- .map_err(|e| internal_error_for(&e)),387+ }
387- None => Ok(None),388+ Err(response) => return Some(Err(response)),
388- };
389- let run_repo = match job_token {
390- Ok(Some(job)) => state
391- .store
392- .run_by_id(&job.run_id)
393- .await
394- .map_err(|e| internal_error_for(&e))
395- .map(|run| run.map(|run| run.repo_id)),
396- Ok(None) => Ok(None),
397- Err(response) => Err(response),
398- };
399- let run_repo = match run_repo {
400- Ok(run_repo) => run_repo,
401- Err(response) => return Some(Err(Box::new(response))),
402- };
403- let Some(job_repo_id) = run_repo else {
404- state.throttle.record_failure(&key, now);
405- return Some(Err(Box::new(access_error(AccessError::Unauthorized))));
406 };389 };
407 // `<repo>.wiki` names the job's repo's wiki. It is hidden while the wiki is off, as for users.390 // `<repo>.wiki` names the job's repo's wiki. It is hidden while the wiki is off, as for users.
408 let (repo_name, wiki) = match forge_core::names::wiki_base(name) {391 let (repo_name, wiki) = match forge_core::names::wiki_base(name) {
@@ -411,13 +394,13 @@ pub async fn job_token_read(
411 };394 };
412 let repo = match find_repo(state, owner, repo_name).await {395 let repo = match find_repo(state, owner, repo_name).await {
413 Ok(Some(repo)) if repo.id == job_repo_id => repo,396 Ok(Some(repo)) if repo.id == job_repo_id => repo,
414- Ok(_) => return Some(Err(Box::new(access_error(AccessError::Unauthorized)))),397+ Ok(_) => return Some(Err(job_unauthorized())),
415 Err(e) => return Some(Err(Box::new(access_error(e)))),398 Err(e) => return Some(Err(Box::new(access_error(e)))),
416 };399 };
417 if wiki {400 if wiki {
418 match state.store.wiki_enabled(&repo.id).await {401 match state.store.wiki_enabled(&repo.id).await {
419 Ok(true) => {}402 Ok(true) => {}
420- Ok(false) => return Some(Err(Box::new(access_error(AccessError::Unauthorized)))),403+ Ok(false) => return Some(Err(job_unauthorized())),
421 Err(e) => return Some(Err(Box::new(internal_error_for(&e)))),404 Err(e) => return Some(Err(Box::new(internal_error_for(&e)))),
422 }405 }
423 return match forge_git::repo::wiki_path(&state.config.data_dir, &repo.id) {406 return match forge_git::repo::wiki_path(&state.config.data_dir, &repo.id) {
@@ -431,6 +414,31 @@ pub async fn job_token_read(
431 }414 }
432 }415 }
433 416
417+async fn job_repo_id(
418+ state: &AppState,
419+ job_id: &str,
420+ token: &str,
421+) -> Result<Option<String>, Box<Response>> {
422+ let Some(job) = state
423+ .store
424+ .job_by_token(job_id, token)
425+ .await
426+ .map_err(|e| Box::new(internal_error_for(&e)))?
427+ else {
428+ return Ok(None);
429+ };
430+ let run = state
431+ .store
432+ .run_by_id(&job.run_id)
433+ .await
434+ .map_err(|e| Box::new(internal_error_for(&e)))?;
435+ Ok(run.map(|run| run.repo_id))
436+}
437+
438+fn job_unauthorized() -> Box<Response> {
439+ Box::new(access_error(AccessError::Unauthorized))
440+}
441+
434 fn internal_error_for(error: &forge_core::Error) -> Response {442 fn internal_error_for(error: &forge_core::Error) -> Response {
435 tracing::error!(error = %error, "ci job token check failed");443 tracing::error!(error = %error, "ci job token check failed");
436 internal_error()444 internal_error()
crates/forge-web-app/src/importer/api.rsmodified+51 -106
@@ -1,8 +1,3 @@
1-//! Remote forge APIs for imports. [`RemoteApi`] is the seam: the import job talks only to the
2-//! trait, so tests use a fake and CI never needs the network. [`GitHub`] and [`GitLab`] are the real
3-//! clients over REST. They paginate, wait out rate limits (and say so through the notice callback),
4-//! and send the token only to the API host, never to a redirect target.
5-
6 use std::fmt;1 use std::fmt;
7 use std::future::Future;2 use std::future::Future;
8 use std::io;3 use std::io;
@@ -17,17 +12,12 @@ use serde::de::DeserializeOwned;
17 12
18 use crate::webhooks::client::{WebhookPolicy, validate_url};13 use crate::webhooks::client::{WebhookPolicy, validate_url};
19 14
20-/// A release asset's bytes as they arrive from the server, ready for the blob writer.
21 pub type AssetStream = BoxStream<'static, io::Result<Bytes>>;15 pub type AssetStream = BoxStream<'static, io::Result<Bytes>>;
22 16
23 const PER_PAGE: usize = 100;17 const PER_PAGE: usize = 100;
24-/// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever.
25-/// Forgejo and Gitea cap `limit` at 50 by default.
26 const FORGEJO_LIMIT: usize = 50;18 const FORGEJO_LIMIT: usize = 50;
27 const MAX_PAGES: usize = 500;19 const MAX_PAGES: usize = 500;
28-/// Longest rate-limit wait a job sits through. A longer reset fails the job; a retry continues.
29 const MAX_RATE_WAIT: u64 = 15 * 60;20 const MAX_RATE_WAIT: u64 = 15 * 60;
30-/// Largest JSON page read.
31 const MAX_JSON_BYTES: usize = 32 * 1024 * 1024;21 const MAX_JSON_BYTES: usize = 32 * 1024 * 1024;
32 const MAX_REDIRECTS: usize = 5;22 const MAX_REDIRECTS: usize = 5;
33 23
@@ -58,7 +48,6 @@ impl fmt::Display for ApiError {
58 }48 }
59 }49 }
60 50
61-/// `secs` as a reader would say it, rounded up to the minute so a retry at that time is not early.
62 fn wait_text(secs: u64) -> String {51 fn wait_text(secs: u64) -> String {
63 let plural = |n: u64| if n == 1 { "" } else { "s" };52 let plural = |n: u64| if n == 1 { "" } else { "s" };
64 if secs < 60 {53 if secs < 60 {
@@ -88,7 +77,6 @@ pub struct ExtMilestone {
88 pub title: String,77 pub title: String,
89 pub description: String,78 pub description: String,
90 pub closed: bool,79 pub closed: bool,
91- /// `YYYY-MM-DD`.
92 pub due_on: Option<String>,80 pub due_on: Option<String>,
93 }81 }
94 82
@@ -143,7 +131,6 @@ pub struct ExtRelease {
143 #[derive(Debug, Clone, PartialEq, Eq, Default)]131 #[derive(Debug, Clone, PartialEq, Eq, Default)]
144 pub struct ExtRepo {132 pub struct ExtRepo {
145 pub name: String,133 pub name: String,
146- /// `owner/name`, or the GitLab project path.
147 pub full_name: String,134 pub full_name: String,
148 pub description: String,135 pub description: String,
149 pub private: bool,136 pub private: bool,
@@ -153,13 +140,10 @@ pub struct ExtRepo {
153 pub web_url: String,140 pub web_url: String,
154 }141 }
155 142
156-/// What an import needs from a remote forge. `repo` is `owner/name` for GitHub and the full
157-/// project path for GitLab.
158 pub trait RemoteApi: Send + Sync {143 pub trait RemoteApi: Send + Sync {
159 fn list_repos(&self, owner: &str) -> impl Future<Output = ApiResult<Vec<ExtRepo>>> + Send;144 fn list_repos(&self, owner: &str) -> impl Future<Output = ApiResult<Vec<ExtRepo>>> + Send;
160 fn labels(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtLabel>>> + Send;145 fn labels(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtLabel>>> + Send;
161 fn milestones(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtMilestone>>> + Send;146 fn milestones(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtMilestone>>> + Send;
162- /// Issues and pull (merge) requests, every state, with `is_pr` set on the latter.
163 fn issues(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtIssue>>> + Send;147 fn issues(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtIssue>>> + Send;
164 fn comments(148 fn comments(
165 &self,149 &self,
@@ -167,7 +151,6 @@ pub trait RemoteApi: Send + Sync {
167 issue: &ExtIssue,151 issue: &ExtIssue,
168 ) -> impl Future<Output = ApiResult<Vec<ExtComment>>> + Send;152 ) -> impl Future<Output = ApiResult<Vec<ExtComment>>> + Send;
169 fn releases(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtRelease>>> + Send;153 fn releases(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtRelease>>> + Send;
170- /// The bytes of a release asset, at most `max_bytes`, streamed as they arrive.
171 fn download(154 fn download(
172 &self,155 &self,
173 asset: &ExtAsset,156 asset: &ExtAsset,
@@ -175,7 +158,6 @@ pub trait RemoteApi: Send + Sync {
175 ) -> impl Future<Output = ApiResult<AssetStream>> + Send;158 ) -> impl Future<Output = ApiResult<AssetStream>> + Send;
176 }159 }
177 160
178-/// True for one URL path segment of an owner, repo or group name.
179 pub fn valid_segment(s: &str) -> bool {161 pub fn valid_segment(s: &str) -> bool {
180 !s.is_empty()162 !s.is_empty()
181 && s.len() <= 100163 && s.len() <= 100
@@ -185,13 +167,11 @@ pub fn valid_segment(s: &str) -> bool {
185 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))167 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
186 }168 }
187 169
188-/// `owner/name` made of valid segments, `min..=max` of them.
189 pub fn valid_path(path: &str, min: usize, max: usize) -> bool {170 pub fn valid_path(path: &str, min: usize, max: usize) -> bool {
190 let parts: Vec<&str> = path.split('/').collect();171 let parts: Vec<&str> = path.split('/').collect();
191 (min..=max).contains(&parts.len()) && parts.iter().all(|p| valid_segment(p))172 (min..=max).contains(&parts.len()) && parts.iter().all(|p| valid_segment(p))
192 }173 }
193 174
194-/// How long to wait after a 403 or 429. `None` when the response is not a rate limit.
195 pub fn rate_wait(175 pub fn rate_wait(
196 retry_after: Option<&str>,176 retry_after: Option<&str>,
197 remaining: Option<&str>,177 remaining: Option<&str>,
@@ -210,18 +190,13 @@ pub fn rate_wait(
210 190
211 pub type Notice = Arc<dyn Fn(String) + Send + Sync>;191 pub type Notice = Arc<dyn Fn(String) + Send + Sync>;
212 192
213-/// How the token is presented to the API host.
214 #[derive(Debug, Clone, Copy, PartialEq, Eq)]193 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
215 pub enum Auth {194 pub enum Auth {
216- /// `Authorization: Bearer`.
217 GitHub,195 GitHub,
218- /// `PRIVATE-TOKEN`.
219 GitLab,196 GitLab,
220- /// `Authorization: token`.
221 Forgejo,197 Forgejo,
222 }198 }
223 199
224-/// A client under the outbound policy, with the token kept private to the API host.
225 pub struct Http {200 pub struct Http {
226 client: reqwest::Client,201 client: reqwest::Client,
227 policy: WebhookPolicy,202 policy: WebhookPolicy,
@@ -282,10 +257,7 @@ impl Http {
282 .map(str::to_owned)257 .map(str::to_owned)
283 }258 }
284 259
285- /// One GET with retries: waits out a rate limit, backs off on a 5xx. Returns a 2xx or 3xx.
286 async fn send(&self, url: &str, accept: &str, authed: bool) -> ApiResult<reqwest::Response> {260 async fn send(&self, url: &str, accept: &str, authed: bool) -> ApiResult<reqwest::Response> {
287- // Every URL, including one taken from an API answer or a redirect: the client's resolver
288- // filters host names, but an address literal never reaches it.
289 validate_url(url, &self.policy)261 validate_url(url, &self.policy)
290 .map_err(|e| ApiError::Http(format!("address refused: {e}")))?;262 .map_err(|e| ApiError::Http(format!("address refused: {e}")))?;
291 let mut attempt = 0u32;263 let mut attempt = 0u32;
@@ -354,7 +326,6 @@ impl Http {
354 serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string()))326 serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string()))
355 }327 }
356 328
357- /// Every page of a list endpoint, 100 per page, stopping at the first short page.
358 pub async fn pages<T: DeserializeOwned>(&self, base: &str) -> ApiResult<Vec<T>> {329 pub async fn pages<T: DeserializeOwned>(&self, base: &str) -> ApiResult<Vec<T>> {
359 let sep = if base.contains('?') { '&' } else { '?' };330 let sep = if base.contains('?') { '&' } else { '?' };
360 let mut out = Vec::new();331 let mut out = Vec::new();
@@ -364,14 +335,12 @@ impl Http {
364 let short = items.len() < PER_PAGE;335 let short = items.len() < PER_PAGE;
365 out.extend(items);336 out.extend(items);
366 if short {337 if short {
367- break;338+ return Ok(out);
368 }339 }
369 }340 }
370- Ok(out)341+ Err(ApiError::TooLarge)
371 }342 }
372 343
373- /// Every page of a Forgejo/Gitea list endpoint (`limit`, `page`). The `Link` header decides
374- /// when it ends; without one, `X-Total-Count`; without either, the first short page.
375 pub async fn limit_pages<T: DeserializeOwned>(&self, base: &str) -> ApiResult<Vec<T>> {344 pub async fn limit_pages<T: DeserializeOwned>(&self, base: &str) -> ApiResult<Vec<T>> {
376 let sep = if base.contains('?') { '&' } else { '?' };345 let sep = if base.contains('?') { '&' } else { '?' };
377 let mut out: Vec<T> = Vec::new();346 let mut out: Vec<T> = Vec::new();
@@ -393,15 +362,12 @@ impl Http {
393 (None, None) => got < FORGEJO_LIMIT,362 (None, None) => got < FORGEJO_LIMIT,
394 };363 };
395 if done {364 if done {
396- break;365+ return Ok(out);
397 }366 }
398 }367 }
399- Ok(out)368+ Err(ApiError::TooLarge)
400 }369 }
401 370
402- /// Downloads a file, following redirects by hand: the token goes to the API host only, and
403- /// each hop is fetched under the same address policy as every other request. The body is
404- /// streamed, so a large asset is never held in memory whole.
405 pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult<AssetStream> {371 pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult<AssetStream> {
406 let mut current = url.to_owned();372 let mut current = url.to_owned();
407 for _ in 0..=MAX_REDIRECTS {373 for _ in 0..=MAX_REDIRECTS {
@@ -435,8 +401,6 @@ impl Http {
435 Err(ApiError::Http("too many redirects".into()))401 Err(ApiError::Http("too many redirects".into()))
436 }402 }
437 403
438- /// The body as it arrives. Counting happens here, so the stream fails with `InvalidData` as
439- /// soon as more than `max` bytes have come, whether or not the server sent a length.
440 fn stream(resp: reqwest::Response, max: u64) -> AssetStream {404 fn stream(resp: reqwest::Response, max: u64) -> AssetStream {
441 let mut seen: u64 = 0;405 let mut seen: u64 = 0;
442 Box::pin(resp.bytes_stream().map(move |chunk| {406 Box::pin(resp.bytes_stream().map(move |chunk| {
@@ -467,8 +431,6 @@ fn s(v: Option<String>) -> String {
467 v.unwrap_or_default()431 v.unwrap_or_default()
468 }432 }
469 433
470-// ---- GitHub ----
471-
472 pub struct GitHub {434 pub struct GitHub {
473 http: Http,435 http: Http,
474 base: String,436 base: String,
@@ -584,8 +546,23 @@ fn login(u: Option<GhUser>) -> String {
584 u.and_then(|u| u.login).unwrap_or_default()546 u.and_then(|u| u.login).unwrap_or_default()
585 }547 }
586 548
587-#[cfg(any(test, feature = "test-support"))]549+fn release_title(name: Option<String>, tag: &str) -> String {
588-pub fn parse_github_labels(json: &[u8]) -> ApiResult<Vec<ExtLabel>> {550+ name.filter(|n| !n.is_empty())
551+ .unwrap_or_else(|| tag.to_owned())
552+}
553+
554+async fn or_user<T>(
555+ org: ApiResult<Vec<T>>,
556+ user: impl Future<Output = ApiResult<Vec<T>>>,
557+) -> ApiResult<Vec<T>> {
558+ match org {
559+ Err(ApiError::NotFound(_)) => user.await,
560+ other => other,
561+ }
562+}
563+
564+#[cfg(test)]
565+fn parse_github_labels(json: &[u8]) -> ApiResult<Vec<ExtLabel>> {
589 let raw: Vec<GhLabel> = from_json(json)?;566 let raw: Vec<GhLabel> = from_json(json)?;
590 Ok(raw.into_iter().map(label_of).collect())567 Ok(raw.into_iter().map(label_of).collect())
591 }568 }
@@ -598,13 +575,13 @@ fn label_of(l: GhLabel) -> ExtLabel {
598 }575 }
599 }576 }
600 577
601-#[cfg(any(test, feature = "test-support"))]578+#[cfg(test)]
602 fn from_json<T: DeserializeOwned>(json: &[u8]) -> ApiResult<T> {579 fn from_json<T: DeserializeOwned>(json: &[u8]) -> ApiResult<T> {
603 serde_json::from_slice(json).map_err(|e| ApiError::Parse(e.to_string()))580 serde_json::from_slice(json).map_err(|e| ApiError::Parse(e.to_string()))
604 }581 }
605 582
606-#[cfg(any(test, feature = "test-support"))]583+#[cfg(test)]
607-pub fn parse_github_issues(json: &[u8]) -> ApiResult<Vec<ExtIssue>> {584+fn parse_github_issues(json: &[u8]) -> ApiResult<Vec<ExtIssue>> {
608 let raw: Vec<GhIssue> = from_json(json)?;585 let raw: Vec<GhIssue> = from_json(json)?;
609 Ok(raw.into_iter().map(gh_issue).collect())586 Ok(raw.into_iter().map(gh_issue).collect())
610 }587 }
@@ -630,8 +607,8 @@ fn gh_issue(i: GhIssue) -> ExtIssue {
630 }607 }
631 }608 }
632 609
633-#[cfg(any(test, feature = "test-support"))]610+#[cfg(test)]
634-pub fn parse_github_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {611+fn parse_github_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {
635 let raw: Vec<GhRelease> = from_json(json)?;612 let raw: Vec<GhRelease> = from_json(json)?;
636 Ok(raw613 Ok(raw
637 .into_iter()614 .into_iter()
@@ -672,15 +649,12 @@ impl RemoteApi for GitHub {
672 .http649 .http
673 .pages(&format!("{}/orgs/{owner}/repos?type=all", self.base))650 .pages(&format!("{}/orgs/{owner}/repos?type=all", self.base))
674 .await;651 .await;
675- let raw = match org {652+ let raw = or_user(
676- Ok(raw) => raw,653+ org,
677- Err(ApiError::NotFound(_)) => {654+ self.http
678- self.http655+ .pages(&format!("{}/users/{owner}/repos?type=owner", self.base)),
679- .pages(&format!("{}/users/{owner}/repos?type=owner", self.base))656+ )
680- .await?657+ .await?;
681- }
682- Err(e) => return Err(e),
683- };
684 Ok(raw658 Ok(raw
685 .into_iter()659 .into_iter()
686 .map(|r| ExtRepo {660 .map(|r| ExtRepo {
@@ -762,7 +736,6 @@ impl RemoteApi for GitHub {
762 .http736 .http
763 .pages(&format!("{}/repos/{repo}/releases", self.base))737 .pages(&format!("{}/repos/{repo}/releases", self.base))
764 .await?;738 .await?;
765- // Reuse the one conversion by round-tripping through the parser's mapping.
766 Ok(raw.into_iter().map(gh_release).collect())739 Ok(raw.into_iter().map(gh_release).collect())
767 }740 }
768 741
@@ -777,10 +750,7 @@ impl RemoteApi for GitHub {
777 fn gh_release(r: GhRelease) -> ExtRelease {750 fn gh_release(r: GhRelease) -> ExtRelease {
778 ExtRelease {751 ExtRelease {
779 id: r.id.to_string(),752 id: r.id.to_string(),
780- title: r753+ title: release_title(r.name, &r.tag_name),
781- .name
782- .filter(|n| !n.is_empty())
783- .unwrap_or_else(|| r.tag_name.clone()),
784 tag: r.tag_name,754 tag: r.tag_name,
785 body: s(r.body),755 body: s(r.body),
786 draft: r.draft,756 draft: r.draft,
@@ -810,16 +780,12 @@ fn check_repo(repo: &str, min: usize, max: usize) -> ApiResult<()> {
810 }780 }
811 }781 }
812 782
813-// ---- GitLab ----
814-
815 pub struct GitLab {783 pub struct GitLab {
816 http: Http,784 http: Http,
817- /// `https://host/api/v4`.
818 base: String,785 base: String,
819 }786 }
820 787
821 impl GitLab {788 impl GitLab {
822- /// `instance` is the instance's web address, e.g. `https://gitlab.com`.
823 pub fn new(http: Http, instance: &str) -> Self {789 pub fn new(http: Http, instance: &str) -> Self {
824 GitLab {790 GitLab {
825 http,791 http,
@@ -952,14 +918,14 @@ fn gl_issue(i: GlIssue, is_pr: bool) -> ExtIssue {
952 }918 }
953 }919 }
954 920
955-#[cfg(any(test, feature = "test-support"))]921+#[cfg(test)]
956-pub fn parse_gitlab_issues(json: &[u8], is_pr: bool) -> ApiResult<Vec<ExtIssue>> {922+fn parse_gitlab_issues(json: &[u8], is_pr: bool) -> ApiResult<Vec<ExtIssue>> {
957 let raw: Vec<GlIssue> = from_json(json)?;923 let raw: Vec<GlIssue> = from_json(json)?;
958 Ok(raw.into_iter().map(|i| gl_issue(i, is_pr)).collect())924 Ok(raw.into_iter().map(|i| gl_issue(i, is_pr)).collect())
959 }925 }
960 926
961-#[cfg(any(test, feature = "test-support"))]927+#[cfg(test)]
962-pub fn parse_gitlab_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {928+fn parse_gitlab_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {
963 let raw: Vec<GlRelease> = from_json(json)?;929 let raw: Vec<GlRelease> = from_json(json)?;
964 Ok(raw.into_iter().map(gl_release).collect())930 Ok(raw.into_iter().map(gl_release).collect())
965 }931 }
@@ -967,10 +933,7 @@ pub fn parse_gitlab_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {
967 fn gl_release(r: GlRelease) -> ExtRelease {933 fn gl_release(r: GlRelease) -> ExtRelease {
968 ExtRelease {934 ExtRelease {
969 id: r.tag_name.clone(),935 id: r.tag_name.clone(),
970- title: r936+ title: release_title(r.name, &r.tag_name),
971- .name
972- .filter(|n| !n.is_empty())
973- .unwrap_or_else(|| r.tag_name.clone()),
974 tag: r.tag_name,937 tag: r.tag_name,
975 body: s(r.description),938 body: s(r.description),
976 draft: r.upcoming_release,939 draft: r.upcoming_release,
@@ -1007,15 +970,12 @@ impl RemoteApi for GitLab {
1007 self.base970 self.base
1008 ))971 ))
1009 .await;972 .await;
1010- let raw = match group {973+ let raw = or_user(
1011- Ok(raw) => raw,974+ group,
1012- Err(ApiError::NotFound(_)) => {975+ self.http
1013- self.http976+ .pages(&format!("{}/users/{enc}/projects", self.base)),
1014- .pages(&format!("{}/users/{enc}/projects", self.base))977+ )
1015- .await?978+ .await?;
1016- }
1017- Err(e) => return Err(e),
1018- };
1019 Ok(raw979 Ok(raw
1020 .into_iter()980 .into_iter()
1021 .map(|p| ExtRepo {981 .map(|p| ExtRepo {
@@ -1125,19 +1085,13 @@ impl RemoteApi for GitLab {
1125 }1085 }
1126 }1086 }
1127 1087
1128-// ---- Forgejo and Gitea ----
1129-
1130-/// A Forgejo or Gitea instance (Codeberg among them), over `/api/v1`.
1131 pub struct Forgejo {1088 pub struct Forgejo {
1132 http: Http,1089 http: Http,
1133- /// `https://host`, the web address the asset links must start with.
1134 origin: String,1090 origin: String,
1135- /// `https://host/api/v1`.
1136 base: String,1091 base: String,
1137 }1092 }
1138 1093
1139 impl Forgejo {1094 impl Forgejo {
1140- /// `instance` is the instance's web address, e.g. `https://codeberg.org`.
1141 pub fn new(http: Http, instance: &str) -> Self {1095 pub fn new(http: Http, instance: &str) -> Self {
1142 let origin = instance.trim_end_matches('/').to_owned();1096 let origin = instance.trim_end_matches('/').to_owned();
1143 Forgejo {1097 Forgejo {
@@ -1192,7 +1146,6 @@ struct FjIssue {
1192 milestone: Option<FjMilestoneRef>,1146 milestone: Option<FjMilestoneRef>,
1193 created_at: Option<String>,1147 created_at: Option<String>,
1194 html_url: Option<String>,1148 html_url: Option<String>,
1195- /// Set on `/pulls` items.
1196 #[serde(default)]1149 #[serde(default)]
1197 merged: bool,1150 merged: bool,
1198 }1151 }
@@ -1266,10 +1219,7 @@ fn fj_issue(i: FjIssue, is_pr: bool) -> ExtIssue {
1266 fn fj_release(r: FjRelease) -> ExtRelease {1219 fn fj_release(r: FjRelease) -> ExtRelease {
1267 ExtRelease {1220 ExtRelease {
1268 id: r.id.to_string(),1221 id: r.id.to_string(),
1269- title: r1222+ title: release_title(r.name, &r.tag_name),
1270- .name
1271- .filter(|n| !n.is_empty())
1272- .unwrap_or_else(|| r.tag_name.clone()),
1273 tag: r.tag_name,1223 tag: r.tag_name,
1274 body: s(r.body),1224 body: s(r.body),
1275 draft: r.draft,1225 draft: r.draft,
@@ -1293,7 +1243,6 @@ fn fj_release(r: FjRelease) -> ExtRelease {
1293 1243
1294 impl RemoteApi for Forgejo {1244 impl RemoteApi for Forgejo {
1295 async fn list_repos(&self, owner: &str) -> ApiResult<Vec<ExtRepo>> {1245 async fn list_repos(&self, owner: &str) -> ApiResult<Vec<ExtRepo>> {
1296- // An empty owner means "mine", which needs a token.
1297 let raw: Vec<FjRepo> = if owner.is_empty() {1246 let raw: Vec<FjRepo> = if owner.is_empty() {
1298 self.http1247 self.http
1299 .limit_pages(&format!("{}/user/repos", self.base))1248 .limit_pages(&format!("{}/user/repos", self.base))
@@ -1306,15 +1255,12 @@ impl RemoteApi for Forgejo {
1306 .http1255 .http
1307 .limit_pages(&format!("{}/orgs/{owner}/repos", self.base))1256 .limit_pages(&format!("{}/orgs/{owner}/repos", self.base))
1308 .await;1257 .await;
1309- match org {1258+ or_user(
1310- Ok(raw) => raw,1259+ org,
1311- Err(ApiError::NotFound(_)) => {1260+ self.http
1312- self.http1261+ .limit_pages(&format!("{}/users/{owner}/repos", self.base)),
1313- .limit_pages(&format!("{}/users/{owner}/repos", self.base))1262+ )
1314- .await?1263+ .await?
1315- }
1316- Err(e) => return Err(e),
1317- }
1318 };1264 };
1319 Ok(raw1265 Ok(raw
1320 .into_iter()1266 .into_iter()
@@ -1413,7 +1359,6 @@ impl RemoteApi for Forgejo {
1413 .http1359 .http
1414 .limit_pages(&format!("{}/repos/{repo}/releases", self.base))1360 .limit_pages(&format!("{}/repos/{repo}/releases", self.base))
1415 .await?;1361 .await?;
1416- // The list embeds each release's assets, so `/releases/{id}/assets` is not needed.
1417 Ok(raw.into_iter().map(fj_release).collect())1362 Ok(raw.into_iter().map(fj_release).collect())
1418 }1363 }
1419 1364
crates/forge-web-app/src/importer/mod.rsmodified+80 -56
@@ -288,7 +288,7 @@ fn clip_title(title: &str) -> String {
288 288
289 /// An asset file name the release store accepts.289 /// An asset file name the release store accepts.
290 pub fn asset_name(name: &str) -> String {290 pub fn asset_name(name: &str) -> String {
291- let mut out: String = name291+ let cleaned: String = name
292 .chars()292 .chars()
293 .map(|c| {293 .map(|c| {
294 if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+') {294 if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+') {
@@ -298,9 +298,7 @@ pub fn asset_name(name: &str) -> String {
298 }298 }
299 })299 })
300 .collect();300 .collect();
301- while out.starts_with('.') {301+ let mut out = cleaned.trim_start_matches('.').to_owned();
302- out.remove(0);
303- }
304 out.truncate(MAX_ASSET_NAME_LEN);302 out.truncate(MAX_ASSET_NAME_LEN);
305 if out.is_empty() {303 if out.is_empty() {
306 "asset".to_owned()304 "asset".to_owned()
@@ -354,7 +352,7 @@ async fn run_production(state: &AppState, job: &ImportJob, spec: &JobSpec) {
354 Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await,352 Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await,
355 Err(e) => fail(state, &rep, &e).await,353 Err(e) => fail(state, &rep, &e).await,
356 },354 },
357- Source::Git => {}355+ Source::Git => run_job::<GitHub>(state, job, spec, None, &Transport::Net).await,
358 }356 }
359 }357 }
360 358
@@ -566,10 +564,6 @@ struct Totals {
566 skipped: usize,564 skipped: usize,
567 }565 }
568 566
569-fn api_err(e: ApiError) -> String {
570- e.to_string()
571-}
572-
573 struct Run<'a, A> {567 struct Run<'a, A> {
574 state: &'a AppState,568 state: &'a AppState,
575 rep: &'a Reporter,569 rep: &'a Reporter,
@@ -614,7 +608,11 @@ impl<A: RemoteApi> Run<'_, A> {
614 608
615 async fn labels(&self, totals: &mut Totals) -> Result<(), String> {609 async fn labels(&self, totals: &mut Totals) -> Result<(), String> {
616 self.rep.stage("labels", 0, 0).await;610 self.rep.stage("labels", 0, 0).await;
617- let labels = self.api.labels(&self.spec.remote).await.map_err(api_err)?;611+ let labels = self
612+ .api
613+ .labels(&self.spec.remote)
614+ .await
615+ .map_err(|e| e.to_string())?;
618 let total = labels.len();616 let total = labels.len();
619 for (i, label) in labels.into_iter().enumerate() {617 for (i, label) in labels.into_iter().enumerate() {
620 self.rep.stage("labels", i, total).await;618 self.rep.stage("labels", i, total).await;
@@ -656,7 +654,7 @@ impl<A: RemoteApi> Run<'_, A> {
656 .api654 .api
657 .milestones(&self.spec.remote)655 .milestones(&self.spec.remote)
658 .await656 .await
659- .map_err(api_err)?;657+ .map_err(|e| e.to_string())?;
660 let total = items.len();658 let total = items.len();
661 for (i, m) in items.into_iter().enumerate() {659 for (i, m) in items.into_iter().enumerate() {
662 self.rep.stage("milestones", i, total).await;660 self.rep.stage("milestones", i, total).await;
@@ -721,7 +719,12 @@ impl<A: RemoteApi> Run<'_, A> {
721 cache.insert(key, label.id.clone());719 cache.insert(key, label.id.clone());
722 Some(label.id)720 Some(label.id)
723 }721 }
724- Err(_) => None,722+ Err(e) => {
723+ self.rep
724+ .log("warn", format!("label `{name}` not set: {e}"))
725+ .await;
726+ None
727+ }
725 }728 }
726 }729 }
727 730
@@ -731,7 +734,7 @@ impl<A: RemoteApi> Run<'_, A> {
731 .api734 .api
732 .issues(&self.spec.remote)735 .issues(&self.spec.remote)
733 .await736 .await
734- .map_err(api_err)?737+ .map_err(|e| e.to_string())?
735 .into_iter()738 .into_iter()
736 .filter(|i| {739 .filter(|i| {
737 if i.is_pr {740 if i.is_pr {
@@ -741,11 +744,10 @@ impl<A: RemoteApi> Run<'_, A> {
741 }744 }
742 })745 })
743 .collect();746 .collect();
744- items.sort_by_key(|i| (i.is_pr, i.number));
745- // GitHub and Forgejo number issues and pull requests together; GitLab keeps two sequences. Sorting
746- // by number alone keeps GitHub numbers aligned, so do that for them.
747 if matches!(self.spec.source, Source::GitHub | Source::Forgejo) {747 if matches!(self.spec.source, Source::GitHub | Source::Forgejo) {
748 items.sort_by_key(|i| i.number);748 items.sort_by_key(|i| i.number);
749+ } else {
750+ items.sort_by_key(|i| (i.is_pr, i.number));
749 }751 }
750 let total = items.len();752 let total = items.len();
751 let mut labels: HashMap<String, String> = self753 let mut labels: HashMap<String, String> = self
@@ -779,7 +781,6 @@ impl<A: RemoteApi> Run<'_, A> {
779 Some(o) => o.local_id,781 Some(o) => o.local_id,
780 None => match self.create_item(item, &mut labels, &milestones).await {782 None => match self.create_item(item, &mut labels, &milestones).await {
781 Ok(id) => {783 Ok(id) => {
782- self.record(kind, &ext, &id, &item.author, &item.url).await;
783 created_since_bump += 1;784 created_since_bump += 1;
784 if created_since_bump == IMPORT_BUMP_BATCH {785 if created_since_bump == IMPORT_BUMP_BATCH {
785 created_since_bump = 0;786 created_since_bump = 0;
@@ -801,47 +802,58 @@ impl<A: RemoteApi> Run<'_, A> {
801 }802 }
802 },803 },
803 };804 };
804- let comments = self805+ self.import_comments(kind, &local, item, totals).await?;
805- .api806+ }
806- .comments(&self.spec.remote, item)807+ self.rep.stage("issues", total, total).await;
807- .await808+ self.bump_issues();
808- .map_err(api_err)?;809+ Ok(())
809- for c in comments {810+ }
810- if self811+
811- .mapped("comment", &format!("{kind}:{}", c.id))812+ async fn import_comments(
812- .await?813+ &self,
813- .is_some()814+ kind: &str,
814- {815+ local: &str,
815- continue;816+ item: &ExtIssue,
817+ totals: &mut Totals,
818+ ) -> Result<(), String> {
819+ let comments = self
820+ .api
821+ .comments(&self.spec.remote, item)
822+ .await
823+ .map_err(|e| e.to_string())?;
824+ for c in comments {
825+ if self
826+ .mapped("comment", &format!("{kind}:{}", c.id))
827+ .await?
828+ .is_some()
829+ {
830+ continue;
831+ }
832+ let note = origin_note(self.spec.source.label(), &c.author, &c.created_at, &c.url);
833+ let body = with_note(&note, &c.body);
834+ match self.store().add_comment(local, &self.user.id, &body).await {
835+ Ok(created) => {
836+ self.record(
837+ "comment",
838+ &format!("{kind}:{}", c.id),
839+ &created.id,
840+ &c.author,
841+ &c.url,
842+ )
843+ .await;
844+ totals.comments += 1;
816 }845 }
817- let note = origin_note(self.spec.source.label(), &c.author, &c.created_at, &c.url);846+ Err(e) => {
818- let body = with_note(&note, &c.body);847+ totals.skipped += 1;
819- match self.store().add_comment(&local, &self.user.id, &body).await {848+ self.rep
820- Ok(created) => {849+ .log(
821- self.record(850+ "warn",
822- "comment",851+ format!("a comment on #{} skipped: {e}", item.number),
823- &format!("{kind}:{}", c.id),
824- &created.id,
825- &c.author,
826- &c.url,
827 )852 )
828 .await;853 .await;
829- totals.comments += 1;
830- }
831- Err(e) => {
832- totals.skipped += 1;
833- self.rep
834- .log(
835- "warn",
836- format!("a comment on #{} skipped: {e}", item.number),
837- )
838- .await;
839- }
840 }854 }
841 }855 }
842 }856 }
843- self.rep.stage("issues", total, total).await;
844- self.bump_issues();
845 Ok(())857 Ok(())
846 }858 }
847 859
@@ -876,6 +888,9 @@ impl<A: RemoteApi> Run<'_, A> {
876 &body,888 &body,
877 )889 )
878 .await?;890 .await?;
891+ let kind = if item.is_pr { "pull" } else { "issue" };
892+ self.record(kind, &item.number.to_string(), &issue.id, &item.author, &item.url)
893+ .await;
879 let mut ids = Vec::new();894 let mut ids = Vec::new();
880 for name in &item.labels {895 for name in &item.labels {
881 if let Some(id) = self.label_id(labels, name, FALLBACK_LABEL_COLOR).await {896 if let Some(id) = self.label_id(labels, name, FALLBACK_LABEL_COLOR).await {
@@ -889,7 +904,6 @@ impl<A: RemoteApi> Run<'_, A> {
889 {904 {
890 ids.push(id);905 ids.push(id);
891 }906 }
892- ids.dedup();
893 if !ids.is_empty() {907 if !ids.is_empty() {
894 self.store()908 self.store()
895 .set_issue_labels(&issue.id, &self.user.id, &ids)909 .set_issue_labels(&issue.id, &self.user.id, &ids)
@@ -929,7 +943,7 @@ impl<A: RemoteApi> Run<'_, A> {
929 .api943 .api
930 .releases(&self.spec.remote)944 .releases(&self.spec.remote)
931 .await945 .await
932- .map_err(api_err)?;946+ .map_err(|e| e.to_string())?;
933 let repo_dir = forge_git::repo::repo_path(&self.state.git.data_dir, &self.repo.id)947 let repo_dir = forge_git::repo::repo_path(&self.state.git.data_dir, &self.repo.id)
934 .map_err(|e| e.to_string())?;948 .map_err(|e| e.to_string())?;
935 let refs = ref_snapshot(self.state, &repo_dir).await?;949 let refs = ref_snapshot(self.state, &repo_dir).await?;
@@ -957,11 +971,21 @@ impl<A: RemoteApi> Run<'_, A> {
957 totals: &mut Totals,971 totals: &mut Totals,
958 ) -> Result<Option<forge_core::releases::Release>, String> {972 ) -> Result<Option<forge_core::releases::Release>, String> {
959 if let Some(o) = self.mapped("release", &rel.id).await? {973 if let Some(o) = self.mapped("release", &rel.id).await? {
960- return self974+ let found = self
961 .store()975 .store()
962 .release(&o.local_id)976 .release(&o.local_id)
963 .await977 .await
964- .map_err(|e| e.to_string());978+ .map_err(|e| e.to_string())?;
979+ if found.is_none() {
980+ totals.skipped += 1;
981+ self.rep
982+ .log(
983+ "warn",
984+ format!("release `{}` skipped: it was deleted here", rel.tag),
985+ )
986+ .await;
987+ }
988+ return Ok(found);
965 }989 }
966 let Some(oid) = refs.get(&format!("refs/tags/{}", rel.tag)) else {990 let Some(oid) = refs.get(&format!("refs/tags/{}", rel.tag)) else {
967 totals.skipped += 1;991 totals.skipped += 1;
crates/forge-web-app/src/importer/remote.rsmodified+20 -18
@@ -8,14 +8,28 @@ use crate::mirrors::policy;
8 use crate::state::AppState;8 use crate::state::AppState;
9 use crate::webhooks::client::{policy_client, validate_url};9 use crate::webhooks::client::{policy_client, validate_url};
10 10
11+fn client(state: &AppState) -> Result<reqwest::Client, String> {
12+ policy_client(policy(state), Duration::from_secs(60), "forge-import/1")
13+ .map_err(|e| format!("could not build the HTTP client: {e}"))
14+}
15+
16+fn instance_host<'a>(state: &AppState, instance: &'a str) -> Result<(&'a str, String), String> {
17+ let instance = instance.trim_end_matches('/');
18+ let host = validate_url(instance, &policy(state))
19+ .map_err(|e| format!("instance address refused: {e}"))?
20+ .host_str()
21+ .unwrap_or_default()
22+ .to_ascii_lowercase();
23+ Ok((instance, host))
24+}
25+
11 /// A GitHub client under the outbound policy.26 /// A GitHub client under the outbound policy.
12 pub fn make_github(27 pub fn make_github(
13 state: &AppState,28 state: &AppState,
14 token: Option<String>,29 token: Option<String>,
15 notice: Notice,30 notice: Notice,
16 ) -> Result<GitHub, String> {31 ) -> Result<GitHub, String> {
17- let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")32+ let client = client(state)?;
18- .map_err(|e| format!("could not build the HTTP client: {e}"))?;
19 Ok(GitHub::new(Http::new(33 Ok(GitHub::new(Http::new(
20 client,34 client,
21 policy(state),35 policy(state),
@@ -33,14 +47,8 @@ pub fn make_gitlab(
33 token: Option<String>,47 token: Option<String>,
34 notice: Notice,48 notice: Notice,
35 ) -> Result<GitLab, String> {49 ) -> Result<GitLab, String> {
36- let instance = instance.trim_end_matches('/');50+ let (instance, host) = instance_host(state, instance)?;
37- let host = validate_url(instance, &policy(state))51+ let client = client(state)?;
38- .map_err(|e| format!("instance address refused: {e}"))?
39- .host_str()
40- .unwrap_or_default()
41- .to_ascii_lowercase();
42- let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")
43- .map_err(|e| format!("could not build the HTTP client: {e}"))?;
44 Ok(GitLab::new(52 Ok(GitLab::new(
45 Http::new(client, policy(state), token, Auth::GitLab, host, notice),53 Http::new(client, policy(state), token, Auth::GitLab, host, notice),
46 instance,54 instance,
@@ -54,14 +62,8 @@ pub fn make_forgejo(
54 token: Option<String>,62 token: Option<String>,
55 notice: Notice,63 notice: Notice,
56 ) -> Result<Forgejo, String> {64 ) -> Result<Forgejo, String> {
57- let instance = instance.trim_end_matches('/');65+ let (instance, host) = instance_host(state, instance)?;
58- let host = validate_url(instance, &policy(state))66+ let client = client(state)?;
59- .map_err(|e| format!("instance address refused: {e}"))?
60- .host_str()
61- .unwrap_or_default()
62- .to_ascii_lowercase();
63- let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")
64- .map_err(|e| format!("could not build the HTTP client: {e}"))?;
65 Ok(Forgejo::new(67 Ok(Forgejo::new(
66 Http::new(client, policy(state), token, Auth::Forgejo, host, notice),68 Http::new(client, policy(state), token, Auth::Forgejo, host, notice),
67 instance,69 instance,
crates/forge-web-app/src/internal.rsmodified+9 -33
@@ -161,14 +161,11 @@ async fn hook_endpoint(
161 Stage::PreReceive => match evaluate_pre_receive(&state.store, &state.git, &req).await {161 Stage::PreReceive => match evaluate_pre_receive(&state.store, &state.git, &req).await {
162 Ok(verdict) => verdict,162 Ok(verdict) => verdict,
163 Err(e) => {163 Err(e) => {
164- // Fail closed: an internal error rejects the push.
165 tracing::error!(error = %e, repo_id = %req.repo_id, "pre-receive check failed");164 tracing::error!(error = %e, repo_id = %req.repo_id, "pre-receive check failed");
166 HookResponse::deny("internal error while checking the push")165 HookResponse::deny("internal error while checking the push")
167 }166 }
168 },167 },
169 Stage::PostReceive if req.wiki => {168 Stage::PostReceive if req.wiki => {
170- // A wiki push changes neither the code repo's refs nor its CI, pull requests or events.
171- // It still goes to the standby.
172 record_wiki_push(&state.store, &req).await;169 record_wiki_push(&state.store, &req).await;
173 crate::live::bump_wiki(state, &req.repo_id);170 crate::live::bump_wiki(state, &req.repo_id);
174 crate::replication::enqueue_repo(state, &req.repo_id);171 crate::replication::enqueue_repo(state, &req.repo_id);
@@ -431,7 +428,6 @@ async fn record_events(store: &Store, req: &HookRequest) -> HookResponse {
431 ));428 ));
432 }429 }
433 }430 }
434- // post-receive cannot reject a push, so the verdict is always allow.
435 HookResponse {431 HookResponse {
436 allow: true,432 allow: true,
437 message: failures.join("\n"),433 message: failures.join("\n"),
@@ -599,7 +595,7 @@ async fn record_wiki_push(store: &Store, req: &HookRequest) {
599 595
600 /// Decides whether a push may proceed. `Ok(deny)` is a policy decision; `Err` is an596 /// Decides whether a push may proceed. `Ok(deny)` is a policy decision; `Err` is an
601 /// internal failure (the caller turns it into a deny).597 /// internal failure (the caller turns it into a deny).
602-pub async fn evaluate_pre_receive(598+async fn evaluate_pre_receive(
603 store: &Store,599 store: &Store,
604 git: &GitEnv,600 git: &GitEnv,
605 req: &HookRequest,601 req: &HookRequest,
@@ -615,8 +611,6 @@ pub async fn evaluate_pre_receive(
615 return Ok(HookResponse::deny("the wiki is disabled"));611 return Ok(HookResponse::deny("the wiki is disabled"));
616 }612 }
617 } else if store.pull_mirror(&repo.id).await?.is_some() {613 } else if store.pull_mirror(&repo.id).await?.is_some() {
618- // A pull mirror's refs come from its remote; a push here would be overwritten by the next sync.
619- // Mirrors do not mirror wikis, so wiki pushes are not refused for this.
620 return Ok(HookResponse::deny("this repository is a pull mirror"));614 return Ok(HookResponse::deny("this repository is a pull mirror"));
621 }615 }
622 let repo_dir = if req.wiki {616 let repo_dir = if req.wiki {
@@ -624,8 +618,6 @@ pub async fn evaluate_pre_receive(
624 } else {618 } else {
625 forge_git::repo::repo_path(&git.data_dir, &repo.id)?619 forge_git::repo::repo_path(&git.data_dir, &repo.id)?
626 };620 };
627- // Loaded once per push; every branch update below is checked against the same rules. Wiki
628- // pushes skip the rules: the wiki has no protected branches, only its main branch.
629 let rules = if req.wiki {621 let rules = if req.wiki {
630 Vec::new()622 Vec::new()
631 } else {623 } else {
@@ -639,7 +631,7 @@ pub async fn evaluate_pre_receive(
639 update.ref_name631 update.ref_name
640 )));632 )));
641 }633 }
642- if !is_valid_oid(&update.old) || !is_valid_oid(&update.new) {634+ if !is_git_oid(&update.old) || !is_git_oid(&update.new) {
643 return Ok(HookResponse::deny(format!(635 return Ok(HookResponse::deny(format!(
644 "invalid object id in update to {:?}",636 "invalid object id in update to {:?}",
645 update.ref_name637 update.ref_name
@@ -758,7 +750,7 @@ pub fn is_zero_oid(oid: &str) -> bool {
758 }750 }
759 751
760 /// True for a SHA-1 or SHA-256 object id: 40 or 64 hex digits.752 /// True for a SHA-1 or SHA-256 object id: 40 or 64 hex digits.
761-pub fn is_valid_oid(oid: &str) -> bool {753+pub fn is_git_oid(oid: &str) -> bool {
762 matches!(oid.len(), 40 | 64) && oid.bytes().all(|b| b.is_ascii_hexdigit())754 matches!(oid.len(), 40 | 64) && oid.bytes().all(|b| b.is_ascii_hexdigit())
763 }755 }
764 756
@@ -771,7 +763,6 @@ mod tests {
771 763
772 #[test]764 #[test]
773 fn ref_name_validity_cases() {765 fn ref_name_validity_cases() {
774- // (ref name, expected validity): must live under refs/, no dotdot or leading dash, no control chars.
775 let cases: [(&str, bool); 12] = [766 let cases: [(&str, bool); 12] = [
776 ("refs/heads/main", true),767 ("refs/heads/main", true),
777 ("refs/tags/v1.0", true),768 ("refs/tags/v1.0", true),
@@ -802,24 +793,21 @@ mod tests {
802 793
803 #[test]794 #[test]
804 fn oid_validation() {795 fn oid_validation() {
805- assert!(is_valid_oid(&"a".repeat(40)));796+ assert!(is_git_oid(&"a".repeat(40)));
806- assert!(is_valid_oid(&"F".repeat(64)));797+ assert!(is_git_oid(&"F".repeat(64)));
807- assert!(is_valid_oid(&"0".repeat(40)));798+ assert!(is_git_oid(&"0".repeat(40)));
808- assert!(!is_valid_oid(&"g".repeat(40)));799+ assert!(!is_git_oid(&"g".repeat(40)));
809- assert!(!is_valid_oid(&"a".repeat(41)));800+ assert!(!is_git_oid(&"a".repeat(41)));
810- assert!(!is_valid_oid("--all"));801+ assert!(!is_git_oid("--all"));
811 }802 }
812 803
813 #[test]804 #[test]
814 fn maintenance_claims_coalesce_per_repo() {805 fn maintenance_claims_coalesce_per_repo() {
815 let mut map = HashMap::new();806 let mut map = HashMap::new();
816- // First push starts a worker; pushes during the run only flag a rerun.
817 assert!(claim_maintenance(&mut map, "r1"));807 assert!(claim_maintenance(&mut map, "r1"));
818 assert!(!claim_maintenance(&mut map, "r1"));808 assert!(!claim_maintenance(&mut map, "r1"));
819 assert!(!claim_maintenance(&mut map, "r1"));809 assert!(!claim_maintenance(&mut map, "r1"));
820- // Other repos are independent.
821 assert!(claim_maintenance(&mut map, "r2"));810 assert!(claim_maintenance(&mut map, "r2"));
822- // One rerun is due after the first run, then the repo is released.
823 assert!(finish_maintenance(&mut map, "r1"));811 assert!(finish_maintenance(&mut map, "r1"));
824 assert!(!finish_maintenance(&mut map, "r1"));812 assert!(!finish_maintenance(&mut map, "r1"));
825 assert!(!map.contains_key("r1"));813 assert!(!map.contains_key("r1"));
@@ -874,7 +862,6 @@ mod tests {
874 assert_eq!(res.status(), 403, "{path} with token {token:?}");862 assert_eq!(res.status(), 403, "{path} with token {token:?}");
875 }863 }
876 }864 }
877- // The right token gets through: an fsck of an instance with no repos is clean.
878 let req = topcoat::router::request::Request::builder()865 let req = topcoat::router::request::Request::builder()
879 .method("POST")866 .method("POST")
880 .uri("/internal/admin/fsck")867 .uri("/internal/admin/fsck")
@@ -919,7 +906,6 @@ mod tests {
919 906
920 #[tokio::test]907 #[tokio::test]
921 async fn hook_routes_are_not_collected_by_discover() {908 async fn hook_routes_are_not_collected_by_discover() {
922- // The public router uses `.discover()`. Hook routes are plain RouteFns and must not be in it.
923 let public = Router::builder().discover().build();909 let public = Router::builder().discover().build();
924 for path in ["/hook/pre-receive", "/hook/post-receive"] {910 for path in ["/hook/pre-receive", "/hook/post-receive"] {
925 let req = topcoat::router::request::Request::builder()911 let req = topcoat::router::request::Request::builder()
@@ -1013,7 +999,6 @@ mod tests {
1013 quarantine_env: BTreeMap::new(),999 quarantine_env: BTreeMap::new(),
1014 };1000 };
1015 1001
1016- // A Write collaborator's direct fast-forward is refused.
1017 let refused = evaluate_pre_receive(&store, &git_env, &request(&writer.id, &first, &second))1002 let refused = evaluate_pre_receive(&store, &git_env, &request(&writer.id, &first, &second))
1018 .await1003 .await
1019 .expect("evaluate");1004 .expect("evaluate");
@@ -1022,7 +1007,6 @@ mod tests {
1022 refused.message,1007 refused.message,
1023 "branch 'main' only accepts changes through pull requests"1008 "branch 'main' only accepts changes through pull requests"
1024 );1009 );
1025- // So is creating the branch.
1026 let created = evaluate_pre_receive(1010 let created = evaluate_pre_receive(
1027 &store,1011 &store,
1028 &git_env,1012 &git_env,
@@ -1032,7 +1016,6 @@ mod tests {
1032 .expect("evaluate");1016 .expect("evaluate");
1033 assert!(!created.allow);1017 assert!(!created.allow);
1034 1018
1035- // Repo admins (Admin collaborators and the owner) may still push.
1036 for actor in [&admin.id, &owner.id] {1019 for actor in [&admin.id, &owner.id] {
1037 let ok = evaluate_pre_receive(&store, &git_env, &request(actor, &first, &second))1020 let ok = evaluate_pre_receive(&store, &git_env, &request(actor, &first, &second))
1038 .await1021 .await
@@ -1081,7 +1064,6 @@ mod tests {
1081 }],1064 }],
1082 quarantine_env: BTreeMap::new(),1065 quarantine_env: BTreeMap::new(),
1083 };1066 };
1084- // Before the pull mirror exists, the push is not refused for that reason.
1085 let before = evaluate_pre_receive(&store, &git_env, &request)1067 let before = evaluate_pre_receive(&store, &git_env, &request)
1086 .await1068 .await
1087 .expect("evaluate");1069 .expect("evaluate");
@@ -1130,14 +1112,12 @@ mod tests {
1130 data_dir: tmp.path().to_path_buf(),1112 data_dir: tmp.path().to_path_buf(),
1131 };1113 };
1132 1114
1133- // Bare repo at the path forge would use for this repo id.
1134 let bare = forge_git::repo::repo_path(&git_env.data_dir, &repo.id).expect("repo path");1115 let bare = forge_git::repo::repo_path(&git_env.data_dir, &repo.id).expect("repo path");
1135 forge_git::repo::init_bare(&git_env, &bare, "main")1116 forge_git::repo::init_bare(&git_env, &bare, "main")
1136 .await1117 .await
1137 .expect("init bare");1118 .expect("init bare");
1138 let bare_str = bare.to_str().expect("utf8 path");1119 let bare_str = bare.to_str().expect("utf8 path");
1139 1120
1140- // Two commits on main, then a divergent commit on a side branch.
1141 let work = tmp.path().join("work");1121 let work = tmp.path().join("work");
1142 git(tmp.path(), &["init", "-b", "main", "work"]);1122 git(tmp.path(), &["init", "-b", "main", "work"]);
1143 let first = commit(&work, "one");1123 let first = commit(&work, "one");
@@ -1164,13 +1144,11 @@ mod tests {
1164 quarantine_env: BTreeMap::new(),1144 quarantine_env: BTreeMap::new(),
1165 };1145 };
1166 1146
1167- // Fast-forward: allowed.
1168 let ff = evaluate_pre_receive(&store, &git_env, &request(&first, &second))1147 let ff = evaluate_pre_receive(&store, &git_env, &request(&first, &second))
1169 .await1148 .await
1170 .expect("evaluate");1149 .expect("evaluate");
1171 assert_eq!(ff, HookResponse::allow());1150 assert_eq!(ff, HookResponse::allow());
1172 1151
1173- // Non-fast-forward: denied.
1174 let forced = evaluate_pre_receive(&store, &git_env, &request(&second, &divergent))1152 let forced = evaluate_pre_receive(&store, &git_env, &request(&second, &divergent))
1175 .await1153 .await
1176 .expect("evaluate");1154 .expect("evaluate");
@@ -1180,7 +1158,6 @@ mod tests {
1180 "force-push to protected branch 'main' is not allowed"1158 "force-push to protected branch 'main' is not allowed"
1181 );1159 );
1182 1160
1183- // Deleting the default branch: denied.
1184 let deleted = evaluate_pre_receive(&store, &git_env, &request(&second, &"0".repeat(40)))1161 let deleted = evaluate_pre_receive(&store, &git_env, &request(&second, &"0".repeat(40)))
1185 .await1162 .await
1186 .expect("evaluate");1163 .expect("evaluate");
@@ -1190,7 +1167,6 @@ mod tests {
1190 "deleting protected branch 'main' is not allowed"1167 "deleting protected branch 'main' is not allowed"
1191 );1168 );
1192 1169
1193- // A rule that allows force pushes lifts only that check; deletion stays denied.
1194 store1170 store
1195 .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(true, false))1171 .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(true, false))
1196 .await1172 .await
crates/forge-web-app/src/layers.rsmodified+23 -29
@@ -1,5 +1,9 @@
1 use std::fmt;1 use std::fmt;
2 2
3+use topcoat::context::Cx;
4+use topcoat::router::request::{method, uri};
5+use topcoat::router::Method;
6+
3 use crate::live::Topic;7 use crate::live::Topic;
4 use crate::state::AppState;8 use crate::state::AppState;
5 9
@@ -69,6 +73,13 @@ pub async fn bump_pending_reviewers(state: &AppState, issue_id: &str) {
69 }73 }
70 }74 }
71 75
76+fn post_segments(cx: &Cx) -> Option<Vec<&str>> {
77+ if *method(cx) != Method::POST {
78+ return None;
79+ }
80+ Some(uri(cx).path().trim_start_matches('/').split('/').collect())
81+}
82+
72 mod settings_write {83 mod settings_write {
73 use topcoat::Result;84 use topcoat::Result;
74 use topcoat::context::{Cx, context};85 use topcoat::context::{Cx, context};
@@ -201,11 +212,10 @@ mod repo_moved {
201 212
202 mod pull_write {213 mod pull_write {
203 use topcoat::context::{Cx, context};214 use topcoat::context::{Cx, context};
204- use topcoat::router::request::{method, uri};
205 use topcoat::router::response::Response;215 use topcoat::router::response::Response;
206- use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path};216+ use topcoat::router::{Body, Layer, LayerFuture, Next, Path};
207 217
208- use super::bump_pending_reviewers;218+ use super::{bump_pending_reviewers, post_segments};
209 use crate::live::{bump_list, bump_pull, bump_repo_pulls};219 use crate::live::{bump_list, bump_pull, bump_repo_pulls};
210 use crate::state::AppState;220 use crate::state::AppState;
211 221
@@ -225,11 +235,7 @@ mod pull_write {
225 235
226 /// The write a request makes to the pull side, when it is a POST that can change one.236 /// The write a request makes to the pull side, when it is a POST that can change one.
227 fn written(cx: &Cx) -> Option<Written> {237 fn written(cx: &Cx) -> Option<Written> {
228- if *method(cx) != Method::POST {238+ let parts = post_segments(cx)?;
229- return None;
230- }
231- let path = uri(cx).path().to_owned();
232- let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
233 let [owner, repo, kind, rest @ ..] = parts.as_slice() else {239 let [owner, repo, kind, rest @ ..] = parts.as_slice() else {
234 return None;240 return None;
235 };241 };
@@ -310,10 +316,10 @@ mod pull_write {
310 316
311 mod discussion_write {317 mod discussion_write {
312 use topcoat::context::{Cx, context};318 use topcoat::context::{Cx, context};
313- use topcoat::router::request::{method, uri};
314 use topcoat::router::response::Response;319 use topcoat::router::response::Response;
315- use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path};320+ use topcoat::router::{Body, Layer, LayerFuture, Next, Path};
316 321
322+ use super::post_segments;
317 use crate::live::Topic;323 use crate::live::Topic;
318 use crate::state::AppState;324 use crate::state::AppState;
319 325
@@ -331,11 +337,7 @@ mod discussion_write {
331 337
332 /// The write a request makes to the discussion side, when it is a POST that can change one.338 /// The write a request makes to the discussion side, when it is a POST that can change one.
333 fn written(cx: &Cx) -> Option<Written> {339 fn written(cx: &Cx) -> Option<Written> {
334- if *method(cx) != Method::POST {340+ let parts = post_segments(cx)?;
335- return None;
336- }
337- let path = uri(cx).path().to_owned();
338- let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
339 let [owner, repo, kind, rest @ ..] = parts.as_slice() else {341 let [owner, repo, kind, rest @ ..] = parts.as_slice() else {
340 return None;342 return None;
341 };343 };
@@ -416,20 +418,16 @@ mod discussion_write {
416 418
417 mod org_write {419 mod org_write {
418 use topcoat::context::{Cx, context};420 use topcoat::context::{Cx, context};
419- use topcoat::router::request::{method, uri};
420 use topcoat::router::response::Response;421 use topcoat::router::response::Response;
421- use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path};422+ use topcoat::router::{Body, Layer, LayerFuture, Next, Path};
422 423
424+ use super::post_segments;
423 use crate::live::Topic;425 use crate::live::Topic;
424 use crate::state::AppState;426 use crate::state::AppState;
425 427
426 /// The org a POST under `/org/{org}/{members|teams|settings}` writes to, by its name.428 /// The org a POST under `/org/{org}/{members|teams|settings}` writes to, by its name.
427 fn written_org(cx: &Cx) -> Option<String> {429 fn written_org(cx: &Cx) -> Option<String> {
428- if *method(cx) != Method::POST {430+ let parts = post_segments(cx)?;
429- return None;
430- }
431- let path = uri(cx).path().to_owned();
432- let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
433 let ["org", name, kind, ..] = parts.as_slice() else {431 let ["org", name, kind, ..] = parts.as_slice() else {
434 return None;432 return None;
435 };433 };
@@ -478,10 +476,10 @@ mod org_write {
478 mod repo_settings_write {476 mod repo_settings_write {
479 use topcoat::Result;477 use topcoat::Result;
480 use topcoat::context::{Cx, context};478 use topcoat::context::{Cx, context};
481- use topcoat::router::request::{method, uri};
482 use topcoat::router::response::Response;479 use topcoat::router::response::Response;
483- use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path};480+ use topcoat::router::{Body, Layer, LayerFuture, Next, Path};
484 481
482+ use super::post_segments;
485 use crate::live::{Topic, bump_repo_pulls, bump_settings};483 use crate::live::{Topic, bump_repo_pulls, bump_settings};
486 use crate::state::AppState;484 use crate::state::AppState;
487 485
@@ -501,11 +499,7 @@ mod repo_settings_write {
501 499
502 /// The `(owner, name)` of a POST under `/{o}/{r}/settings/...` or `/{o}/{r}/security/...`.500 /// The `(owner, name)` of a POST under `/{o}/{r}/settings/...` or `/{o}/{r}/security/...`.
503 fn written(cx: &Cx) -> Option<(String, String)> {501 fn written(cx: &Cx) -> Option<(String, String)> {
504- if *method(cx) != Method::POST {502+ let parts = post_segments(cx)?;
505- return None;
506- }
507- let path = uri(cx).path().to_owned();
508- let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
509 match parts.as_slice() {503 match parts.as_slice() {
510 [owner, name, "settings" | "security", ..] => {504 [owner, name, "settings" | "security", ..] => {
511 Some(((*owner).to_owned(), (*name).to_owned()))505 Some(((*owner).to_owned(), (*name).to_owned()))
crates/forge-web-app/src/lfs/gc.rsmodified+17 -5
@@ -9,7 +9,7 @@ use std::time::{Duration, SystemTime};
9 use forge_core::Store;9 use forge_core::Store;
10 use serde::{Deserialize, Serialize};10 use serde::{Deserialize, Serialize};
11 11
12-use super::{is_valid_oid, lfs_root, tmp_dir};12+use super::{is_sha256_hex, lfs_root, tmp_dir};
13 13
14 /// The age an unlinked file must reach before it is deleted.14 /// The age an unlinked file must reach before it is deleted.
15 pub const GC_MIN_AGE: Duration = Duration::from_secs(24 * 60 * 60);15 pub const GC_MIN_AGE: Duration = Duration::from_secs(24 * 60 * 60);
@@ -68,7 +68,11 @@ pub async fn gc(
68 }68 }
69 // Look again just before deleting: an upload may have renamed the file into place and69 // Look again just before deleting: an upload may have renamed the file into place and
70 // linked it since the listing was taken.70 // linked it since the listing was taken.
71- let fresh = tokio::fs::metadata(&candidate.path).await?;71+ let fresh = match tokio::fs::metadata(&candidate.path).await {
72+ Ok(fresh) => fresh,
73+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
74+ Err(e) => return Err(e.into()),
75+ };
72 if !is_older_than(fresh.modified()?, now, min_age)76 if !is_older_than(fresh.modified()?, now, min_age)
73 || store.lfs_oid_is_linked(&candidate.oid).await?77 || store.lfs_oid_is_linked(&candidate.oid).await?
74 {78 {
@@ -105,7 +109,11 @@ fn list_files(dir: &Path) -> forge_core::Result<Vec<(PathBuf, SystemTime)>> {
105 };109 };
106 for entry in entries {110 for entry in entries {
107 let entry = entry?;111 let entry = entry?;
108- let meta = entry.metadata()?;112+ let meta = match entry.metadata() {
113+ Ok(meta) => meta,
114+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
115+ Err(e) => return Err(e.into()),
116+ };
109 if meta.is_file() {117 if meta.is_file() {
110 found.push((entry.path(), meta.modified()?));118 found.push((entry.path(), meta.modified()?));
111 }119 }
@@ -132,12 +140,16 @@ fn collect_objects(root: &Path) -> forge_core::Result<Vec<Candidate>> {
132 };140 };
133 for file in std::fs::read_dir(b.path())? {141 for file in std::fs::read_dir(b.path())? {
134 let file = file?;142 let file = file?;
135- let meta = file.metadata()?;143+ let meta = match file.metadata() {
144+ Ok(meta) => meta,
145+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
146+ Err(e) => return Err(e.into()),
147+ };
136 let Some(oid) = file.file_name().to_str().map(str::to_owned) else {148 let Some(oid) = file.file_name().to_str().map(str::to_owned) else {
137 continue;149 continue;
138 };150 };
139 if !meta.is_file()151 if !meta.is_file()
140- || !is_valid_oid(&oid)152+ || !is_sha256_hex(&oid)
141 || !oid.starts_with(&format!("{a_name}{b_name}"))153 || !oid.starts_with(&format!("{a_name}{b_name}"))
142 {154 {
143 continue;155 continue;
crates/forge-web-app/src/lfs/mod.rsmodified+8 -8
@@ -17,7 +17,7 @@ use forge_core::Result;
17 use crate::state::AppState;17 use crate::state::AppState;
18 18
19 /// True for a 64-character lowercase hex SHA-256.19 /// True for a 64-character lowercase hex SHA-256.
20-pub fn is_valid_oid(oid: &str) -> bool {20+pub fn is_sha256_hex(oid: &str) -> bool {
21 oid.len() == 6421 oid.len() == 64
22 && oid22 && oid
23 .bytes()23 .bytes()
@@ -34,7 +34,7 @@ pub fn tmp_dir(data_dir: &Path) -> PathBuf {
34 lfs_root(data_dir).join("tmp")34 lfs_root(data_dir).join("tmp")
35 }35 }
36 36
37-/// The on-disk path of object `oid`. Callers pass a validated oid (see [`is_valid_oid`]); for any37+/// The on-disk path of object `oid`. Callers pass a validated oid (see [`is_sha256_hex`]); for any
38 /// other input the path is still inside the store, just not in a fan-out directory.38 /// other input the path is still inside the store, just not in a fan-out directory.
39 pub fn object_path(data_dir: &Path, oid: &str) -> PathBuf {39 pub fn object_path(data_dir: &Path, oid: &str) -> PathBuf {
40 match (oid.get(0..2), oid.get(2..4)) {40 match (oid.get(0..2), oid.get(2..4)) {
@@ -56,12 +56,12 @@ mod tests {
56 #[test]56 #[test]
57 fn oid_must_be_64_lowercase_hex() {57 fn oid_must_be_64_lowercase_hex() {
58 let good = "4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393";58 let good = "4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393";
59- assert!(is_valid_oid(good));59+ assert!(is_sha256_hex(good));
60- assert!(!is_valid_oid(&good[..63]));60+ assert!(!is_sha256_hex(&good[..63]));
61- assert!(!is_valid_oid(&format!("{good}0")));61+ assert!(!is_sha256_hex(&format!("{good}0")));
62- assert!(!is_valid_oid(&good.to_uppercase()));62+ assert!(!is_sha256_hex(&good.to_uppercase()));
63- assert!(!is_valid_oid(&format!("{}g", &good[..63])));63+ assert!(!is_sha256_hex(&format!("{}g", &good[..63])));
64- assert!(!is_valid_oid(""));64+ assert!(!is_sha256_hex(""));
65 }65 }
66 66
67 #[test]67 #[test]
crates/forge-web-app/src/lfs/routes.rsmodified+6 -12
@@ -8,10 +8,10 @@
8 use std::net::IpAddr;8 use std::net::IpAddr;
9 use std::path::Path;9 use std::path::Path;
10 use std::sync::atomic::{AtomicU64, Ordering};10 use std::sync::atomic::{AtomicU64, Ordering};
11-use std::time::{SystemTime, UNIX_EPOCH};
12 11
13 use forge_core::Action;12 use forge_core::Action;
14 use forge_core::lfs_token::{self, LfsOp};13 use forge_core::lfs_token::{self, LfsOp};
14+use forge_core::time::now_unix;
15 use futures_util::{StreamExt, TryStreamExt};15 use futures_util::{StreamExt, TryStreamExt};
16 use http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue};16 use http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue};
17 use http_body::Frame;17 use http_body::Frame;
@@ -26,7 +26,7 @@ use topcoat::router::request::headers;
26 use topcoat::router::response::Response;26 use topcoat::router::response::Response;
27 use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route, to_bytes};27 use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route, to_bytes};
28 28
29-use super::{is_valid_oid, object_path, tmp_dir};29+use super::{is_sha256_hex, object_path, tmp_dir};
30 use crate::access::{AccessError, find_repo, resolve_repo_for};30 use crate::access::{AccessError, find_repo, resolve_repo_for};
31 use crate::client_ip::client_ip;31 use crate::client_ip::client_ip;
32 use crate::git_http::{access_error, authenticate};32 use crate::git_http::{access_error, authenticate};
@@ -86,7 +86,7 @@ async fn batch(cx: &Cx, body: Body) -> topcoat::Result<Response> {
86 };86 };
87 let max = state.live().lfs.max_object_bytes();87 let max = state.live().lfs.max_object_bytes();
88 for object in &request.objects {88 for object in &request.objects {
89- if !is_valid_oid(&object.oid) {89+ if !is_sha256_hex(&object.oid) {
90 return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid"));90 return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid"));
91 }91 }
92 if object.size > max {92 if object.size > max {
@@ -199,7 +199,7 @@ async fn get_object(cx: &Cx) -> topcoat::Result<Response> {
199 let owner = owner(cx);199 let owner = owner(cx);
200 let name = repo(cx);200 let name = repo(cx);
201 let oid = oid(cx);201 let oid = oid(cx);
202- if !is_valid_oid(oid) {202+ if !is_sha256_hex(oid) {
203 return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid"));203 return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid"));
204 }204 }
205 205
@@ -239,7 +239,7 @@ async fn put_object(cx: &Cx, body: Body) -> topcoat::Result<Response> {
239 let owner = owner(cx);239 let owner = owner(cx);
240 let name = repo(cx);240 let name = repo(cx);
241 let oid = oid(cx);241 let oid = oid(cx);
242- if !is_valid_oid(oid) {242+ if !is_sha256_hex(oid) {
243 return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid"));243 return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid"));
244 }244 }
245 245
@@ -298,7 +298,7 @@ async fn verify(cx: &Cx, body: Body) -> topcoat::Result<Response> {
298 ));298 ));
299 }299 }
300 };300 };
301- if !is_valid_oid(&request.oid) {301+ if !is_sha256_hex(&request.oid) {
302 return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid"));302 return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid"));
303 }303 }
304 Ok(304 Ok(
@@ -504,9 +504,3 @@ fn lfs_json(status: StatusCode, value: Value) -> Response {
504 fn message(status: StatusCode, text: impl Into<String>) -> Response {504 fn message(status: StatusCode, text: impl Into<String>) -> Response {
505 lfs_json(status, json!({ "message": text.into() }))505 lfs_json(status, json!({ "message": text.into() }))
506 }506 }
507-
508-fn now_unix() -> i64 {
509- SystemTime::now()
510- .duration_since(UNIX_EPOCH)
511- .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
512-}
crates/forge-web-app/src/lfs_pointer.rsmodified+3 -3
@@ -9,10 +9,10 @@
9 //!9 //!
10 //! Extra `key value` lines are allowed. The parser is pure and accepts nothing else.10 //! Extra `key value` lines are allowed. The parser is pure and accepts nothing else.
11 11
12-use crate::lfs::is_valid_oid;12+use crate::lfs::is_sha256_hex;
13 13
14 /// Pointer files are about 130 bytes. Anything larger is never treated as a pointer.14 /// Pointer files are about 130 bytes. Anything larger is never treated as a pointer.
15-pub const MAX_POINTER_BYTES: usize = 1024;15+const MAX_POINTER_BYTES: usize = 1024;
16 16
17 const VERSION_LINE: &str = "version https://git-lfs.github.com/spec/v1";17 const VERSION_LINE: &str = "version https://git-lfs.github.com/spec/v1";
18 18
@@ -42,7 +42,7 @@ pub fn parse(data: &[u8]) -> Option<Pointer> {
42 match key {42 match key {
43 "oid" => {43 "oid" => {
44 let hex = value.strip_prefix("sha256:")?;44 let hex = value.strip_prefix("sha256:")?;
45- if oid.is_some() || !is_valid_oid(hex) {45+ if oid.is_some() || !is_sha256_hex(hex) {
46 return None;46 return None;
47 }47 }
48 oid = Some(hex.to_owned());48 oid = Some(hex.to_owned());
crates/forge-web-app/src/live.rsmodified+7 -10
@@ -277,9 +277,8 @@ where
277 events_response(cx, events)277 events_response(cx, events)
278 }278 }
279 279
280-/// The events of [`stream_changes_with`] as a stream, each named `name`, for a caller that merges280+/// The events of [`stream_changes_with`] as a stream, each named `name`.
281-/// several streams into one response (see `pages::shell_events`).281+async fn named_changes<F, Fut>(
282-pub async fn named_changes<F, Fut>(
283 hub: &LiveHub,282 hub: &LiveHub,
284 topics: Vec<Topic>,283 topics: Vec<Topic>,
285 extra: Vec<watch::Receiver<u64>>,284 extra: Vec<watch::Receiver<u64>>,
@@ -479,14 +478,12 @@ impl StreamSlot {
479 let ip = crate::client_ip::client_ip(cx);478 let ip = crate::client_ip::client_ip(cx);
480 let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner());479 let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner());
481 let (total, per_client) = &mut *open;480 let (total, per_client) = &mut *open;
482- let count = per_client481+ let map = per_client.get_or_insert_with(HashMap::new);
483- .get_or_insert_with(HashMap::new)482+ let count = map.get(&ip).copied().unwrap_or(0);
484- .entry(ip)483+ if *total >= MAX_STREAMS || count >= MAX_STREAMS_PER_CLIENT {
485- .or_insert(0);
486- if *total >= MAX_STREAMS || *count >= MAX_STREAMS_PER_CLIENT {
487 return None;484 return None;
488 }485 }
489- *count += 1;486+ *map.entry(ip).or_insert(0) += 1;
490 *total += 1;487 *total += 1;
491 Some(StreamSlot { ip: Some(ip) })488 Some(StreamSlot { ip: Some(ip) })
492 }489 }
@@ -513,7 +510,7 @@ impl Drop for StreamSlot {
513 510
514 /// How long the browser waits before it reconnects a dropped event stream. The browser's default is511 /// How long the browser waits before it reconnects a dropped event stream. The browser's default is
515 /// a few seconds; one second makes a page come back as soon as a server restart is done.512 /// a few seconds; one second makes a page come back as soon as a server restart is done.
516-pub const STREAM_RETRY: Duration = Duration::from_secs(1);513+const STREAM_RETRY: Duration = Duration::from_secs(1);
517 514
518 /// The response of an event stream: keep-alive comments while idle, no buffering by a reverse515 /// The response of an event stream: keep-alive comments while idle, no buffering by a reverse
519 /// proxy, and a `retry` field first so every stream reconnects after `STREAM_RETRY`.516 /// proxy, and a `retry` field first so every stream reconnects after `STREAM_RETRY`.
crates/forge-web-app/src/mail/smtp.rsmodified+5 -2
@@ -31,8 +31,11 @@ impl SmtpMailer {
31 .mail_settings()31 .mail_settings()
32 .await32 .await
33 .map_err(|e| MailError::Transient(format!("cannot read the mail settings: {e}")))?;33 .map_err(|e| MailError::Transient(format!("cannot read the mail settings: {e}")))?;
34- let password = self.store.mail_password().await.map_err(|e| {34+ let password = self.store.mail_password().await.map_err(|e| match e {
35- MailError::Permanent(format!("cannot open the stored SMTP password: {e}"))35+ forge_core::Error::Database(_) => {
36+ MailError::Transient(format!("cannot read the stored SMTP password: {e}"))
37+ }
38+ _ => MailError::Permanent(format!("cannot open the stored SMTP password: {e}")),
36 })?;39 })?;
37 let message = build_message(&settings, mail)?;40 let message = build_message(&settings, mail)?;
38 let transport = build_transport(&settings, password.as_ref().map(|p| p.expose()))?;41 let transport = build_transport(&settings, password.as_ref().map(|p| p.expose()))?;
crates/forge-web-app/src/mail/worker.rsmodified+2 -31
@@ -7,17 +7,14 @@
7 use std::time::Duration;7 use std::time::Duration;
8 8
9 use forge_core::mail::{MailError, OutboxEntry, OutgoingMail, retry_delay};9 use forge_core::mail::{MailError, OutboxEntry, OutgoingMail, retry_delay};
10-use forge_core::time::{now_stamp, stamp_after};10+use forge_core::time::{now_stamp, sleep_until, stamp_after};
11 use time::OffsetDateTime;11 use time::OffsetDateTime;
12-use time::format_description::well_known::Rfc3339;
13 12
14 use crate::mail::live;13 use crate::mail::live;
15 use crate::state::AppState;14 use crate::state::AppState;
16 15
17 /// The longest the worker sleeps. It guards against a missed wake, not polling.16 /// The longest the worker sleeps. It guards against a missed wake, not polling.
18 const BACKSTOP: Duration = Duration::from_secs(15 * 60);17 const BACKSTOP: Duration = Duration::from_secs(15 * 60);
19-/// The shortest sleep, so a due time that has already passed does not spin the loop.
20-const MIN_SLEEP: Duration = Duration::from_secs(1);
21 /// Messages leased per pass.18 /// Messages leased per pass.
22 const BATCH: u32 = 20;19 const BATCH: u32 = 20;
23 /// How long a leased row stays with this pass before another may take it.20 /// How long a leased row stays with this pass before another may take it.
@@ -77,7 +74,7 @@ async fn tick(state: &AppState) -> forge_core::Result<Duration> {
77 deliver(state, &entry).await;74 deliver(state, &entry).await;
78 }75 }
79 let next = state.store.next_mail_due().await?;76 let next = state.store.next_mail_due().await?;
80- Ok(sleep_for(next.as_deref(), OffsetDateTime::now_utc()))77+ Ok(sleep_until(next.as_deref(), OffsetDateTime::now_utc(), BACKSTOP))
81 }78 }
82 79
83 /// Sends one leased message and records the outcome.80 /// Sends one leased message and records the outcome.
@@ -117,16 +114,6 @@ async fn deliver(state: &AppState, entry: &OutboxEntry) {
117 live::bump();114 live::bump();
118 }115 }
119 116
120-/// How long the worker sleeps: until `next_due` (an RFC 3339 stamp), clamped to
121-/// `MIN_SLEEP..=BACKSTOP`. `None` (nothing queued) or an unparsable stamp gives `BACKSTOP`.
122-pub fn sleep_for(next_due: Option<&str>, now: OffsetDateTime) -> Duration {
123- let Some(due) = next_due.and_then(|s| OffsetDateTime::parse(s, &Rfc3339).ok()) else {
124- return BACKSTOP;
125- };
126- let until = Duration::try_from(due - now).unwrap_or(Duration::ZERO);
127- until.clamp(MIN_SLEEP, BACKSTOP)
128-}
129-
130 #[cfg(test)]117 #[cfg(test)]
131 mod tests {118 mod tests {
132 use std::sync::Arc;119 use std::sync::Arc;
@@ -159,22 +146,6 @@ mod tests {
159 (state, fake)146 (state, fake)
160 }147 }
161 148
162- #[test]
163- fn sleep_stops_at_the_next_due_time_and_is_clamped() {
164- use time::macros::datetime;
165-
166- let now = datetime!(2026-10-15 12:00:00 UTC);
167- let stamp = |t: OffsetDateTime| t.format(&Rfc3339).expect("stamp");
168- assert_eq!(sleep_for(None, now), BACKSTOP);
169- let in_10s = stamp(now + time::Duration::seconds(10));
170- assert_eq!(sleep_for(Some(&in_10s), now), Duration::from_secs(10));
171- let in_1h = stamp(now + time::Duration::hours(1));
172- assert_eq!(sleep_for(Some(&in_1h), now), BACKSTOP);
173- let past = stamp(now - time::Duration::seconds(5));
174- assert_eq!(sleep_for(Some(&past), now), MIN_SLEEP);
175- assert_eq!(sleep_for(Some("soon"), now), BACKSTOP);
176- }
177-
178 #[tokio::test]149 #[tokio::test]
179 async fn a_row_leased_before_a_restart_is_sent_by_the_first_pass_after_boot() {150 async fn a_row_leased_before_a_restart_is_sent_by_the_first_pass_after_boot() {
180 let dir = tempfile::tempdir().expect("tempdir");151 let dir = tempfile::tempdir().expect("tempdir");
crates/forge-web-app/src/merge.rsmodified+24 -53
@@ -1,6 +1,3 @@
1-//! Merging a pull request: the merge gate, the merge itself and what follows it, shared by the
2-//! merge page, auto-merge and the merge queue.
3-
4 use forge_core::protection::{RuleFlags, effective};1 use forge_core::protection::{RuleFlags, effective};
5 use forge_core::store::commit_status::StatusState;2 use forge_core::store::commit_status::StatusState;
6 use forge_core::{MergeStyle, PullRequest, ReviewState, Role, User};3 use forge_core::{MergeStyle, PullRequest, ReviewState, Role, User};
@@ -19,11 +16,8 @@ use crate::state::AppState;
19 use crate::views::now_unix;16 use crate::views::now_unix;
20 use crate::webhooks::emit::{Sender, emit_item_action};17 use crate::webhooks::emit::{Sender, emit_item_action};
21 18
22-/// Commits listed in a squash message.
23 pub const MAX_SQUASH_COMMITS: usize = 250;19 pub const MAX_SQUASH_COMMITS: usize = 250;
24 20
25-/// Refusal codes, sent as `?merge_error=<code>` on the pull request page. The page owns the
26-/// wording for each code; a code outside this set is never echoed back.
27 pub const ERR_CONFLICT: &str = "conflict";21 pub const ERR_CONFLICT: &str = "conflict";
28 pub const ERR_UP_TO_DATE: &str = "up_to_date";22 pub const ERR_UP_TO_DATE: &str = "up_to_date";
29 pub const ERR_FF_IMPOSSIBLE: &str = "ff_impossible";23 pub const ERR_FF_IMPOSSIBLE: &str = "ff_impossible";
@@ -57,15 +51,12 @@ pub const HEAD_MISSING_MSG: &str =
57 "The head repository was deleted, so this pull request cannot be merged.";51 "The head repository was deleted, so this pull request cannot be merged.";
58 pub const BASE_MISSING_MSG: &str = "The base branch does not exist.";52 pub const BASE_MISSING_MSG: &str = "The base branch does not exist.";
59 53
60-/// What a merge attempt did: the base branch now points at `commit`, or the attempt was refused
61-/// with an HTTP status and a message for the viewer.
62 #[derive(Debug, PartialEq, Eq)]54 #[derive(Debug, PartialEq, Eq)]
63 pub enum MergeOutcome {55 pub enum MergeOutcome {
64 Merged { commit: String },56 Merged { commit: String },
65 Refused { status: StatusCode, message: String },57 Refused { status: StatusCode, message: String },
66 }58 }
67 59
68-/// The refusal code for a message `perform_merge` returns, if it has one.
69 pub fn refusal_code(message: &str) -> Option<&'static str> {60 pub fn refusal_code(message: &str) -> Option<&'static str> {
70 Some(match message {61 Some(match message {
71 CONFLICTS_MSG => ERR_CONFLICT,62 CONFLICTS_MSG => ERR_CONFLICT,
@@ -81,6 +72,18 @@ pub fn refusal_code(message: &str) -> Option<&'static str> {
81 })72 })
82 }73 }
83 74
75+pub struct MergeRefusal {
76+ pub status: StatusCode,
77+ pub message: String,
78+}
79+
80+fn refusal(message: &str) -> MergeRefusal {
81+ MergeRefusal {
82+ status: StatusCode::CONFLICT,
83+ message: message.to_owned(),
84+ }
85+}
86+
84 pub fn refused(status: StatusCode, message: &str) -> MergeOutcome {87 pub fn refused(status: StatusCode, message: &str) -> MergeOutcome {
85 MergeOutcome::Refused {88 MergeOutcome::Refused {
86 status,89 status,
@@ -88,31 +91,22 @@ pub fn refused(status: StatusCode, message: &str) -> MergeOutcome {
88 }91 }
89 }92 }
90 93
91-/// Whether `user` is a reviewer whose approvals and change requests count under merge rules:
92-/// the repo owner, an instance admin, or a collaborator with Write, Maintain or Admin.
93 pub fn counts_for_merge_rules(repo: &forge_core::Repo, user: &User, role: Option<Role>) -> bool {94 pub fn counts_for_merge_rules(repo: &forge_core::Repo, user: &User, role: Option<Role>) -> bool {
94 user.is_admin95 user.is_admin
95 || user.id == repo.owner_id96 || user.id == repo.owner_id
96 || matches!(role, Some(Role::Write | Role::Maintain | Role::Admin))97 || matches!(role, Some(Role::Write | Role::Maintain | Role::Admin))
97 }98 }
98 99
99-/// The base branch's merge rule for a pull request, with the facts that rule checks.
100 #[derive(Debug, Clone, PartialEq, Eq)]100 #[derive(Debug, Clone, PartialEq, Eq)]
101 pub struct MergeGate {101 pub struct MergeGate {
102 pub rule: RuleFlags,102 pub rule: RuleFlags,
103- /// Distinct counting reviewers whose latest submitted review is an approval.
104 pub approvals: u32,103 pub approvals: u32,
105- /// Some counting reviewer's latest submitted review requests changes.
106 pub changes_requested: bool,104 pub changes_requested: bool,
107- /// The head contains the current base tip. Always true when the rule does not require it.
108 pub up_to_date: bool,105 pub up_to_date: bool,
109- /// The pull request is a draft.
110 pub draft: bool,106 pub draft: bool,
111- /// Each required check context with its state on the head commit (`None`: not reported).
112 pub required: Vec<RequiredCheck>,107 pub required: Vec<RequiredCheck>,
113 }108 }
114 109
115-/// One required status check and where it stands on the pull request head.
116 #[derive(Debug, Clone, PartialEq, Eq)]110 #[derive(Debug, Clone, PartialEq, Eq)]
117 pub struct RequiredCheck {111 pub struct RequiredCheck {
118 pub context: String,112 pub context: String,
@@ -120,7 +114,6 @@ pub struct RequiredCheck {
120 }114 }
121 115
122 impl MergeGate {116 impl MergeGate {
123- /// Every refusal code that currently blocks the merge, in the order they are reported.
124 pub fn blockers(&self) -> Vec<&'static str> {117 pub fn blockers(&self) -> Vec<&'static str> {
125 let mut out = Vec::new();118 let mut out = Vec::new();
126 if self.draft {119 if self.draft {
@@ -145,13 +138,10 @@ impl MergeGate {
145 out138 out
146 }139 }
147 140
148- /// The refusal code for the first rule that blocks the merge, if any.
149 pub fn blocked(&self) -> Option<&'static str> {141 pub fn blocked(&self) -> Option<&'static str> {
150 self.blockers().first().copied()142 self.blockers().first().copied()
151 }143 }
152 144
153- /// Whether waiting could clear every blocker: only missing approvals or checks that are not
154- /// green yet. Auto-merge may be enabled only then (or when nothing blocks).
155 pub fn waiting_only(&self) -> bool {145 pub fn waiting_only(&self) -> bool {
156 self.blockers()146 self.blockers()
157 .iter()147 .iter()
@@ -159,11 +149,6 @@ impl MergeGate {
159 }149 }
160 }150 }
161 151
162-/// Evaluates the effective rule for the pull request's base branch. Approvals and change requests
163-/// count only from `counts_for_merge_rules` reviewers, using each reviewer's latest review; an
164-/// approval counts only while the head is the commit it was given on.
165-/// Repo admins are not exempt. A base branch that does not exist counts as up to date; the merge
166-/// itself reports that.
167 pub async fn merge_gate(152 pub async fn merge_gate(
168 state: &AppState,153 state: &AppState,
169 repo: &forge_core::Repo,154 repo: &forge_core::Repo,
@@ -174,8 +159,6 @@ pub async fn merge_gate(
174 let mut approvals = 0u32;159 let mut approvals = 0u32;
175 let mut changes_requested = false;160 let mut changes_requested = false;
176 for (author_id, _, review, commit) in state.store.latest_review_states(&pr.issue.id).await? {161 for (author_id, _, review, commit) in state.store.latest_review_states(&pr.issue.id).await? {
177- // An approval is of the commits the reviewer saw: a push after it leaves it uncounted
178- // until they approve again. A change request stands until it is dismissed or replaced.
179 if review == ReviewState::Approved && commit != pr.head_oid {162 if review == ReviewState::Approved && commit != pr.head_oid {
180 continue;163 continue;
181 }164 }
@@ -230,12 +213,6 @@ pub async fn merge_gate(
230 })213 })
231 }214 }
232 215
233-/// Merges `pr` into its base branch in `repo` as `viewer`.
234-///
235-/// The base tip is `expected_base` when given, otherwise the current tip of the base branch. The
236-/// merge is checked and built against that tip, and the ref moves only if it still points there.
237-/// `message` replaces the default commit message (not used by fast-forward). Refusals that the
238-/// viewer can act on come back as `MergeOutcome::Refused`; git and database failures are errors.
239 pub async fn perform_merge(216 pub async fn perform_merge(
240 state: &AppState,217 state: &AppState,
241 repo: &forge_core::Repo,218 repo: &forge_core::Repo,
@@ -258,7 +235,12 @@ pub async fn perform_merge(
258 };235 };
259 let new = match merge_commit(state, repo, pr, viewer, style, message, &base_tip).await? {236 let new = match merge_commit(state, repo, pr, viewer, style, message, &base_tip).await? {
260 Ok(new) => new,237 Ok(new) => new,
261- Err(refusal) => return Ok(refusal),238+ Err(refusal) => {
239+ return Ok(MergeOutcome::Refused {
240+ status: refusal.status,
241+ message: refusal.message,
242+ });
243+ }
262 };244 };
263 245
264 match update_ref_cas(&state.git, &base_path, &refname, &new, &base_tip).await {246 match update_ref_cas(&state.git, &base_path, &refname, &new, &base_tip).await {
@@ -273,9 +255,6 @@ pub async fn perform_merge(
273 Ok(MergeOutcome::Merged { commit: new })255 Ok(MergeOutcome::Merged { commit: new })
274 }256 }
275 257
276-/// The commit that merging `pr` into `base_tip` makes in `style`, committed as `committer`. No ref
277-/// moves. A refusal the caller can act on comes back as the inner `Err`. Fast-forward returns the
278-/// head itself.
279 pub async fn merge_commit(258 pub async fn merge_commit(
280 state: &AppState,259 state: &AppState,
281 repo: &forge_core::Repo,260 repo: &forge_core::Repo,
@@ -284,7 +263,7 @@ pub async fn merge_commit(
284 style: MergeStyle,263 style: MergeStyle,
285 message: Option<&str>,264 message: Option<&str>,
286 base_tip: &str,265 base_tip: &str,
287-) -> forge_core::Result<std::result::Result<String, MergeOutcome>> {266+) -> forge_core::Result<std::result::Result<String, MergeRefusal>> {
288 let base_path = repo_path(&state.git.data_dir, &repo.id)?;267 let base_path = repo_path(&state.git.data_dir, &repo.id)?;
289 let base_tip = base_tip.to_owned();268 let base_tip = base_tip.to_owned();
290 let viewer = committer;269 let viewer = committer;
@@ -292,9 +271,9 @@ pub async fn merge_commit(
292 let tree = match check_merge(&state.git, &base_path, &base_tip, head).await? {271 let tree = match check_merge(&state.git, &base_path, &base_tip, head).await? {
293 MergeCheck::Clean { tree } => tree,272 MergeCheck::Clean { tree } => tree,
294 MergeCheck::Conflict { .. } => {273 MergeCheck::Conflict { .. } => {
295- return Ok(Err(refused(StatusCode::CONFLICT, CONFLICTS_MSG)));274+ return Ok(Err(refusal(CONFLICTS_MSG)));
296 }275 }
297- MergeCheck::UpToDate => return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG))),276+ MergeCheck::UpToDate => return Ok(Err(refusal(UP_TO_DATE_MSG))),
298 };277 };
299 278
300 let now = now_unix();279 let now = now_unix();
@@ -306,7 +285,7 @@ pub async fn merge_commit(
306 let new = match style {285 let new = match style {
307 MergeStyle::FastForward => {286 MergeStyle::FastForward => {
308 if !is_ancestor(&state.git, &base_path, &base_tip, head).await? {287 if !is_ancestor(&state.git, &base_path, &base_tip, head).await? {
309- return Ok(Err(refused(StatusCode::CONFLICT, FF_MSG)));288+ return Ok(Err(refusal(FF_MSG)));
310 }289 }
311 head.to_owned()290 head.to_owned()
312 }291 }
@@ -314,10 +293,10 @@ pub async fn merge_commit(
314 match rebase_commits(&state.git, &base_path, &base_tip, head, &committer).await? {293 match rebase_commits(&state.git, &base_path, &base_tip, head, &committer).await? {
315 RebaseResult::Clean { tip, count } if count > 0 => tip,294 RebaseResult::Clean { tip, count } if count > 0 => tip,
316 RebaseResult::Clean { .. } => {295 RebaseResult::Clean { .. } => {
317- return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG)));296+ return Ok(Err(refusal(UP_TO_DATE_MSG)));
318 }297 }
319 RebaseResult::Conflict { .. } => {298 RebaseResult::Conflict { .. } => {
320- return Ok(Err(refused(StatusCode::CONFLICT, REBASE_CONFLICT_MSG)));299+ return Ok(Err(refusal(REBASE_CONFLICT_MSG)));
321 }300 }
322 }301 }
323 }302 }
@@ -370,9 +349,6 @@ pub async fn merge_commit(
370 Ok(Ok(new))349 Ok(Ok(new))
371 }350 }
372 351
373-/// The work after a merge moved `refname` from `base_tip` to `new`: the pull request is marked
374-/// merged, its events and notifications go out, and the ref update runs its post-update work.
375-/// Failures here are logged, not reported: the merge is already in place.
376 pub async fn finish_merge(352 pub async fn finish_merge(
377 state: &AppState,353 state: &AppState,
378 repo: &forge_core::Repo,354 repo: &forge_core::Repo,
@@ -393,7 +369,6 @@ pub async fn finish_merge(
393 }369 }
394 }370 }
395 trigger_maintenance(&state.git, &repo.id);371 trigger_maintenance(&state.git, &repo.id);
396- // Boxed: the queue lands through this path, and the post-update work can reach the queue again.
397 if let Err(e) = Box::pin(after_ref_update(372 if let Err(e) = Box::pin(after_ref_update(
398 state, repo, &viewer.id, refname, base_tip, new,373 state, repo, &viewer.id, refname, base_tip, new,
399 ))374 ))
@@ -403,8 +378,6 @@ pub async fn finish_merge(
403 }378 }
404 }379 }
405 380
406-/// The address written into a commit for `user`: their email, or a noreply address on this
407-/// instance's host when they have none.
408 pub fn contact_email(base_url: &str, user: &User) -> String {381 pub fn contact_email(base_url: &str, user: &User) -> String {
409 match user382 match user
410 .email383 .email
@@ -429,7 +402,6 @@ pub fn base_url_host(base_url: &str) -> String {
429 .unwrap_or_else(|| "localhost".to_owned())402 .unwrap_or_else(|| "localhost".to_owned())
430 }403 }
431 404
432-/// `Merge pull request #N from owner/branch`, a blank line, then the pull request title.
433 pub async fn default_merge_message(405 pub async fn default_merge_message(
434 state: &AppState,406 state: &AppState,
435 pr: &PullRequest,407 pr: &PullRequest,
@@ -452,7 +424,6 @@ pub async fn default_merge_message(
452 ))424 ))
453 }425 }
454 426
455-/// `<title> (#N)`, a blank line, then one `- <summary>` line per commit, oldest first.
456 pub fn squash_message(pr: &PullRequest, commits: &[CommitInfo]) -> String {427 pub fn squash_message(pr: &PullRequest, commits: &[CommitInfo]) -> String {
457 let mut text = format!("{} (#{})\n\n", pr.issue.title, pr.issue.number);428 let mut text = format!("{} (#{})\n\n", pr.issue.title, pr.issue.number);
458 for commit in commits {429 for commit in commits {
crates/forge-web-app/src/merge_queue.rsmodified+25 -30
@@ -23,7 +23,7 @@ use forge_git::repo::repo_path;
23 use crate::ci::schedule::merge_queue_run;23 use crate::ci::schedule::merge_queue_run;
24 use crate::merge::{24 use crate::merge::{
25 ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE,25 ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE,
26- ERR_QUEUE_ALREADY, MergeOutcome, finish_merge, merge_commit, merge_gate,26+ ERR_QUEUE_ALREADY, finish_merge, merge_commit, merge_gate,
27 };27 };
28 use crate::notify::{self, Activity};28 use crate::notify::{self, Activity};
29 use crate::state::AppState;29 use crate::state::AppState;
@@ -86,17 +86,25 @@ pub async fn enqueue(
86 /// Takes a waiting entry out of the queue, with `reason`. The caller starts the queue again with86 /// Takes a waiting entry out of the queue, with `reason`. The caller starts the queue again with
87 /// `advance`. A candidate that is already testing keeps its CI run; its result is then ignored.87 /// `advance`. A candidate that is already testing keeps its CI run; its result is then ignored.
88 pub async fn remove(state: &AppState, repo: &Repo, entry: &QueueEntry, reason: &str) {88 pub async fn remove(state: &AppState, repo: &Repo, entry: &QueueEntry, reason: &str) {
89- match state89+ if let Err(e) = remove_entry(state, repo, entry, reason).await {
90+ tracing::error!(error = %e, repo_id = %repo.id, "merge queue: removing an entry failed");
91+ }
92+}
93+
94+async fn remove_entry(
95+ state: &AppState,
96+ repo: &Repo,
97+ entry: &QueueEntry,
98+ reason: &str,
99+) -> forge_core::Result<()> {
100+ if state
90 .store101 .store
91 .queue_finish(&entry.id, QueueState::Removed, reason)102 .queue_finish(&entry.id, QueueState::Removed, reason)
92- .await103+ .await?
93 {104 {
94- Ok(true) => notify_entry(state, repo, entry),105+ notify_entry(state, repo, entry);
95- Ok(false) => {}
96- Err(e) => {
97- tracing::error!(error = %e, repo_id = %repo.id, "merge queue: removing an entry failed");
98- }
99 }106 }
107+ Ok(())
100 }108 }
101 109
102 /// A pull request's head moved or it was closed: if it waits in a queue, it leaves the queue and110 /// A pull request's head moved or it was closed: if it waits in a queue, it leaves the queue and
@@ -219,12 +227,14 @@ async fn start(
219 let tested =227 let tested =
220 match merge_commit(state, repo, pr, &user, entry.merge_style, None, &base_tip).await? {228 match merge_commit(state, repo, pr, &user, entry.merge_style, None, &base_tip).await? {
221 Ok(oid) => oid,229 Ok(oid) => oid,
222- Err(MergeOutcome::Refused { message, .. }) => {230+ Err(refusal) => {
223- let text = format!("could not build the merge with the target branch: {message}.");231+ let text = format!(
232+ "could not build the merge with the target branch: {}.",
233+ refusal.message
234+ );
224 fail(state, repo, entry, pr, "conflict", &text).await?;235 fail(state, repo, entry, pr, "conflict", &text).await?;
225 return Ok(false);236 return Ok(false);
226 }237 }
227- Err(MergeOutcome::Merged { .. }) => return Ok(false),
228 };238 };
229 let test_ref = test_ref_name(&entry.branch, entry.pull_number);239 let test_ref = test_ref_name(&entry.branch, entry.pull_number);
230 set_ref(&state.git, &base_path, &test_ref, &tested).await?;240 set_ref(&state.git, &base_path, &test_ref, &tested).await?;
@@ -335,7 +345,7 @@ async fn land(
335 let tested = entry.tested_oid.clone().unwrap_or_default();345 let tested = entry.tested_oid.clone().unwrap_or_default();
336 let base = entry.base_oid.clone().unwrap_or_default();346 let base = entry.base_oid.clone().unwrap_or_default();
337 let Some(user) = state.store.user_by_id(&entry.enqueued_by).await? else {347 let Some(user) = state.store.user_by_id(&entry.enqueued_by).await? else {
338- finish_removed(state, repo, entry, "removed").await?;348+ remove_entry(state, repo, entry, "removed").await?;
339 return Ok(true);349 return Ok(true);
340 };350 };
341 let collaborator = state.store.collaborator_role(&repo.id, &user.id).await?;351 let collaborator = state.store.collaborator_role(&repo.id, &user.id).await?;
@@ -344,13 +354,13 @@ async fn land(
344 .org_repo_role(&repo.owner_id, &user.id, &repo.id)354 .org_repo_role(&repo.owner_id, &user.id, &repo.id)
345 .await?;355 .await?;
346 if authorize(Some(&user), repo, collaborator, org, Action::Write).is_err() {356 if authorize(Some(&user), repo, collaborator, org, Action::Write).is_err() {
347- finish_removed(state, repo, entry, "permission").await?;357+ remove_entry(state, repo, entry, "permission").await?;
348 return Ok(true);358 return Ok(true);
349 }359 }
350 // Reviews may have changed while the candidate was tested (a change request, a dismissed360 // Reviews may have changed while the candidate was tested (a change request, a dismissed
351 // approval): the same readiness test as before testing, now right before the target moves.361 // approval): the same readiness test as before testing, now right before the target moves.
352 if let Some(reason) = unready(state, repo, pr).await? {362 if let Some(reason) = unready(state, repo, pr).await? {
353- finish_removed(state, repo, entry, reason).await?;363+ remove_entry(state, repo, entry, reason).await?;
354 return Ok(true);364 return Ok(true);
355 }365 }
356 let refname = format!("refs/heads/{}", entry.branch);366 let refname = format!("refs/heads/{}", entry.branch);
@@ -370,25 +380,10 @@ async fn land(
370 }380 }
371 }381 }
372 finish_merge(state, repo, pr, &user, &refname, &base, &tested).await;382 finish_merge(state, repo, pr, &user, &refname, &base, &tested).await;
373- finish_removed(state, repo, entry, "merged").await?;383+ remove_entry(state, repo, entry, "merged").await?;
374 Ok(true)384 Ok(true)
375 }385 }
376 386
377-/// Ends a merging entry as removed with `reason`.
378-async fn finish_removed(
379- state: &AppState,
380- repo: &Repo,
381- entry: &QueueEntry,
382- reason: &str,
383-) -> forge_core::Result<()> {
384- state
385- .store
386- .queue_finish(&entry.id, QueueState::Removed, reason)
387- .await?;
388- notify_entry(state, repo, entry);
389- Ok(())
390-}
391-
392 /// Ends an entry as failed and comments on its pull request, mentioning the person who queued it.387 /// Ends an entry as failed and comments on its pull request, mentioning the person who queued it.
393 async fn fail(388 async fn fail(
394 state: &AppState,389 state: &AppState,
crates/forge-web-app/src/mirrors/worker.rsmodified+2 -44
@@ -5,9 +5,8 @@
5 use std::collections::HashSet;5 use std::collections::HashSet;
6 use std::time::Duration;6 use std::time::Duration;
7 7
8-use forge_core::time::now_stamp;8+use forge_core::time::{now_stamp, sleep_until};
9 use time::OffsetDateTime;9 use time::OffsetDateTime;
10-use time::format_description::well_known::Rfc3339;
11 use tokio::sync::mpsc;10 use tokio::sync::mpsc;
12 11
13 use super::{policy, run_one};12 use super::{policy, run_one};
@@ -16,8 +15,6 @@ use crate::webhooks::client::WebhookPolicy;
16 15
17 /// The longest the worker sleeps. It guards against a missed wake, not polling.16 /// The longest the worker sleeps. It guards against a missed wake, not polling.
18 const BACKSTOP: Duration = Duration::from_secs(15 * 60);17 const BACKSTOP: Duration = Duration::from_secs(15 * 60);
19-/// The shortest sleep, so a due time that has already passed does not spin the loop.
20-const MIN_SLEEP: Duration = Duration::from_secs(1);
21 /// Runs in flight at once.18 /// Runs in flight at once.
22 const MAX_RUNNING: usize = 2;19 const MAX_RUNNING: usize = 2;
23 /// Due mirrors read per pass.20 /// Due mirrors read per pass.
@@ -45,7 +42,7 @@ async fn run(state: AppState) {
45 // Wake when the earliest enabled mirror is due, so a push mirror queued with a short42 // Wake when the earliest enabled mirror is due, so a push mirror queued with a short
46 // debounce runs on time instead of waiting for the next poll.43 // debounce runs on time instead of waiting for the next poll.
47 let nap = match state.store.next_mirror_due().await {44 let nap = match state.store.next_mirror_due().await {
48- Ok(next) => sleep_for(next.as_deref(), OffsetDateTime::now_utc()),45+ Ok(next) => sleep_until(next.as_deref(), OffsetDateTime::now_utc(), BACKSTOP),
49 Err(e) => {46 Err(e) => {
50 tracing::error!(error = %e, "mirrors: could not read the next due time");47 tracing::error!(error = %e, "mirrors: could not read the next due time");
51 BACKSTOP48 BACKSTOP
@@ -62,17 +59,6 @@ async fn run(state: AppState) {
62 }59 }
63 }60 }
64 61
65-/// How long the worker sleeps before its next pass: until `next_due` (an RFC 3339 stamp, the
66-/// earliest enabled mirror), clamped to `MIN_SLEEP..=BACKSTOP`. `None` (nothing enabled) or an
67-/// unparsable stamp gives `BACKSTOP`.
68-pub fn sleep_for(next_due: Option<&str>, now: OffsetDateTime) -> Duration {
69- let Some(due) = next_due.and_then(|s| OffsetDateTime::parse(s, &Rfc3339).ok()) else {
70- return BACKSTOP;
71- };
72- let until = Duration::try_from(due - now).unwrap_or(Duration::ZERO);
73- until.clamp(MIN_SLEEP, BACKSTOP)
74-}
75-
76 /// Starts runs for due mirrors until the concurrency limit, skipping mirrors and repos already62 /// Starts runs for due mirrors until the concurrency limit, skipping mirrors and repos already
77 /// in flight.63 /// in flight.
78 async fn claim(64 async fn claim(
@@ -119,34 +105,6 @@ mod tests {
119 use super::super::pull_refs;105 use super::super::pull_refs;
120 use crate::test_support::test_state;106 use crate::test_support::test_state;
121 107
122- #[test]
123- fn sleep_stops_at_the_next_due_time_and_is_clamped() {
124- use std::time::Duration;
125-
126- use time::OffsetDateTime;
127- use time::format_description::well_known::Rfc3339;
128- use time::macros::datetime;
129-
130- let now = datetime!(2026-10-15 12:00:00 UTC);
131- let stamp = |t: OffsetDateTime| t.format(&Rfc3339).expect("stamp");
132- // Nothing enabled: the backstop.
133- assert_eq!(super::sleep_for(None, now), super::BACKSTOP);
134- // A push queued with a 10 s debounce: sleep until it is due.
135- let in_10s = stamp(now + time::Duration::seconds(10));
136- assert_eq!(
137- super::sleep_for(Some(&in_10s), now),
138- Duration::from_secs(10)
139- );
140- // Due later than the backstop: wake at the backstop.
141- let in_1h = stamp(now + time::Duration::hours(1));
142- assert_eq!(super::sleep_for(Some(&in_1h), now), super::BACKSTOP);
143- // Already due (or in flight and still due): do not spin, wait the minimum.
144- let past = stamp(now - time::Duration::seconds(5));
145- assert_eq!(super::sleep_for(Some(&past), now), super::MIN_SLEEP);
146- // A stamp that does not parse falls back to the backstop.
147- assert_eq!(super::sleep_for(Some("soon"), now), super::BACKSTOP);
148- }
149-
150 /// Plain git against a bare repo, for setting up the fake upstream.108 /// Plain git against a bare repo, for setting up the fake upstream.
151 fn plumbing(git_dir: &Path, args: &[&str]) -> String {109 fn plumbing(git_dir: &Path, args: &[&str]) -> String {
152 let out = std::process::Command::new("git")110 let out = std::process::Command::new("git")
crates/forge-web-app/src/notify.rsmodified+4 -6
@@ -238,12 +238,10 @@ async fn fan_out(
238 238
239 /// Keeps the stronger of the reasons already recorded for a user and `reason`.239 /// Keeps the stronger of the reasons already recorded for a user and `reason`.
240 fn add(candidates: &mut BTreeMap<String, Reason>, user_id: String, reason: Reason) {240 fn add(candidates: &mut BTreeMap<String, Reason>, user_id: String, reason: Reason) {
241- match candidates.get(&user_id) {241+ candidates
242- Some(prev) if prev.rank() >= reason.rank() => {}242+ .entry(user_id)
243- _ => {243+ .and_modify(|r| *r = strongest(*r, reason))
244- candidates.insert(user_id, reason);244+ .or_insert(reason);
245- }
246- }
247 }245 }
248 246
249 fn strongest(a: Reason, b: Reason) -> Reason {247 fn strongest(a: Reason, b: Reason) -> Reason {
crates/forge-web-app/src/oci/auth.rsmodified+3 -17
@@ -8,13 +8,14 @@
8 use forge_core::User;8 use forge_core::User;
9 use forge_core::oci as rules;9 use forge_core::oci as rules;
10 use forge_core::packages::{KIND_OCI, Package};10 use forge_core::packages::{KIND_OCI, Package};
11+use forge_core::time::unix_now;
11 use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE};12 use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE};
12 use topcoat::context::{Cx, context};13 use topcoat::context::{Cx, context};
13 use topcoat::router::StatusCode;14 use topcoat::router::StatusCode;
14 use topcoat::router::request::headers;15 use topcoat::router::request::headers;
15 use topcoat::router::response::Response;16 use topcoat::router::response::Response;
16 17
17-use super::oci_error;18+use super::{name_unknown, oci_error};
18 use crate::api::{self, Refusal};19 use crate::api::{self, Refusal};
19 use crate::client_ip::client_ip;20 use crate::client_ip::client_ip;
20 use crate::package_ops::{self, PackageError};21 use crate::package_ops::{self, PackageError};
@@ -50,7 +51,7 @@ pub async fn caller(cx: &Cx) -> Result<Caller, Refusal> {
50 if let Some(bearer) = value.strip_prefix("Bearer ").map(str::trim)51 if let Some(bearer) = value.strip_prefix("Bearer ").map(str::trim)
51 && !bearer.starts_with("forge_")52 && !bearer.starts_with("forge_")
52 {53 {
53- let now = unix_now();54+ let now = unix_now() as i64;
54 return match rules::verify_token(&state.key, bearer, now) {55 return match rules::verify_token(&state.key, bearer, now) {
55 Some(Some(user_id)) => match state.store.user_by_id(&user_id).await {56 Some(Some(user_id)) => match state.store.user_by_id(&user_id).await {
56 Ok(Some(user)) if !user.is_org() => Ok(Caller { user: Some(user) }),57 Ok(Some(user)) if !user.is_org() => Ok(Caller { user: Some(user) }),
@@ -155,14 +156,6 @@ pub async fn authorize(
155 }156 }
156 }157 }
157 158
158-fn name_unknown() -> Response {
159- oci_error(
160- StatusCode::NOT_FOUND,
161- "NAME_UNKNOWN",
162- "repository name not known to registry",
163- )
164-}
165-
166 /// The 401 that asks for credentials. It names the token endpoint, and the repository's scope when159 /// The 401 that asks for credentials. It names the token endpoint, and the repository's scope when
167 /// the request names one.160 /// the request names one.
168 pub fn challenge(state: &AppState, name: Option<&str>) -> Response {161 pub fn challenge(state: &AppState, name: Option<&str>) -> Response {
@@ -214,10 +207,3 @@ pub fn package_failure(error: PackageError) -> Refusal {
214 pub fn internal_refusal(error: impl std::fmt::Display) -> Refusal {207 pub fn internal_refusal(error: impl std::fmt::Display) -> Refusal {
215 Box::new(internal(error))208 Box::new(internal(error))
216 }209 }
217-
218-/// The current time in seconds since the epoch.
219-pub fn unix_now() -> i64 {
220- std::time::SystemTime::now()
221- .duration_since(std::time::UNIX_EPOCH)
222- .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
223-}
crates/forge-web-app/src/oci/blobs.rsmodified+9 -14
@@ -13,11 +13,11 @@ use std::time::{Duration, SystemTime};
13 13
14 use forge_core::oci as rules;14 use forge_core::oci as rules;
15 use forge_core::packages::{KIND_OCI, Package};15 use forge_core::packages::{KIND_OCI, Package};
16+use forge_core::token::sha256_reader;
16 use futures_util::StreamExt;17 use futures_util::StreamExt;
17 use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue};18 use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue};
18 use http_body::Frame;19 use http_body::Frame;
19 use http_body_util::StreamBody;20 use http_body_util::StreamBody;
20-use sha2::{Digest, Sha256};
21 use tokio::io::{AsyncReadExt, AsyncWriteExt};21 use tokio::io::{AsyncReadExt, AsyncWriteExt};
22 use topcoat::router::response::Response;22 use topcoat::router::response::Response;
23 use topcoat::router::{Body, StatusCode};23 use topcoat::router::{Body, StatusCode};
@@ -46,7 +46,7 @@ pub fn blob_key(hex: &str) -> String {
46 46
47 /// A session id as this module makes them: 26 ASCII letters or digits. Anything else is not a47 /// A session id as this module makes them: 26 ASCII letters or digits. Anything else is not a
48 /// session, so no id can name a path outside the uploads directory.48 /// session, so no id can name a path outside the uploads directory.
49-pub fn valid_session_id(id: &str) -> bool {49+fn valid_session_id(id: &str) -> bool {
50 id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric())50 id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric())
51 }51 }
52 52
@@ -172,17 +172,12 @@ pub async fn append(
172 172
173 /// The sha256 of a file, hex.173 /// The sha256 of a file, hex.
174 pub async fn file_sha256(path: &Path) -> std::io::Result<String> {174 pub async fn file_sha256(path: &Path) -> std::io::Result<String> {
175- let mut file = tokio::fs::File::open(path).await?;175+ let path = path.to_owned();
176- let mut hasher = Sha256::new();176+ tokio::task::spawn_blocking(move || {
177- let mut buf = vec![0u8; CHUNK];177+ sha256_reader(std::fs::File::open(path)?).map(|(_, hex)| hex)
178- loop {178+ })
179- let read = file.read(&mut buf).await?;179+ .await
180- if read == 0 {180+ .map_err(std::io::Error::other)?
181- break;
182- }
183- hasher.update(&buf[..read]);
184- }
185- Ok(hex::encode(hasher.finalize()))
186 }181 }
187 182
188 /// Links `digest` to `package` once its bytes are in the blob store. Holds the garbage collection183 /// Links `digest` to `package` once its bytes are in the blob store. Holds the garbage collection
@@ -355,6 +350,7 @@ pub async fn delete_blob(state: &AppState, target: &Target, digest: &str) -> Res
355 let Some(package) = target.package.as_ref() else {350 let Some(package) = target.package.as_ref() else {
356 return unknown_blob();351 return unknown_blob();
357 };352 };
353+ let _gc = gc::lock().await;
358 match state.store.oci_blob_size(&package.id, digest).await {354 match state.store.oci_blob_size(&package.id, digest).await {
359 Ok(Some(_)) => {}355 Ok(Some(_)) => {}
360 Ok(None) => return unknown_blob(),356 Ok(None) => return unknown_blob(),
@@ -371,7 +367,6 @@ pub async fn delete_blob(state: &AppState, target: &Target, digest: &str) -> Res
371 Ok(false) => {}367 Ok(false) => {}
372 Err(e) => return internal(e),368 Err(e) => return internal(e),
373 }369 }
374- let _gc = gc::lock().await;
375 if let Err(e) = state.store.oci_unlink_blob(&package.id, digest).await {370 if let Err(e) = state.store.oci_unlink_blob(&package.id, digest).await {
376 return internal(e);371 return internal(e);
377 }372 }
crates/forge-web-app/src/oci/manifests.rsmodified+4 -12
@@ -12,22 +12,22 @@ use topcoat::router::{Body, StatusCode, to_bytes};
12 12
13 use super::auth::{self, Caller, internal};13 use super::auth::{self, Caller, internal};
14 use super::blobs::{insert, write_package};14 use super::blobs::{insert, write_package};
15-use super::{gc, oci_error};15+use super::{gc, name_unknown, oci_error};
16 use crate::package_ops::bump_linked_repo;16 use crate::package_ops::bump_linked_repo;
17 use crate::state::AppState;17 use crate::state::AppState;
18 18
19 /// Largest manifest accepted, in bytes.19 /// Largest manifest accepted, in bytes.
20-pub const MAX_MANIFEST_BYTES: usize = 4 * 1024 * 1024;20+const MAX_MANIFEST_BYTES: usize = 4 * 1024 * 1024;
21 21
22 /// What a manifest reference names: a digest, or a tag.22 /// What a manifest reference names: a digest, or a tag.
23-pub enum Reference<'a> {23+enum Reference<'a> {
24 Digest(&'a str),24 Digest(&'a str),
25 Tag(&'a str),25 Tag(&'a str),
26 }26 }
27 27
28 /// Reads a reference from a path segment. A reference with a colon is a digest, anything else a28 /// Reads a reference from a path segment. A reference with a colon is a digest, anything else a
29 /// tag. The error is the response to send.29 /// tag. The error is the response to send.
30-pub fn parse_reference(reference: &str) -> Result<Reference<'_>, Box<Response>> {30+fn parse_reference(reference: &str) -> Result<Reference<'_>, Box<Response>> {
31 if reference.contains(':') {31 if reference.contains(':') {
32 if rules::parse_digest(reference).is_some() {32 if rules::parse_digest(reference).is_some() {
33 Ok(Reference::Digest(reference))33 Ok(Reference::Digest(reference))
@@ -61,14 +61,6 @@ fn manifest_unknown() -> Response {
61 )61 )
62 }62 }
63 63
64-fn name_unknown() -> Response {
65- oci_error(
66- StatusCode::NOT_FOUND,
67- "NAME_UNKNOWN",
68- "repository name not known to registry",
69- )
70-}
71-
72 /// `PUT /v2/{name}/manifests/{reference}`. The referenced blobs must already be in the package, so64 /// `PUT /v2/{name}/manifests/{reference}`. The referenced blobs must already be in the package, so
73 /// a manifest never names bytes the registry lacks. The digest of the bytes is the manifest's id.65 /// a manifest never names bytes the registry lacks. The digest of the bytes is the manifest's id.
74 pub async fn put_manifest(66 pub async fn put_manifest(
crates/forge-web-app/src/oci/mod.rsmodified+11 -2
@@ -25,7 +25,8 @@ use topcoat::router::response::Response;
25 use topcoat::router::{Body, StatusCode, path_param, route};25 use topcoat::router::{Body, StatusCode, path_param, route};
26 26
27 use crate::state::AppState;27 use crate::state::AppState;
28-use auth::{Caller, unix_now};28+use auth::Caller;
29+use forge_core::time::now_unix;
29 30
30 path_param!(*rest);31 path_param!(*rest);
31 32
@@ -38,6 +39,14 @@ pub fn oci_error(status: StatusCode, code: &str, message: &str) -> Response {
38 json_response(status, &body)39 json_response(status, &body)
39 }40 }
40 41
42+fn name_unknown() -> Response {
43+ oci_error(
44+ StatusCode::NOT_FOUND,
45+ "NAME_UNKNOWN",
46+ "repository name not known to registry",
47+ )
48+}
49+
41 fn json_response(status: StatusCode, value: &Value) -> Response {50 fn json_response(status: StatusCode, value: &Value) -> Response {
42 let mut res = Response::new(Body::from(value.to_string()));51 let mut res = Response::new(Body::from(value.to_string()));
43 *res.status_mut() = status;52 *res.status_mut() = status;
@@ -123,7 +132,7 @@ async fn token(cx: &Cx) -> topcoat::Result<Response> {
123 Err(res) => return Ok(*res),132 Err(res) => return Ok(*res),
124 };133 };
125 let subject = caller.user.as_ref().map(|user| user.id.as_str());134 let subject = caller.user.as_ref().map(|user| user.id.as_str());
126- let now = unix_now();135+ let now = now_unix();
127 let token = forge_core::oci::issue_token(&state.key, subject, now + auth::TOKEN_TTL_SECS);136 let token = forge_core::oci::issue_token(&state.key, subject, now + auth::TOKEN_TTL_SECS);
128 // Clients parse `issued_at` as an RFC 3339 time, so a number is refused.137 // Clients parse `issued_at` as an RFC 3339 time, so a number is refused.
129 let issued_at = time::OffsetDateTime::now_utc()138 let issued_at = time::OffsetDateTime::now_utc()
crates/forge-web-app/src/package_ops.rsmodified+8 -12
@@ -20,8 +20,6 @@ use crate::state::AppState;
20 pub const MAX_CRATE_BYTES: u64 = 10 * 1024 * 1024;20 pub const MAX_CRATE_BYTES: u64 = 10 * 1024 * 1024;
21 /// Largest publish body accepted: the crate plus its JSON metadata.21 /// Largest publish body accepted: the crate plus its JSON metadata.
22 pub const MAX_PUBLISH_BYTES: usize = 16 * 1024 * 1024;22 pub const MAX_PUBLISH_BYTES: usize = 16 * 1024 * 1024;
23-/// Bytes handed to the blob writer at a time.
24-const PUSH_CHUNK: usize = 1024 * 1024;
25 23
26 /// Why a registry request failed. The API maps each to a status and a cargo error body.24 /// Why a registry request failed. The API maps each to a status and a cargo error body.
27 #[derive(Debug)]25 #[derive(Debug)]
@@ -320,7 +318,7 @@ pub async fn download(
320 }318 }
321 319
322 /// The blob key of a version's `.crate` file.320 /// The blob key of a version's `.crate` file.
323-pub fn blob_key(version_id: &str) -> String {321+fn blob_key(version_id: &str) -> String {
324 format!("packages/{version_id}")322 format!("packages/{version_id}")
325 }323 }
326 324
@@ -349,15 +347,13 @@ async fn link_repo(
349 Ok(())347 Ok(())
350 }348 }
351 349
352-/// Streams `bytes` into the blob store under `key`, returning the sha256 the store computed.350+/// Streams `bytes` into the blob store under `key`.
353-async fn store_bytes(state: &AppState, key: &str, bytes: &[u8]) -> forge_core::Result<String> {351+async fn store_bytes(state: &AppState, key: &str, bytes: &[u8]) -> forge_core::Result<()> {
354 let mut writer = state.blobs.begin(key, MAX_CRATE_BYTES).await?;352 let mut writer = state.blobs.begin(key, MAX_CRATE_BYTES).await?;
355- for chunk in bytes.chunks(PUSH_CHUNK) {353+ if let Err(e) = writer.push(bytes).await {
356- if let Err(e) = writer.push(chunk).await {354+ writer.abort().await;
357- writer.abort().await;355+ return Err(e);
358- return Err(e);
359- }
360 }356 }
361- let (_, sha) = writer.finish().await?;357+ writer.finish().await?;
362- Ok(sha)358+ Ok(())
363 }359 }
crates/forge-web-app/src/post_update.rsmodified+51 -55
@@ -12,11 +12,12 @@
12 //! `internal::trigger_maintenance`. Callers that update a ref outside receive-pack (the merge12 //! `internal::trigger_maintenance`. Callers that update a ref outside receive-pack (the merge
13 //! route) call it themselves.13 //! route) call it themselves.
14 14
15-use std::path::PathBuf;15+use std::path::{Path, PathBuf};
16 16
17 use forge_core::issue_refs::{find_closing_refs, find_issue_refs};17 use forge_core::issue_refs::{find_closing_refs, find_issue_refs};
18 use forge_core::time::now_stamp;18 use forge_core::time::now_stamp;
19 use forge_core::{IssueState, Repo, StateReason};19 use forge_core::{IssueState, Repo, StateReason};
20+use forge_git::browse::CommitInfo;
20 use forge_git::{history, trailers};21 use forge_git::{history, trailers};
21 use serde_json::json;22 use serde_json::json;
22 23
@@ -46,23 +47,19 @@ pub async fn after_ref_update(
46 ) -> forge_core::Result<()> {47 ) -> forge_core::Result<()> {
47 let sender = lookup_sender(state, actor_id).await;48 let sender = lookup_sender(state, actor_id).await;
48 emit_ref_update(state, repo, &sender, refname, old, new).await;49 emit_ref_update(state, repo, &sender, refname, old, new).await;
49- // Code views that follow a branch or the ref list re-read it.
50 state50 state
51 .live51 .live
52 .bump(&crate::live::Topic::RepoRefs(repo.id.clone()));52 .bump(&crate::live::Topic::RepoRefs(repo.id.clone()));
53- // The pusher's contribution calendar on their profile counts the push.
54 if !actor_id.is_empty() {53 if !actor_id.is_empty() {
55 state54 state
56 .live55 .live
57 .bump(&crate::live::Topic::User(actor_id.to_owned()));56 .bump(&crate::live::Topic::User(actor_id.to_owned()));
58 }57 }
59- // The owner's repo listing sorts by last update, so a push by someone else moves it too.
60 if repo.owner_id != actor_id {58 if repo.owner_id != actor_id {
61 state59 state
62 .live60 .live
63 .bump(&crate::live::Topic::User(repo.owner_id.clone()));61 .bump(&crate::live::Topic::User(repo.owner_id.clone()));
64 }62 }
65- // The explore list shows each public repo's last activity, so a push moves it there.
66 if repo.visibility == forge_core::Visibility::Public {63 if repo.visibility == forge_core::Visibility::Public {
67 state.live.bump(&crate::live::Topic::Explore);64 state.live.bump(&crate::live::Topic::Explore);
68 }65 }
@@ -72,31 +69,26 @@ pub async fn after_ref_update(
72 {69 {
73 tracing::error!(error = %e, repo_id = %repo.id, "mirrors: could not queue push mirrors");70 tracing::error!(error = %e, repo_id = %repo.id, "mirrors: could not queue push mirrors");
74 }71 }
75- if refname == format!("refs/heads/{}", repo.default_branch) && !is_zero_oid(new) {72+ let branch = refname.starts_with("refs/heads/") && !is_zero_oid(new);
73+ let default = branch && refname == format!("refs/heads/{}", repo.default_branch);
74+ if default {
76 crate::advisories::scan::spawn_repo_scan(state, repo);75 crate::advisories::scan::spawn_repo_scan(state, repo);
77 }76 }
78 crate::replication::enqueue_repo(state, &repo.id);77 crate::replication::enqueue_repo(state, &repo.id);
79- if refname == format!("refs/heads/{}", repo.default_branch) && !is_zero_oid(new) {78+ if branch {
80- match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) {
81- Ok(repo_dir) => {
82- tokio::spawn(close_from_pushed_commits(
83- state.clone(),
84- repo.clone(),
85- sender,
86- repo_dir,
87- actor_id.to_owned(),
88- old.to_owned(),
89- new.to_owned(),
90- ));
91- }
92- Err(e) => {
93- tracing::error!(error = %e, repo_id = %repo.id, "issue refs: bad repo path");
94- }
95- }
96- }
97- if refname.starts_with("refs/heads/") && !is_zero_oid(new) {
98 match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) {79 match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) {
99 Ok(repo_dir) => {80 Ok(repo_dir) => {
81+ if default {
82+ tokio::spawn(close_from_pushed_commits(
83+ state.clone(),
84+ repo.clone(),
85+ sender,
86+ repo_dir.clone(),
87+ actor_id.to_owned(),
88+ old.to_owned(),
89+ new.to_owned(),
90+ ));
91+ }
100 tokio::spawn(credit_coauthors(92 tokio::spawn(credit_coauthors(
101 state.clone(),93 state.clone(),
102 repo.clone(),94 repo.clone(),
@@ -107,16 +99,40 @@ pub async fn after_ref_update(
107 ));99 ));
108 }100 }
109 Err(e) => {101 Err(e) => {
110- tracing::error!(error = %e, repo_id = %repo.id, "co-authors: bad repo path");102+ tracing::error!(error = %e, repo_id = %repo.id, "pushed commits: bad repo path");
111 }103 }
112 }104 }
113 }105 }
114 let synced = pulls_sync::sync_pulls_for_ref(state, repo, actor_id, refname, old, new).await;106 let synced = pulls_sync::sync_pulls_for_ref(state, repo, actor_id, refname, old, new).await;
115- // A push can move, merge or open any pull of the repo, so every pull page is woken.
116 crate::live::bump_repo_pulls(state, &repo.id).await;107 crate::live::bump_repo_pulls(state, &repo.id).await;
117 synced108 synced
118 }109 }
119 110
111+/// Lists the commits a ref update added, newest first. A new branch (`old` is zero) reads at most
112+/// `MAX_NEW_BRANCH_COMMITS`; an update reads `max_update`. Errors are logged and yield `None`.
113+async fn pushed_commits(
114+ state: &AppState,
115+ repo: &Repo,
116+ repo_dir: &Path,
117+ old: &str,
118+ new: &str,
119+ max_update: usize,
120+) -> Option<Vec<CommitInfo>> {
121+ let old = (!is_zero_oid(old)).then_some(old);
122+ let max = if old.is_some() {
123+ max_update
124+ } else {
125+ MAX_NEW_BRANCH_COMMITS
126+ };
127+ match history::new_commits(&state.git, repo_dir, old, new, max).await {
128+ Ok(commits) => Some(commits),
129+ Err(e) => {
130+ tracing::error!(error = %e, repo_id = %repo.id, "pushed commits: listing failed");
131+ None
132+ }
133+ }
134+}
135+
120 /// Processes the commits added to the default branch by one ref update, oldest first.136 /// Processes the commits added to the default branch by one ref update, oldest first.
121 async fn close_from_pushed_commits(137 async fn close_from_pushed_commits(
122 state: AppState,138 state: AppState,
@@ -127,18 +143,10 @@ async fn close_from_pushed_commits(
127 old: String,143 old: String,
128 new: String,144 new: String,
129 ) {145 ) {
130- let old = (!is_zero_oid(&old)).then_some(old.as_str());146+ let Some(commits) =
131- let max = if old.is_some() {147+ pushed_commits(&state, &repo, &repo_dir, &old, &new, MAX_PUSH_COMMITS).await
132- MAX_PUSH_COMMITS148+ else {
133- } else {149+ return;
134- MAX_NEW_BRANCH_COMMITS
135- };
136- let commits = match history::new_commits(&state.git, &repo_dir, old, &new, max).await {
137- Ok(commits) => commits,
138- Err(e) => {
139- tracing::error!(error = %e, repo_id = %repo.id, "issue refs: listing commits failed");
140- return;
141- }
142 };150 };
143 let actor = (!actor_id.is_empty()).then_some(actor_id.as_str());151 let actor = (!actor_id.is_empty()).then_some(actor_id.as_str());
144 for commit in &commits {152 for commit in &commits {
@@ -160,18 +168,10 @@ async fn credit_coauthors(
160 old: String,168 old: String,
161 new: String,169 new: String,
162 ) {170 ) {
163- let old = (!is_zero_oid(&old)).then_some(old.as_str());171+ let Some(commits) =
164- let max = if old.is_some() {172+ pushed_commits(&state, &repo, &repo_dir, &old, &new, MAX_COAUTHOR_COMMITS).await
165- MAX_COAUTHOR_COMMITS173+ else {
166- } else {174+ return;
167- MAX_NEW_BRANCH_COMMITS
168- };
169- let commits = match history::new_commits(&state.git, &repo_dir, old, &new, max).await {
170- Ok(commits) => commits,
171- Err(e) => {
172- tracing::error!(error = %e, repo_id = %repo.id, "co-authors: listing commits failed");
173- return;
174- }
175 };175 };
176 let actor = (!actor_id.is_empty()).then_some(actor_id.as_str());176 let actor = (!actor_id.is_empty()).then_some(actor_id.as_str());
177 let at = now_stamp();177 let at = now_stamp();
@@ -233,7 +233,6 @@ async fn apply_commit_refs(
233 .await?;233 .await?;
234 if closed {234 if closed {
235 state.live.bump_issue(&repo.id, &issue.id);235 state.live.bump_issue(&repo.id, &issue.id);
236- // A pull is an issue row too, so a keyword can close one.
237 crate::live::bump_pull(state, &repo.id, &issue.id);236 crate::live::bump_pull(state, &repo.id, &issue.id);
238 emit_item_action(state, repo, sender, false, number, "closed").await;237 emit_item_action(state, repo, sender, false, number, "closed").await;
239 notify::dispatch(238 notify::dispatch(
@@ -412,7 +411,6 @@ mod tests {
412 assert_eq!(body["commits"][0]["id"], c1.as_str());411 assert_eq!(body["commits"][0]["id"], c1.as_str());
413 assert_eq!(body["commits"][0]["message"], "one");412 assert_eq!(body["commits"][0]["message"], "one");
414 413
415- // Creating the branch also sends a create event for it.
416 let creates = fx.deliveries(WebhookEvent::Create).await;414 let creates = fx.deliveries(WebhookEvent::Create).await;
417 assert_eq!(creates.len(), 1);415 assert_eq!(creates.len(), 1);
418 assert_eq!(creates[0].1["ref"], "main");416 assert_eq!(creates[0].1["ref"], "main");
@@ -428,8 +426,6 @@ mod tests {
428 assert_eq!(body["total_commits"], 1);426 assert_eq!(body["total_commits"], 1);
429 assert_eq!(body["commits"][0]["id"], c2.as_str());427 assert_eq!(body["commits"][0]["id"], c2.as_str());
430 428
431- // A topic branch: create, then delete. Git will not delete the bare repo's
432- // current branch, so the delete uses a branch that is not HEAD.
433 fx.update_ref("refs/heads/topic", ZERO, &c2).await;429 fx.update_ref("refs/heads/topic", ZERO, &c2).await;
434 fx.update_ref("refs/heads/topic", &c2, ZERO).await;430 fx.update_ref("refs/heads/topic", &c2, ZERO).await;
435 let deletes = fx.deliveries(WebhookEvent::Delete).await;431 let deletes = fx.deliveries(WebhookEvent::Delete).await;
crates/forge-web-app/src/raw/media.rsmodified+17 -81
@@ -1,14 +1,7 @@
1-//! Raw-origin route `/{owner}/{repo}/-/media/{ref}/{path...}`. The literal `-` keeps it apart
2-//! from raw paths, since no ref name may start with `-`. It reads the Git LFS pointer at
3-//! `ref:path` and streams the object it names, when the repo links that object. Access follows
4-//! the raw route in `raw.rs`: public repos are open, and private repos need a signed `?token=`.
5-
6-use forge_core::raw_token::verify_raw;
7 use forge_core::{Repo, Visibility};1 use forge_core::{Repo, Visibility};
8 use futures_util::TryStreamExt;2 use futures_util::TryStreamExt;
9 use http_body::Frame;3 use http_body::Frame;
10 use http_body_util::StreamBody;4 use http_body_util::StreamBody;
11-use serde::Deserialize;
12 use tokio_util::io::ReaderStream;5 use tokio_util::io::ReaderStream;
13 use topcoat::context::{Cx, context};6 use topcoat::context::{Cx, context};
14 use topcoat::router::request::method;7 use topcoat::router::request::method;
@@ -21,42 +14,31 @@ use topcoat::router::{
21 use crate::lfs::{has_object, object_path};14 use crate::lfs::{has_object, object_path};
22 use crate::lfs_pointer;15 use crate::lfs_pointer;
23 use crate::raw::{16 use crate::raw::{
24- CACHE_NONE, CACHE_PRIVATE, CACHE_PUBLIC, LINK_TTL_SECS, Lookup, Meta, OCTET, encode_path,17+ CACHE_NONE, Lookup, Meta, OCTET, TokenQuery, encode_path, finish, lookup, plain,
25- finish, lookup, now_unix, plain,18+ resolve_repo, signed_url,
26 };19 };
27 use crate::state::AppState;20 use crate::state::AppState;
28 21
29-#[derive(Deserialize)]
30-struct TokenQuery {
31- token: Option<String>,
32-}
33-
34-/// Absolute URL of the media route for `path` at `rev` on the user-content origin. Private repos
35-/// get a signed `?token=`, the same as raw URLs. The route is `/{owner}/{repo}/-/media/...`.
36 pub fn media_url(state: &AppState, repo: &Repo, rev: &str, path: &str) -> String {22 pub fn media_url(state: &AppState, repo: &Repo, rev: &str, path: &str) -> String {
37- let base = state.config.user_content_base_url.trim_end_matches('/');23+ let encoded = format!(
38- let mut url = format!(24+ "{}/{}/-/media/{}/{}",
39- "{base}/{}/{}/-/media/{}/{}",
40 encode_path(&repo.owner_name),25 encode_path(&repo.owner_name),
41 encode_path(&repo.name),26 encode_path(&repo.name),
42 encode_path(rev),27 encode_path(rev),
43 encode_path(path)28 encode_path(path)
44 );29 );
45- if matches!(repo.visibility, Visibility::Private) {30+ signed_url(
46- let expires = now_unix().saturating_add(LINK_TTL_SECS);31+ state,
47- url.push_str("?token=");32+ &encoded,
48- url.push_str(&forge_core::raw_token::sign_raw(33+ &repo.id,
49- &state.key, &repo.id, expires,34+ matches!(repo.visibility, Visibility::Private),
50- ));35+ )
51- }
52- url
53 }36 }
54 37
55 pub fn media_file(cx: &Cx, _body: Body) -> RouteFuture<'_> {38 pub fn media_file(cx: &Cx, _body: Body) -> RouteFuture<'_> {
56 Box::pin(async move { Ok(serve(cx).await) })39 Box::pin(async move { Ok(serve(cx).await) })
57 }40 }
58 41
59-/// Serves one LFS object. Every failure is turned into a response here, so the route never errors.
60 async fn serve(cx: &Cx) -> Response {42 async fn serve(cx: &Cx) -> Response {
61 let state = context::<AppState>(cx).clone();43 let state = context::<AppState>(cx).clone();
62 let owner = path_param_segment(cx, "owner").to_owned();44 let owner = path_param_segment(cx, "owner").to_owned();
@@ -69,38 +51,13 @@ async fn serve(cx: &Cx) -> Response {
69 .ok()51 .ok()
70 .and_then(|query| query.token);52 .and_then(|query| query.token);
71 53
72- let repo = match state.store.repo_by_owner_and_name(&owner, &name).await {54+ let (repo, repo_dir, cache) =
73- Ok(Some(repo)) => repo,55+ match resolve_repo(&state, &owner, &name, token.as_deref()).await {
74- // A missing repo and a private repo without a valid token look the same.56+ Ok(found) => found,
75- Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None),57+ Err(response) => return response,
76- Err(e) => {58+ };
77- tracing::error!(error = %e, "media: repo lookup failed");
78- return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None);
79- }
80- };
81- let cache = match repo.visibility {
82- Visibility::Public => CACHE_PUBLIC,
83- Visibility::Private => {
84- let valid = token
85- .as_deref()
86- .is_some_and(|t| verify_raw(&state.key, t, &repo.id, now_unix()));
87- if !valid {
88- return plain(StatusCode::NOT_FOUND, CACHE_NONE, None);
89- }
90- CACHE_PRIVATE
91- }
92- };
93 59
94- let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) {
95- Ok(path) => path,
96- Err(e) => {
97- tracing::error!(error = %e, "media: repo path failed");
98- return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None);
99- }
100- };
101 let looked = tokio::task::spawn_blocking(move || lookup(&repo_dir, &rest, None)).await;60 let looked = tokio::task::spawn_blocking(move || lookup(&repo_dir, &rest, None)).await;
102- // Pointers are a few hundred bytes, so they always come back inline. Anything else is not
103- // a pointer, and a symlink is never one.
104 let data = match looked {61 let data = match looked {
105 Ok(Ok(Lookup::Inline {62 Ok(Ok(Lookup::Inline {
106 symlink: false,63 symlink: false,
@@ -121,7 +78,6 @@ async fn serve(cx: &Cx) -> Response {
121 let Some(pointer) = lfs_pointer::parse(&data) else {78 let Some(pointer) = lfs_pointer::parse(&data) else {
122 return plain(StatusCode::NOT_FOUND, CACHE_NONE, None);79 return plain(StatusCode::NOT_FOUND, CACHE_NONE, None);
123 };80 };
124- // The repo must link the object, even when the file is on disk: objects are shared by every repo.
125 let size = match has_object(&state, &repo.id, &pointer.oid).await {81 let size = match has_object(&state, &repo.id, &pointer.oid).await {
126 Ok(Some(size)) => size,82 Ok(Some(size)) => size,
127 Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None),83 Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None),
@@ -142,7 +98,6 @@ async fn serve(cx: &Cx) -> Response {
142 return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None);98 return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None);
143 }99 }
144 };100 };
145- // The Content-Length comes from the link, so a file of another size would break the response.
146 let on_disk = match file.metadata().await {101 let on_disk = match file.metadata().await {
147 Ok(meta) => meta.len(),102 Ok(meta) => meta.len(),
148 Err(e) => {103 Err(e) => {
@@ -178,7 +133,8 @@ async fn serve(cx: &Cx) -> Response {
178 mod tests {133 mod tests {
179 use super::*;134 use super::*;
180 135
181- use forge_core::raw_token::sign_raw;136+ use crate::raw::now_unix;
137+ use forge_core::raw_token::{sign_raw, verify_raw};
182 use sha2::{Digest, Sha256};138 use sha2::{Digest, Sha256};
183 use topcoat::router::Router;139 use topcoat::router::Router;
184 use topcoat::router::request::Request;140 use topcoat::router::request::Request;
@@ -224,7 +180,6 @@ mod tests {
224 );180 );
225 }181 }
226 182
227- /// Commits `files` on `main` in a work tree and pushes it to `bare`.
228 fn populate(work: &std::path::Path, bare: &std::path::Path, files: &[(&str, Vec<u8>)]) {183 fn populate(work: &std::path::Path, bare: &std::path::Path, files: &[(&str, Vec<u8>)]) {
229 std::fs::create_dir_all(work).expect("mkdir work");184 std::fs::create_dir_all(work).expect("mkdir work");
230 git(work, &["init", "-q", "-b", "main"]);185 git(work, &["init", "-q", "-b", "main"]);
@@ -292,7 +247,6 @@ mod tests {
292 &[("big.bin", stored_pointer)],247 &[("big.bin", stored_pointer)],
293 );248 );
294 249
295- // The object is linked to both repos and written once to the shared store.
296 for repo in [&public, &private] {250 for repo in [&public, &private] {
297 store251 store
298 .insert_lfs_object(&repo.id, &oid, object.len() as u64)252 .insert_lfs_object(&repo.id, &oid, object.len() as u64)
@@ -339,13 +293,10 @@ mod tests {
339 .to_vec()293 .to_vec()
340 }294 }
341 295
342- /// The public route, read-only, on one fixture: the linked object as a download, HEAD, and
343- /// the 404 cases (unlinked object, non-pointer, absent path, unknown repo).
344 #[tokio::test]296 #[tokio::test]
345 async fn public_media_serves_downloads_heads_and_404s() {297 async fn public_media_serves_downloads_heads_and_404s() {
346 let fx = fixture().await;298 let fx = fixture().await;
347 299
348- // Scenario: a linked object is served as a download with its headers.
349 let res = get(&fx.router, "GET", "/tahinli/pub/-/media/main/big.bin").await;300 let res = get(&fx.router, "GET", "/tahinli/pub/-/media/main/big.bin").await;
350 assert_eq!(res.status(), StatusCode::OK, "linked object");301 assert_eq!(res.status(), StatusCode::OK, "linked object");
351 assert_eq!(302 assert_eq!(
@@ -375,7 +326,6 @@ mod tests {
375 );326 );
376 assert_eq!(body_bytes(res).await, fx.object, "linked object body");327 assert_eq!(body_bytes(res).await, fx.object, "linked object body");
377 328
378- // Scenario: HEAD has the headers and no body.
379 let res = get(&fx.router, "HEAD", "/tahinli/pub/-/media/main/big.bin").await;329 let res = get(&fx.router, "HEAD", "/tahinli/pub/-/media/main/big.bin").await;
380 assert_eq!(res.status(), StatusCode::OK, "head");330 assert_eq!(res.status(), StatusCode::OK, "head");
381 assert_eq!(331 assert_eq!(
@@ -385,11 +335,9 @@ mod tests {
385 );335 );
386 assert!(body_bytes(res).await.is_empty(), "head body");336 assert!(body_bytes(res).await.is_empty(), "head body");
387 337
388- // Scenario: the pointer exists, but the repo does not link its object.
389 let res = get(&fx.router, "GET", "/tahinli/pub/-/media/main/missing.bin").await;338 let res = get(&fx.router, "GET", "/tahinli/pub/-/media/main/missing.bin").await;
390 assert_eq!(res.status(), StatusCode::NOT_FOUND, "unlinked object");339 assert_eq!(res.status(), StatusCode::NOT_FOUND, "unlinked object");
391 340
392- // Scenario: a non-pointer file, an absent path and an unknown repo all 404.
393 let text = get(&fx.router, "GET", "/tahinli/pub/-/media/main/plain.txt").await;341 let text = get(&fx.router, "GET", "/tahinli/pub/-/media/main/plain.txt").await;
394 assert_eq!(text.status(), StatusCode::NOT_FOUND, "non-pointer");342 assert_eq!(text.status(), StatusCode::NOT_FOUND, "non-pointer");
395 let absent = get(&fx.router, "GET", "/tahinli/pub/-/media/main/nope.bin").await;343 let absent = get(&fx.router, "GET", "/tahinli/pub/-/media/main/nope.bin").await;
@@ -398,30 +346,24 @@ mod tests {
398 assert_eq!(unknown_repo.status(), StatusCode::NOT_FOUND, "unknown repo");346 assert_eq!(unknown_repo.status(), StatusCode::NOT_FOUND, "unknown repo");
399 }347 }
400 348
401- /// Private media and signed URLs, read-only, on one fixture: a private repo needs a valid
402- /// token, and `media_url` encodes paths and signs only private repos.
403 #[tokio::test]349 #[tokio::test]
404 async fn private_media_needs_a_valid_token_and_urls_sign_private_repos_only() {350 async fn private_media_needs_a_valid_token_and_urls_sign_private_repos_only() {
405 let fx = fixture().await;351 let fx = fixture().await;
406 let path = "/tahinli/priv/-/media/main/big.bin";352 let path = "/tahinli/priv/-/media/main/big.bin";
407 353
408- // Scenario: no token is a 404.
409 let none = get(&fx.router, "GET", path).await;354 let none = get(&fx.router, "GET", path).await;
410 assert_eq!(none.status(), StatusCode::NOT_FOUND, "no token");355 assert_eq!(none.status(), StatusCode::NOT_FOUND, "no token");
411 356
412- // Scenario: a valid token serves the object.
413 let now = now_unix();357 let now = now_unix();
414 let valid = sign_raw(&fx.state.key, &fx.private.id, now + 60);358 let valid = sign_raw(&fx.state.key, &fx.private.id, now + 60);
415 let ok = get(&fx.router, "GET", &format!("{path}?token={valid}")).await;359 let ok = get(&fx.router, "GET", &format!("{path}?token={valid}")).await;
416 assert_eq!(ok.status(), StatusCode::OK, "valid token");360 assert_eq!(ok.status(), StatusCode::OK, "valid token");
417 assert_eq!(body_bytes(ok).await, fx.object, "valid token body");361 assert_eq!(body_bytes(ok).await, fx.object, "valid token body");
418 362
419- // Scenario: an expired token is a 404.
420 let expired = sign_raw(&fx.state.key, &fx.private.id, now - 1);363 let expired = sign_raw(&fx.state.key, &fx.private.id, now - 1);
421 let res = get(&fx.router, "GET", &format!("{path}?token={expired}")).await;364 let res = get(&fx.router, "GET", &format!("{path}?token={expired}")).await;
422 assert_eq!(res.status(), StatusCode::NOT_FOUND, "expired token");365 assert_eq!(res.status(), StatusCode::NOT_FOUND, "expired token");
423 366
424- // Scenario: a token signed for the public repo does not open the private one.
425 let other = sign_raw(&fx.state.key, &fx.public.id, now + 60);367 let other = sign_raw(&fx.state.key, &fx.public.id, now + 60);
426 let res = get(&fx.router, "GET", &format!("{path}?token={other}")).await;368 let res = get(&fx.router, "GET", &format!("{path}?token={other}")).await;
427 assert_eq!(369 assert_eq!(
@@ -430,14 +372,12 @@ mod tests {
430 "token for another repo"372 "token for another repo"
431 );373 );
432 374
433- // Scenario: a public URL is encoded and unsigned.
434 let public = media_url(&fx.state, &fx.public, "main", "a b/big.bin");375 let public = media_url(&fx.state, &fx.public, "main", "a b/big.bin");
435 assert_eq!(376 assert_eq!(
436 public, "http://127.0.0.1:7661/tahinli/pub/-/media/main/a%20b/big.bin",377 public, "http://127.0.0.1:7661/tahinli/pub/-/media/main/a%20b/big.bin",
437 "public url"378 "public url"
438 );379 );
439 380
440- // Scenario: a private URL carries a token that verifies for the private repo.
441 let private = media_url(&fx.state, &fx.private, "main", "big.bin");381 let private = media_url(&fx.state, &fx.private, "main", "big.bin");
442 assert!(382 assert!(
443 private.starts_with("http://127.0.0.1:7661/tahinli/priv/-/media/main/big.bin?token="),383 private.starts_with("http://127.0.0.1:7661/tahinli/priv/-/media/main/big.bin?token="),
@@ -453,9 +393,6 @@ mod tests {
453 );393 );
454 }394 }
455 395
456- /// A branch named `media` must not shadow the media route. The raw route serves its files,
457- /// and the URL from `media_url` still serves the linked LFS object. This test pushes a
458- /// branch, so it keeps its own fixture.
459 #[tokio::test]396 #[tokio::test]
460 async fn branch_named_media_does_not_shadow_the_media_route() {397 async fn branch_named_media_does_not_shadow_the_media_route() {
461 let fx = fixture().await;398 let fx = fixture().await;
@@ -479,7 +416,6 @@ mod tests {
479 "branch raw body"416 "branch raw body"
480 );417 );
481 418
482- // `-` is never a ref, so a raw path under it is not resolved.
483 let dash = get(&fx.router, "GET", "/tahinli/pub/-/README.md").await;419 let dash = get(&fx.router, "GET", "/tahinli/pub/-/README.md").await;
484 assert_eq!(dash.status(), StatusCode::NOT_FOUND, "dash is not a ref");420 assert_eq!(dash.status(), StatusCode::NOT_FOUND, "dash is not a ref");
485 421
crates/forge-web-app/src/raw/mod.rsmodified+58 -93
@@ -1,15 +1,12 @@
1-//! Raw user-content origin (separate listener, explicit routes; never `.discover()`).
2-//! See docs/architecture.md, section 5.5.
3-
4 pub mod media;1 pub mod media;
5 pub mod snippet_raw;2 pub mod snippet_raw;
6 3
7-use std::path::Path;4+use std::path::{Path, PathBuf};
8 use std::process::Stdio;5 use std::process::Stdio;
9-use std::time::{SystemTime, UNIX_EPOCH};
10 6
11 use bytes::Bytes;7 use bytes::Bytes;
12 use forge_core::raw_token::{sign_raw, verify_raw};8 use forge_core::raw_token::{sign_raw, verify_raw};
9+pub use forge_core::time::now_unix;
13 use forge_core::{Repo, Visibility};10 use forge_core::{Repo, Visibility};
14 use forge_git::GitCommand;11 use forge_git::GitCommand;
15 use forge_git::browse::{self, EntryKind};12 use forge_git::browse::{self, EntryKind};
@@ -28,49 +25,51 @@ use topcoat::router::{
28 header, parse_query_params, path_param_segment, path_param_segments,25 header, parse_query_params, path_param_segment, path_param_segments,
29 };26 };
30 27
31-use crate::internal::is_valid_oid;28+use crate::internal::is_git_oid;
32 use crate::state::AppState;29 use crate::state::AppState;
33 30
34-/// Blobs up to this size are read in full. Larger blobs are streamed from `git cat-file`.
35 const MAX_INLINE_BYTES: u64 = 8 * 1024 * 1024;31 const MAX_INLINE_BYTES: u64 = 8 * 1024 * 1024;
36-/// Bytes inspected to decide text versus binary.
37 const SNIFF_BYTES: usize = 8000;32 const SNIFF_BYTES: usize = 8000;
38-/// Lifetime of a signed private raw URL.
39 pub const LINK_TTL_SECS: i64 = 600;33 pub const LINK_TTL_SECS: i64 = 600;
40 34
41 const CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox";35 const CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox";
42 const CORP: &str = "cross-origin";36 const CORP: &str = "cross-origin";
43-/// Raw responses revalidate on every use (an unchanged blob answers 304 through If-None-Match),
44-/// so a repo made private, or a reader who lost access, stops being served at once.
45 pub const CACHE_PRIVATE: &str = "private, no-cache";37 pub const CACHE_PRIVATE: &str = "private, no-cache";
46 pub const CACHE_PUBLIC: &str = "public, no-cache";38 pub const CACHE_PUBLIC: &str = "public, no-cache";
47 pub const CACHE_NONE: &str = "no-store";39 pub const CACHE_NONE: &str = "no-store";
48 const TEXT: &str = "text/plain; charset=utf-8";40 const TEXT: &str = "text/plain; charset=utf-8";
49 pub const OCTET: &str = "application/octet-stream";41 pub const OCTET: &str = "application/octet-stream";
50 42
51-/// Absolute URL of a file on the raw origin. For private repos it carries a signed `?token=`
52-/// valid for 10 minutes. `rev` is the ref name or commit oid as shown in the app URL.
53 pub fn raw_url(state: &AppState, repo: &Repo, rev: &str, path: &str) -> String {43 pub fn raw_url(state: &AppState, repo: &Repo, rev: &str, path: &str) -> String {
54- let base = state.config.user_content_base_url.trim_end_matches('/');44+ let mut encoded = format!(
55- let mut url = format!(45+ "{}/{}/{}",
56- "{base}/{}/{}/{}",
57 encode_path(&repo.owner_name),46 encode_path(&repo.owner_name),
58 encode_path(&repo.name),47 encode_path(&repo.name),
59 encode_path(rev)48 encode_path(rev)
60 );49 );
61 if !path.is_empty() {50 if !path.is_empty() {
62- url.push('/');51+ encoded.push('/');
63- url.push_str(&encode_path(path));52+ encoded.push_str(&encode_path(path));
64 }53 }
65- if matches!(repo.visibility, Visibility::Private) {54+ signed_url(
55+ state,
56+ &encoded,
57+ &repo.id,
58+ matches!(repo.visibility, Visibility::Private),
59+ )
60+}
61+
62+pub fn signed_url(state: &AppState, path: &str, id: &str, private: bool) -> String {
63+ let base = state.config.user_content_base_url.trim_end_matches('/');
64+ let mut url = format!("{base}/{path}");
65+ if private {
66 let expires = now_unix().saturating_add(LINK_TTL_SECS);66 let expires = now_unix().saturating_add(LINK_TTL_SECS);
67 url.push_str("?token=");67 url.push_str("?token=");
68- url.push_str(&sign_raw(&state.key, &repo.id, expires));68+ url.push_str(&sign_raw(&state.key, id, expires));
69 }69 }
70 url70 url
71 }71 }
72 72
73-/// Percent-encodes each `/`-separated segment and keeps the separators.
74 pub fn encode_path(value: &str) -> String {73 pub fn encode_path(value: &str) -> String {
75 value74 value
76 .split('/')75 .split('/')
@@ -79,7 +78,6 @@ pub fn encode_path(value: &str) -> String {
79 .join("/")78 .join("/")
80 }79 }
81 80
82-/// Percent-encodes everything except RFC 3986 unreserved characters.
83 fn encode_segment(segment: &str) -> String {81 fn encode_segment(segment: &str) -> String {
84 let mut out = String::with_capacity(segment.len());82 let mut out = String::with_capacity(segment.len());
85 for byte in segment.bytes() {83 for byte in segment.bytes() {
@@ -92,7 +90,6 @@ fn encode_segment(segment: &str) -> String {
92 out90 out
93 }91 }
94 92
95-/// Explicit routes only. No cookie layer: this origin never reads or sets cookies.
96 pub fn router(state: AppState) -> Router {93 pub fn router(state: AppState) -> Router {
97 Router::builder()94 Router::builder()
98 .route(RouteFn::new(95 .route(RouteFn::new(
@@ -100,22 +97,17 @@ pub fn router(state: AppState) -> Router {
100 "/{owner}/{repo}/{*rest}",97 "/{owner}/{repo}/{*rest}",
101 raw_file,98 raw_file,
102 ))99 ))
103- // Media is served from the LFS store, so it is routed before the catch-all raw route.
104- // It sits under the literal `-` segment, which no ref can use, so a branch named `media`
105- // still resolves through the raw route.
106 .route(RouteFn::new(100 .route(RouteFn::new(
107 vec![Method::GET, Method::HEAD],101 vec![Method::GET, Method::HEAD],
108 "/{owner}/{repo}/-/media/{*rest}",102 "/{owner}/{repo}/-/media/{*rest}",
109 crate::raw::media::media_file,103 crate::raw::media::media_file,
110 ))104 ))
111- // Snippet files sit under the same reserved `-` segment: `/-/snippets/{id}/{file}`.
112 .route(RouteFn::new(105 .route(RouteFn::new(
113 vec![Method::GET, Method::HEAD],106 vec![Method::GET, Method::HEAD],
114 "/-/snippets/{id}/{*rest}",107 "/-/snippets/{id}/{*rest}",
115 crate::raw::snippet_raw::snippet_file,108 crate::raw::snippet_raw::snippet_file,
116 ))109 ))
117 .route(RouteFn::new(Method::GET, "/healthz", healthz))110 .route(RouteFn::new(Method::GET, "/healthz", healthz))
118- // Responses must match the bytes behind the ETag and Content-Length.
119 .with(Compression::disable())111 .with(Compression::disable())
120 .with(state)112 .with(state)
121 .build()113 .build()
@@ -138,7 +130,40 @@ fn raw_file(cx: &Cx, _body: topcoat::router::Body) -> RouteFuture<'_> {
138 Box::pin(async move { Ok(serve(cx).await) })130 Box::pin(async move { Ok(serve(cx).await) })
139 }131 }
140 132
141-/// Serves one file. Every failure is turned into a response here, so the route never errors.133+async fn resolve_repo(
134+ state: &AppState,
135+ owner: &str,
136+ name: &str,
137+ token: Option<&str>,
138+) -> Result<(Repo, PathBuf, &'static str), Response> {
139+ let repo = match state.store.repo_by_owner_and_name(owner, name).await {
140+ Ok(Some(repo)) => repo,
141+ Ok(None) => return Err(plain(StatusCode::NOT_FOUND, CACHE_NONE, None)),
142+ Err(e) => {
143+ tracing::error!(error = %e, "raw: repo lookup failed");
144+ return Err(plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None));
145+ }
146+ };
147+ let cache = match repo.visibility {
148+ Visibility::Public => CACHE_PUBLIC,
149+ Visibility::Private => {
150+ let valid = token.is_some_and(|t| verify_raw(&state.key, t, &repo.id, now_unix()));
151+ if !valid {
152+ return Err(plain(StatusCode::NOT_FOUND, CACHE_NONE, None));
153+ }
154+ CACHE_PRIVATE
155+ }
156+ };
157+ let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) {
158+ Ok(path) => path,
159+ Err(e) => {
160+ tracing::error!(error = %e, "raw: repo path failed");
161+ return Err(plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None));
162+ }
163+ };
164+ Ok((repo, repo_dir, cache))
165+}
166+
142 async fn serve(cx: &Cx) -> Response {167 async fn serve(cx: &Cx) -> Response {
143 let state = context::<AppState>(cx).clone();168 let state = context::<AppState>(cx).clone();
144 let owner = path_param_segment(cx, "owner").to_owned();169 let owner = path_param_segment(cx, "owner").to_owned();
@@ -146,8 +171,6 @@ async fn serve(cx: &Cx) -> Response {
146 let rest = path_param_segments(cx, "rest")171 let rest = path_param_segments(cx, "rest")
147 .collect::<Vec<&str>>()172 .collect::<Vec<&str>>()
148 .join("/");173 .join("/");
149- // `-` is never a ref name (git and the pre-receive hook reject it). It is reserved for the
150- // `/-/media/` route, so a raw path whose first segment is `-` is a plain 404.
151 if rest.split('/').next() == Some("-") {174 if rest.split('/').next() == Some("-") {
152 return plain(StatusCode::NOT_FOUND, CACHE_NONE, None);175 return plain(StatusCode::NOT_FOUND, CACHE_NONE, None);
153 }176 }
@@ -160,34 +183,9 @@ async fn serve(cx: &Cx) -> Response {
160 .and_then(|v| v.to_str().ok())183 .and_then(|v| v.to_str().ok())
161 .map(str::to_owned);184 .map(str::to_owned);
162 185
163- let repo = match state.store.repo_by_owner_and_name(&owner, &name).await {186+ let (_, repo_dir, cache) = match resolve_repo(&state, &owner, &name, token.as_deref()).await {
164- Ok(Some(repo)) => repo,187+ Ok(found) => found,
165- // A missing repo and a private repo without a valid token look the same.188+ Err(response) => return response,
166- Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None),
167- Err(e) => {
168- tracing::error!(error = %e, "raw: repo lookup failed");
169- return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None);
170- }
171- };
172- let cache = match repo.visibility {
173- Visibility::Public => CACHE_PUBLIC,
174- Visibility::Private => {
175- let valid = token
176- .as_deref()
177- .is_some_and(|t| verify_raw(&state.key, t, &repo.id, now_unix()));
178- if !valid {
179- return plain(StatusCode::NOT_FOUND, CACHE_NONE, None);
180- }
181- CACHE_PRIVATE
182- }
183- };
184-
185- let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) {
186- Ok(path) => path,
187- Err(e) => {
188- tracing::error!(error = %e, "raw: repo path failed");
189- return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None);
190- }
191 };189 };
192 190
193 let lookup_dir = repo_dir.clone();191 let lookup_dir = repo_dir.clone();
@@ -260,11 +258,9 @@ async fn serve(cx: &Cx) -> Response {
260 len: size,258 len: size,
261 };259 };
262 if is_head {260 if is_head {
263- // Dropping the child kills it: only the headers were needed.
264 drop(child);261 drop(child);
265 return finish(StatusCode::OK, Body::empty(), &oid, cache, Some(meta));262 return finish(StatusCode::OK, Body::empty(), &oid, cache, Some(meta));
266 }263 }
267- // The child lives inside the closure, so it stays alive until the body is consumed.
268 let chunks = stream::iter([Ok::<Bytes, std::io::Error>(Bytes::from(sample))])264 let chunks = stream::iter([Ok::<Bytes, std::io::Error>(Bytes::from(sample))])
269 .chain(ReaderStream::new(stdout))265 .chain(ReaderStream::new(stdout))
270 .map_ok(Frame::data)266 .map_ok(Frame::data)
@@ -278,7 +274,6 @@ async fn serve(cx: &Cx) -> Response {
278 }274 }
279 }275 }
280 276
281-/// Result of the blocking lookup.
282 pub enum Lookup {277 pub enum Lookup {
283 Missing,278 Missing,
284 NotModified {279 NotModified {
@@ -295,7 +290,6 @@ pub enum Lookup {
295 },290 },
296 }291 }
297 292
298-/// Resolves `rest` (`<ref>/<path>`) to an entry. Trees, submodules and missing paths are `Missing`.
299 pub fn lookup(293 pub fn lookup(
300 repo_dir: &Path,294 repo_dir: &Path,
301 rest: &str,295 rest: &str,
@@ -341,9 +335,8 @@ pub fn lookup(
341 })335 })
342 }336 }
343 337
344-/// `git cat-file blob <oid>` with piped stdout. The OID must be full hex.
345 fn spawn_cat_file(state: &AppState, repo_dir: &Path, oid: &str) -> std::io::Result<Child> {338 fn spawn_cat_file(state: &AppState, repo_dir: &Path, oid: &str) -> std::io::Result<Child> {
346- if !is_valid_oid(oid) {339+ if !is_git_oid(oid) {
347 return Err(std::io::Error::other("invalid object id"));340 return Err(std::io::Error::other("invalid object id"));
348 }341 }
349 let mut cmd = GitCommand::new(&state.git, "cat-file")342 let mut cmd = GitCommand::new(&state.git, "cat-file")
@@ -356,7 +349,6 @@ fn spawn_cat_file(state: &AppState, repo_dir: &Path, oid: &str) -> std::io::Resu
356 cmd.spawn()349 cmd.spawn()
357 }350 }
358 351
359-/// Content type and whether the response must be an attachment.
360 fn classify(file_name: &str, sample: &[u8], complete: bool) -> (&'static str, bool) {352 fn classify(file_name: &str, sample: &[u8], complete: bool) -> (&'static str, bool) {
361 let ext = file_name353 let ext = file_name
362 .rsplit_once('.')354 .rsplit_once('.')
@@ -385,8 +377,6 @@ fn image_type(ext: &str) -> Option<&'static str> {
385 })377 })
386 }378 }
387 379
388-/// No NUL in the first 8000 bytes and valid UTF-8. For a partial sample (`complete` is false) an
389-/// incomplete sequence at the end is accepted.
390 fn is_text(sample: &[u8], complete: bool) -> bool {380 fn is_text(sample: &[u8], complete: bool) -> bool {
391 let probe = &sample[..sample.len().min(SNIFF_BYTES)];381 let probe = &sample[..sample.len().min(SNIFF_BYTES)];
392 if probe.contains(&0) {382 if probe.contains(&0) {
@@ -398,7 +388,6 @@ fn is_text(sample: &[u8], complete: bool) -> bool {
398 }388 }
399 }389 }
400 390
401-/// True when an `If-None-Match` header lists `etag` (or `*`). Weak prefixes are ignored.
402 fn etag_matches(header_value: &str, etag: &str) -> bool {391 fn etag_matches(header_value: &str, etag: &str) -> bool {
403 header_value.split(',').map(str::trim).any(|candidate| {392 header_value.split(',').map(str::trim).any(|candidate| {
404 candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag393 candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag
@@ -411,7 +400,6 @@ pub struct Meta {
411 pub len: u64,400 pub len: u64,
412 }401 }
413 402
414-/// Builds a response with the security and caching headers that every raw response carries.
415 pub fn finish(403 pub fn finish(
416 status: StatusCode,404 status: StatusCode,
417 body: Body,405 body: Body,
@@ -458,7 +446,6 @@ pub fn finish(
458 res446 res
459 }447 }
460 448
461-/// Error or empty response with no ETag and a text body.
462 pub fn plain(status: StatusCode, cache: &'static str, body: Option<&'static str>) -> Response {449 pub fn plain(status: StatusCode, cache: &'static str, body: Option<&'static str>) -> Response {
463 let text = body.unwrap_or(match status {450 let text = body.unwrap_or(match status {
464 StatusCode::NOT_FOUND => "not found",451 StatusCode::NOT_FOUND => "not found",
@@ -471,14 +458,6 @@ pub fn plain(status: StatusCode, cache: &'static str, body: Option<&'static str>
471 res458 res
472 }459 }
473 460
474-pub fn now_unix() -> i64 {
475- SystemTime::now()
476- .duration_since(UNIX_EPOCH)
477- .ok()
478- .and_then(|d| i64::try_from(d.as_secs()).ok())
479- .unwrap_or(0)
480-}
481-
482 #[cfg(test)]461 #[cfg(test)]
483 mod tests {462 mod tests {
484 use super::*;463 use super::*;
@@ -515,7 +494,6 @@ mod tests {
515 );494 );
516 }495 }
517 496
518- /// Creates a work tree with `files` and a symlink, then pushes it to `bare` as `main`.
519 fn populate(work: &Path, bare: &Path, files: &[(&str, Vec<u8>)]) {497 fn populate(work: &Path, bare: &Path, files: &[(&str, Vec<u8>)]) {
520 std::fs::create_dir_all(work).expect("mkdir work");498 std::fs::create_dir_all(work).expect("mkdir work");
521 git(work, &["init", "-q", "-b", "main"]);499 git(work, &["init", "-q", "-b", "main"]);
@@ -648,11 +626,9 @@ mod tests {
648 assert_eq!(header_str(res, "referrer-policy"), "no-referrer");626 assert_eq!(header_str(res, "referrer-policy"), "no-referrer");
649 }627 }
650 628
651- /// One fixture (one 9 MB repo, private repo and signer) serves every read-only scenario below.
652 #[tokio::test]629 #[tokio::test]
653 async fn raw_serves_every_scenario_from_one_fixture() {630 async fn raw_serves_every_scenario_from_one_fixture() {
654 let fx = fixture().await;631 let fx = fixture().await;
655- // Scenario: a public text file is plain and sandboxed.
656 {632 {
657 let res = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await;633 let res = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await;
658 assert_eq!(res.status(), 200);634 assert_eq!(res.status(), 200);
@@ -663,16 +639,13 @@ mod tests {
663 assert_eq!(body_bytes(res).await, b"hello raw\n");639 assert_eq!(body_bytes(res).await, b"hello raw\n");
664 }640 }
665 641
666- // Scenario: a nested path resolves.
667 {642 {
668 let res = get(&fx.router, "GET", "/tahinli/pub/main/sub/a.txt", None).await;643 let res = get(&fx.router, "GET", "/tahinli/pub/main/sub/a.txt", None).await;
669 assert_eq!(res.status(), 200);644 assert_eq!(res.status(), 200);
670 assert_eq!(body_bytes(res).await, b"nested\n");645 assert_eq!(body_bytes(res).await, b"nested\n");
671 }646 }
672 647
673- // Scenario: html is forced to an attachment and png is an image.
674 {648 {
675- // (path, want content-type, want content-disposition)
676 let cases = [649 let cases = [
677 ("/tahinli/pub/main/page.html", TEXT, "attachment"),650 ("/tahinli/pub/main/page.html", TEXT, "attachment"),
678 ("/tahinli/pub/main/pic.png", "image/png", ""),651 ("/tahinli/pub/main/pic.png", "image/png", ""),
@@ -689,7 +662,6 @@ mod tests {
689 }662 }
690 }663 }
691 664
692- // Scenario: a symlink is served as its target text.
693 {665 {
694 let res = get(&fx.router, "GET", "/tahinli/pub/main/link", None).await;666 let res = get(&fx.router, "GET", "/tahinli/pub/main/link", None).await;
695 assert_eq!(res.status(), 200);667 assert_eq!(res.status(), 200);
@@ -697,7 +669,6 @@ mod tests {
697 assert_eq!(body_bytes(res).await, b"hello.txt");669 assert_eq!(body_bytes(res).await, b"hello.txt");
698 }670 }
699 671
700- // Scenario: a private repo requires a valid, unexpired token for that repo.
701 {672 {
702 let path = "/tahinli/priv/main/hello.txt";673 let path = "/tahinli/priv/main/hello.txt";
703 let now = now_unix();674 let now = now_unix();
@@ -721,7 +692,6 @@ mod tests {
721 assert_eq!(res.status(), 404);692 assert_eq!(res.status(), 404);
722 }693 }
723 694
724- // Scenario: missing repos and directories are 404.
725 {695 {
726 for uri in [696 for uri in [
727 "/tahinli/nope/main/hello.txt",697 "/tahinli/nope/main/hello.txt",
@@ -733,7 +703,6 @@ mod tests {
733 }703 }
734 }704 }
735 705
736- // Scenario: a matching etag gives 304.
737 {706 {
738 let first = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await;707 let first = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await;
739 let etag = header_str(&first, "etag");708 let etag = header_str(&first, "etag");
@@ -749,7 +718,6 @@ mod tests {
749 assert_eq!(header_str(&again, "etag"), etag);718 assert_eq!(header_str(&again, "etag"), etag);
750 }719 }
751 720
752- // Scenario: HEAD has headers and no body.
753 {721 {
754 let res = get(&fx.router, "HEAD", "/tahinli/pub/main/hello.txt", None).await;722 let res = get(&fx.router, "HEAD", "/tahinli/pub/main/hello.txt", None).await;
755 assert_eq!(res.status(), 200);723 assert_eq!(res.status(), 200);
@@ -758,7 +726,6 @@ mod tests {
758 assert!(body_bytes(res).await.is_empty());726 assert!(body_bytes(res).await.is_empty());
759 }727 }
760 728
761- // Scenario: a large file streams intact.
762 {729 {
763 let res = get(&fx.router, "GET", "/tahinli/pub/main/big.txt", None).await;730 let res = get(&fx.router, "GET", "/tahinli/pub/main/big.txt", None).await;
764 assert_eq!(res.status(), 200);731 assert_eq!(res.status(), 200);
@@ -773,7 +740,6 @@ mod tests {
773 assert!(body == expected, "streamed body differs");740 assert!(body == expected, "streamed body differs");
774 }741 }
775 742
776- // Scenario: app routes are not on the raw origin, but healthz is.
777 {743 {
778 for path in ["/login", "/settings/keys", "/tahinli/pub/tree/main"] {744 for path in ["/login", "/settings/keys", "/tahinli/pub/tree/main"] {
779 let res = get(&fx.router, "GET", path, None).await;745 let res = get(&fx.router, "GET", path, None).await;
@@ -783,7 +749,6 @@ mod tests {
783 assert_eq!(health.status(), 200);749 assert_eq!(health.status(), 200);
784 }750 }
785 751
786- // Scenario: raw URLs are encoded, and private ones are signed.
787 {752 {
788 let url = raw_url(&fx.state, &fx.public, "main", "my file#1.txt");753 let url = raw_url(&fx.state, &fx.public, "main", "my file#1.txt");
789 assert_eq!(754 assert_eq!(
crates/forge-web-app/src/raw/snippet_raw.rsmodified+15 -35
@@ -1,11 +1,5 @@
1-//! Raw-origin route `/-/snippets/{id}/{file}`. The literal `-` keeps it apart from repo raw paths,1+use forge_core::raw_token::verify_raw;
2-//! as it does for media. Snippet files are served as text under the same sandbox headers as raw
3-//! files. Public and unlisted snippets are open. A private snippet needs a signed `?token=`,
4-//! signed over the snippet id by the same `sign_raw` that guards private repo files.
5-
6-use forge_core::raw_token::{sign_raw, verify_raw};
7 use forge_core::store::snippets::{Snippet, SnippetVisibility};2 use forge_core::store::snippets::{Snippet, SnippetVisibility};
8-use serde::Deserialize;
9 use sha2::{Digest, Sha256};3 use sha2::{Digest, Sha256};
10 use topcoat::context::{Cx, context};4 use topcoat::context::{Cx, context};
11 use topcoat::router::request::{headers, method};5 use topcoat::router::request::{headers, method};
@@ -16,42 +10,32 @@ use topcoat::router::{
16 };10 };
17 11
18 use crate::raw::{12 use crate::raw::{
19- CACHE_NONE, CACHE_PRIVATE, CACHE_PUBLIC, LINK_TTL_SECS, Meta, encode_path, finish, now_unix,13+ CACHE_NONE, CACHE_PRIVATE, CACHE_PUBLIC, Meta, TEXT, TokenQuery, encode_path, finish,
20- plain,14+ now_unix, plain, signed_url,
21 };15 };
22 use crate::state::AppState;16 use crate::state::AppState;
23 17
24-const TEXT: &str = "text/plain; charset=utf-8";
25 const MARKDOWN: &str = "text/markdown; charset=utf-8";18 const MARKDOWN: &str = "text/markdown; charset=utf-8";
26 const JSON: &str = "application/json; charset=utf-8";19 const JSON: &str = "application/json; charset=utf-8";
27 20
28-#[derive(Deserialize)]
29-struct TokenQuery {
30- token: Option<String>,
31-}
32-
33-/// Absolute URL of one file of a snippet on the user-content origin. A private snippet's URL
34-/// carries a signed `?token=` valid for the same 10 minutes as private raw URLs.
35 pub fn snippet_raw_url(state: &AppState, snippet: &Snippet, file: &str) -> String {21 pub fn snippet_raw_url(state: &AppState, snippet: &Snippet, file: &str) -> String {
36- let base = state.config.user_content_base_url.trim_end_matches('/');22+ let encoded = format!(
37- let mut url = format!(23+ "-/snippets/{}/{}",
38- "{base}/-/snippets/{}/{}",
39 encode_path(&snippet.id),24 encode_path(&snippet.id),
40 encode_path(file)25 encode_path(file)
41 );26 );
42- if snippet.visibility == SnippetVisibility::Private {27+ signed_url(
43- let expires = now_unix().saturating_add(LINK_TTL_SECS);28+ state,
44- url.push_str("?token=");29+ &encoded,
45- url.push_str(&sign_raw(&state.key, &snippet.id, expires));30+ &snippet.id,
46- }31+ snippet.visibility == SnippetVisibility::Private,
47- url32+ )
48 }33 }
49 34
50 pub fn snippet_file(cx: &Cx, _body: Body) -> RouteFuture<'_> {35 pub fn snippet_file(cx: &Cx, _body: Body) -> RouteFuture<'_> {
51 Box::pin(async move { Ok(serve(cx).await) })36 Box::pin(async move { Ok(serve(cx).await) })
52 }37 }
53 38
54-/// Content type for a snippet file, chosen from its extension. Everything is text.
55 fn content_type(file_name: &str) -> &'static str {39 fn content_type(file_name: &str) -> &'static str {
56 match file_name40 match file_name
57 .rsplit_once('.')41 .rsplit_once('.')
@@ -64,7 +48,6 @@ fn content_type(file_name: &str) -> &'static str {
64 }48 }
65 }49 }
66 50
67-/// Serves one file. Every failure is turned into a response here, so the route never errors.
68 async fn serve(cx: &Cx) -> Response {51 async fn serve(cx: &Cx) -> Response {
69 let state = context::<AppState>(cx).clone();52 let state = context::<AppState>(cx).clone();
70 let id = path_param_segment(cx, "id").to_owned();53 let id = path_param_segment(cx, "id").to_owned();
@@ -84,7 +67,6 @@ async fn serve(cx: &Cx) -> Response {
84 67
85 let snippet = match state.store.get_snippet(&id).await {68 let snippet = match state.store.get_snippet(&id).await {
86 Ok(Some(snippet)) => snippet,69 Ok(Some(snippet)) => snippet,
87- // A missing snippet and a private one without a valid token look the same.
88 Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None),70 Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None),
89 Err(e) => {71 Err(e) => {
90 tracing::error!(error = %e, "snippet raw: lookup failed");72 tracing::error!(error = %e, "snippet raw: lookup failed");
@@ -110,12 +92,10 @@ async fn serve(cx: &Cx) -> Response {
110 };92 };
111 let etag = hex::encode(Sha256::digest(file.content.as_bytes()));93 let etag = hex::encode(Sha256::digest(file.content.as_bytes()));
112 let quoted = format!("\"{etag}\"");94 let quoted = format!("\"{etag}\"");
113- if if_none_match.is_some_and(|value| {95+ if if_none_match
114- value96+ .as_deref()
115- .split(',')97+ .is_some_and(|value| super::etag_matches(value, &quoted))
116- .map(str::trim)98+ {
117- .any(|c| c == "*" || c.strip_prefix("W/").unwrap_or(c) == quoted)
118- }) {
119 return finish(StatusCode::NOT_MODIFIED, Body::empty(), &etag, cache, None);99 return finish(StatusCode::NOT_MODIFIED, Body::empty(), &etag, cache, None);
120 }100 }
121 101
crates/forge-web-app/src/self_update.rsmodified+7 -72
@@ -1,12 +1,3 @@
1-//! Self-update: a green CI run of the forge's own repo replaces the running binary and restarts.
2-//!
3-//! Event-driven. `maybe_deploy` runs from the runner finish path when a job finishes. Nothing
4-//! polls. After the swap the process exits with `RESTART_EXIT_CODE`, and the systemd unit
5-//! (`Restart=on-failure`) starts the new binary.
6-//!
7-//! Runners update the same way. The claim route advertises the running binary's sha256 to a runner
8-//! of the same target, and `GET /api/v1/ci/runners/binary` serves the bytes.
9-
10 use std::path::{Path, PathBuf};1 use std::path::{Path, PathBuf};
11 use std::sync::OnceLock;2 use std::sync::OnceLock;
12 use std::sync::atomic::{AtomicBool, Ordering};3 use std::sync::atomic::{AtomicBool, Ordering};
@@ -14,6 +5,7 @@ use std::time::Duration;
14 5
15 use forge_core::ci::{CiRun, RunState};6 use forge_core::ci::{CiRun, RunState};
16 use forge_core::config::SelfUpdateConfig;7 use forge_core::config::SelfUpdateConfig;
8+use forge_core::token::sha256_reader;
17 use futures_util::StreamExt;9 use futures_util::StreamExt;
18 use futures_util::stream::BoxStream;10 use futures_util::stream::BoxStream;
19 use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue};11 use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue};
@@ -26,30 +18,21 @@ use topcoat::router::{Body, HeaderMap, StatusCode, response::Response};
26 use crate::state::AppState;18 use crate::state::AppState;
27 19
28 pub use forge_ci::proto::RESTART_EXIT_CODE;20 pub use forge_ci::proto::RESTART_EXIT_CODE;
29-/// Response header carrying the sha256 of the running binary, lowercase hex.
30 pub const SHA_HEADER: &str = "Forge-Binary-Sha256";21 pub const SHA_HEADER: &str = "Forge-Binary-Sha256";
31-/// Request header a runner sends with its `<arch>-<os>` target.
32 pub const TARGET_HEADER: &str = "Forge-Runner-Target";22 pub const TARGET_HEADER: &str = "Forge-Runner-Target";
33-/// How long the staged binary may take to answer `--version`.
34 const SANITY_TIMEOUT: Duration = Duration::from_secs(10);23 const SANITY_TIMEOUT: Duration = Duration::from_secs(10);
35 24
36-/// Serialises deploys. A deploy that finds another one running is skipped.
37 static DEPLOY_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());25 static DEPLOY_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
38-/// Wakes the server so it stops after a swap.
39 static RESTART: tokio::sync::Notify = tokio::sync::Notify::const_new();26 static RESTART: tokio::sync::Notify = tokio::sync::Notify::const_new();
40 static RESTART_REQUESTED: AtomicBool = AtomicBool::new(false);27 static RESTART_REQUESTED: AtomicBool = AtomicBool::new(false);
41 28
42-/// The running binary, hashed once at startup.
43 pub struct Running {29 pub struct Running {
44- /// The executable path, used to place the sibling `.prev`, `.bad` and staging files.
45 pub path: PathBuf,30 pub path: PathBuf,
46 pub sha256: String,31 pub sha256: String,
47 }32 }
48 33
49 static RUNNING: OnceLock<Option<Running>> = OnceLock::new();34 static RUNNING: OnceLock<Option<Running>> = OnceLock::new();
50 35
51-/// The running binary, hashed on first use. `None` if it cannot be read, which disables
52-/// advertising and serving, and deploys.
53 pub fn running() -> Option<&'static Running> {36 pub fn running() -> Option<&'static Running> {
54 RUNNING37 RUNNING
55 .get_or_init(|| match load_running() {38 .get_or_init(|| match load_running() {
@@ -67,12 +50,10 @@ pub fn running() -> Option<&'static Running> {
67 50
68 fn load_running() -> std::io::Result<Running> {51 fn load_running() -> std::io::Result<Running> {
69 let path = std::env::current_exe()?;52 let path = std::env::current_exe()?;
70- let sha256 = sha256_reader(std::fs::File::open(image_path())?)?;53+ let sha256 = sha256_reader(std::fs::File::open(image_path())?)?.1;
71 Ok(Running { path, sha256 })54 Ok(Running { path, sha256 })
72 }55 }
73 56
74-/// The file that holds the running image. On Linux that is `/proc/self/exe`, which still names the
75-/// old inode after a rename over the executable. Elsewhere it is the executable path.
76 fn image_path() -> PathBuf {57 fn image_path() -> PathBuf {
77 let proc_exe = PathBuf::from("/proc/self/exe");58 let proc_exe = PathBuf::from("/proc/self/exe");
78 if proc_exe.exists() {59 if proc_exe.exists() {
@@ -82,21 +63,15 @@ fn image_path() -> PathBuf {
82 }63 }
83 }64 }
84 65
85-/// Resolves once a swap has asked the server to stop.
86 pub async fn restart_requested() {66 pub async fn restart_requested() {
87 RESTART.notified().await;67 RESTART.notified().await;
88 }68 }
89 69
90-/// Asks the server to stop gracefully and exit with `RESTART_EXIT_CODE`, so the supervisor starts
91-/// the binary again. The same path a self-update swap takes, without a swap. Used by the admin
92-/// "Restart server" button.
93 pub fn request_restart() {70 pub fn request_restart() {
94 RESTART_REQUESTED.store(true, Ordering::SeqCst);71 RESTART_REQUESTED.store(true, Ordering::SeqCst);
95 RESTART.notify_one();72 RESTART.notify_one();
96 }73 }
97 74
98-/// An id that is new for every process start. A page that sees it change knows the server
99-/// restarted.
100 pub fn boot_id() -> &'static str {75 pub fn boot_id() -> &'static str {
101 static ID: OnceLock<String> = OnceLock::new();76 static ID: OnceLock<String> = OnceLock::new();
102 ID.get_or_init(|| {77 ID.get_or_init(|| {
@@ -107,24 +82,18 @@ pub fn boot_id() -> &'static str {
107 })82 })
108 }83 }
109 84
110-/// Whether a swap asked the process to exit with `RESTART_EXIT_CODE`.
111 pub fn restart_pending() -> bool {85 pub fn restart_pending() -> bool {
112 RESTART_REQUESTED.load(Ordering::SeqCst)86 RESTART_REQUESTED.load(Ordering::SeqCst)
113 }87 }
114 88
115-/// `<arch>-<os>` for this build, as a runner reports it in `Forge-Runner-Target`.
116 pub fn target() -> String {89 pub fn target() -> String {
117 format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS)90 format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS)
118 }91 }
119 92
120-/// Whether a runner's requested target is this build's target.
121 fn target_matches(requested: Option<&str>) -> bool {93 fn target_matches(requested: Option<&str>) -> bool {
122 requested == Some(target().as_str())94 requested == Some(target().as_str())
123 }95 }
124 96
125-/// Whether a finished run should deploy. Pure, so the rules can be tested. A run deploys only when
126-/// it is a successful push to the configured branch of the configured repo, and it is still the
127-/// newest run on that branch. Pull request runs (including fork runs) never deploy.
128 pub fn should_deploy(97 pub fn should_deploy(
129 cfg: &SelfUpdateConfig,98 cfg: &SelfUpdateConfig,
130 repo_full_name: &str,99 repo_full_name: &str,
@@ -140,8 +109,6 @@ pub fn should_deploy(
140 && newest_on_ref == Some(run.id.as_str())109 && newest_on_ref == Some(run.id.as_str())
141 }110 }
142 111
143-/// Why a candidate binary must not be installed, or `None` to install it. `bad_list` is the text
144-/// of `<exe>.bad`: one hex sha256 per line, `#` starts a comment.
145 pub fn skip_reason(candidate_sha: &str, running_sha: &str, bad_list: &str) -> Option<&'static str> {112 pub fn skip_reason(candidate_sha: &str, running_sha: &str, bad_list: &str) -> Option<&'static str> {
146 if candidate_sha.eq_ignore_ascii_case(running_sha) {113 if candidate_sha.eq_ignore_ascii_case(running_sha) {
147 return Some("same as the running binary");114 return Some("same as the running binary");
@@ -154,7 +121,6 @@ pub fn skip_reason(candidate_sha: &str, running_sha: &str, bad_list: &str) -> Op
154 listed.then_some("listed in the bad list")121 listed.then_some("listed in the bad list")
155 }122 }
156 123
157-/// `<name>.<suffix>` next to `exe`, for example `forge.prev`.
158 fn sibling(exe: &Path, suffix: &str) -> PathBuf {124 fn sibling(exe: &Path, suffix: &str) -> PathBuf {
159 let name = exe125 let name = exe
160 .file_name()126 .file_name()
@@ -163,7 +129,6 @@ fn sibling(exe: &Path, suffix: &str) -> PathBuf {
163 exe.with_file_name(format!("{name}.{suffix}"))129 exe.with_file_name(format!("{name}.{suffix}"))
164 }130 }
165 131
166-/// Called when a job finishes. Starts a deploy in the background when the run qualifies.
167 pub async fn maybe_deploy(state: &AppState, run: &CiRun) {132 pub async fn maybe_deploy(state: &AppState, run: &CiRun) {
168 let cfg = &state.config.self_update;133 let cfg = &state.config.self_update;
169 if !cfg.enabled || !matches!(run.state, RunState::Success) {134 if !cfg.enabled || !matches!(run.state, RunState::Success) {
@@ -198,8 +163,6 @@ pub async fn maybe_deploy(state: &AppState, run: &CiRun) {
198 tokio::spawn(async move { deploy(state, run).await });163 tokio::spawn(async move { deploy(state, run).await });
199 }164 }
200 165
201-/// Installs the run's artifact over the running binary and asks the server to restart. Logs and
202-/// returns on any failure, leaving the running binary in place.
203 pub async fn deploy(state: AppState, run: CiRun) {166 pub async fn deploy(state: AppState, run: CiRun) {
204 let Ok(_guard) = DEPLOY_LOCK.try_lock() else {167 let Ok(_guard) = DEPLOY_LOCK.try_lock() else {
205 tracing::info!(run_id = %run.id, "self-update: a deploy is already running, skipping");168 tracing::info!(run_id = %run.id, "self-update: a deploy is already running, skipping");
@@ -224,7 +187,6 @@ async fn deploy_inner(state: &AppState, run: &CiRun) -> Result<(), String> {
224 tracing::info!(run_id = %run.id, job = %cfg.job, "self-update: no such job in the run, skipping");187 tracing::info!(run_id = %run.id, job = %cfg.job, "self-update: no such job in the run, skipping");
225 return Ok(());188 return Ok(());
226 };189 };
227- // "dist_forge" was the old default; CI no longer uploads it, so it means the arch-named binary.
228 let configured = match cfg.artifact.as_str() {190 let configured = match cfg.artifact.as_str() {
229 "dist_forge" => "forge-{target}",191 "dist_forge" => "forge-{target}",
230 other => other,192 other => other,
@@ -246,7 +208,6 @@ async fn deploy_inner(state: &AppState, run: &CiRun) -> Result<(), String> {
246 .map_err(|e| e.to_string())?208 .map_err(|e| e.to_string())?
247 .ok_or("the artifact bytes are missing")?;209 .ok_or("the artifact bytes are missing")?;
248 210
249- // Stage next to the executable, so the final rename stays on one filesystem.
250 let staged = sibling(&running.path, "new");211 let staged = sibling(&running.path, "new");
251 let sha = match write_staged(read.stream, &staged).await {212 let sha = match write_staged(read.stream, &staged).await {
252 Ok(sha) => sha,213 Ok(sha) => sha,
@@ -288,8 +249,6 @@ async fn deploy_inner(state: &AppState, run: &CiRun) -> Result<(), String> {
288 Ok(())249 Ok(())
289 }250 }
290 251
291-/// Streams the artifact to `path`, hashing as it goes. The file is executable and synced before
292-/// this returns. Returns the sha256 in lowercase hex.
293 async fn write_staged(252 async fn write_staged(
294 mut stream: BoxStream<'static, std::io::Result<bytes::Bytes>>,253 mut stream: BoxStream<'static, std::io::Result<bytes::Bytes>>,
295 path: &Path,254 path: &Path,
@@ -313,7 +272,6 @@ async fn write_staged(
313 Ok(hex::encode(hasher.finalize()))272 Ok(hex::encode(hasher.finalize()))
314 }273 }
315 274
316-/// Runs `<staged> --version` with a timeout. Only exit 0 passes.
317 async fn sanity_check(path: &Path) -> Result<(), String> {275 async fn sanity_check(path: &Path) -> Result<(), String> {
318 use std::process::Stdio;276 use std::process::Stdio;
319 277
@@ -333,8 +291,6 @@ async fn sanity_check(path: &Path) -> Result<(), String> {
333 }291 }
334 }292 }
335 293
336-/// Keeps the current binary as `<exe>.prev` (a hard link when possible), then renames `staged`
337-/// over `exe`.
338 fn swap(exe: &Path, staged: &Path) -> Result<(), String> {294 fn swap(exe: &Path, staged: &Path) -> Result<(), String> {
339 let prev = sibling(exe, "prev");295 let prev = sibling(exe, "prev");
340 if prev.exists() {296 if prev.exists() {
@@ -346,8 +302,6 @@ fn swap(exe: &Path, staged: &Path) -> Result<(), String> {
346 std::fs::rename(staged, exe).map_err(|e| format!("cannot replace the binary: {e}"))302 std::fs::rename(staged, exe).map_err(|e| format!("cannot replace the binary: {e}"))
347 }303 }
348 304
349-/// Whether a claim response should advertise the binary: self-update is on and the runner asked
350-/// for this target. Adds `Forge-Binary-Sha256` to a 200 or 204 response.
351 pub fn advertise(state: &AppState, request: &HeaderMap, res: &mut Response) {305 pub fn advertise(state: &AppState, request: &HeaderMap, res: &mut Response) {
352 if !state.config.self_update.enabled {306 if !state.config.self_update.enabled {
353 return;307 return;
@@ -367,18 +321,16 @@ pub fn advertise(state: &AppState, request: &HeaderMap, res: &mut Response) {
367 }321 }
368 }322 }
369 323
370-/// The running binary as a streamed response, with its sha256. The caller checks auth and that324+const BODY_FRAME_BYTES: usize = 64 * 1024;
371-/// self-update is enabled. `Err` when the binary cannot be read.325+
372 pub async fn binary_response() -> Result<Response, String> {326 pub async fn binary_response() -> Result<Response, String> {
373 let running = running().ok_or("the running binary was not hashed at startup")?;327 let running = running().ok_or("the running binary was not hashed at startup")?;
374 let file = tokio::fs::File::open(image_path())328 let file = tokio::fs::File::open(image_path())
375 .await329 .await
376 .map_err(|e| e.to_string())?;330 .map_err(|e| e.to_string())?;
377 let len = file.metadata().await.map_err(|e| e.to_string())?.len();331 let len = file.metadata().await.map_err(|e| e.to_string())?.len();
378- // 64 KiB frames, not ReaderStream's 4 KiB default: the binary is ~1 GB, and 4 KiB frames mean332+ let frames = ReaderStream::with_capacity(file, BODY_FRAME_BYTES)
379- // ~250k body frames to push through hyper for every download.333+ .map(|chunk| chunk.map(http_body::Frame::data));
380- let frames =
381- ReaderStream::with_capacity(file, 64 * 1024).map(|chunk| chunk.map(http_body::Frame::data));
382 let mut res = Response::new(Body::new(StreamBody::new(frames)));334 let mut res = Response::new(Body::new(StreamBody::new(frames)));
383 let headers = res.headers_mut();335 let headers = res.headers_mut();
384 headers.insert(336 headers.insert(
@@ -392,19 +344,6 @@ pub async fn binary_response() -> Result<Response, String> {
392 Ok(res)344 Ok(res)
393 }345 }
394 346
395-fn sha256_reader(mut reader: impl std::io::Read) -> std::io::Result<String> {
396- let mut hasher = Sha256::new();
397- let mut buf = vec![0u8; 64 * 1024];
398- loop {
399- let n = reader.read(&mut buf)?;
400- if n == 0 {
401- break;
402- }
403- hasher.update(&buf[..n]);
404- }
405- Ok(hex::encode(hasher.finalize()))
406-}
407-
408 #[cfg(test)]347 #[cfg(test)]
409 mod tests {348 mod tests {
410 use super::*;349 use super::*;
@@ -437,7 +376,6 @@ mod tests {
437 }376 }
438 }377 }
439 378
440- /// A push run of the deploy branch that is still the newest run.
441 fn good() -> CiRun {379 fn good() -> CiRun {
442 run("push", "refs/heads/main", RunState::Success, None)380 run("push", "refs/heads/main", RunState::Success, None)
443 }381 }
@@ -448,7 +386,6 @@ mod tests {
448 let mut off = cfg();386 let mut off = cfg();
449 off.enabled = false;387 off.enabled = false;
450 let failed = |state| run("push", "refs/heads/main", state, None);388 let failed = |state| run("push", "refs/heads/main", state, None);
451- // (case, config, repo, run, latest run id, want deploy)
452 let cases = vec![389 let cases = vec![
453 (390 (
454 "good push",391 "good push",
@@ -504,7 +441,6 @@ mod tests {
504 Some("run-7"),441 Some("run-7"),
505 false,442 false,
506 ),443 ),
507- // Even if a PR run were stored on the branch ref, the trigger and pull number exclude it.
508 (444 (
509 "pull request on branch ref",445 "pull request on branch ref",
510 &on,446 &on,
@@ -617,7 +553,6 @@ mod tests {
617 skip_reason("1111", "ffff", bad),553 skip_reason("1111", "ffff", bad),
618 Some("listed in the bad list")554 Some("listed in the bad list")
619 );555 );
620- // A comment line is not a sha.
621 assert_eq!(skip_reason("rolled", "ffff", bad), None);556 assert_eq!(skip_reason("rolled", "ffff", bad), None);
622 assert_eq!(skip_reason("3333", "ffff", bad), None);557 assert_eq!(skip_reason("3333", "ffff", bad), None);
623 }558 }
@@ -631,7 +566,7 @@ mod tests {
631 566
632 #[test]567 #[test]
633 fn sha256_of_known_bytes() {568 fn sha256_of_known_bytes() {
634- let digest = sha256_reader(&b"abc"[..]).unwrap();569+ let digest = sha256_reader(&b"abc"[..]).unwrap().1;
635 assert_eq!(570 assert_eq!(
636 digest,571 digest,
637 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"572 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
crates/forge-web-app/src/signatures.rsmodified+5 -22
@@ -298,22 +298,16 @@ async fn gpg_with_input(state: &AppState, args: &[&str], armored: &str) -> Resul
298 }298 }
299 }299 }
300 300
301-/// Creates the forge keyring directory, mode 0700 on unix.301+/// Creates the forge keyring directory, mode 0700.
302 async fn ensure_gnupg_home(state: &AppState) -> std::io::Result<()> {302 async fn ensure_gnupg_home(state: &AppState) -> std::io::Result<()> {
303 let home = gnupg_home(state);303 let home = gnupg_home(state);
304 tokio::fs::create_dir_all(&home).await?;304 tokio::fs::create_dir_all(&home).await?;
305- set_private_dir(&home).await305+ set_mode(&home, 0o700).await
306 }306 }
307 307
308-#[cfg(unix)]308+async fn set_mode(path: &Path, mode: u32) -> std::io::Result<()> {
309-async fn set_private_dir(path: &Path) -> std::io::Result<()> {
310 use std::os::unix::fs::PermissionsExt;309 use std::os::unix::fs::PermissionsExt;
311- tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).await310+ tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).await
312-}
313-
314-#[cfg(not(unix))]
315-async fn set_private_dir(_path: &Path) -> std::io::Result<()> {
316- Ok(())
317 }311 }
318 312
319 /// Reads an armored public key, imports it into the forge keyring and returns its primary313 /// Reads an armored public key, imports it into the forge keyring and returns its primary
@@ -479,22 +473,11 @@ pub async fn rebuild_allowed_signers(state: &AppState) -> Result<(), forge_core:
479 TMP_SEQ.fetch_add(1, Ordering::Relaxed)473 TMP_SEQ.fetch_add(1, Ordering::Relaxed)
480 ));474 ));
481 tokio::fs::write(&tmp, lines.as_bytes()).await?;475 tokio::fs::write(&tmp, lines.as_bytes()).await?;
482- set_private(&tmp).await?;476+ set_mode(&tmp, 0o600).await?;
483 tokio::fs::rename(&tmp, &target).await?;477 tokio::fs::rename(&tmp, &target).await?;
484 Ok(())478 Ok(())
485 }479 }
486 480
487-#[cfg(unix)]
488-async fn set_private(path: &Path) -> std::io::Result<()> {
489- use std::os::unix::fs::PermissionsExt;
490- tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).await
491-}
492-
493-#[cfg(not(unix))]
494-async fn set_private(_path: &Path) -> std::io::Result<()> {
495- Ok(())
496-}
497-
498 /// Called after a user's keys were added or removed. Rebuilds the SSH allowed-signers file and481 /// Called after a user's keys were added or removed. Rebuilds the SSH allowed-signers file and
499 /// drops the cached verdicts those keys can change.482 /// drops the cached verdicts those keys can change.
500 pub async fn on_keys_changed(state: &AppState, user_id: &str) {483 pub async fn on_keys_changed(state: &AppState, user_id: &str) {
crates/forge-web-app/src/ssh_backend.rsmodified+1 -9
@@ -1,9 +1,9 @@
1 //! `impl forge_ssh::GitBackend` for forge: key lookup, authz and git process construction.1 //! `impl forge_ssh::GitBackend` for forge: key lookup, authz and git process construction.
2 2
3 use std::path::PathBuf;3 use std::path::PathBuf;
4-use std::time::{SystemTime, UNIX_EPOCH};
5 4
6 use forge_core::lfs_token::{self, LfsOp};5 use forge_core::lfs_token::{self, LfsOp};
6+use forge_core::time::now_unix;
7 use forge_core::{Repo, User};7 use forge_core::{Repo, User};
8 use forge_git::GitService;8 use forge_git::GitService;
9 use forge_ssh::{GitBackend, LfsOperation, RepoPath};9 use forge_ssh::{GitBackend, LfsOperation, RepoPath};
@@ -64,14 +64,6 @@ impl SshBackend {
64 }64 }
65 }65 }
66 66
67-fn now_unix() -> i64 {
68- SystemTime::now()
69- .duration_since(UNIX_EPOCH)
70- .ok()
71- .and_then(|d| i64::try_from(d.as_secs()).ok())
72- .unwrap_or(0)
73-}
74-
75 impl GitBackend for SshBackend {67 impl GitBackend for SshBackend {
76 async fn authenticate_key(&self, _algorithm: &str, key_blob: &[u8]) -> Option<String> {68 async fn authenticate_key(&self, _algorithm: &str, key_blob: &[u8]) -> Option<String> {
77 let key = match self.state.store.ssh_key_by_blob(key_blob).await {69 let key = match self.state.store.ssh_key_by_blob(key_blob).await {
crates/forge-web-app/src/test_support/fixture.rsmodified+1 -11
@@ -66,7 +66,7 @@ impl Fixture {
66 .create_repo(&owner.id, REPO, "", visibility, "main")66 .create_repo(&owner.id, REPO, "", visibility, "main")
67 .await67 .await
68 .unwrap();68 .unwrap();
69- let bare = repo_dir(&dir, &repo.id);69+ let bare = forge_git::repo::repo_path(&dir, &repo.id).unwrap();
70 std::fs::create_dir_all(bare.parent().unwrap()).unwrap();70 std::fs::create_dir_all(bare.parent().unwrap()).unwrap();
71 git(71 git(
72 &dir,72 &dir,
@@ -142,16 +142,6 @@ impl Fixture {
142 }142 }
143 }143 }
144 144
145-/// Same layout as `forge_git::repo::repo_path`, computed here so the test can create it.
146-fn repo_dir(data_dir: &Path, repo_id: &str) -> PathBuf {
147- let id = repo_id.to_ascii_lowercase();
148- data_dir
149- .join("repos")
150- .join(&id[0..2])
151- .join(&id[2..4])
152- .join(format!("{id}.git"))
153-}
154-
155 /// GET through the router: `(status, headers, body)`.145 /// GET through the router: `(status, headers, body)`.
156 pub async fn get(router: &Router, uri: &str) -> (u16, http::HeaderMap, Vec<u8>) {146 pub async fn get(router: &Router, uri: &str) -> (u16, http::HeaderMap, Vec<u8>) {
157 let req = Request::builder()147 let req = Request::builder()
crates/forge-web-app/src/test_support/http.rsadded+16 -0
@@ -0,0 +1,16 @@
1+use forge_core::Store;
2+use forge_core::token::{generate_token, hash_token};
3+
4+pub async fn token_for(store: &Store, user_id: &str, scopes: &[&str]) -> String {
5+ let raw = generate_token();
6+ let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect();
7+ store
8+ .create_token(user_id, "test", &hash_token(&raw), &scopes, None)
9+ .await
10+ .expect("token");
11+ raw
12+}
13+
14+pub fn bearer(raw: &str) -> String {
15+ format!("Bearer {raw}")
16+}
crates/forge-web-app/src/test_support/mod.rsmodified+1 -0
@@ -4,6 +4,7 @@
4 //! or state field is added in one place.4 //! or state field is added in one place.
5 5
6 pub mod fixture;6 pub mod fixture;
7+pub mod http;
7 8
8 use std::path::Path;9 use std::path::Path;
9 use std::sync::Arc;10 use std::sync::Arc;
crates/forge-web-app/src/views/diff.rsmodified+6 -12
@@ -24,8 +24,8 @@ use crate::i18n::browse as b;
24 use crate::i18n::code::{self as g, K};24 use crate::i18n::code::{self as g, K};
25 use crate::i18n::pulls_review::{self as pr_g, K as PrK};25 use crate::i18n::pulls_review::{self as pr_g, K as PrK};
26 use crate::state::AppState;26 use crate::state::AppState;
27-use crate::views::review_thread::{ThreadCtx, review_thread_in};27+use crate::views::enc;
28-use crate::views::url_path;28+use crate::views::review_thread::{ThreadCtx, review_thread};
29 29
30 /// Key of the diff view: `split` or `unified`.30 /// Key of the diff view: `split` or `unified`.
31 pub const DIFF_VIEW: &str = "diff_view";31 pub const DIFF_VIEW: &str = "diff_view";
@@ -402,7 +402,7 @@ impl FileView {
402 let blob_path = file.new_path.as_ref().or(file.old_path.as_ref());402 let blob_path = file.new_path.as_ref().or(file.old_path.as_ref());
403 let blob_href = match (blob_commit, blob_path) {403 let blob_href = match (blob_commit, blob_path) {
404 (Some(commit), Some(path)) => {404 (Some(commit), Some(path)) => {
405- format!("/{owner}/{repo}/blob/{commit}/{}", url_path(path))405+ format!("/{owner}/{repo}/blob/{commit}/{}", enc(path))
406 }406 }
407 _ => String::new(),407 _ => String::new(),
408 };408 };
@@ -532,14 +532,8 @@ pub async fn diff_section(
532 .files532 .files
533 .iter()533 .iter()
534 .enumerate()534 .enumerate()
535- .map(|(i, file)| {
536- (
537- i,
538- FileView::new(i, file, oid, parent, owner, repo, lang, &mut comments),
539- )
540- })
541 .filter(|(i, _)| opts.only.is_none_or(|only| only == *i))535 .filter(|(i, _)| opts.only.is_none_or(|only| only == *i))
542- .map(|(_, file)| file)536+ .map(|(i, file)| FileView::new(i, file, oid, parent, owner, repo, lang, &mut comments))
543 .collect();537 .collect();
544 let alone = opts.only.is_some();538 let alone = opts.only.is_some();
545 if split {539 if split {
@@ -750,7 +744,7 @@ async fn diff_split_line(cx: &Cx, row: SplitRow, lang: Lang, anchored: bool) ->
750 <td colspan=(span)>744 <td colspan=(span)>
751 <div class="review-threads">745 <div class="review-threads">
752 for thread in threads.into_iter() {746 for thread in threads.into_iter() {
753- review_thread_in(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files")747+ review_thread(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files")
754 }748 }
755 if let Some(form) = form {749 if let Some(form) = form {
756 inline_comment_form(form: form, lang: lang)750 inline_comment_form(form: form, lang: lang)
@@ -801,7 +795,7 @@ async fn diff_line(cx: &Cx, row: DiffRow, lang: Lang) -> Result<impl View> {
801 <td colspan=(span)>795 <td colspan=(span)>
802 <div class="review-threads">796 <div class="review-threads">
803 for thread in threads.into_iter() {797 for thread in threads.into_iter() {
804- review_thread_in(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files")798+ review_thread(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files")
805 }799 }
806 if let Some(form) = form {800 if let Some(form) = form {
807 inline_comment_form(form: form, lang: lang)801 inline_comment_form(form: form, lang: lang)
crates/forge-web-app/src/views/heatmap.rsmodified+18 -43
@@ -15,7 +15,7 @@ use forge_core::time::stamp_to_unix;
15 use topcoat::Result;15 use topcoat::Result;
16 use topcoat::view::{View, component, view};16 use topcoat::view::{View, component, view};
17 17
18-use super::{civil_from_days, now_unix, relative_time};18+use super::{civil_from_days, days_from_civil, now_unix, relative_time};
19 use crate::i18n::Lang;19 use crate::i18n::Lang;
20 use crate::i18n::misc::{self as g, K};20 use crate::i18n::misc::{self as g, K};
21 21
@@ -61,8 +61,6 @@ pub struct Calendar {
61 pub longest_streak: u64,61 pub longest_streak: u64,
62 /// The highest count on a single day.62 /// The highest count on a single day.
63 pub best_day: u64,63 pub best_day: u64,
64- /// Today's count.
65- pub today_count: u64,
66 }64 }
67 65
68 /// Level for a day's count: 0 for none, then fixed buckets 1-3 (1), 4-7 (2), 8-12 (3) and 13 or66 /// Level for a day's count: 0 for none, then fixed buckets 1-3 (1), 4-7 (2), 8-12 (3) and 13 or
@@ -143,7 +141,6 @@ pub fn build(counts: &[(String, u32)], today: (i64, i64, i64)) -> Calendar {
143 current_streak,141 current_streak,
144 longest_streak: longest,142 longest_streak: longest,
145 best_day,143 best_day,
146- today_count,
147 }144 }
148 }145 }
149 146
@@ -161,18 +158,6 @@ fn parse_date(text: &str) -> Option<i64> {
161 (civil_from_days(days) == (year, month, day)).then_some(days)158 (civil_from_days(days) == (year, month, day)).then_some(days)
162 }159 }
163 160
164-/// Days since 1970-01-01 for `(year, month, day)`. Howard Hinnant's days-from-civil algorithm, the
165-/// inverse of `civil_from_days`.
166-fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
167- let y = if month <= 2 { year - 1 } else { year };
168- let era = y.div_euclid(400);
169- let yoe = y - era * 400;
170- let mp = (month + 9) % 12;
171- let doy = (153 * mp + 2) / 5 + day - 1;
172- let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
173- era * 146_097 + doe - 719_468
174-}
175-
176 /// Monday = 0 through Sunday = 6. 1970-01-01 was a Thursday.161 /// Monday = 0 through Sunday = 6. 1970-01-01 was a Thursday.
177 fn weekday(days: i64) -> u8 {162 fn weekday(days: i64) -> u8 {
178 (days + 3).rem_euclid(7) as u8163 (days + 3).rem_euclid(7) as u8
@@ -275,6 +260,20 @@ fn day_row(lang: Lang, item: &ContributionItem, now: i64) -> DayRow {
275 }260 }
276 }261 }
277 262
263+#[component]
264+async fn day_line(cx: &Cx, row: DayRow) -> Result<impl View> {
265+ Ok(view! {
266+ <span>(row.before.as_str())</span>
267+ if let Some(href) = row.href {
268+ <a href=(href.as_str())>(row.link.as_str())</a>
269+ } else {
270+ <span>(row.link.as_str())</span>
271+ }
272+ <span>(row.after.as_str())</span>
273+ <time data-rel="true" datetime=(row.updated.as_str())>(row.relative.as_str())</time>
274+ })
275+}
276+
278 /// Items split into runs that share a key, in the order each key is first met. Items without a277 /// Items split into runs that share a key, in the order each key is first met. Items without a
279 /// key (`None`) are each their own run.278 /// key (`None`) are each their own run.
280 fn group_first_seen<'a>(279 fn group_first_seen<'a>(
@@ -510,39 +509,18 @@ pub async fn contribution_calendar(
510 for entry in day.rows.into_iter() {509 for entry in day.rows.into_iter() {
511 if entry.pushes.is_empty() {510 if entry.pushes.is_empty() {
512 <li>511 <li>
513- <span>(entry.row.before.as_str())</span>512+ day_line(row: entry.row)
514- if let Some(href) = entry.row.href {
515- <a href=(href.as_str())>(entry.row.link.as_str())</a>
516- } else {
517- <span>(entry.row.link.as_str())</span>
518- }
519- <span>(entry.row.after.as_str())</span>
520- <time data-rel="true" datetime=(entry.row.updated.as_str())>(entry.row.relative.as_str())</time>
521 </li>513 </li>
522 } else {514 } else {
523 <li class="day-group">515 <li class="day-group">
524 <details>516 <details>
525 <summary>517 <summary>
526- <span>(entry.row.before.as_str())</span>518+ day_line(row: entry.row)
527- if let Some(href) = entry.row.href {
528- <a href=(href.as_str())>(entry.row.link.as_str())</a>
529- } else {
530- <span>(entry.row.link.as_str())</span>
531- }
532- <span>(entry.row.after.as_str())</span>
533- <time data-rel="true" datetime=(entry.row.updated.as_str())>(entry.row.relative.as_str())</time>
534 </summary>519 </summary>
535 <ul>520 <ul>
536 for push in entry.pushes.into_iter() {521 for push in entry.pushes.into_iter() {
537 <li>522 <li>
538- <span>(push.before.as_str())</span>523+ day_line(row: push)
539- if let Some(href) = push.href {
540- <a href=(href.as_str())>(push.link.as_str())</a>
541- } else {
542- <span>(push.link.as_str())</span>
543- }
544- <span>(push.after.as_str())</span>
545- <time data-rel="true" datetime=(push.updated.as_str())>(push.relative.as_str())</time>
546 </li>524 </li>
547 }525 }
548 </ul>526 </ul>
@@ -586,7 +564,6 @@ mod tests {
586 assert_eq!(cal.current_streak, 0);564 assert_eq!(cal.current_streak, 0);
587 assert_eq!(cal.longest_streak, 0);565 assert_eq!(cal.longest_streak, 0);
588 assert_eq!(cal.best_day, 0);566 assert_eq!(cal.best_day, 0);
589- assert_eq!(cal.today_count, 0);
590 assert!(cal.weeks.iter().flatten().flatten().all(|d| d.level == 0));567 assert!(cal.weeks.iter().flatten().flatten().all(|d| d.level == 0));
591 }568 }
592 569
@@ -598,7 +575,6 @@ mod tests {
598 );575 );
599 assert_eq!(cal.current_streak, 3);576 assert_eq!(cal.current_streak, 3);
600 assert_eq!(cal.longest_streak, 3);577 assert_eq!(cal.longest_streak, 3);
601- assert_eq!(cal.today_count, 5);
602 assert_eq!(cal.total, 8);578 assert_eq!(cal.total, 8);
603 }579 }
604 580
@@ -608,7 +584,6 @@ mod tests {
608 &counts(&[("2026-10-13", 1), ("2026-10-14", 1), ("2026-10-15", 1)]),584 &counts(&[("2026-10-13", 1), ("2026-10-14", 1), ("2026-10-15", 1)]),
609 TODAY,585 TODAY,
610 );586 );
611- assert_eq!(cal.today_count, 0);
612 assert_eq!(cal.current_streak, 3);587 assert_eq!(cal.current_streak, 3);
613 }588 }
614 589
crates/forge-web-app/src/views/mod.rsmodified+13 -91
@@ -135,6 +135,7 @@ fn percent_decode(s: &str) -> String {
135 while i < bytes.len() {135 while i < bytes.len() {
136 if bytes[i] == b'%'136 if bytes[i] == b'%'
137 && let Some(hex) = s.get(i + 1..i + 3)137 && let Some(hex) = s.get(i + 1..i + 3)
138+ && hex.bytes().all(|b| b.is_ascii_hexdigit())
138 && let Ok(byte) = u8::from_str_radix(hex, 16)139 && let Ok(byte) = u8::from_str_radix(hex, 16)
139 {140 {
140 out.push(byte);141 out.push(byte);
@@ -196,7 +197,6 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str
196 let Some(owner) = parts.first() else {197 let Some(owner) = parts.first() else {
197 return Vec::new();198 return Vec::new();
198 };199 };
199- // The page's own name: the part of its title after the last " · ", when there is one.
200 let titled = title.rsplit_once(" · ").map(|(_, last)| last.to_owned());200 let titled = title.rsplit_once(" · ").map(|(_, last)| last.to_owned());
201 match parts201 match parts
202 .iter()202 .iter()
@@ -210,10 +210,7 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str
210 Some("/snippets".to_owned()),210 Some("/snippets".to_owned()),
211 )];211 )];
212 match rest {212 match rest {
213- // A snippet's own page is named by its title.
214 [] => segments.push((title.to_owned(), None)),213 [] => segments.push((title.to_owned(), None)),
215- // A page under a snippet goes back to the snippet, then names its step. The revisions
216- // page is titled by the snippet; the edit page by what it does.
217 [.., last] => {214 [.., last] => {
218 let back = if *last == "revisions" {215 let back = if *last == "revisions" {
219 title.to_owned()216 title.to_owned()
@@ -249,12 +246,8 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str
249 segments.push((crumb_label(part), Some(repo_href(owner, repo, "tree", &at))));246 segments.push((crumb_label(part), Some(repo_href(owner, repo, "tree", &at))));
250 }247 }
251 }248 }
252- // The repo's home: the repo name is the last segment already.
253 [] => {}249 [] => {}
254 [kind, rest @ ..] => {250 [kind, rest @ ..] => {
255- // Titles read "owner/repo · Page": the path bar has the repo already. A page titled by
256- // the repo alone is named by its route. A title ending in the repo plus a word
257- // ("Install · owner/repo wiki") reads by the part before it.
258 let full = format!("{owner}/{repo}");251 let full = format!("{owner}/{repo}");
259 let mut tail = title.rsplit(" · ");252 let mut tail = title.rsplit(" · ");
260 let named = match tail.next() {253 let named = match tail.next() {
@@ -269,7 +262,6 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str
269 kind.as_str()262 kind.as_str()
270 };263 };
271 match (repo_section_label(lang, section), rest) {264 match (repo_section_label(lang, section), rest) {
272- // Files at one commit, from the home page's timeline: under that commit.
273 (None, [oid]) if kind == "scrub" => {265 (None, [oid]) if kind == "scrub" => {
274 let short: String = oid.chars().take(7).collect();266 let short: String = oid.chars().take(7).collect();
275 segments.push((267 segments.push((
@@ -279,7 +271,6 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str
279 segments.push((short, Some(repo_href(owner, repo, "commit", oid))));271 segments.push((short, Some(repo_href(owner, repo, "commit", oid))));
280 segments.push((step_label(lang, "files"), None));272 segments.push((step_label(lang, "files"), None));
281 }273 }
282- // Compare and search: their word, then what is compared.
283 (None, rest) if matches!(kind.as_str(), "compare" | "search") => {274 (None, rest) if matches!(kind.as_str(), "compare" | "search") => {
284 let word = if kind == "compare" {275 let word = if kind == "compare" {
285 s(lang, "Compare", "Karşılaştır")276 s(lang, "Compare", "Karşılaştır")
@@ -294,7 +285,6 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str
294 segments.push((rest.join("/"), None));285 segments.push((rest.join("/"), None));
295 }286 }
296 }287 }
297- // A section's own page, or a word that is no section: one segment.
298 (None, _) | (Some(_), []) => {288 (None, _) | (Some(_), []) => {
299 let page = named.unwrap_or_else(|| {289 let page = named.unwrap_or_else(|| {
300 parts[2..]290 parts[2..]
@@ -322,8 +312,6 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str
322 format!("#{item}"),312 format!("#{item}"),
323 Some(repo_href(owner, repo, section, item)),313 Some(repo_href(owner, repo, section, item)),
324 ));314 ));
325- // The step, by its word: an edit history ends in an id, so its
326- // word is History; a comment's edit is Edit.
327 let step = if rest.iter().any(|part| part == "history") {315 let step = if rest.iter().any(|part| part == "history") {
328 "history"316 "history"
329 } else {317 } else {
@@ -554,8 +542,6 @@ pub async fn shell(
554 #[default] child: Child<'_>,542 #[default] child: Child<'_>,
555 ) -> Result<impl View> {543 ) -> Result<impl View> {
556 let full_title = format!("{title} \u{b7} forge");544 let full_title = format!("{title} \u{b7} forge");
557- // The unread count, the profile corner's inbox counts, their CI runs and the items waiting on
558- // them. Signed-in only.
559 let (unread, inbox, runs) = match viewer {545 let (unread, inbox, runs) = match viewer {
560 Some((user, _)) => match try_context::<AppState>(cx) {546 Some((user, _)) => match try_context::<AppState>(cx) {
561 Some(state) => (547 Some(state) => (
@@ -568,14 +554,9 @@ pub async fn shell(
568 None => (0, InboxKinds::default(), no_runs()),554 None => (0, InboxKinds::default(), no_runs()),
569 };555 };
570 let signed_in = viewer.is_some();556 let signed_in = viewer.is_some();
571- // Both kinds of visitor post to `/-/theme`. Signed-in users send their CSRF token and get the
572- // stored preference saved. Anonymous visitors get the cookie. Either way the browser comes
573- // back to the page it was on.
574 let theme_csrf = viewer.map(|(_, session)| session.csrf_token.clone());557 let theme_csrf = viewer.map(|(_, session)| session.csrf_token.clone());
575 let back = uri(cx).path_and_query().map(|p| p.as_str().to_owned());558 let back = uri(cx).path_and_query().map(|p| p.as_str().to_owned());
576 let lang = i18n::lang(cx, viewer.map(|(user, _)| user));559 let lang = i18n::lang(cx, viewer.map(|(user, _)| user));
577- // A signed-in viewer's account preferences, read once for the banner, the tree width and the
578- // profile corner. Signed-out visitors keep theirs in the browser.
579 let prefs = match (viewer, try_context::<AppState>(cx)) {560 let prefs = match (viewer, try_context::<AppState>(cx)) {
580 (Some((user, _)), Some(state)) => Some(state.store.user_prefs(&user.id).await?),561 (Some((user, _)), Some(state)) => Some(state.store.user_prefs(&user.id).await?),
581 _ => None,562 _ => None,
@@ -584,7 +565,6 @@ pub async fn shell(
584 let sound_attr = sound_attr(prefs.as_ref());565 let sound_attr = sound_attr(prefs.as_ref());
585 let banner_back = back.clone().unwrap_or_else(|| "/".to_owned());566 let banner_back = back.clone().unwrap_or_else(|| "/".to_owned());
586 let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss);567 let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss);
587- // The admin area and the user settings swap the global links for their own list. Signed-in only.
588 let section = if signed_in {568 let section = if signed_in {
589 section_for(lang, uri(cx).path())569 section_for(lang, uri(cx).path())
590 } else {570 } else {
@@ -592,12 +572,8 @@ pub async fn shell(
592 };572 };
593 let width = page_width(uri(cx).path());573 let width = page_width(uri(cx).path());
594 let theme_attr = crate::theme::data_theme(cx, viewer.map(|(user, _)| user));574 let theme_attr = crate::theme::data_theme(cx, viewer.map(|(user, _)| user));
595- // The relative-time wording and the server's clock, for nav.js to keep `<time data-rel>` labels current.
596 let rel_words_attr = rel_words(lang);575 let rel_words_attr = rel_words(lang);
597 let rel_now_attr = now_unix().to_string();576 let rel_now_attr = now_unix().to_string();
598- // Always set, defaults included, so a page never keeps the colours of the one before it.
599- // Each of the four choices is resolved on its own, so an id that is no longer offered falls
600- // back to its default.
601 let (stored_accent_light, stored_accent_dark, stored_base_light, stored_base_dark) =577 let (stored_accent_light, stored_accent_dark, stored_base_light, stored_base_dark) =
602 match viewer {578 match viewer {
603 Some((user, _)) => (579 Some((user, _)) => (
@@ -613,25 +589,20 @@ pub async fn shell(
613 crate::accent_palette::BASE_DEFAULT,589 crate::accent_palette::BASE_DEFAULT,
614 ),590 ),
615 };591 };
616- // A `hue-N` choice passes through as itself; an id forge does not offer shows the default.
617 let accent_light_id = crate::accent::accent_id(stored_accent_light);592 let accent_light_id = crate::accent::accent_id(stored_accent_light);
618 let accent_dark_id = crate::accent::accent_id(stored_accent_dark);593 let accent_dark_id = crate::accent::accent_id(stored_accent_dark);
619 let base_light_id = crate::accent::base_id(stored_base_light);594 let base_light_id = crate::accent::base_id(stored_base_light);
620 let base_dark_id = crate::accent::base_id(stored_base_dark);595 let base_dark_id = crate::accent::base_id(stored_base_dark);
621- // The stylesheet that styles the hue choices, when there is one. The presets need none.
622 let custom_css = crate::accent::custom_css_href(596 let custom_css = crate::accent::custom_css_href(
623 accent_light_id,597 accent_light_id,
624 accent_dark_id,598 accent_dark_id,
625 base_light_id,599 base_light_id,
626 base_dark_id,600 base_dark_id,
627 );601 );
628- // The side of the shell sidebar: `right` only when stored so, `left` otherwise.
629 let sidebar_side = match viewer {602 let sidebar_side = match viewer {
630 Some((user, _)) if user.sidebar_side == "right" => "right",603 Some((user, _)) if user.sidebar_side == "right" => "right",
631 _ => "left",604 _ => "left",
632 };605 };
633- // The stored preference, "auto" included, drives the button: its icon, its label and the
634- // value it posts (the next preference in the cycle auto, light, dark).
635 let theme_pref = crate::theme::preference(cx, viewer.map(|(user, _)| user));606 let theme_pref = crate::theme::preference(cx, viewer.map(|(user, _)| user));
636 let next_theme = theme_pref.next().as_str();607 let next_theme = theme_pref.next().as_str();
637 let theme_state = match theme_pref {608 let theme_state = match theme_pref {
@@ -653,10 +624,7 @@ pub async fn shell(
653 let palette_label = br::t(lang, br::K::PaletteOpen).to_owned();624 let palette_label = br::t(lang, br::K::PaletteOpen).to_owned();
654 let explore_label = t(lang, Key::Explore);625 let explore_label = t(lang, Key::Explore);
655 let home_label = o::t(lang, OK::Home);626 let home_label = o::t(lang, OK::Home);
656- // The path bar: one segment per part of the request path, the last one unlinked.
657 let mut segments = path_segments(lang, uri(cx).path(), title);627 let mut segments = path_segments(lang, uri(cx).path(), title);
658- // A page with no place of its own in the path, such as settings, names its section and itself.
659- // A page below one of the section's tabs (an account under Users) names that tab too.
660 if segments.is_empty() {628 if segments.is_empty() {
661 if let Some(section) = &section {629 if let Some(section) = &section {
662 let first = section.items.first().map(|item| item.href.clone());630 let first = section.items.first().map(|item| item.href.clone());
@@ -673,7 +641,6 @@ pub async fn shell(
673 }641 }
674 segments.push((title.to_owned(), None));642 segments.push((title.to_owned(), None));
675 }643 }
676- // Places the path does not show, such as a job's run, go just before the page itself.
677 if !parents.is_empty() {644 if !parents.is_empty() {
678 let at = segments.len().saturating_sub(1);645 let at = segments.len().saturating_sub(1);
679 for (offset, (label, href)) in parents.into_iter().enumerate() {646 for (offset, (label, href)) in parents.into_iter().enumerate() {
@@ -699,15 +666,12 @@ pub async fn shell(
699 })666 })
700 .collect();667 .collect();
701 let strip = live_strip(lang, &runs);668 let strip = live_strip(lang, &runs);
702- // The strip's count phrases, as templates for nav.js: `{n}` stands for the count.
703 let running_tpl = count_template(&mi::running_count(lang, 2), 2);669 let running_tpl = count_template(&mi::running_count(lang, 2), 2);
704 let failed_tpl = count_template(&mi::failed_count(lang, 2), 2);670 let failed_tpl = count_template(&mi::failed_count(lang, 2), 2);
705 let passed_tpl = count_template(&mi::passed_count(lang, 2), 2);671 let passed_tpl = count_template(&mi::passed_count(lang, 2), 2);
706 let cancelled_tpl = count_template(&mi::cancelled_count(lang, 2), 2);672 let cancelled_tpl = count_template(&mi::cancelled_count(lang, 2), 2);
707 let runs_label = mi::t(lang, MK::YourCiRuns);673 let runs_label = mi::t(lang, MK::YourCiRuns);
708 let search_for_label = mi::t(lang, MK::SearchPublicReposFor);674 let search_for_label = mi::t(lang, MK::SearchPublicReposFor);
709- // The profile corner, the signed-in account panel. Its dot says something waits: an unread
710- // notification, a review request, a mention or a failed run.
711 let corner = viewer.map(|(user, session)| ProfileCorner {675 let corner = viewer.map(|(user, session)| ProfileCorner {
712 username: user.username.clone(),676 username: user.username.clone(),
713 name: user677 name: user
@@ -767,7 +731,6 @@ pub async fn shell(
767 }731 }
768 </ol>732 </ol>
769 if signed_in {733 if signed_in {
770- // The palette's strings ride on its button, so nav.js builds the dialog in the viewer's language.
771 <button type="button" class="pathbar-edit" data-palette-open="" data-path=(path_attr.as_str()) aria-label=(palette_label.as_str()) title=(palette_label.as_str())734 <button type="button" class="pathbar-edit" data-palette-open="" data-path=(path_attr.as_str()) aria-label=(palette_label.as_str()) title=(palette_label.as_str())
772 data-placeholder=(br::t(lang, br::K::PalettePlaceholder)) data-repos=(br::t(lang, br::K::PaletteRepos))735 data-placeholder=(br::t(lang, br::K::PalettePlaceholder)) data-repos=(br::t(lang, br::K::PaletteRepos))
773 data-orgs=(o::t(lang, OK::Organizations)) data-pages=(br::t(lang, br::K::PalettePages))736 data-orgs=(o::t(lang, OK::Organizations)) data-pages=(br::t(lang, br::K::PalettePages))
@@ -852,7 +815,6 @@ pub async fn shell(
852 </body>815 </body>
853 </html>816 </html>
854 }817 }
855- // Boxed: the shell's view is part of every page's view, and inline it overflows the stack of a deep page.
856 .boxed())818 .boxed())
857 }819 }
858 820
@@ -1050,7 +1012,6 @@ pub fn section_for(lang: Lang, path: &str) -> Option<Section> {
1050 let second = match (first, second) {1012 let second = match (first, second) {
1051 (_, "sessions") => "security",1013 (_, "sessions") => "security",
1052 (_, "gpg" | "tokens") => "keys",1014 (_, "gpg" | "tokens") => "keys",
1053- // Invites are a rail item of Users, replication one of Backups.
1054 ("admin", "invites") => "users",1015 ("admin", "invites") => "users",
1055 ("admin", "replication") => "backups",1016 ("admin", "replication") => "backups",
1056 (_, other) => other,1017 (_, other) => other,
@@ -1059,7 +1020,6 @@ pub fn section_for(lang: Lang, path: &str) -> Option<Section> {
1059 .iter()1020 .iter()
1060 .find(|item| item.key == second)1021 .find(|item| item.key == second)
1061 .map_or("", |item| item.key);1022 .map_or("", |item| item.key);
1062- // Every page of the user's settings follows their own change stream (see `pages::settings_live`).
1063 let live = if first == "settings" {1023 let live = if first == "settings" {
1064 "/settings/events"1024 "/settings/events"
1065 } else {1025 } else {
@@ -1211,8 +1171,6 @@ pub async fn security_headers(cx: &Cx, body: Body, next: Next<'_>) -> Result<Res
1211 next.run(cx, body).await1171 next.run(cx, body).await
1212 }1172 }
1213 1173
1214-// Repo browsing helpers: URLs, times and sizes, and the shared tabs and ref selector.
1215-
1216 /// Percent-encodes everything except unreserved characters and `/`.1174 /// Percent-encodes everything except unreserved characters and `/`.
1217 pub fn enc(s: &str) -> String {1175 pub fn enc(s: &str) -> String {
1218 let mut out = String::with_capacity(s.len());1176 let mut out = String::with_capacity(s.len());
@@ -1242,13 +1200,7 @@ pub fn repo_href(owner: &str, repo: &str, section: &str, rest: &str) -> String {
1242 href1200 href
1243 }1201 }
1244 1202
1245-/// Current time as Unix seconds.1203+pub use forge_core::time::now_unix;
1246-pub fn now_unix() -> i64 {
1247- std::time::SystemTime::now()
1248- .duration_since(std::time::UNIX_EPOCH)
1249- .map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
1250- .unwrap_or(0)
1251-}
1252 1204
1253 /// ISO 8601 UTC timestamp, `YYYY-MM-DDTHH:MM:SSZ`.1205 /// ISO 8601 UTC timestamp, `YYYY-MM-DDTHH:MM:SSZ`.
1254 pub fn iso_time(unix: i64) -> String {1206 pub fn iso_time(unix: i64) -> String {
@@ -1449,33 +1401,20 @@ pub async fn repo_tabs(
1449 let issues_count = open_issues.filter(|n| *n > 0).map(|n| n.to_string());1401 let issues_count = open_issues.filter(|n| *n > 0).map(|n| n.to_string());
1450 let pulls = repo_href(&owner, &repo, "pulls", "");1402 let pulls = repo_href(&owner, &repo, "pulls", "");
1451 let pulls_count = open_pulls.filter(|n| *n > 0).map(|n| n.to_string());1403 let pulls_count = open_pulls.filter(|n| *n > 0).map(|n| n.to_string());
1452- let pulls_on = active == "pulls";
1453 let commits = repo_href(&owner, &repo, "commits", &default_branch);1404 let commits = repo_href(&owner, &repo, "commits", &default_branch);
1454 let branches = repo_href(&owner, &repo, "branches", "");1405 let branches = repo_href(&owner, &repo, "branches", "");
1455 let tags = repo_href(&owner, &repo, "tags", "");1406 let tags = repo_href(&owner, &repo, "tags", "");
1456 let releases = repo_href(&owner, &repo, "releases", "");1407 let releases = repo_href(&owner, &repo, "releases", "");
1457 let ci = repo_href(&owner, &repo, "ci", "");1408 let ci = repo_href(&owner, &repo, "ci", "");
1458- let ci_on = active == "ci";
1459- // The four code pages sit in a menu after the Code tab, which stays active while one is open.
1460 let more_on = matches!(1409 let more_on = matches!(
1461 active.as_str(),1410 active.as_str(),
1462 "commits" | "branches" | "tags" | "releases"1411 "commits" | "branches" | "tags" | "releases"
1463 );1412 );
1464 let code_on = active == "code" || more_on;1413 let code_on = active == "code" || more_on;
1465- let issues_on = active == "issues";
1466- let commits_on = active == "commits";
1467- let branches_on = active == "branches";
1468- let tags_on = active == "tags";
1469- let releases_on = active == "releases";
1470- // Shown only to people who may manage the repo (owner, instance admin, or Admin collaborator).
1471 let settings = repo_href(&owner, &repo, "settings", "");1414 let settings = repo_href(&owner, &repo, "settings", "");
1472- let settings_on = active == "settings";
1473 let discussions_tab = repo_href(&owner, &repo, "discussions", "");1415 let discussions_tab = repo_href(&owner, &repo, "discussions", "");
1474- let discussions_on = active == "discussions";
1475 let wiki_tab = repo_href(&owner, &repo, "wiki", "");1416 let wiki_tab = repo_href(&owner, &repo, "wiki", "");
1476- let wiki_on = active == "wiki";
1477 let security_tab = repo_href(&owner, &repo, "security", "");1417 let security_tab = repo_href(&owner, &repo, "security", "");
1478- let security_on = active == "security";
1479 Ok(view! {1418 Ok(view! {
1480 <nav class="repo-tabs" aria-label=(g::t(lang, K::RepositoryNav))>1419 <nav class="repo-tabs" aria-label=(g::t(lang, K::RepositoryNav))>
1481 <a class=(tab_class(code_on)) href=(home)>1420 <a class=(tab_class(code_on)) href=(home)>
@@ -1486,44 +1425,44 @@ pub async fn repo_tabs(
1486 <svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>1425 <svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>
1487 </summary>1426 </summary>
1488 <div class="tab-more-list">1427 <div class="tab-more-list">
1489- <a class=(tab_more_class(commits_on)) href=(commits)>(g::t(lang, K::TabCommits))</a>1428+ <a class=(tab_more_class(active == "commits")) href=(commits)>(g::t(lang, K::TabCommits))</a>
1490- <a class=(tab_more_class(branches_on)) href=(branches)>(g::t(lang, K::BranchesTitle))</a>1429+ <a class=(tab_more_class(active == "branches")) href=(branches)>(g::t(lang, K::BranchesTitle))</a>
1491- <a class=(tab_more_class(tags_on)) href=(tags)>(g::t(lang, K::TagsTitle))</a>1430+ <a class=(tab_more_class(active == "tags")) href=(tags)>(g::t(lang, K::TagsTitle))</a>
1492- <a class=(tab_more_class(releases_on)) href=(releases)>(g::t(lang, K::TabReleases))</a>1431+ <a class=(tab_more_class(active == "releases")) href=(releases)>(g::t(lang, K::TabReleases))</a>
1493 </div>1432 </div>
1494 </details>1433 </details>
1495- <a class=(tab_class(issues_on)) href=(issues)>1434+ <a class=(tab_class(active == "issues")) href=(issues)>
1496 (g::t(lang, K::TabIssues))1435 (g::t(lang, K::TabIssues))
1497 if let Some(count) = issues_count {1436 if let Some(count) = issues_count {
1498 " " <span class="tab-count" data-arrive=(count.as_str())>(count.as_str())</span>1437 " " <span class="tab-count" data-arrive=(count.as_str())>(count.as_str())</span>
1499 }1438 }
1500 </a>1439 </a>
1501- <a class=(tab_class(pulls_on)) href=(pulls)>1440+ <a class=(tab_class(active == "pulls")) href=(pulls)>
1502 (g::t(lang, K::TabPulls))1441 (g::t(lang, K::TabPulls))
1503 if let Some(count) = pulls_count {1442 if let Some(count) = pulls_count {
1504 " " <span class="tab-count" data-arrive=(count.as_str())>(count.as_str())</span>1443 " " <span class="tab-count" data-arrive=(count.as_str())>(count.as_str())</span>
1505 }1444 }
1506 </a>1445 </a>
1507- <a class=(tab_class(ci_on)) href=(ci)>1446+ <a class=(tab_class(active == "ci")) href=(ci)>
1508 (g::t(lang, K::TabCi))1447 (g::t(lang, K::TabCi))
1509 </a>1448 </a>
1510 if discussions {1449 if discussions {
1511- <a class=(tab_class(discussions_on)) href=(discussions_tab)>1450+ <a class=(tab_class(active == "discussions")) href=(discussions_tab)>
1512 (g::t(lang, K::TabDiscussions))1451 (g::t(lang, K::TabDiscussions))
1513 </a>1452 </a>
1514 }1453 }
1515 if wiki {1454 if wiki {
1516- <a class=(tab_class(wiki_on)) href=(wiki_tab)>1455+ <a class=(tab_class(active == "wiki")) href=(wiki_tab)>
1517 (g::t(lang, K::TabWiki))1456 (g::t(lang, K::TabWiki))
1518 </a>1457 </a>
1519 }1458 }
1520 if security {1459 if security {
1521- <a class=(tab_class(security_on)) href=(security_tab)>1460+ <a class=(tab_class(active == "security")) href=(security_tab)>
1522 (t(lang, Key::Security))1461 (t(lang, Key::Security))
1523 </a>1462 </a>
1524 }1463 }
1525 if can_admin {1464 if can_admin {
1526- <a class=(tab_class(settings_on)) href=(settings)>1465+ <a class=(tab_class(active == "settings")) href=(settings)>
1527 (g::t(lang, K::TabSettings))1466 (g::t(lang, K::TabSettings))
1528 </a>1467 </a>
1529 }1468 }
@@ -1612,7 +1551,6 @@ pub async fn ref_selector(
1612 branches_href: String,1551 branches_href: String,
1613 tags_href: String,1552 tags_href: String,
1614 ) -> Result<impl View> {1553 ) -> Result<impl View> {
1615- // A tag shows a tag icon only when it is the current ref and no branch of that name is.
1616 let is_tag = !branches.iter().any(|b| b.current) && tags.iter().any(|t| t.current);1554 let is_tag = !branches.iter().any(|b| b.current) && tags.iter().any(|t| t.current);
1617 let none = branches.is_empty() && tags.is_empty();1555 let none = branches.is_empty() && tags.is_empty();
1618 let now = now_unix();1556 let now = now_unix();
@@ -1696,20 +1634,6 @@ fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
1696 era * 146_097 + doe - 719_4681634 era * 146_097 + doe - 719_468
1697 }1635 }
1698 1636
1699-/// Percent-encodes each byte outside the unreserved set, keeping `/` as the separator.
1700-pub fn url_path(path: &str) -> String {
1701- let mut out = String::with_capacity(path.len());
1702- for b in path.bytes() {
1703- match b {
1704- b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
1705- out.push(char::from(b));
1706- }
1707- _ => out.push_str(&format!("%{b:02X}")),
1708- }
1709- }
1710- out
1711-}
1712-
1713 /// The highlight classes, shared by the route and the page links (which hash them).1637 /// The highlight classes, shared by the route and the page links (which hash them).
1714 pub fn highlight_css_text() -> &'static str {1638 pub fn highlight_css_text() -> &'static str {
1715 highlight_css()1639 highlight_css()
@@ -1988,7 +1912,6 @@ mod tests {
1988 let csp = csp_for(origin.as_deref());1912 let csp = csp_for(origin.as_deref());
1989 assert!(csp.contains("img-src 'self' data: https://raw.forge.test:8443;"));1913 assert!(csp.contains("img-src 'self' data: https://raw.forge.test:8443;"));
1990 assert!(csp.contains("form-action 'self'; frame-ancestors 'none'"));1914 assert!(csp.contains("form-action 'self'; frame-ancestors 'none'"));
1991- // A base URL that is not an origin falls back to the plain policy.
1992 assert_eq!(origin_of("not a url"), None);1915 assert_eq!(origin_of("not a url"), None);
1993 assert_eq!(origin_of("ftp://files.test"), None);1916 assert_eq!(origin_of("ftp://files.test"), None);
1994 assert_eq!(origin_of("https://user:pw@files.test"), None);1917 assert_eq!(origin_of("https://user:pw@files.test"), None);
@@ -2019,7 +1942,6 @@ mod tests {
2019 assert_eq!(relative_time(Lang::Tr, 0, 3 * 86_400), "3 gün önce");1942 assert_eq!(relative_time(Lang::Tr, 0, 3 * 86_400), "3 gün önce");
2020 assert_eq!(relative_time(Lang::Tr, 0, 2 * 2_592_000), "2 ay önce");1943 assert_eq!(relative_time(Lang::Tr, 0, 2 * 2_592_000), "2 ay önce");
2021 assert_eq!(relative_time(Lang::Tr, 0, 365 * 86_400), "1 yıl önce");1944 assert_eq!(relative_time(Lang::Tr, 0, 365 * 86_400), "1 yıl önce");
2022- // The client re-words a label from these: the words for the same units, in the same order.
2023 assert_eq!(1945 assert_eq!(
2024 rel_words(Lang::En),1946 rel_words(Lang::En),
2025 "just now|{n} minute ago|{n} minutes ago|{n} hour ago|{n} hours ago|{n} day ago|\1947 "just now|{n} minute ago|{n} minutes ago|{n} hour ago|{n} hours ago|{n} day ago|\
crates/forge-web-app/src/views/review_thread.rsmodified+13 -47
@@ -127,14 +127,7 @@ fn body_parts(
127 struct ThreadParts {127 struct ThreadParts {
128 hunk: Option<String>,128 hunk: Option<String>,
129 comments: Vec<CommentRow>,129 comments: Vec<CommentRow>,
130- resolve_action: Option<String>,130+ footer: ThreadFooter,
131- resolve_value: String,
132- resolve_label: String,
133- reply_action: Option<String>,
134- reply_id: String,
135- csrf: String,
136- return_to: String,
137- lang: Lang,
138 }131 }
139 132
140 fn comment_row(133 fn comment_row(
@@ -162,26 +155,10 @@ fn comment_row(
162 }155 }
163 }156 }
164 157
165-/// One thread, in English. Pages that know the viewer's language use `review_thread_in`.158+/// One thread with its strings in `lang`. `show_hunk` adds the stored diff hunk as a code block;
166-/// `show_hunk` adds the stored diff hunk as a code block; `return_to` is `files` or159+/// `return_to` is `files` or `conversation` and tells the POST routes which tab to redirect to.
167-/// `conversation` and tells the POST routes which tab to redirect to.
168 #[component]160 #[component]
169 pub async fn review_thread(161 pub async fn review_thread(
170- cx: &Cx,
171- thread: Thread,
172- ctx: ThreadCtx,
173- show_hunk: bool,
174- return_to: &str,
175-) -> Result<impl View> {
176- Ok(view! {
177- review_thread_in(lang: Lang::En, thread: thread, ctx: ctx, show_hunk: show_hunk,
178- return_to: return_to)
179- })
180-}
181-
182-/// One thread with its strings in `lang`. See `review_thread` for the arguments.
183-#[component]
184-pub async fn review_thread_in(
185 cx: &Cx,162 cx: &Cx,
186 lang: Lang,163 lang: Lang,
187 thread: Thread,164 thread: Thread,
@@ -218,9 +195,7 @@ pub async fn review_thread_in(
218 })195 })
219 .collect();196 .collect();
220 197
221- let parts = ThreadParts {198+ let footer = ThreadFooter {
222- hunk,
223- comments,
224 resolve_action,199 resolve_action,
225 resolve_value: resolve_value.to_owned(),200 resolve_value: resolve_value.to_owned(),
226 resolve_label: resolve_label.to_owned(),201 resolve_label: resolve_label.to_owned(),
@@ -230,6 +205,11 @@ pub async fn review_thread_in(
230 return_to,205 return_to,
231 lang,206 lang,
232 };207 };
208+ let parts = ThreadParts {
209+ hunk,
210+ comments,
211+ footer,
212+ };
233 213
234 // One `<details>` for every thread: open unless resolved, so a resolved thread starts214 // One `<details>` for every thread: open unless resolved, so a resolved thread starts
235 // collapsed and can still be expanded. Its summary row carries the location and the badges.215 // collapsed and can still be expanded. Its summary row carries the location and the badges.
@@ -267,25 +247,11 @@ async fn thread_parts(cx: &Cx, parts: ThreadParts) -> Result<impl View> {
267 let ThreadParts {247 let ThreadParts {
268 hunk,248 hunk,
269 comments,249 comments,
270- resolve_action,250+ footer,
271- resolve_value,
272- resolve_label,
273- reply_action,
274- reply_id,
275- csrf,
276- return_to,
277- lang,
278 } = parts;251 } = parts;
279- let footer = ThreadFooter {252+ let csrf = footer.csrf.clone();
280- resolve_action,253+ let return_to = footer.return_to.clone();
281- resolve_value,254+ let lang = footer.lang;
282- resolve_label,
283- reply_action,
284- reply_id,
285- csrf: csrf.clone(),
286- return_to: return_to.clone(),
287- lang,
288- };
289 Ok(view! {255 Ok(view! {
290 if let Some(text) = hunk {256 if let Some(text) = hunk {
291 <pre class="review-hunk"><code>(text.as_str())</code></pre>257 <pre class="review-hunk"><code>(text.as_str())</code></pre>
crates/forge-web-app/src/web_push/crypto.rsmodified+7 -36
@@ -1,7 +1,3 @@
1-//! Web Push, on the RustCrypto crates: the RFC 8291 message encryption (aes128gcm content coding,
2-//! RFC 8188) and the RFC 8292 VAPID authorization (an ES256 JWT). This module converts the
3-//! base64url values that browsers and the database hold into key types, and builds the request.
4-
5 use std::time::{SystemTime, UNIX_EPOCH};1 use std::time::{SystemTime, UNIX_EPOCH};
6 2
7 use aes_gcm::Aes128Gcm;3 use aes_gcm::Aes128Gcm;
@@ -17,29 +13,21 @@ use sha2::Sha256;
17 13
18 use forge_core::{Error, Result};14 use forge_core::{Error, Result};
19 15
20-/// The uncompressed P-256 point length: 0x04 followed by X and Y.
21 const POINT_LEN: usize = 65;16 const POINT_LEN: usize = 65;
22-/// The record size the body declares (RFC 8188 `rs`). One record holds the whole message.
23 const RECORD_SIZE: u32 = 4096;17 const RECORD_SIZE: u32 = 4096;
24-/// How long a VAPID token stays valid, in seconds: 12 hours, the most RFC 8292 allows.
25 const VAPID_TTL: u64 = 12 * 60 * 60;18 const VAPID_TTL: u64 = 12 * 60 * 60;
26-/// How long the push service may hold a message for an offline browser, in seconds.
27 const PUSH_TTL: &str = "43200";19 const PUSH_TTL: &str = "43200";
28 20
29-/// Decodes base64url, with or without padding.
30 pub fn decode_b64(text: &str) -> Result<Vec<u8>> {21 pub fn decode_b64(text: &str) -> Result<Vec<u8>> {
31 URL_SAFE_NO_PAD22 URL_SAFE_NO_PAD
32 .decode(text.trim_end_matches('='))23 .decode(text.trim_end_matches('='))
33 .map_err(|_| Error::Invalid("not base64url".into()))24 .map_err(|_| Error::Invalid("not base64url".into()))
34 }25 }
35 26
36-/// Encodes base64url without padding, the form push services and browsers use.
37 pub fn encode_b64(bytes: &[u8]) -> String {27 pub fn encode_b64(bytes: &[u8]) -> String {
38 URL_SAFE_NO_PAD.encode(bytes)28 URL_SAFE_NO_PAD.encode(bytes)
39 }29 }
40 30
41-/// A random P-256 private key from the system RNG. A draw that is zero or not below the curve
42-/// order is rare enough that it is simply drawn again.
43 fn random_secret() -> p256::SecretKey {31 fn random_secret() -> p256::SecretKey {
44 loop {32 loop {
45 let mut bytes = [0u8; 32];33 let mut bytes = [0u8; 32];
@@ -50,29 +38,23 @@ fn random_secret() -> p256::SecretKey {
50 }38 }
51 }39 }
52 40
53-/// A new VAPID private key (32 bytes) from the system RNG.
54 pub fn new_vapid_private() -> [u8; 32] {41 pub fn new_vapid_private() -> [u8; 32] {
55- let mut out = [0u8; 32];42+ random_secret().to_bytes().into()
56- out.copy_from_slice(&random_secret().to_bytes());
57- out
58 }43 }
59 44
60-/// The key pair the VAPID signature is made with, from its 32-byte private scalar.
61 pub fn vapid_key_pair(private: &[u8; 32]) -> Result<SigningKey> {45 pub fn vapid_key_pair(private: &[u8; 32]) -> Result<SigningKey> {
62 SigningKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into()))46 SigningKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into()))
63 }47 }
64 48
65-/// The public key of a VAPID private key, as the uncompressed point in base64url. This is the
66-/// `applicationServerKey` the browser subscribes with.
67 pub fn vapid_public_key(private: &[u8; 32]) -> Result<String> {49 pub fn vapid_public_key(private: &[u8; 32]) -> Result<String> {
68- let secret =50+ Ok(encode_b64(
69- p256::SecretKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into()))?;51+ vapid_key_pair(private)?
70- let point = secret.public_key().to_sec1_point(false);52+ .verifying_key()
71- Ok(encode_b64(point.as_bytes()))53+ .to_sec1_point(false)
54+ .as_bytes(),
55+ ))
72 }56 }
73 57
74-/// The RFC 8291 body for one message. The ephemeral key and the salt are arguments so that a test
75-/// can fix them; `push_request` draws both at random.
76 fn encrypt_body(58 fn encrypt_body(
77 ua_public: &p256::PublicKey,59 ua_public: &p256::PublicKey,
78 auth: &[u8],60 auth: &[u8],
@@ -86,7 +68,6 @@ fn encrypt_body(
86 let ua_point = ua_public.to_sec1_point(false);68 let ua_point = ua_public.to_sec1_point(false);
87 let shared = p256::ecdh::diffie_hellman(as_secret.to_nonzero_scalar(), ua_public.as_affine());69 let shared = p256::ecdh::diffie_hellman(as_secret.to_nonzero_scalar(), ua_public.as_affine());
88 70
89- // IKM: the ECDH secret, salted with the auth secret, expanded over both public keys.
90 let mut key_info = b"WebPush: info\0".to_vec();71 let mut key_info = b"WebPush: info\0".to_vec();
91 key_info.extend_from_slice(ua_point.as_bytes());72 key_info.extend_from_slice(ua_point.as_bytes());
92 key_info.extend_from_slice(as_public.as_bytes());73 key_info.extend_from_slice(as_public.as_bytes());
@@ -95,7 +76,6 @@ fn encrypt_body(
95 .expand(&key_info, &mut ikm)76 .expand(&key_info, &mut ikm)
96 .map_err(|e| encryption_error(&e))?;77 .map_err(|e| encryption_error(&e))?;
97 78
98- // The content encryption key and the nonce, from a PRK salted with the message salt.
99 let mut cek = [0u8; 16];79 let mut cek = [0u8; 16];
100 let mut nonce = [0u8; 12];80 let mut nonce = [0u8; 12];
101 let prk = Hkdf::<Sha256>::new(Some(salt), &ikm);81 let prk = Hkdf::<Sha256>::new(Some(salt), &ikm);
@@ -104,8 +84,6 @@ fn encrypt_body(
104 prk.expand(b"Content-Encoding: nonce\0", &mut nonce)84 prk.expand(b"Content-Encoding: nonce\0", &mut nonce)
105 .map_err(|e| encryption_error(&e))?;85 .map_err(|e| encryption_error(&e))?;
106 86
107- // The plaintext ends with 0x02, the delimiter of the last record. With the 16-byte tag the one
108- // record must fit in `RECORD_SIZE`.
109 if payload.len() + 1 + 16 > RECORD_SIZE as usize {87 if payload.len() + 1 + 16 > RECORD_SIZE as usize {
110 return Err(Error::Invalid("the push message is too large".into()));88 return Err(Error::Invalid("the push message is too large".into()));
111 }89 }
@@ -124,8 +102,6 @@ fn encrypt_body(
124 Ok(body)102 Ok(body)
125 }103 }
126 104
127-/// The VAPID token (RFC 8292) for a push to `uri`: an ES256 JWT whose audience is the origin of
128-/// the endpoint. The signature is the raw 64-byte `r || s`, not DER.
129 fn vapid_token(uri: &http::Uri, subject: &str, key_pair: &SigningKey) -> Result<String> {105 fn vapid_token(uri: &http::Uri, subject: &str, key_pair: &SigningKey) -> Result<String> {
130 let bad_endpoint = || Error::Invalid("bad push endpoint".into());106 let bad_endpoint = || Error::Invalid("bad push endpoint".into());
131 let scheme = uri.scheme_str().ok_or_else(bad_endpoint)?;107 let scheme = uri.scheme_str().ok_or_else(bad_endpoint)?;
@@ -150,9 +126,6 @@ fn vapid_token(uri: &http::Uri, subject: &str, key_pair: &SigningKey) -> Result<
150 ))126 ))
151 }127 }
152 128
153-/// Builds the POST for one push: the body is encrypted for the browser's key and auth secret,
154-/// and the request carries the VAPID `Authorization` for `endpoint`'s origin. `subject` is the
155-/// contact URL (`mailto:` or `https:`).
156 pub fn push_request(129 pub fn push_request(
157 endpoint: &str,130 endpoint: &str,
158 p256dh: &[u8],131 p256dh: &[u8],
@@ -258,7 +231,6 @@ mod tests {
258 assert_eq!(request.headers()["content-encoding"], "aes128gcm");231 assert_eq!(request.headers()["content-encoding"], "aes128gcm");
259 assert_eq!(request.headers()["ttl"], "43200");232 assert_eq!(request.headers()["ttl"], "43200");
260 233
261- // The VAPID header names the push service's origin and carries the instance's public key.
262 let auth_header = request.headers()["authorization"]234 let auth_header = request.headers()["authorization"]
263 .to_str()235 .to_str()
264 .expect("ascii")236 .expect("ascii")
@@ -279,7 +251,6 @@ mod tests {
279 assert_eq!(claims["aud"], "https://push.example.test");251 assert_eq!(claims["aud"], "https://push.example.test");
280 assert_eq!(claims["sub"], "mailto:tahinli@example.test");252 assert_eq!(claims["sub"], "mailto:tahinli@example.test");
281 253
282- // The body is encrypted: it is longer than the plaintext and does not contain it.
283 let body = request.body();254 let body = request.body();
284 assert!(body.len() > payload.len());255 assert!(body.len() > payload.len());
285 assert!(!body.windows(payload.len()).any(|w| w == payload.as_slice()));256 assert!(!body.windows(payload.len()).any(|w| w == payload.as_slice()));
crates/forge-web-app/src/web_push/mod.rsmodified+31 -68
@@ -1,13 +1,3 @@
1-//! Web Push: a notification for the inbox also reaches the user's devices when no tab is open. A
2-//! browser (or an installed app) subscribes through the service worker, the server keeps the
3-//! subscription, and [`queue`] sends the message to every device of a user.
4-//!
5-//! Delivery never blocks the caller: [`queue`] spawns the work, which looks up the user's devices,
6-//! encrypts the message per device (RFC 8291), signs the request with the instance's VAPID key
7-//! (RFC 8292) and posts it to the push service. A device the service reports gone (404 or 410) is
8-//! removed. Every change to a user's devices is announced on [`PushLive`], so an open settings page
9-//! refreshes through its event stream.
10-
11 pub mod crypto;1 pub mod crypto;
12 2
13 use std::sync::OnceLock;3 use std::sync::OnceLock;
@@ -23,13 +13,9 @@ use crate::i18n::{self, Lang, misc, push as text};
23 use crate::state::AppState;13 use crate::state::AppState;
24 use crate::webhooks::client::{WebhookPolicy, policy_client, validate_url};14 use crate::webhooks::client::{WebhookPolicy, policy_client, validate_url};
25 15
26-/// How long one push request may take before it counts as failed.
27 const SEND_TIMEOUT: Duration = Duration::from_secs(15);16 const SEND_TIMEOUT: Duration = Duration::from_secs(15);
28-/// Longest body text in a notification, in characters.
29 const BODY_CHARS: usize = 140;17 const BODY_CHARS: usize = 140;
30 18
31-/// Announces changes to a user's devices to the settings pages that show them. Only the event
32-/// stream reads it; nothing here is stored, and a second server process would not see it.
33 pub struct PushLive {19 pub struct PushLive {
34 tx: broadcast::Sender<String>,20 tx: broadcast::Sender<String>,
35 }21 }
@@ -43,59 +29,44 @@ impl Default for PushLive {
43 }29 }
44 30
45 impl PushLive {31 impl PushLive {
46- /// Says that the devices of `user_id` changed. Nobody listening is fine.
47 pub fn publish(&self, user_id: &str) {32 pub fn publish(&self, user_id: &str) {
48 let _ = self.tx.send(user_id.to_owned());33 let _ = self.tx.send(user_id.to_owned());
49 }34 }
50 35
51- /// A receiver for every change, from every user. A stream filters for its own user.
52 pub fn subscribe(&self) -> broadcast::Receiver<String> {36 pub fn subscribe(&self) -> broadcast::Receiver<String> {
53 self.tx.subscribe()37 self.tx.subscribe()
54 }38 }
55 }39 }
56 40
57-/// What a notification says. Built per recipient, in the recipient's language.
58 #[derive(Clone)]41 #[derive(Clone)]
59 pub enum Alert {42 pub enum Alert {
60- /// Activity on an issue or pull request the user hears about.
61 Activity {43 Activity {
62- /// `owner/repo`.
63 repo: String,44 repo: String,
64 number: i64,45 number: i64,
65 title: String,46 title: String,
66- /// The verb of the activity (`misc::K::VerbOpened` and so on).
67 verb: misc::K,47 verb: misc::K,
68 actor: Option<String>,48 actor: Option<String>,
69- /// The relative link the notification opens.
70 url: String,49 url: String,
71- /// The thread id. A newer notification for the same thread replaces the older one.
72 thread: String,50 thread: String,
73 },51 },
74- /// New security advisory alerts on a repo.
75 Advisories {52 Advisories {
76 repo: String,53 repo: String,
77 count: u64,54 count: u64,
78 url: String,55 url: String,
79 },56 },
80- /// A site admin alert.
81 Admin { subject: String, detail: String },57 Admin { subject: String, detail: String },
82- /// The test button.
83 Test,58 Test,
84 }59 }
85 60
86-/// The JSON the service worker reads. Small, and nothing in it is a secret.
87 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]61 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
88 pub struct Message {62 pub struct Message {
89 pub title: String,63 pub title: String,
90 pub body: String,64 pub body: String,
91- /// A relative link on this origin.
92 pub url: String,65 pub url: String,
93- /// Notifications with the same tag replace each other on the device.
94 pub tag: String,66 pub tag: String,
95 }67 }
96 68
97 impl Alert {69 impl Alert {
98- /// The message for a recipient who reads `lang`.
99 pub fn message(&self, lang: Lang) -> Message {70 pub fn message(&self, lang: Lang) -> Message {
100 match self {71 match self {
101 Alert::Activity {72 Alert::Activity {
@@ -137,7 +108,6 @@ impl Alert {
137 }108 }
138 }109 }
139 110
140-/// Shortens text to the body limit, in characters, one line.
141 fn clip(text: &str) -> String {111 fn clip(text: &str) -> String {
142 let one_line: String = text.split_whitespace().collect::<Vec<_>>().join(" ");112 let one_line: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
143 if one_line.chars().count() <= BODY_CHARS {113 if one_line.chars().count() <= BODY_CHARS {
@@ -148,9 +118,7 @@ fn clip(text: &str) -> String {
148 short118 short
149 }119 }
150 120
151-/// A relative link only. The service worker opens it on this origin, so anything that could leave121+fn safe_url(url: &str) -> String {
152-/// the origin (a scheme, a protocol-relative `//host`) falls back to the notifications page.
153-pub fn safe_url(url: &str) -> String {
154 if url.starts_with('/') && !url.starts_with("//") && !url.contains('\\') {122 if url.starts_with('/') && !url.starts_with("//") && !url.contains('\\') {
155 url.to_owned()123 url.to_owned()
156 } else {124 } else {
@@ -158,12 +126,10 @@ pub fn safe_url(url: &str) -> String {
158 }126 }
159 }127 }
160 128
161-/// A short label for a device, from its User-Agent: "Chrome on Android", "Safari on iPhone".
162 pub fn agent_label(user_agent: &str) -> String {129 pub fn agent_label(user_agent: &str) -> String {
163 agent_label_in(Lang::En, user_agent)130 agent_label_in(Lang::En, user_agent)
164 }131 }
165 132
166-/// [`agent_label`] in the viewer's language: "Chrome on Linux", "Linux üzerinde Chrome".
167 pub fn agent_label_in(lang: Lang, user_agent: &str) -> String {133 pub fn agent_label_in(lang: Lang, user_agent: &str) -> String {
168 let os = if user_agent.contains("iPhone") {134 let os = if user_agent.contains("iPhone") {
169 "iPhone"135 "iPhone"
@@ -190,7 +156,10 @@ pub fn agent_label_in(lang: Lang, user_agent: &str) -> String {
190 "Opera"156 "Opera"
191 } else if user_agent.contains("Firefox/") {157 } else if user_agent.contains("Firefox/") {
192 "Firefox"158 "Firefox"
193- } else if user_agent.contains("Chrome/") || user_agent.contains("Chromium/") {159+ } else if user_agent.contains("Chrome/")
160+ || user_agent.contains("Chromium/")
161+ || user_agent.contains("CriOS/")
162+ {
194 "Chrome"163 "Chrome"
195 } else if user_agent.contains("Safari/") {164 } else if user_agent.contains("Safari/") {
196 "Safari"165 "Safari"
@@ -206,9 +175,6 @@ pub fn agent_label_in(lang: Lang, user_agent: &str) -> String {
206 }175 }
207 }176 }
208 177
209-/// The HTTP client for push requests: the webhook outbound policy (no internal addresses, no
210-/// redirects, no proxy). An endpoint is any URL a signed-in browser sent, so it gets the same
211-/// treatment as a hook URL. Built once; the policy comes from the config, which does not change.
212 fn client(policy: &WebhookPolicy) -> Option<&'static reqwest::Client> {178 fn client(policy: &WebhookPolicy) -> Option<&'static reqwest::Client> {
213 static CLIENT: OnceLock<Option<reqwest::Client>> = OnceLock::new();179 static CLIENT: OnceLock<Option<reqwest::Client>> = OnceLock::new();
214 CLIENT180 CLIENT
@@ -224,15 +190,11 @@ fn client(policy: &WebhookPolicy) -> Option<&'static reqwest::Client> {
224 .as_ref()190 .as_ref()
225 }191 }
226 192
227-/// The instance's VAPID key pair. The private key is stored sealed with the instance key; the
228-/// first call creates the pair.
229 pub struct VapidKeys {193 pub struct VapidKeys {
230 pub private: [u8; 32],194 pub private: [u8; 32],
231- /// The public key, base64url. The browser subscribes with it.
232 pub public: String,195 pub public: String,
233 }196 }
234 197
235-/// The VAPID keys of this instance, creating and storing them on first use.
236 pub async fn vapid_keys(state: &AppState) -> Result<VapidKeys> {198 pub async fn vapid_keys(state: &AppState) -> Result<VapidKeys> {
237 let (public, sealed) = match state.store.web_push_keys().await? {199 let (public, sealed) = match state.store.web_push_keys().await? {
238 Some(pair) => pair,200 Some(pair) => pair,
@@ -250,7 +212,6 @@ pub async fn vapid_keys(state: &AppState) -> Result<VapidKeys> {
250 Ok(VapidKeys { private, public })212 Ok(VapidKeys { private, public })
251 }213 }
252 214
253-/// The contact the push service may use about this instance: the base URL when it is https.
254 fn subject(base_url: &str) -> String {215 fn subject(base_url: &str) -> String {
255 let base = base_url.trim_end_matches('/');216 let base = base_url.trim_end_matches('/');
256 if base.starts_with("https://") {217 if base.starts_with("https://") {
@@ -260,17 +221,14 @@ fn subject(base_url: &str) -> String {
260 }221 }
261 }222 }
262 223
263-/// What the push service answered for one device.
264 #[derive(Debug, PartialEq, Eq)]224 #[derive(Debug, PartialEq, Eq)]
265-pub enum Outcome {225+enum Outcome {
266 Delivered,226 Delivered,
267- /// 404 or 410: the subscription is gone and the device must be forgotten.
268 Gone,227 Gone,
269 Failed(String),228 Failed(String),
270 }229 }
271 230
272-/// Encrypts `payload` for one device and posts it to the device's push service.231+async fn send_one(
273-pub async fn send_one(
274 client: &reqwest::Client,232 client: &reqwest::Client,
275 policy: &WebhookPolicy,233 policy: &WebhookPolicy,
276 keys: &VapidKeys,234 keys: &VapidKeys,
@@ -278,7 +236,6 @@ pub async fn send_one(
278 sub: &PushSubscription,236 sub: &PushSubscription,
279 payload: &[u8],237 payload: &[u8],
280 ) -> Outcome {238 ) -> Outcome {
281- // Checked again on each send: an address literal never reaches the resolver's filter.
282 if let Err(e) = validate_url(&sub.endpoint, policy) {239 if let Err(e) = validate_url(&sub.endpoint, policy) {
283 return Outcome::Failed(e.to_string());240 return Outcome::Failed(e.to_string());
284 }241 }
@@ -313,7 +270,6 @@ pub async fn send_one(
313 }270 }
314 }271 }
315 272
316-/// Queues `alert` for every device of `user_id`. Returns at once: the work runs on a spawned task.
317 pub fn queue(state: &AppState, user_id: &str, alert: Alert) {273 pub fn queue(state: &AppState, user_id: &str, alert: Alert) {
318 let state = state.clone();274 let state = state.clone();
319 let user_id = user_id.to_owned();275 let user_id = user_id.to_owned();
@@ -324,12 +280,10 @@ pub fn queue(state: &AppState, user_id: &str, alert: Alert) {
324 });280 });
325 }281 }
326 282
327-/// Sends `alert` to every device of `user_id` now and returns how many devices there are. Devices283+async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result<()> {
328-/// the push service reports gone are removed. [`queue`] is the caller's entry point.
329-pub async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result<usize> {
330 let devices = state.store.push_subscriptions(user_id).await?;284 let devices = state.store.push_subscriptions(user_id).await?;
331 if devices.is_empty() {285 if devices.is_empty() {
332- return Ok(0);286+ return Ok(());
333 }287 }
334 let lang = match state.store.user_by_id(user_id).await? {288 let lang = match state.store.user_by_id(user_id).await? {
335 Some(user) => i18n::resolve(Some(user.language.as_str()), &http::HeaderMap::new()),289 Some(user) => i18n::resolve(Some(user.language.as_str()), &http::HeaderMap::new()),
@@ -346,11 +300,23 @@ pub async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result<u
346 for device in &devices {300 for device in &devices {
347 match send_one(client, &policy, &keys, &subject, device, &payload).await {301 match send_one(client, &policy, &keys, &subject, device, &payload).await {
348 Outcome::Delivered => {302 Outcome::Delivered => {
349- state.store.mark_push_delivered(&device.id).await?;303+ if let Err(e) = state.store.mark_push_delivered(&device.id).await {
304+ tracing::warn!(
305+ error = %e,
306+ device = %device.id,
307+ "web push: the delivery stamp was not saved"
308+ );
309+ }
350 state.push_live.publish(user_id);310 state.push_live.publish(user_id);
351 }311 }
352 Outcome::Gone => {312 Outcome::Gone => {
353- state.store.delete_push_endpoint(&device.endpoint).await?;313+ if let Err(e) = state.store.delete_push_endpoint(&device.endpoint).await {
314+ tracing::warn!(
315+ error = %e,
316+ device = %device.id,
317+ "web push: the gone device was not removed"
318+ );
319+ }
354 state.push_live.publish(user_id);320 state.push_live.publish(user_id);
355 }321 }
356 Outcome::Failed(reason) => {322 Outcome::Failed(reason) => {
@@ -358,7 +324,7 @@ pub async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result<u
358 }324 }
359 }325 }
360 }326 }
361- Ok(devices.len())327+ Ok(())
362 }328 }
363 329
364 #[cfg(test)]330 #[cfg(test)]
@@ -449,8 +415,6 @@ mod tests {
449 assert_eq!(rx.try_recv().expect("event"), "tahinli");415 assert_eq!(rx.try_recv().expect("event"), "tahinli");
450 }416 }
451 417
452- /// A local stand-in for a push service: `/gone` answers 410, `/ok` answers 201, and each
453- /// request is read in full (headers and body) before it is answered.
454 async fn mock_push_service() -> std::net::SocketAddr {418 async fn mock_push_service() -> std::net::SocketAddr {
455 use tokio::io::{AsyncReadExt, AsyncWriteExt};419 use tokio::io::{AsyncReadExt, AsyncWriteExt};
456 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")420 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
@@ -523,7 +487,6 @@ mod tests {
523 async fn a_device_the_service_reports_gone_is_removed_and_a_live_one_is_kept() {487 async fn a_device_the_service_reports_gone_is_removed_and_a_live_one_is_kept() {
524 let dir = tempfile::tempdir().expect("tempdir");488 let dir = tempfile::tempdir().expect("tempdir");
525 let mut state = crate::test_support::test_state(dir.path()).await;489 let mut state = crate::test_support::test_state(dir.path()).await;
526- // The mock push service is on loopback over http, which the policy refuses by default.
527 let mut config = crate::test_support::test_config(dir.path());490 let mut config = crate::test_support::test_config(dir.path());
528 config.webhooks = forge_core::config::WebhookConfig {491 config.webhooks = forge_core::config::WebhookConfig {
529 allow_http: true,492 allow_http: true,
@@ -538,13 +501,15 @@ mod tests {
538 let addr = mock_push_service().await;501 let addr = mock_push_service().await;
539 let gone = format!("http://{addr}/gone");502 let gone = format!("http://{addr}/gone");
540 let ok = format!("http://{addr}/ok");503 let ok = format!("http://{addr}/ok");
504+ let gone_device = device(gone.clone());
505+ let ok_device = device(ok.clone());
541 state506 state
542 .store507 .store
543 .save_push_subscription(508 .save_push_subscription(
544 &user.id,509 &user.id,
545 &gone,510 &gone,
546- &device(gone.clone()).p256dh,511+ &gone_device.p256dh,
547- &device(gone.clone()).auth,512+ &gone_device.auth,
548 "Chrome on Linux",513 "Chrome on Linux",
549 )514 )
550 .await515 .await
@@ -554,17 +519,16 @@ mod tests {
554 .save_push_subscription(519 .save_push_subscription(
555 &user.id,520 &user.id,
556 &ok,521 &ok,
557- &device(ok.clone()).p256dh,522+ &ok_device.p256dh,
558- &device(ok.clone()).auth,523+ &ok_device.auth,
559 "Chrome on Linux",524 "Chrome on Linux",
560 )525 )
561 .await526 .await
562 .expect("save ok");527 .expect("save ok");
563 528
564- let sent = deliver(&state, &user.id, &Alert::Test)529+ deliver(&state, &user.id, &Alert::Test)
565 .await530 .await
566 .expect("deliver");531 .expect("deliver");
567- assert_eq!(sent, 2);
568 let left = state532 let left = state
569 .store533 .store
570 .push_subscriptions(&user.id)534 .push_subscriptions(&user.id)
@@ -615,7 +579,6 @@ mod tests {
615 send(format!("http://{addr}/gone"), open).await,579 send(format!("http://{addr}/gone"), open).await,
616 Outcome::Gone580 Outcome::Gone
617 );581 );
618- // The default policy refuses an internal address before anything is sent.
619 let strict = WebhookPolicy::from_config(&forge_core::config::WebhookConfig::default())582 let strict = WebhookPolicy::from_config(&forge_core::config::WebhookConfig::default())
620 .expect("policy");583 .expect("policy");
621 assert!(matches!(584 assert!(matches!(
crates/forge-web-app/src/webhooks/client.rsmodified+20 -36
@@ -80,7 +80,6 @@ impl WebhookPolicy {
80 80
81 /// True when the address falls inside a CIDR network in the allow list.81 /// True when the address falls inside a CIDR network in the allow list.
82 pub fn ip_allowed(&self, ip: IpAddr) -> bool {82 pub fn ip_allowed(&self, ip: IpAddr) -> bool {
83- // An IPv4-mapped address matches an IPv4 network, so check both forms.
84 let mapped = ip.to_canonical();83 let mapped = ip.to_canonical();
85 self.allowed_hosts.iter().any(|entry| match entry {84 self.allowed_hosts.iter().any(|entry| match entry {
86 AllowEntry::Net(net) => net.contains(&ip) || net.contains(&mapped),85 AllowEntry::Net(net) => net.contains(&ip) || net.contains(&mapped),
@@ -131,7 +130,6 @@ pub fn validate_url(url: &str, policy: &WebhookPolicy) -> Result<Url, UrlError>
131 if !parsed.username().is_empty() || parsed.password().is_some() {130 if !parsed.username().is_empty() || parsed.password().is_some() {
132 return Err(UrlError::Userinfo);131 return Err(UrlError::Userinfo);
133 }132 }
134- // An explicit port is parsed by `Url` (so >65535 fails above); only 0 needs rejecting here.
135 if parsed.port() == Some(0) {133 if parsed.port() == Some(0) {
136 return Err(UrlError::BadPort);134 return Err(UrlError::BadPort);
137 }135 }
@@ -139,7 +137,6 @@ pub fn validate_url(url: &str, policy: &WebhookPolicy) -> Result<Url, UrlError>
139 if host.is_empty() {137 if host.is_empty() {
140 return Err(UrlError::MissingHost);138 return Err(UrlError::MissingHost);
141 }139 }
142- // IPv6 literals come back bracketed, e.g. "[::1]".
143 let bare = host.trim_start_matches('[').trim_end_matches(']');140 let bare = host.trim_start_matches('[').trim_end_matches(']');
144 if let Ok(ip) = bare.parse::<IpAddr>() {141 if let Ok(ip) = bare.parse::<IpAddr>() {
145 check_literal(ip, policy)?;142 check_literal(ip, policy)?;
@@ -156,7 +153,8 @@ fn check_literal(ip: IpAddr, policy: &WebhookPolicy) -> Result<(), UrlError> {
156 }153 }
157 154
158 /// True for addresses a webhook must not reach by default: loopback, private, link-local, CGNAT,155 /// True for addresses a webhook must not reach by default: loopback, private, link-local, CGNAT,
159-/// unspecified, multicast, broadcast, documentation and reserved ranges. IPv4 addresses embedded156+/// unspecified, multicast, broadcast, documentation and reserved ranges (including 0.0.0.0/8,
157+/// 100.64.0.0/10 CGNAT, 192.0.0.0/24, 198.18.0.0/15 and 240.0.0.0/4). IPv4 addresses embedded
160 /// in IPv6 (mapped, compatible, NAT64, 6to4, Teredo) are judged by the embedded IPv4 address.158 /// in IPv6 (mapped, compatible, NAT64, 6to4, Teredo) are judged by the embedded IPv4 address.
161 pub fn is_forbidden_ip(ip: IpAddr) -> bool {159 pub fn is_forbidden_ip(ip: IpAddr) -> bool {
162 match ip {160 match ip {
@@ -174,11 +172,11 @@ fn is_forbidden_v4(ip: Ipv4Addr) -> bool {
174 || ip.is_multicast()172 || ip.is_multicast()
175 || ip.is_broadcast()173 || ip.is_broadcast()
176 || ip.is_documentation()174 || ip.is_documentation()
177- || a == 0 // 0.0.0.0/8175+ || a == 0
178- || (a == 100 && (b & 0xc0) == 64) // 100.64.0.0/10 CGNAT176+ || (a == 100 && (b & 0xc0) == 64)
179- || (a == 192 && b == 0 && c == 0) // 192.0.0.0/24 IETF protocol assignments177+ || (a == 192 && b == 0 && c == 0)
180- || (a == 198 && (b & 0xfe) == 18) // 198.18.0.0/15 benchmarking178+ || (a == 198 && (b & 0xfe) == 18)
181- || a >= 240 // 240.0.0.0/4 reserved179+ || a >= 240
182 }180 }
183 181
184 fn is_forbidden_v6(ip: Ipv6Addr) -> bool {182 fn is_forbidden_v6(ip: Ipv6Addr) -> bool {
@@ -189,27 +187,22 @@ fn is_forbidden_v6(ip: Ipv6Addr) -> bool {
189 if ip.is_loopback() || ip.is_unspecified() || ip.is_multicast() {187 if ip.is_loopback() || ip.is_unspecified() || ip.is_multicast() {
190 return true;188 return true;
191 }189 }
192- if (s[0] & 0xfe00) == 0xfc00 // fc00::/7 unique local190+ if (s[0] & 0xfe00) == 0xfc00
193- || (s[0] & 0xffc0) == 0xfe80 // fe80::/10 link-local191+ || (s[0] & 0xffc0) == 0xfe80
194- || (s[0] == 0x2001 && s[1] == 0x0db8) // 2001:db8::/32 documentation192+ || (s[0] == 0x2001 && s[1] == 0x0db8)
195 || (s[0] == 0x0100 && s[1] == 0 && s[2] == 0 && s[3] == 0)193 || (s[0] == 0x0100 && s[1] == 0 && s[2] == 0 && s[3] == 0)
196- // 100::/64 discard
197 {194 {
198 return true;195 return true;
199 }196 }
200- // IPv4-compatible ::/96 (deprecated).
201 if s[..6] == [0; 6] {197 if s[..6] == [0; 6] {
202 return is_forbidden_v4(v4_from(s[6], s[7]));198 return is_forbidden_v4(v4_from(s[6], s[7]));
203 }199 }
204- // NAT64 well-known prefix 64:ff9b::/96, and the local-use 64:ff9b:1::/48.
205 if s[0] == 0x0064 && s[1] == 0xff9b {200 if s[0] == 0x0064 && s[1] == 0xff9b {
206 return s[2] == 0x0001 || (s[2..6] == [0; 4] && is_forbidden_v4(v4_from(s[6], s[7])));201 return s[2] == 0x0001 || (s[2..6] == [0; 4] && is_forbidden_v4(v4_from(s[6], s[7])));
207 }202 }
208- // 6to4 2002::/16 embeds the IPv4 address in the second and third segments.
209 if s[0] == 0x2002 {203 if s[0] == 0x2002 {
210 return is_forbidden_v4(v4_from(s[1], s[2]));204 return is_forbidden_v4(v4_from(s[1], s[2]));
211 }205 }
212- // Teredo 2001::/32 embeds the server address and an obfuscated client address.
213 if s[0] == 0x2001 && s[1] == 0 {206 if s[0] == 0x2001 && s[1] == 0 {
214 let client = Ipv4Addr::from(!u32::from(v4_from(s[6], s[7])));207 let client = Ipv4Addr::from(!u32::from(v4_from(s[6], s[7])));
215 return is_forbidden_v4(v4_from(s[2], s[3])) || is_forbidden_v4(client);208 return is_forbidden_v4(v4_from(s[2], s[3])) || is_forbidden_v4(client);
@@ -291,18 +284,15 @@ pub struct HookClient {
291 284
292 impl HookClient {285 impl HookClient {
293 pub fn new(policy: WebhookPolicy) -> reqwest::Result<Arc<Self>> {286 pub fn new(policy: WebhookPolicy) -> reqwest::Result<Arc<Self>> {
294- let policy = Arc::new(policy);287+ let client = policy_client(
295- let client = reqwest::Client::builder()288+ policy.clone(),
296- .redirect(reqwest::redirect::Policy::none())289+ Duration::from_secs(20),
297- .connect_timeout(Duration::from_secs(10))290+ concat!("forge-hookshot/", env!("CARGO_PKG_VERSION")),
298- .timeout(Duration::from_secs(20))291+ )?;
299- .dns_resolver(Arc::new(PolicyResolver {292+ Ok(Arc::new(Self {
300- policy: policy.clone(),293+ client,
301- }))294+ policy: Arc::new(policy),
302- .user_agent(concat!("forge-hookshot/", env!("CARGO_PKG_VERSION")))295+ }))
303- .no_proxy()
304- .build()?;
305- Ok(Arc::new(Self { client, policy }))
306 }296 }
307 297
308 /// POSTs `body` to `url`. Never follows redirects, and reads at most [`MAX_BODY_BYTES`] of the response.298 /// POSTs `body` to `url`. Never follows redirects, and reads at most [`MAX_BODY_BYTES`] of the response.
@@ -377,11 +367,7 @@ impl HookClient {
377 367
378 /// Signs a delivery body: `sha256=` followed by the hex HMAC-SHA256 of `body` under `secret`.368 /// Signs a delivery body: `sha256=` followed by the hex HMAC-SHA256 of `body` under `secret`.
379 pub fn sign(secret: &[u8], body: &[u8]) -> String {369 pub fn sign(secret: &[u8], body: &[u8]) -> String {
380- // HMAC accepts keys of any length, so the error branch is unreachable.370+ let mut mac = HmacSha256::new_from_slice(secret).expect("HMAC takes keys of any length");
381- let mut mac = match HmacSha256::new_from_slice(secret) {
382- Ok(mac) => mac,
383- Err(_) => return String::new(),
384- };
385 mac.update(body);371 mac.update(body);
386 format!("sha256={}", hex::encode(mac.finalize().into_bytes()))372 format!("sha256={}", hex::encode(mac.finalize().into_bytes()))
387 }373 }
@@ -537,7 +523,6 @@ mod tests {
537 523
538 #[test]524 #[test]
539 fn sign_matches_rfc4231_case_2() {525 fn sign_matches_rfc4231_case_2() {
540- // RFC 4231 test case 2: key "Jefe", data "what do ya want for nothing?".
541 assert_eq!(526 assert_eq!(
542 sign(b"Jefe", b"what do ya want for nothing?"),527 sign(b"Jefe", b"what do ya want for nothing?"),
543 "sha256=5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"528 "sha256=5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
@@ -607,7 +592,6 @@ mod tests {
607 592
608 #[tokio::test]593 #[tokio::test]
609 async fn send_accepts_allowed_cidr_and_hostname() {594 async fn send_accepts_allowed_cidr_and_hostname() {
610- // (name, allowed entry, host used in the URL); both must deliver the same response.
611 let cases = [595 let cases = [
612 ("loopback cidr", "127.0.0.1/32", "127.0.0.1"),596 ("loopback cidr", "127.0.0.1/32", "127.0.0.1"),
613 ("hostname", "localhost", "localhost"),597 ("hostname", "localhost", "localhost"),
crates/forge-web-app/src/webhooks/emit.rsmodified+9 -5
@@ -486,13 +486,17 @@ async fn new_commits(
486 } else {486 } else {
487 MAX_NEW_REF_COMMITS487 MAX_NEW_REF_COMMITS
488 };488 };
489- match forge_git::history::new_commits(&state.git, &dir, old, new, max).await {489+ let commits = match forge_git::history::new_commits(&state.git, &dir, old, new, max).await {
490- Ok(commits) => {490+ Ok(commits) => commits,
491- let total = commits.len();
492- (commits, total)
493- }
494 Err(e) => {491 Err(e) => {
495 tracing::error!(error = %e, repo_id = %repo.id, "webhooks: listing push commits failed");492 tracing::error!(error = %e, repo_id = %repo.id, "webhooks: listing push commits failed");
493+ return (Vec::new(), 0);
494+ }
495+ };
496+ match forge_git::history::count_new_commits(&state.git, &dir, old, new).await {
497+ Ok(total) => (commits, total as usize),
498+ Err(e) => {
499+ tracing::error!(error = %e, repo_id = %repo.id, "webhooks: counting push commits failed");
496 (Vec::new(), 0)500 (Vec::new(), 0)
497 }501 }
498 }502 }
crates/forge-web-app/src/webhooks/payload.rsmodified+4 -9
@@ -53,7 +53,7 @@ pub fn sender(id: &str, username: &str) -> Value {
53 53
54 /// `issues` payload: `issue`. The emit side adds `label` or `assignee` for those actions.54 /// `issues` payload: `issue`. The emit side adds `label` or `assignee` for those actions.
55 pub fn issues(base_url: &str, repo: &Repo, issue: &Issue) -> Value {55 pub fn issues(base_url: &str, repo: &Repo, issue: &Issue) -> Value {
56- json!({ "issue": issue_object(base_url, repo, issue, false) })56+ json!({ "issue": issue_object(issue, &item_url(base_url, repo, "issues", issue.number)) })
57 }57 }
58 58
59 /// `pull_request` payload: `number` and `pull_request`.59 /// `pull_request` payload: `number` and `pull_request`.
@@ -80,7 +80,7 @@ pub fn issue_comment(
80 issue.number,80 issue.number,
81 );81 );
82 json!({82 json!({
83- "issue": issue_object(base_url, repo, issue, pull),83+ "issue": issue_object(issue, &page),
84 "comment": {84 "comment": {
85 "id": comment.id,85 "id": comment.id,
86 "body": comment.body,86 "body": comment.body,
@@ -154,18 +154,13 @@ pub fn ping(hook_id: &str) -> Value {
154 })154 })
155 }155 }
156 156
157-fn issue_object(base_url: &str, repo: &Repo, issue: &Issue, pull: bool) -> Value {157+fn issue_object(issue: &Issue, html_url: &str) -> Value {
158 json!({158 json!({
159 "number": issue.number,159 "number": issue.number,
160 "title": issue.title,160 "title": issue.title,
161 "body": issue.body,161 "body": issue.body,
162 "state": issue.state.as_str(),162 "state": issue.state.as_str(),
163- "html_url": item_url(163+ "html_url": html_url,
164- base_url,
165- repo,
166- if pull { "pulls" } else { "issues" },
167- issue.number,
168- ),
169 })164 })
170 }165 }
171 166
crates/forge-web-pages/src/pages/issue_parts.rsmodified+2 -2
@@ -29,7 +29,7 @@ use crate::pages::tree::link_context;
29 use crate::render::markdown::{LinkContext, render_markdown};29 use crate::render::markdown::{LinkContext, render_markdown};
30 use crate::state::AppState;30 use crate::state::AppState;
31 use crate::views::parts::{confirm_act, post_act, reveal};31 use crate::views::parts::{confirm_act, post_act, reveal};
32-use crate::views::review_thread::{ThreadCtx, review_thread_in};32+use crate::views::review_thread::{ThreadCtx, review_thread};
33 use crate::views::user_facing_message;33 use crate::views::user_facing_message;
34 use crate::views::{34 use crate::views::{
35 When, alert, avatar_url, avatar_url_unknown, display_name, now_unix, repo_href, short_oid,35 When, alert, avatar_url, avatar_url_unknown, display_name, now_unix, repo_href, short_oid,
@@ -648,7 +648,7 @@ pub async fn review_item(cx: &Cx, lang: Lang, review: ReviewView) -> Result<impl
648 <div class="issue-item-body markdown-body">(Unescaped::new_unchecked(body))</div>648 <div class="issue-item-body markdown-body">(Unescaped::new_unchecked(body))</div>
649 }649 }
650 for thread in threads.into_iter() {650 for thread in threads.into_iter() {
651- review_thread_in(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: true, return_to: "conversation")651+ review_thread(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: true, return_to: "conversation")
652 }652 }
653 </article>653 </article>
654 })654 })
crates/forge-web-repo/src/pages/branches.rsmodified+2 -3
@@ -31,8 +31,7 @@ use crate::post_update::after_ref_update;
31 use crate::state::AppState;31 use crate::state::AppState;
32 use crate::views::commit_line::commit_line;32 use crate::views::commit_line::commit_line;
33 use crate::views::parts::{confirm_act, reveal};33 use crate::views::parts::{confirm_act, reveal};
34-use crate::views::url_path;34+use crate::views::{alert, enc, iso_time, now_unix, relative_time, repo_href, shell};
35-use crate::views::{alert, iso_time, now_unix, relative_time, repo_href, shell};
36 35
37 path_param!(owner);36 path_param!(owner);
38 path_param!(repo);37 path_param!(repo);
@@ -222,7 +221,7 @@ async fn branches_page(cx: &Cx) -> Result<impl View> {
222 &repo.owner_name,221 &repo.owner_name,
223 &repo.name,222 &repo.name,
224 "compare",223 "compare",
225- &url_path(&format!("{}...{}", repo.default_branch, info.name)),224+ &enc(&format!("{}...{}", repo.default_branch, info.name)),
226 ));225 ));
227 }226 }
228 }227 }
crates/forge-web-repo/src/pages/commits.rsmodified+6 -10
@@ -28,7 +28,7 @@ use crate::signatures::{self, SigBadge};
28 use crate::state::AppState;28 use crate::state::AppState;
29 use crate::views::commit_line::commit_line;29 use crate::views::commit_line::commit_line;
30 use crate::views::commit_status::{StatusLang, StatusSummary, commit_status, status_list};30 use crate::views::commit_status::{StatusLang, StatusSummary, commit_status, status_list};
31-use crate::views::{shell, url_path};31+use crate::views::{enc, shell};
32 32
33 path_param!(owner);33 path_param!(owner);
34 path_param!(repo);34 path_param!(repo);
@@ -267,7 +267,7 @@ async fn commits_page(cx: &Cx) -> Result<impl View> {
267 Some(p) => format!("{ref_name}/{p}"),267 Some(p) => format!("{ref_name}/{p}"),
268 None => ref_name.clone(),268 None => ref_name.clone(),
269 };269 };
270- let base = format!("/{owner_name}/{repo_name}/commits/{}", url_path(&spec));270+ let base = format!("/{owner_name}/{repo_name}/commits/{}", enc(&spec));
271 let href_for = |n: u32| {271 let href_for = |n: u32| {
272 if n <= 1 {272 if n <= 1 {
273 base.clone()273 base.clone()
@@ -286,11 +286,7 @@ async fn commits_page(cx: &Cx) -> Result<impl View> {
286 .store286 .store
287 .statuses_for_many_rows(&ctx.repo.id, &oids)287 .statuses_for_many_rows(&ctx.repo.id, &oids)
288 .await?;288 .await?;
289- let shown_oids: Vec<String> = commits289+ let shown_oids: Vec<String> = commits.iter().map(|info| info.oid.clone()).collect();
290- .iter()
291- .take(PAGE_SIZE)
292- .map(|info| info.oid.clone())
293- .collect();
294 let sigs = signatures::badges(state, &ctx.repo, &shown_oids).await;290 let sigs = signatures::badges(state, &ctx.repo, &shown_oids).await;
295 let rows: Vec<CommitRow> = commits291 let rows: Vec<CommitRow> = commits
296 .iter()292 .iter()
@@ -302,7 +298,7 @@ async fn commits_page(cx: &Cx) -> Result<impl View> {
302 .collect();298 .collect();
303 let empty = rows.is_empty();299 let empty = rows.is_empty();
304 let title = format!("{owner_name}/{repo_name}");300 let title = format!("{owner_name}/{repo_name}");
305- let clear_href = format!("/{owner_name}/{repo_name}/commits/{}", url_path(&ref_name));301+ let clear_href = format!("/{owner_name}/{repo_name}/commits/{}", enc(&ref_name));
306 let has_filter = filter.is_some();302 let has_filter = filter.is_some();
307 let filter_text = filter.unwrap_or_default();303 let filter_text = filter.unwrap_or_default();
308 let page_label = i18n::page_label(lang, page_no);304 let page_label = i18n::page_label(lang, page_no);
@@ -411,7 +407,7 @@ mod tests {
411 use crate::i18n::Lang;407 use crate::i18n::Lang;
412 use crate::test_support::fixture::{Fixture, OWNER, REPO, get, git};408 use crate::test_support::fixture::{Fixture, OWNER, REPO, get, git};
413 use crate::views::relative_time;409 use crate::views::relative_time;
414- use crate::views::url_path;410+ use crate::views::enc;
415 411
416 #[test]412 #[test]
417 fn dates_and_relative_units_format() {413 fn dates_and_relative_units_format() {
@@ -426,7 +422,7 @@ mod tests {
426 relative_time(Lang::En, 10_000 - 86_400, 10_000),422 relative_time(Lang::En, 10_000 - 86_400, 10_000),
427 "1 day ago"423 "1 day ago"
428 );424 );
429- assert_eq!(url_path("a b/c#d"), "a%20b/c%23d");425+ assert_eq!(enc("a b/c#d"), "a%20b/c%23d");
430 }426 }
431 427
432 /// Pages through history (50, then 5), and refuses bad pages and unknown refs.428 /// Pages through history (50, then 5), and refuses bad pages and unknown refs.
crates/forge-web-repo/src/pages/compare.rsmodified+3 -4
@@ -39,8 +39,7 @@ use crate::templates;
39 use crate::views::commit_line::commit_line;39 use crate::views::commit_line::commit_line;
40 use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};40 use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};
41 use crate::views::parts::reveal;41 use crate::views::parts::reveal;
42-use crate::views::url_path;42+use crate::views::{alert, enc, repo_href, shell, user_facing_message};
43-use crate::views::{alert, repo_href, shell, user_facing_message};
44 use crate::webhooks::emit::{Sender, emit_pull};43 use crate::webhooks::emit::{Sender, emit_pull};
45 44
46 path_param!(owner);45 path_param!(owner);
@@ -263,7 +262,7 @@ async fn compare_view(
263 262
264 let compare_path = format!(263 let compare_path = format!(
265 "/{owner}/{name}/compare/{}",264 "/{owner}/{name}/compare/{}",
266- url_path(&format!("{base}...{head}"))265+ enc(&format!("{base}...{head}"))
267 );266 );
268 let mut opts = DiffOpts::from_cx(267 let mut opts = DiffOpts::from_cx(
269 cx,268 cx,
@@ -476,7 +475,7 @@ async fn compare_picker(cx: &Cx) -> Result<impl View> {
476 "/{}/{}/compare/{}",475 "/{}/{}/compare/{}",
477 ctx.repo.owner_name,476 ctx.repo.owner_name,
478 ctx.repo.name,477 ctx.repo.name,
479- url_path(&format!("{base}...{head}"))478+ enc(&format!("{base}...{head}"))
480 );479 );
481 return Err(see_other(target).into());480 return Err(see_other(target).into());
482 }481 }