From 2e748ef70e9a18af72120071b8fe1179fab1932c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 1 Dec 2026 13:41:45 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20forge-web-app?= =?UTF-8?q?=20drops=20dead=20code,=20duplicated=20helpers=20and=20stale=20?= =?UTF-8?q?comments;=20fixes:=20nice=5Fmax=20no=20longer=20overflows=20on?= =?UTF-8?q?=20huge=20runner=20rates,=20runner=20log=20seqs=20saturate,=20d?= =?UTF-8?q?isabled=20alert=20categories=20clear=20their=20alerts,=20LFS=20?= =?UTF-8?q?over=20SSH=20gets=20a=20direction-scoped=20token,=20ci-job=20is?= =?UTF-8?q?=20a=20reserved=20name=20so=20no=20user=20is=20locked=20out=20o?= =?UTF-8?q?f=20git=20over=20HTTP,=20and=20other=20verified=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-core/src/names.rs | 1 + crates/forge-core/src/store/mod.rs | 13 + crates/forge-core/src/time.rs | 49 ++- crates/forge-core/src/token.rs | 15 + crates/forge-git/src/history.rs | 26 ++ crates/forge-git/src/repo.rs | 9 +- .../src/pages/admin_live_tests.rs | 2 +- .../src/pages/settings_security.rs | 8 +- crates/forge-web-app/build.rs | 2 +- crates/forge-web-app/src/admin_client.rs | 13 +- crates/forge-web-app/src/advisories/scan.rs | 14 +- crates/forge-web-app/src/alerts.rs | 153 ++++++--- crates/forge-web-app/src/api/gitea.rs | 324 +++++++++--------- crates/forge-web-app/src/api/mod.rs | 56 ++- crates/forge-web-app/src/api/packages.rs | 30 +- crates/forge-web-app/src/api/releases.rs | 134 ++++---- crates/forge-web-app/src/api/statuses.rs | 51 +-- crates/forge-web-app/src/auth.rs | 68 +--- crates/forge-web-app/src/automerge.rs | 8 +- crates/forge-web-app/src/backup/mod.rs | 38 +- crates/forge-web-app/src/backup/restore.rs | 248 +++++--------- crates/forge-web-app/src/backup/scheduler.rs | 51 +-- crates/forge-web-app/src/backup/tests.rs | 20 +- crates/forge-web-app/src/backup/verify.rs | 115 ++++--- crates/forge-web-app/src/ci/api.rs | 235 +++++-------- crates/forge-web-app/src/ci/metrics_chart.rs | 11 +- crates/forge-web-app/src/ci/reaper.rs | 14 +- crates/forge-web-app/src/ci/release.rs | 55 --- crates/forge-web-app/src/ci/runner_log.rs | 9 - crates/forge-web-app/src/ci/runner_metrics.rs | 2 +- crates/forge-web-app/src/ci/schedule.rs | 245 ++++++------- crates/forge-web-app/src/client_ip.rs | 31 +- crates/forge-web-app/src/exporter.rs | 52 +-- crates/forge-web-app/src/git_http.rs | 62 ++-- crates/forge-web-app/src/importer/api.rs | 157 +++------ crates/forge-web-app/src/importer/mod.rs | 136 +++++--- crates/forge-web-app/src/importer/remote.rs | 38 +- crates/forge-web-app/src/internal.rs | 42 +-- crates/forge-web-app/src/layers.rs | 52 ++- crates/forge-web-app/src/lfs/gc.rs | 22 +- crates/forge-web-app/src/lfs/mod.rs | 16 +- crates/forge-web-app/src/lfs/routes.rs | 18 +- crates/forge-web-app/src/lfs_pointer.rs | 6 +- crates/forge-web-app/src/live.rs | 17 +- crates/forge-web-app/src/mail/smtp.rs | 7 +- crates/forge-web-app/src/mail/worker.rs | 33 +- crates/forge-web-app/src/merge.rs | 77 ++--- crates/forge-web-app/src/merge_queue.rs | 55 ++- crates/forge-web-app/src/mirrors/worker.rs | 46 +-- crates/forge-web-app/src/notify.rs | 10 +- crates/forge-web-app/src/oci/auth.rs | 20 +- crates/forge-web-app/src/oci/blobs.rs | 23 +- crates/forge-web-app/src/oci/manifests.rs | 16 +- crates/forge-web-app/src/oci/mod.rs | 13 +- crates/forge-web-app/src/package_ops.rs | 20 +- crates/forge-web-app/src/post_update.rs | 106 +++--- crates/forge-web-app/src/raw/media.rs | 98 +----- crates/forge-web-app/src/raw/mod.rs | 151 ++++---- crates/forge-web-app/src/raw/snippet_raw.rs | 50 +-- crates/forge-web-app/src/self_update.rs | 79 +---- crates/forge-web-app/src/signatures.rs | 27 +- crates/forge-web-app/src/ssh_backend.rs | 10 +- .../forge-web-app/src/test_support/fixture.rs | 12 +- crates/forge-web-app/src/test_support/http.rs | 16 + crates/forge-web-app/src/test_support/mod.rs | 1 + crates/forge-web-app/src/views/diff.rs | 18 +- crates/forge-web-app/src/views/heatmap.rs | 61 +--- crates/forge-web-app/src/views/mod.rs | 104 +----- .../forge-web-app/src/views/review_thread.rs | 60 +--- crates/forge-web-app/src/web_push/crypto.rs | 43 +-- crates/forge-web-app/src/web_push/mod.rs | 99 ++---- crates/forge-web-app/src/webhooks/client.rs | 56 ++- crates/forge-web-app/src/webhooks/emit.rs | 14 +- crates/forge-web-app/src/webhooks/payload.rs | 13 +- .../forge-web-pages/src/pages/issue_parts.rs | 4 +- crates/forge-web-repo/src/pages/branches.rs | 5 +- crates/forge-web-repo/src/pages/commits.rs | 16 +- crates/forge-web-repo/src/pages/compare.rs | 7 +- 78 files changed, 1598 insertions(+), 2440 deletions(-) create mode 100644 crates/forge-web-app/src/test_support/http.rs diff --git a/crates/forge-core/src/names.rs b/crates/forge-core/src/names.rs index 460e672..1dc5345 100644 --- a/crates/forge-core/src/names.rs +++ b/crates/forge-core/src/names.rs @@ -28,6 +28,7 @@ pub const RESERVED: &[&str] = &[ "orgs", "raw", "git", + "ci-job", "internal", "help", "about", diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 3b31045..4849876 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -745,6 +745,19 @@ impl Store { } } + pub async fn user_roles( + &self, + repo: &Repo, + user: Option<&User>, + ) -> Result<(Option, Option)> { + let Some(user) = user else { + return Ok((None, None)); + }; + let collaborator = self.collaborator_role(&repo.id, &user.id).await?; + let org = self.org_repo_role(&repo.owner_id, &user.id, &repo.id).await?; + Ok((collaborator, org)) + } + /// Adds or replaces a collaborator's role on a repo. pub async fn set_collaborator(&self, repo_id: &str, user_id: &str, role: Role) -> Result<()> { let conn = self.inner.conn.lock().await; diff --git a/crates/forge-core/src/time.rs b/crates/forge-core/src/time.rs index 0eec834..1b12764 100644 --- a/crates/forge-core/src/time.rs +++ b/crates/forge-core/src/time.rs @@ -3,7 +3,9 @@ use std::time::Duration; use time::{ - OffsetDateTime, SignedDuration, format_description::FormatItem, macros::format_description, + OffsetDateTime, SignedDuration, + format_description::{FormatItem, well_known::Rfc3339}, + macros::format_description, }; const FORMAT: &[FormatItem<'static>] = @@ -19,6 +21,16 @@ pub fn now_stamp() -> String { format_stamp(OffsetDateTime::now_utc()) } +pub fn unix_now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +pub fn now_unix() -> i64 { + i64::try_from(unix_now()).unwrap_or(0) +} + /// The stamp for `now + after`, in the same format as [`now_stamp`]. /// Saturates at the maximum representable time instead of panicking. pub fn stamp_after(after: Duration) -> String { @@ -43,15 +55,48 @@ pub fn stamp_from_unix(unix: i64) -> Option { /// Unix seconds for a stamp written by [`now_stamp`]. `None` when the text is not a stamp. pub fn stamp_to_unix(stamp: &str) -> Option { - OffsetDateTime::parse(stamp, &time::format_description::well_known::Rfc3339) + OffsetDateTime::parse(stamp, &Rfc3339) .ok() .map(OffsetDateTime::unix_timestamp) } +/// The shortest sleep, so a due time that has already passed does not spin a worker loop. +const MIN_SLEEP: Duration = Duration::from_secs(1); + +/// How long a worker sleeps: until `next_due` (an RFC 3339 stamp), clamped to +/// `MIN_SLEEP..=backstop`. `None` (nothing due) or an unparsable stamp gives `backstop`. +pub fn sleep_until(next_due: Option<&str>, now: OffsetDateTime, backstop: Duration) -> Duration { + let Some(due) = next_due.and_then(|s| OffsetDateTime::parse(s, &Rfc3339).ok()) else { + return backstop; + }; + let until = Duration::try_from(due - now).unwrap_or(Duration::ZERO); + until.clamp(MIN_SLEEP, backstop) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn sleep_stops_at_the_next_due_time_and_is_clamped() { + use time::macros::datetime; + + let backstop = Duration::from_secs(900); + let now = datetime!(2026-10-15 12:00:00 UTC); + let stamp = |t: OffsetDateTime| t.format(&Rfc3339).expect("stamp"); + assert_eq!(sleep_until(None, now, backstop), backstop); + let in_10s = stamp(now + SignedDuration::seconds(10)); + assert_eq!( + sleep_until(Some(&in_10s), now, backstop), + Duration::from_secs(10) + ); + let in_1h = stamp(now + SignedDuration::hours(1)); + assert_eq!(sleep_until(Some(&in_1h), now, backstop), backstop); + let past = stamp(now - SignedDuration::seconds(5)); + assert_eq!(sleep_until(Some(&past), now, backstop), MIN_SLEEP); + assert_eq!(sleep_until(Some("soon"), now, backstop), backstop); + } + fn is_valid_stamp(s: &str) -> bool { let b = s.as_bytes(); b.len() == 30 diff --git a/crates/forge-core/src/token.rs b/crates/forge-core/src/token.rs index 886a5c5..2134c47 100644 --- a/crates/forge-core/src/token.rs +++ b/crates/forge-core/src/token.rs @@ -39,6 +39,21 @@ pub fn hash_token(token: &str) -> String { hex::encode(Sha256::digest(token.as_bytes())) } +pub fn sha256_reader(mut reader: impl std::io::Read) -> std::io::Result<(u64, String)> { + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 64 * 1024]; + let mut total = 0u64; + loop { + let n = reader.read(&mut buf)?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + total += n as u64; + } + Ok((total, hex::encode(hasher.finalize()))) +} + /// Constant-time byte comparison. pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { a.ct_eq(b).into() diff --git a/crates/forge-git/src/history.rs b/crates/forge-git/src/history.rs index ad782dd..3e75ac5 100644 --- a/crates/forge-git/src/history.rs +++ b/crates/forge-git/src/history.rs @@ -289,6 +289,32 @@ pub async fn count(env: &GitEnv, repo: &Path, commit: &str, path: Option<&str>) .map_err(|_| Error::Failed(format!("unexpected rev-list count: {:?}", text.trim()))) } +pub async fn count_new_commits( + env: &GitEnv, + repo: &Path, + old: Option<&str>, + new: &str, +) -> Result { + validate_oid(new)?; + let exclude; + let mut revs = vec![new]; + if let Some(old) = old { + validate_oid(old)?; + exclude = format!("^{old}"); + revs.push(&exclude); + } + let out = git(env, "rev-list") + .git_dir(repo) + .arg("--count") + .user_revs(&revs)? + .output() + .await?; + let text = String::from_utf8_lossy(&out); + text.trim() + .parse::() + .map_err(|_| Error::Failed(format!("unexpected rev-list count: {:?}", text.trim()))) +} + pub async fn new_commits( env: &GitEnv, repo: &Path, diff --git a/crates/forge-git/src/repo.rs b/crates/forge-git/src/repo.rs index c2ab086..7dc7781 100644 --- a/crates/forge-git/src/repo.rs +++ b/crates/forge-git/src/repo.rs @@ -2,6 +2,8 @@ use std::path::{Path, PathBuf}; +use forge_core::time::unix_now; + use crate::command::{GitCommand, GitEnv}; use crate::error::{Error, Result}; @@ -43,13 +45,6 @@ pub struct TrashEntry { pub wiki: bool, } -fn unix_now() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0) -} - /// Renames the bare repo for `repo_id` into `data_dir/trash/-.git` and returns the /// new path. A rename stays on one filesystem, so nothing is copied and nothing is deleted. /// Fails without touching anything when the repo directory is missing or the target exists. diff --git a/crates/forge-web-account/src/pages/admin_live_tests.rs b/crates/forge-web-account/src/pages/admin_live_tests.rs index 6290c72..b5a48ac 100644 --- a/crates/forge-web-account/src/pages/admin_live_tests.rs +++ b/crates/forge-web-account/src/pages/admin_live_tests.rs @@ -270,7 +270,7 @@ async fn backups_replication_health_and_server_send_for_their_changes() { crate::alerts::raise( &fx.state, - "runner_offline", + crate::alerts::AlertTopic::RunnerOffline, "runner-offline:tahinli-ci", "tahinli-ci", "silent for an hour", diff --git a/crates/forge-web-account/src/pages/settings_security.rs b/crates/forge-web-account/src/pages/settings_security.rs index 94cf1a0..f8ff5a5 100644 --- a/crates/forge-web-account/src/pages/settings_security.rs +++ b/crates/forge-web-account/src/pages/settings_security.rs @@ -19,7 +19,7 @@ use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; use crate::auth::{ - hash_password_async, logout, require_csrf, require_user, two_factor_enabled, unix_now, + hash_password_async, logout, require_csrf, require_user, two_factor_enabled, verify_password_async, verify_second_factor, }; use crate::i18n::packages::{self as pk, K as PK}; @@ -906,7 +906,7 @@ async fn two_factor_confirm(cx: &Cx, Form(form): Form) -> Result { @@ -1228,7 +1228,7 @@ mod tests { } fn now_code(shared: &[u8]) -> String { - totp::code_at(shared, totp::step_for(crate::auth::unix_now())) + totp::code_at(shared, totp::step_for(forge_core::time::unix_now())) } /// Turns two-factor on directly in the store. Returns the shared secret. @@ -1698,7 +1698,7 @@ mod tests { // The confirm step already used the current code, so disabling takes the next step's // code. Reusing the current one would be refused as a replay. - let next = totp::code_at(&shared, totp::step_for(crate::auth::unix_now()) + 1); + let next = totp::code_at(&shared, totp::step_for(forge_core::time::unix_now()) + 1); let disable = format!("csrf={CSRF}¤t_password={PASSWORD}&code={next}"); let reply = send( &fx.router, diff --git a/crates/forge-web-app/build.rs b/crates/forge-web-app/build.rs index 9364b81..b7e571a 100644 --- a/crates/forge-web-app/build.rs +++ b/crates/forge-web-app/build.rs @@ -177,7 +177,7 @@ fn swatch_rules(css: &mut String) { /// chips. fn accents_scss() -> String { let mut css = String::from( - "/* Generated by crates/forge-web/build.rs from forge-web-base/src/accent_palette.rs. Edit that file. */\n", + "/* Generated by crates/forge-web-app/build.rs from forge-web-base/src/accent_palette.rs. Edit that file. */\n", ); assert_eq!(PALETTES[0].id, DEFAULT, "the default palette comes first"); assert_eq!(BASES[0].id, BASE_DEFAULT, "the default base comes first"); diff --git a/crates/forge-web-app/src/admin_client.rs b/crates/forge-web-app/src/admin_client.rs index f14fcce..14a42e4 100644 --- a/crates/forge-web-app/src/admin_client.rs +++ b/crates/forge-web-app/src/admin_client.rs @@ -191,17 +191,10 @@ mod tests { } #[tokio::test] - async fn no_socket_means_no_server() { + async fn no_server_without_a_live_socket() { let dir = tempfile::tempdir().expect("tempdir"); - let config = crate::test_support::test_config(dir.path()); + let config = test_config(dir.path()); assert!(running_server(&config).await.expect("probe").is_none()); - } - - #[tokio::test] - async fn stale_socket_means_no_server() { - let dir = tempfile::tempdir().expect("tempdir"); - let config = crate::test_support::test_config(dir.path()); - // A socket file with no listener behind it, left by a crashed server. let listener = std::os::unix::net::UnixListener::bind(dir.path().join(SOCKET_FILE)).expect("bind"); drop(listener); @@ -209,7 +202,7 @@ mod tests { } /// Serves the internal router on a real unix socket, as boot does, and talks to it through - /// the client. Checks the answer, a refusal with the wrong token, and the no-server path. + /// the client. Checks the answer and a refusal with the wrong token. #[tokio::test] async fn client_talks_to_the_server_over_the_socket() { let dir = tempfile::tempdir().expect("tempdir"); diff --git a/crates/forge-web-app/src/advisories/scan.rs b/crates/forge-web-app/src/advisories/scan.rs index f9fb993..b6487d9 100644 --- a/crates/forge-web-app/src/advisories/scan.rs +++ b/crates/forge-web-app/src/advisories/scan.rs @@ -126,23 +126,17 @@ pub fn collect_dependencies( } let text = match read_text_blob(repo, commit, &path, MAX_LOCKFILE_BYTES) { Ok(Some(text)) => text, - Ok(None) => continue, - Err(e) => { - tracing::warn!(error = %e, path = %path, "advisories: lockfile unreadable"); - continue; + Ok(None) => { + return Err(format!("{path}: not UTF-8 text or over the size limit")); } + Err(e) => return Err(format!("{path}: {e}")), }; let parsed = match entry.name.as_str() { "Cargo.lock" => parse_cargo_lock(&text, &path), "package-lock.json" => parse_package_lock(&text, &path), _ => Ok(parse_go_sum(&text, &path)), }; - match parsed { - Ok(deps) => found.extend(deps), - Err(e) => { - tracing::warn!(error = %e, path = %path, "advisories: lockfile skipped") - } - } + found.extend(parsed.map_err(|e| format!("{path}: {e}"))?); } EntryKind::Symlink | EntryKind::Submodule => {} } diff --git a/crates/forge-web-app/src/alerts.rs b/crates/forge-web-app/src/alerts.rs index 288a790..50428f1 100644 --- a/crates/forge-web-app/src/alerts.rs +++ b/crates/forge-web-app/src/alerts.rs @@ -36,27 +36,79 @@ fn started() -> i64 { *STARTED.get_or_init(now_unix) } -fn kind_of(topic: &str) -> AlertKind { - match topic { - "runner_offline" => AlertKind::RunnerOffline, - "backup_failed" | "backup_verify_failed" | "backup_overdue" | "fsck_failed" => { - AlertKind::Backup +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum AlertTopic { + RunnerOffline, + BackupFailed, + BackupVerifyFailed, + BackupOverdue, + FsckFailed, + DiskLow, + CiKilled, + SelfUpdateRestart, + SelfUpdateFailed, + Replication, +} + +impl AlertTopic { + const ALL: [Self; 10] = [ + Self::RunnerOffline, + Self::BackupFailed, + Self::BackupVerifyFailed, + Self::BackupOverdue, + Self::FsckFailed, + Self::DiskLow, + Self::CiKilled, + Self::SelfUpdateRestart, + Self::SelfUpdateFailed, + Self::Replication, + ]; + + fn as_str(self) -> &'static str { + match self { + Self::RunnerOffline => "runner_offline", + Self::BackupFailed => "backup_failed", + Self::BackupVerifyFailed => "backup_verify_failed", + Self::BackupOverdue => "backup_overdue", + Self::FsckFailed => "fsck_failed", + Self::DiskLow => "disk_low", + Self::CiKilled => "ci_killed", + Self::SelfUpdateRestart => "self_update_restart", + Self::SelfUpdateFailed => "self_update_failed", + Self::Replication => "replication", + } + } + + fn parse(stored: &str) -> Option { + Self::ALL.into_iter().find(|t| t.as_str() == stored) + } + + fn kind(self) -> AlertKind { + match self { + Self::RunnerOffline => AlertKind::RunnerOffline, + Self::BackupFailed | Self::BackupVerifyFailed | Self::BackupOverdue | Self::FsckFailed => { + AlertKind::Backup + } + Self::DiskLow => AlertKind::Disk, + Self::CiKilled => AlertKind::CiKilled, + Self::SelfUpdateRestart | Self::SelfUpdateFailed => AlertKind::SelfUpdate, + Self::Replication => AlertKind::Replication, } - "disk_low" => AlertKind::Disk, - "ci_killed" => AlertKind::CiKilled, - "self_update_restart" | "self_update_failed" => AlertKind::SelfUpdate, - _ => AlertKind::Replication, } } /// Raises the alert `key` of `topic`. The admins hear about it once, until it resolves. -pub async fn raise(state: &AppState, topic: &str, key: &str, subject: &str, detail: &str) { - if !state.live().alerts.kind_enabled(kind_of(topic)) { +pub async fn raise(state: &AppState, topic: AlertTopic, key: &str, subject: &str, detail: &str) { + if !state.live().alerts.kind_enabled(topic.kind()) { return; } - match state.store.raise_alert(key, topic, subject, detail).await { + match state + .store + .raise_alert(key, topic.as_str(), subject, detail) + .await + { Ok(true) => { - if topic == "runner_offline" { + if topic == AlertTopic::RunnerOffline { OFFLINE_ACTIVE.store(true, Ordering::Relaxed); } deliver(state, key, topic, subject, detail, false).await; @@ -71,9 +123,12 @@ pub async fn resolve(state: &AppState, key: &str) { match state.store.resolve_alert(key).await { Ok(Some(alert)) => { crate::live::admin().bump(&crate::live::Topic::AdminHealth); - let kind = kind_of(&alert.kind); - if state.live().alerts.kind_enabled(kind) { - deliver(state, key, &alert.kind, &alert.subject, &alert.detail, true).await; + let Some(topic) = AlertTopic::parse(&alert.kind) else { + tracing::error!(key, kind = %alert.kind, "alerts: resolved an unknown topic"); + return; + }; + if state.live().alerts.kind_enabled(topic.kind()) { + deliver(state, key, topic, &alert.subject, &alert.detail, true).await; } } Ok(None) => {} @@ -82,13 +137,13 @@ pub async fn resolve(state: &AppState, key: &str) { } /// Tells the admins that something happened, once per `key`. -pub async fn event(state: &AppState, topic: &str, key: &str, subject: &str, detail: &str) { - if !state.live().alerts.kind_enabled(kind_of(topic)) { +pub async fn event(state: &AppState, topic: AlertTopic, key: &str, subject: &str, detail: &str) { + if !state.live().alerts.kind_enabled(topic.kind()) { return; } match state .store - .record_alert_event(key, topic, subject, detail) + .record_alert_event(key, topic.as_str(), subject, detail) .await { 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 async fn deliver( state: &AppState, key: &str, - topic: &str, + topic: AlertTopic, subject: &str, detail: &str, resolved: bool, @@ -121,7 +176,7 @@ async fn deliver( for admin in admins.into_iter().filter(|u| !u.is_org()) { if let Err(e) = state .store - .add_admin_notice(&admin.id, key, topic, subject, detail, resolved) + .add_admin_notice(&admin.id, key, topic.as_str(), subject, detail, resolved) .await { tracing::error!(error = %e, key, "alerts: writing an inbox row failed"); @@ -151,10 +206,10 @@ async fn deliver( } } let lang = i18n::resolve(Some(admin.language.as_str()), &http::HeaderMap::new()); - let title = text::title(lang, topic, subject, resolved); + let title = text::title(lang, topic.as_str(), subject, resolved); let body = text::mail_body( lang, - &text::body(lang, topic, subject, detail, resolved), + &text::body(lang, topic.as_str(), subject, detail, resolved), &format!("{base}/admin/health"), &format!("{base}/admin/server?tab=alerts"), ); @@ -221,7 +276,7 @@ pub async fn job_ended( let detail = format!("job {} of run {}", job.name, job.run_id); event( state, - "ci_killed", + AlertTopic::CiKilled, &format!("ci_killed:{}", job.run_id), &runner, &detail, @@ -239,11 +294,11 @@ pub async fn backup_finished(state: &AppState, outcome: Result<(), &str>) { } Err(error) => { let topic = if error.contains("failed verification") { - "backup_verify_failed" + AlertTopic::BackupVerifyFailed } else { - "backup_failed" + AlertTopic::BackupFailed }; - raise(state, topic, topic, "", error).await; + raise(state, topic, topic.as_str(), "", error).await; } } } @@ -252,7 +307,7 @@ pub async fn backup_finished(state: &AppState, outcome: Result<(), &str>) { pub async fn fsck_finished(state: &AppState, outcome: Result<(), &str>) { match outcome { Ok(()) => resolve(state, "fsck_failed").await, - Err(error) => raise(state, "fsck_failed", "fsck_failed", "", error).await, + Err(error) => raise(state, AlertTopic::FsckFailed, "fsck_failed", "", error).await, } } @@ -260,7 +315,7 @@ pub async fn fsck_finished(state: &AppState, outcome: Result<(), &str>) { pub async fn self_update_deployed(state: &AppState, version: &str) { raise( state, - "self_update_restart", + AlertTopic::SelfUpdateRestart, "self_update_restart", version, "", @@ -272,7 +327,7 @@ pub async fn self_update_deployed(state: &AppState, version: &str) { pub async fn self_update_failed(state: &AppState, run_id: &str, error: &str) { event( state, - "self_update_failed", + AlertTopic::SelfUpdateFailed, &format!("self_update_failed:{run_id}"), "", error, @@ -297,7 +352,7 @@ pub async fn on_boot(state: &AppState) { deliver( state, "self_update_restart", - "self_update_restart", + AlertTopic::SelfUpdateRestart, &version, "", true, @@ -311,12 +366,7 @@ pub async fn on_boot(state: &AppState) { /// Raises an alert for each runner silent for longer than the configured minutes and resolves the /// ones that are not any more. Runs on every CI reaper pass: one query. -pub async fn check_runners(state: &AppState) { - check_runners_at(state, now_unix()).await; -} - -/// [`check_runners`] with an explicit clock. -pub async fn check_runners_at(state: &AppState, now: i64) { +pub async fn check_runners(state: &AppState, now: i64) { let live = state.live(); let cfg = &live.alerts; let runners = match state.store.list_runners().await { @@ -347,7 +397,7 @@ pub async fn check_runners_at(state: &AppState, now: i64) { let key = format!("runner_offline:{}", runner.id); offline.insert(key.clone()); let since = seen.map_or_else(String::new, |t| forge_core::tz::format_in_tz(t, "UTC")); - raise(state, "runner_offline", &key, &runner.name, &since).await; + raise(state, AlertTopic::RunnerOffline, &key, &runner.name, &since).await; } // Whatever is active but no longer offline (back, disabled or deleted) is resolved. match state.store.active_alert_keys("runner_offline").await { @@ -388,6 +438,7 @@ async fn check_disk(state: &AppState) { let live = state.live(); let cfg = &live.alerts; if !cfg.kind_enabled(AlertKind::Disk) { + resolve(state, "disk_low").await; return; } let dir = live.data_dir.clone(); @@ -410,7 +461,7 @@ async fn check_disk(state: &AppState) { ); raise( state, - "disk_low", + AlertTopic::DiskLow, "disk_low", &dir.to_string_lossy(), &detail, @@ -424,6 +475,7 @@ async fn check_disk(state: &AppState) { async fn check_backup_overdue(state: &AppState, now: i64) { let live = state.live(); if !live.backup.enabled() || !live.alerts.kind_enabled(AlertKind::Backup) { + resolve(state, "backup_overdue").await; return; } let last_ok = match state.store.last_ok(RunKind::Backup).await { @@ -439,7 +491,7 @@ async fn check_backup_overdue(state: &AppState, now: i64) { || "never".to_owned(), |t| forge_core::tz::format_in_tz(t, "UTC"), ); - raise(state, "backup_overdue", "backup_overdue", "", &detail).await; + raise(state, AlertTopic::BackupOverdue, "backup_overdue", "", &detail).await; } else { resolve(state, "backup_overdue").await; } @@ -448,6 +500,7 @@ async fn check_backup_overdue(state: &AppState, now: i64) { async fn check_replication(state: &AppState, now: i64) { let live = state.live(); if !live.replication.enabled() || !live.alerts.kind_enabled(AlertKind::Replication) { + resolve(state, "replication").await; return; } let rows = match state.store.list_replication_status().await { @@ -474,7 +527,7 @@ async fn check_replication(state: &AppState, now: i64) { } } match problem { - Some(detail) => raise(state, "replication", "replication", "", &detail).await, + Some(detail) => raise(state, AlertTopic::Replication, "replication", "", &detail).await, None => resolve(state, "replication").await, } } @@ -533,8 +586,8 @@ mod tests { let tahinli = admin(&state, "tahinli", true).await; let second = admin(&state, "tahinli2", false).await; - raise(&state, "disk_low", "disk_low", "/data", "4% free").await; - raise(&state, "disk_low", "disk_low", "/data", "3% free").await; + raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "4% free").await; + raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "3% free").await; assert_eq!(inbox(&state, &tahinli).await.len(), 1, "deduplicated"); assert_eq!(inbox(&state, &second).await.len(), 1); assert_eq!(state.store.active_alerts().await.unwrap().len(), 1); @@ -553,7 +606,7 @@ mod tests { assert_eq!(queued_mail(&state).await, 2); assert_eq!(state.store.unread_count(&tahinli).await.unwrap(), 2); - raise(&state, "disk_low", "disk_low", "/data", "2% free").await; + raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "2% free").await; assert_eq!( inbox(&state, &tahinli).await.len(), 3, @@ -569,19 +622,19 @@ mod tests { let mut config = (*state.config).clone(); config.alerts.on_disk = false; state.set_config(config.clone()); - raise(&state, "disk_low", "disk_low", "/data", "4% free").await; + raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "4% free").await; assert!(inbox(&state, &tahinli).await.is_empty()); config.alerts.on_disk = true; config.alerts.email = false; state.set_config(config.clone()); - raise(&state, "disk_low", "disk_low", "/data", "4% free").await; + raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "4% free").await; assert_eq!(inbox(&state, &tahinli).await.len(), 1); assert_eq!(queued_mail(&state).await, 0); config.alerts.enabled = false; state.set_config(config); - raise(&state, "backup_failed", "backup_failed", "", "boom").await; + raise(&state, AlertTopic::BackupFailed, "backup_failed", "", "boom").await; assert_eq!( inbox(&state, &tahinli).await.len(), 1, @@ -608,12 +661,12 @@ mod tests { state.store.runner_by_secret(&secret).await.unwrap(); let now = now_unix(); - check_runners_at(&state, now).await; + check_runners(&state, now).await; assert!(inbox(&state, &tahinli).await.is_empty(), "fresh heartbeat"); // Eleven minutes of silence on a fake clock (the default is ten). - check_runners_at(&state, now + 11 * 60).await; - check_runners_at(&state, now + 12 * 60).await; + check_runners(&state, now + 11 * 60).await; + check_runners(&state, now + 12 * 60).await; let rows = inbox(&state, &tahinli).await; assert_eq!(rows.len(), 1, "told once"); assert_eq!(rows[0].subject, "tahinli-ci"); diff --git a/crates/forge-web-app/src/api/gitea.rs b/crates/forge-web-app/src/api/gitea.rs index 0655537..cb35184 100644 --- a/crates/forge-web-app/src/api/gitea.rs +++ b/crates/forge-web-app/src/api/gitea.rs @@ -222,6 +222,10 @@ fn internal(e: impl std::fmt::Display) -> Refusal { api::internal(e) } +fn respond(result: Result) -> topcoat::Result { + Ok(result.unwrap_or_else(|res| *res)) +} + #[route(GET "/api/v1/version")] async fn version_route(cx: &Cx) -> topcoat::Result { Ok(api::json( @@ -480,7 +484,7 @@ fn filter_of(cx: &Cx, pg: &Paging) -> Result { Ok(IssueFilter { state: state_filter(cx)?, sort: IssueSort::Oldest, - page: pg.page as u32, + page: u32::try_from(pg.page).unwrap_or(u32::MAX), per_page: pg.limit as u32, ..IssueFilter::default() }) @@ -565,34 +569,31 @@ fn comment_json( #[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/comments")] async fn issue_comments(cx: &Cx) -> topcoat::Result { + respond(issue_comments_inner(cx).await) +} + +async fn issue_comments_inner(cx: &Cx) -> Result { let state = context::(cx); - let ctx = match read_ctx(cx).await { - Ok(ctx) => ctx, - Err(res) => return Ok(*res), - }; - let result: Result = async { - let issue = issue_row(state, &ctx.repo, index(cx)).await?; - let all = state - .store - .list_comments(&issue.id) - .await - .map_err(internal)?; - let numbered: Vec<(usize, Comment)> = all.into_iter().enumerate().collect(); - let pg = paging(cx, DEFAULT_PAGE); - let (page, total) = slice(numbered, &pg); - let authors = names( - state, - page.iter().map(|(_, c)| c.author_id.clone()).collect(), - ) - .await?; - let items = page - .iter() - .map(|(pos, c)| comment_json(&ctx, issue.number, *pos, c, &authors)) - .collect(); - Ok(page_response(cx, items, total, &pg)) - } - .await; - Ok(result.unwrap_or_else(|res| *res)) + let ctx = read_ctx(cx).await?; + let issue = issue_row(state, &ctx.repo, index(cx)).await?; + let all = state + .store + .list_comments(&issue.id) + .await + .map_err(internal)?; + let numbered: Vec<(usize, Comment)> = all.into_iter().enumerate().collect(); + let pg = paging(cx, DEFAULT_PAGE); + let (page, total) = slice(numbered, &pg); + let authors = names( + state, + page.iter().map(|(_, c)| c.author_id.clone()).collect(), + ) + .await?; + let items = page + .iter() + .map(|(pos, c)| comment_json(&ctx, issue.number, *pos, c, &authors)) + .collect(); + Ok(page_response(cx, items, total, &pg)) } /// Reactions of one target as the Gitea list. Forge keeps the first ten users per emoji. @@ -611,12 +612,16 @@ async fn reactions_json( let mut out = Vec::new(); for summary in map.get(target_id).into_iter().flatten() { for username in &summary.users { - let id = match state.store.user_by_username(username).await { - Ok(Some(user)) => user.id, - _ => continue, + let Some(user) = state + .store + .user_by_username(username) + .await + .map_err(internal)? + else { + continue; }; out.push(json!({ - "user": user_json(&ctx.base, &id, username), + "user": user_json(&ctx.base, &user.id, username), "reaction": summary.reaction.name(), "created_at": created_at, })); @@ -627,63 +632,56 @@ async fn reactions_json( #[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/reactions")] async fn issue_reactions(cx: &Cx) -> topcoat::Result { + respond(issue_reactions_inner(cx).await) +} + +async fn issue_reactions_inner(cx: &Cx) -> Result { let state = context::(cx); - let ctx = match read_ctx(cx).await { - Ok(ctx) => ctx, - Err(res) => return Ok(*res), - }; - let result: Result = async { - let issue = issue_row(state, &ctx.repo, index(cx)).await?; - let all = reactions_json( - state, - &ctx, - ReactionTarget::Issue, - &issue.id, - &issue.created_at, - ) - .await?; - let pg = paging(cx, 1000); - let (page, total) = slice(all, &pg); - Ok(page_response(cx, page, total, &pg)) - } - .await; - Ok(result.unwrap_or_else(|res| *res)) + let ctx = read_ctx(cx).await?; + let issue = issue_row(state, &ctx.repo, index(cx)).await?; + let all = reactions_json( + state, + &ctx, + ReactionTarget::Issue, + &issue.id, + &issue.created_at, + ) + .await?; + let pg = paging(cx, 1000); + let (page, total) = slice(all, &pg); + Ok(page_response(cx, page, total, &pg)) } #[route(GET "/api/v1/repos/{owner}/{repo}/issues/comments/{id}/reactions")] async fn comment_reactions(cx: &Cx) -> topcoat::Result { + respond(comment_reactions_inner(cx).await) +} + +async fn comment_reactions_inner(cx: &Cx) -> Result { let state = context::(cx); - let ctx = match read_ctx(cx).await { - Ok(ctx) => ctx, - Err(res) => return Ok(*res), - }; - let result: Result = async { - let id: i64 = id(cx).parse().map_err(|_| bad("invalid comment id"))?; - let (number, position) = - split_comment_id(id).ok_or_else(|| not_found("comment not found"))?; - let issue = issue_row(state, &ctx.repo, &number.to_string()).await?; - let all = state - .store - .list_comments(&issue.id) - .await - .map_err(internal)?; - let comment = all - .get(position) - .ok_or_else(|| not_found("comment not found"))?; - let items = reactions_json( - state, - &ctx, - ReactionTarget::Comment, - &comment.id, - &comment.created_at, - ) - .await?; - let pg = paging(cx, 1000); - let (page, total) = slice(items, &pg); - Ok(page_response(cx, page, total, &pg)) - } - .await; - Ok(result.unwrap_or_else(|res| *res)) + let ctx = read_ctx(cx).await?; + let id: i64 = id(cx).parse().map_err(|_| bad("invalid comment id"))?; + let (number, position) = split_comment_id(id).ok_or_else(|| not_found("comment not found"))?; + let issue = issue_row(state, &ctx.repo, &number.to_string()).await?; + let all = state + .store + .list_comments(&issue.id) + .await + .map_err(internal)?; + let comment = all + .get(position) + .ok_or_else(|| not_found("comment not found"))?; + let items = reactions_json( + state, + &ctx, + ReactionTarget::Comment, + &comment.id, + &comment.created_at, + ) + .await?; + let pg = paging(cx, 1000); + let (page, total) = slice(items, &pg); + Ok(page_response(cx, page, total, &pg)) } fn pr_branch( @@ -794,36 +792,33 @@ async fn pull_json( #[route(GET "/api/v1/repos/{owner}/{repo}/pulls")] async fn list_pulls_route(cx: &Cx) -> topcoat::Result { + respond(list_pulls_inner(cx).await) +} + +async fn list_pulls_inner(cx: &Cx) -> Result { let state = context::(cx); - let ctx = match read_ctx(cx).await { - Ok(ctx) => ctx, - Err(res) => return Ok(*res), - }; - let result: Result = async { - let pg = paging(cx, DEFAULT_PAGE); - let filter = filter_of(cx, &pg)?; - let (rows, total) = state + let ctx = read_ctx(cx).await?; + let pg = paging(cx, DEFAULT_PAGE); + let filter = filter_of(cx, &pg)?; + let (rows, total) = state + .store + .list_pulls(&ctx.repo.id, &filter) + .await + .map_err(internal)?; + let milestones = milestone_map(state, &ctx.repo).await?; + let mut out = Vec::with_capacity(rows.len()); + for item in &rows { + let Some(pull) = state .store - .list_pulls(&ctx.repo.id, &filter) + .pull_by_number(&ctx.repo.id, item.issue.number) .await - .map_err(internal)?; - let milestones = milestone_map(state, &ctx.repo).await?; - let mut out = Vec::with_capacity(rows.len()); - for item in &rows { - let Some(pull) = state - .store - .pull_by_number(&ctx.repo.id, item.issue.number) - .await - .map_err(internal)? - else { - continue; - }; - out.push(pull_json(state, &ctx, item, &pull, &milestones).await?); - } - Ok(page_response(cx, out, total as usize, &pg)) + .map_err(internal)? + else { + continue; + }; + out.push(pull_json(state, &ctx, item, &pull, &milestones).await?); } - .await; - Ok(result.unwrap_or_else(|res| *res)) + Ok(page_response(cx, out, total as usize, &pg)) } /// 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 topcoat::Result { + respond(pull_reviews_inner(cx).await) +} + +async fn pull_reviews_inner(cx: &Cx) -> Result { let state = context::(cx); - let ctx = match read_ctx(cx).await { - Ok(ctx) => ctx, - Err(res) => return Ok(*res), - }; - let result: Result = async { - let issue = pull_issue(state, &ctx.repo, index(cx)).await?; - let reviews = state - .store - .list_reviews(&issue.id) - .await - .map_err(internal)?; - let comments = review_comments(state, &issue.id).await?; - let pg = paging(cx, DEFAULT_PAGE); - let (page, total) = slice(reviews, &pg); - let items = page - .iter() - .map(|r| { - let count = comments.iter().filter(|c| c.review_id == r.id).count(); - review_json(&ctx, issue.number, r, count) - }) - .collect(); - Ok(page_response(cx, items, total, &pg)) - } - .await; - Ok(result.unwrap_or_else(|res| *res)) + let ctx = read_ctx(cx).await?; + let issue = pull_issue(state, &ctx.repo, index(cx)).await?; + let reviews = state + .store + .list_reviews(&issue.id) + .await + .map_err(internal)?; + let comments = review_comments(state, &issue.id).await?; + let pg = paging(cx, DEFAULT_PAGE); + let (page, total) = slice(reviews, &pg); + let items = page + .iter() + .map(|r| { + let count = comments.iter().filter(|c| c.review_id == r.id).count(); + review_json(&ctx, issue.number, r, count) + }) + .collect(); + Ok(page_response(cx, items, total, &pg)) } /// 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 { #[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews/{review_id}/comments")] async fn pull_review_comments(cx: &Cx) -> topcoat::Result { + respond(pull_review_comments_inner(cx).await) +} + +async fn pull_review_comments_inner(cx: &Cx) -> Result { let state = context::(cx); - let ctx = match read_ctx(cx).await { - Ok(ctx) => ctx, - Err(res) => return Ok(*res), + let ctx = read_ctx(cx).await?; + let issue = pull_issue(state, &ctx.repo, index(cx)).await?; + let raw = review_id(cx); + let reviews = state + .store + .list_reviews(&issue.id) + .await + .map_err(internal)?; + let review = reviews + .iter() + .find(|r| r.id == raw || (is_numeric(raw) && raw.parse() == Ok(numeric_id(&r.id)))) + .ok_or_else(|| not_found("review not found"))?; + let own: Vec = review_comments(state, &issue.id) + .await? + .into_iter() + .filter(|c| c.review_id == review.id) + .collect(); + let items = own + .iter() + .map(|c| review_comment_json(&ctx, issue.number, c)) + .collect::>(); + let total = items.len(); + let pg = Paging { + page: 1, + limit: total.max(1), }; - let result: Result = async { - let issue = pull_issue(state, &ctx.repo, index(cx)).await?; - let raw = review_id(cx); - let reviews = state - .store - .list_reviews(&issue.id) - .await - .map_err(internal)?; - let review = reviews - .iter() - .find(|r| r.id == raw || (is_numeric(raw) && raw.parse() == Ok(numeric_id(&r.id)))) - .ok_or_else(|| not_found("review not found"))?; - let own: Vec = review_comments(state, &issue.id) - .await? - .into_iter() - .filter(|c| c.review_id == review.id) - .collect(); - let items = own - .iter() - .map(|c| review_comment_json(&ctx, issue.number, c)) - .collect::>(); - let total = items.len(); - // Review comments are not paged by the downloader; return them whole. - let pg = Paging { - page: 1, - limit: total.max(1), - }; - Ok(page_response(cx, items, total, &pg)) - } - .await; - Ok(result.unwrap_or_else(|res| *res)) + Ok(page_response(cx, items, total, &pg)) } diff --git a/crates/forge-web-app/src/api/mod.rs b/crates/forge-web-app/src/api/mod.rs index abde51a..bdf3697 100644 --- a/crates/forge-web-app/src/api/mod.rs +++ b/crates/forge-web-app/src/api/mod.rs @@ -18,7 +18,7 @@ use forge_core::{Action, Denied, Repo, User, authorize, token::hash_token}; use forge_git::browse; use http::HeaderMap; use http::header::{AUTHORIZATION, CONTENT_TYPE, HeaderValue, RETRY_AFTER, WWW_AUTHENTICATE}; -use serde_json::{Value, json}; +use serde_json::json; use topcoat::router::StatusCode; use topcoat::router::response::Response; @@ -31,9 +31,10 @@ pub const REPO_SCOPE: &str = "repo"; /// A failed step. The response is boxed, as in git_http, to keep `Result` small. pub type Refusal = Box; -/// Builds a JSON response with the given status. -pub fn json(status: StatusCode, value: &Value) -> Response { - let mut res = Response::new(topcoat::router::Body::from(value.to_string())); +pub fn json(status: StatusCode, value: &T) -> Response { + let mut res = Response::new(topcoat::router::Body::from( + serde_json::to_string(value).unwrap_or_default(), + )); *res.status_mut() = status; res.headers_mut().insert( CONTENT_TYPE, @@ -185,25 +186,29 @@ pub async fn load_repo( Ok(None) => return Err(refused(actor, Denied::NotFound)), Err(e) => return Err(internal(e)), }; - let (role, org_role) = match actor { - Some(user) => ( - state - .store - .collaborator_role(&repo.id, &user.id) - .await - .map_err(internal)?, - state - .store - .org_repo_role(&repo.owner_id, &user.id, &repo.id) - .await - .map_err(internal)?, - ), - None => (None, None), - }; + let (role, org_role) = state + .store + .user_roles(&repo, actor) + .await + .map_err(internal)?; authorize(actor, &repo, role, org_role, action).map_err(|denied| refused(actor, denied))?; Ok(repo) } +pub async fn load_writer( + state: &AppState, + ip: IpAddr, + headers: &HeaderMap, + owner: &str, + name: &str, +) -> Result<(Repo, User), Refusal> { + let Some(user) = authenticate(state, ip, headers).await? else { + return Err(Box::new(unauthorized())); + }; + let repo = load_repo(state, Some(&user), owner, name, Action::Write).await?; + Ok((repo, user)) +} + /// On-disk path of a repo's bare directory. pub fn repo_dir(state: &AppState, repo: &Repo) -> Result { 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( + body: topcoat::router::Body, + limit: usize, +) -> Result { + let bytes = read_body(body, limit).await?; + serde_json::from_slice(&bytes).map_err(|e| { + Box::new(error( + StatusCode::BAD_REQUEST, + &format!("invalid JSON body: {e}"), + )) + }) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/forge-web-app/src/api/packages.rs b/crates/forge-web-app/src/api/packages.rs index d12328c..80ee284 100644 --- a/crates/forge-web-app/src/api/packages.rs +++ b/crates/forge-web-app/src/api/packages.rs @@ -128,6 +128,16 @@ async fn owner_of(cx: &Cx) -> Result { } } +async fn writer(cx: &Cx) -> Result { + match caller(cx, true).await? { + Some(user) => Ok(user), + None => Err(Box::new(cargo_error( + StatusCode::UNAUTHORIZED, + "authentication required", + ))), + } +} + #[route(GET "/api/packages/{owner}/cargo/config.json")] async fn config(cx: &Cx) -> topcoat::Result { let state = context::(cx); @@ -218,14 +228,8 @@ async fn download(cx: &Cx) -> topcoat::Result { #[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/new")] async fn publish(cx: &Cx, body: Body) -> topcoat::Result { let state = context::(cx); - let actor = match caller(cx, true).await { - Ok(Some(actor)) => actor, - Ok(None) => { - return Ok(cargo_error( - StatusCode::UNAUTHORIZED, - "authentication required", - )); - } + let actor = match writer(cx).await { + Ok(actor) => actor, Err(res) => return Ok(*res), }; let owner = match owner_of(cx).await { @@ -263,14 +267,8 @@ async fn unyank(cx: &Cx) -> topcoat::Result { async fn set_yank(cx: &Cx, yanked: bool) -> topcoat::Result { let state = context::(cx); - let actor = match caller(cx, true).await { - Ok(Some(actor)) => actor, - Ok(None) => { - return Ok(cargo_error( - StatusCode::UNAUTHORIZED, - "authentication required", - )); - } + let actor = match writer(cx).await { + Ok(actor) => actor, Err(res) => return Ok(*res), }; let owner = match owner_of(cx).await { diff --git a/crates/forge-web-app/src/api/releases.rs b/crates/forge-web-app/src/api/releases.rs index ea72a1b..df34982 100644 --- a/crates/forge-web-app/src/api/releases.rs +++ b/crates/forge-web-app/src/api/releases.rs @@ -8,7 +8,7 @@ use std::io; use forge_core::releases::{Release, ReleaseAsset}; -use forge_core::{Action, Repo as CoreRepo, User}; +use forge_core::{Action, Repo as CoreRepo}; use futures_util::StreamExt; use http::header::CONTENT_TYPE; use serde::Deserialize; @@ -132,22 +132,21 @@ async fn get_release_by_tag(cx: &Cx) -> topcoat::Result { #[route(POST "/api/v1/repos/{owner}/{repo}/releases")] async fn create_release(cx: &Cx, body: Body) -> topcoat::Result { let state = context::(cx); - let (repo, user) = match write_context(cx).await { + let (repo, user) = match api::load_writer( + state, + client_ip(cx), + headers(cx), + owner(cx), + repo(cx), + ) + .await + { Ok(found) => found, Err(res) => return Ok(*res), }; - let bytes = match api::read_body(body, MAX_JSON_BYTES).await { - Ok(bytes) => bytes, - Err(res) => return Ok(*res), - }; - let input: CreateBody = match serde_json::from_slice(&bytes) { + let input: CreateBody = match api::json_body(body, MAX_JSON_BYTES).await { Ok(input) => input, - Err(e) => { - return Ok(api::error( - StatusCode::BAD_REQUEST, - &format!("invalid JSON body: {e}"), - )); - } + Err(res) => return Ok(*res), }; let title = input.title.unwrap_or_else(|| input.tag.clone()); let created = release_ops::create( @@ -177,7 +176,15 @@ async fn create_release(cx: &Cx, body: Body) -> topcoat::Result { #[route(PATCH "/api/v1/repos/{owner}/{repo}/releases/{id}")] async fn edit_release(cx: &Cx, body: Body) -> topcoat::Result { let state = context::(cx); - let (repo, user) = match write_context(cx).await { + let (repo, user) = match api::load_writer( + state, + client_ip(cx), + headers(cx), + owner(cx), + repo(cx), + ) + .await + { Ok(found) => found, Err(res) => return Ok(*res), }; @@ -185,18 +192,9 @@ async fn edit_release(cx: &Cx, body: Body) -> topcoat::Result { Ok(release) => release, Err(res) => return Ok(*res), }; - let bytes = match api::read_body(body, MAX_JSON_BYTES).await { - Ok(bytes) => bytes, - Err(res) => return Ok(*res), - }; - let patch: PatchBody = match serde_json::from_slice(&bytes) { + let patch: PatchBody = match api::json_body(body, MAX_JSON_BYTES).await { Ok(patch) => patch, - Err(e) => { - return Ok(api::error( - StatusCode::BAD_REQUEST, - &format!("invalid JSON body: {e}"), - )); - } + Err(res) => return Ok(*res), }; let edit = EditRelease { title: patch.title.unwrap_or_else(|| release.title.clone()), @@ -219,7 +217,15 @@ async fn edit_release(cx: &Cx, body: Body) -> topcoat::Result { #[route(DELETE "/api/v1/repos/{owner}/{repo}/releases/{id}")] async fn delete_release(cx: &Cx) -> topcoat::Result { let state = context::(cx); - let (repo, user) = match write_context(cx).await { + let (repo, user) = match api::load_writer( + state, + client_ip(cx), + headers(cx), + owner(cx), + repo(cx), + ) + .await + { Ok(found) => found, Err(res) => return Ok(*res), }; @@ -237,7 +243,15 @@ async fn delete_release(cx: &Cx) -> topcoat::Result { #[route(PUT "/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}")] async fn upload_asset(cx: &Cx, body: Body) -> topcoat::Result { let state = context::(cx); - let (repo, user) = match write_context(cx).await { + let (repo, user) = match api::load_writer( + state, + client_ip(cx), + headers(cx), + owner(cx), + repo(cx), + ) + .await + { Ok(found) => found, Err(res) => return Ok(*res), }; @@ -288,7 +302,15 @@ async fn upload_asset(cx: &Cx, body: Body) -> topcoat::Result { #[route(DELETE "/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}")] async fn delete_asset(cx: &Cx) -> topcoat::Result { let state = context::(cx); - let (repo, _user) = match write_context(cx).await { + let (repo, _user) = match api::load_writer( + state, + client_ip(cx), + headers(cx), + owner(cx), + repo(cx), + ) + .await + { Ok(found) => found, Err(res) => return Ok(*res), }; @@ -321,7 +343,7 @@ async fn read_context(cx: &Cx) -> Result<(CoreRepo, bool), Refusal> { let state = context::(cx); let actor = api::authenticate(state, client_ip(cx), headers(cx)).await?; let repo = api::load_repo(state, actor.as_ref(), owner(cx), repo(cx), Action::Read).await?; - let can_write = api::load_repo( + let can_write = match api::load_repo( state, actor.as_ref(), owner(cx), @@ -329,21 +351,14 @@ async fn read_context(cx: &Cx) -> Result<(CoreRepo, bool), Refusal> { Action::Write, ) .await - .is_ok(); + { + Ok(_) => true, + Err(res) if res.status() == StatusCode::INTERNAL_SERVER_ERROR => return Err(res), + Err(_) => false, + }; Ok((repo, can_write)) } -/// Authenticates a required caller with write access and loads the repo. -async fn write_context(cx: &Cx) -> Result<(CoreRepo, User), Refusal> { - let state = context::(cx); - let actor = api::authenticate(state, client_ip(cx), headers(cx)).await?; - let repo = api::load_repo(state, actor.as_ref(), owner(cx), repo(cx), Action::Write).await?; - match actor { - Some(user) => Ok((repo, user)), - None => Err(Box::new(api::unauthorized())), - } -} - /// The release with this id, which must belong to `repo`. Anything else is a 404, so ids from /// other repos cannot be probed. `id` is the forge id or the integer shown as `id` in the JSON. /// Callers of this function already have write access, or check drafts themselves. @@ -453,40 +468,23 @@ fn no_content() -> Response { #[cfg(test)] mod tests { - use std::path::{Path, PathBuf}; + use std::path::PathBuf; use forge_core::releases::NewRelease; - use forge_core::token::{generate_token, hash_token}; use forge_core::{Role, Store, User, Visibility}; use forge_git::repo::{init_bare, repo_path}; use http::header::{AUTHORIZATION, CONTENT_TYPE}; use topcoat::router::request::Request; use topcoat::router::{Body, Router, to_bytes}; + use crate::test_support::fixture::git; + use crate::test_support::http::{bearer, token_for}; use crate::test_support::{app_router, test_state}; const OWNER: &str = "tahinli"; const REPO: &str = "proj"; const MIB: u64 = 1024 * 1024; - fn git(dir: &Path, args: &[&str]) -> String { - let out = std::process::Command::new("git") - .current_dir(dir) - .args(args) - .env("GIT_AUTHOR_NAME", "test") - .env("GIT_AUTHOR_EMAIL", "test@example.com") - .env("GIT_COMMITTER_NAME", "test") - .env("GIT_COMMITTER_EMAIL", "test@example.com") - .output() - .expect("git runs"); - assert!( - out.status.success(), - "git {args:?} failed: {}", - String::from_utf8_lossy(&out.stderr) - ); - String::from_utf8_lossy(&out.stdout).trim().to_owned() - } - struct Fixture { _tmp: tempfile::TempDir, router: Router, @@ -555,20 +553,6 @@ mod tests { } } - async fn token_for(store: &Store, user_id: &str, scopes: &[&str]) -> String { - let raw = generate_token(); - let scopes: Vec = scopes.iter().map(|s| (*s).to_owned()).collect(); - store - .create_token(user_id, "test", &hash_token(&raw), &scopes, None) - .await - .expect("token"); - raw - } - - fn bearer(raw: &str) -> String { - format!("Bearer {raw}") - } - /// Sends one request through the router: `(status, json body)`. async fn send( router: &Router, diff --git a/crates/forge-web-app/src/api/statuses.rs b/crates/forge-web-app/src/api/statuses.rs index b82e411..f6604fe 100644 --- a/crates/forge-web-app/src/api/statuses.rs +++ b/crates/forge-web-app/src/api/statuses.rs @@ -36,33 +36,24 @@ struct ReportBody { #[route(POST "/api/v1/repos/{owner}/{repo}/statuses/{sha}")] async fn report_status(cx: &Cx, body: Body) -> topcoat::Result { let state = context::(cx); - let actor = match api::authenticate(state, client_ip(cx), headers(cx)).await { - Ok(actor) => actor, - Err(res) => return Ok(*res), - }; - let repo = match api::load_repo(state, actor.as_ref(), owner(cx), repo(cx), Action::Write).await + let (repo, user) = match api::load_writer( + state, + client_ip(cx), + headers(cx), + owner(cx), + repo(cx), + ) + .await { - Ok(repo) => repo, + Ok(found) => found, Err(res) => return Ok(*res), }; - let Some(user) = actor else { - return Ok(api::unauthorized()); - }; let Some(sha) = api::normalize_sha(sha(cx)) else { return Ok(not_a_full_sha()); }; - let bytes = match api::read_body(body, MAX_BODY_BYTES).await { - Ok(bytes) => bytes, - Err(res) => return Ok(*res), - }; - let report: ReportBody = match serde_json::from_slice(&bytes) { + let report: ReportBody = match api::json_body(body, MAX_BODY_BYTES).await { Ok(report) => report, - Err(e) => { - return Ok(api::error( - StatusCode::BAD_REQUEST, - &format!("invalid JSON body: {e}"), - )); - } + Err(res) => return Ok(*res), }; let Some(status_state) = StatusState::parse(&report.state) else { return Ok(api::error( @@ -171,14 +162,15 @@ fn commit_not_found() -> Response { #[cfg(test)] mod tests { - use forge_core::token::{generate_token, hash_token}; - use forge_core::{Role, Store, Visibility}; + use forge_core::token::generate_token; + use forge_core::{Role, Visibility}; use http::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE}; use topcoat::router::request::Request; use topcoat::router::{Body, Router, to_bytes}; use crate::auth::SESSION_COOKIE; use crate::test_support::fixture::{Fixture, OWNER, REPO}; + use crate::test_support::http::{bearer, token_for}; /// Sends one request through the router: `(status, json body)`. async fn send( @@ -209,21 +201,6 @@ mod tests { (status, json) } - /// A personal access token for `user_id` with the given scopes. Returns the raw token. - async fn token_for(store: &Store, user_id: &str, scopes: &[&str]) -> String { - let raw = generate_token(); - let scopes: Vec = scopes.iter().map(|s| (*s).to_owned()).collect(); - store - .create_token(user_id, "test", &hash_token(&raw), &scopes, None) - .await - .expect("token"); - raw - } - - fn bearer(raw: &str) -> String { - format!("Bearer {raw}") - } - struct Setup { fx: Fixture, reader_token: String, diff --git a/crates/forge-web-app/src/auth.rs b/crates/forge-web-app/src/auth.rs index 7b326f3..798f6d0 100644 --- a/crates/forge-web-app/src/auth.rs +++ b/crates/forge-web-app/src/auth.rs @@ -1,13 +1,8 @@ -//! Session cookie, current user, CSRF checks and login redirect helpers. -//! -//! The browser holds the raw session token in `__Host-forge_session`. The database -//! stores only `hash_token(token)`, so a leaked DB row cannot be replayed as a cookie. - use std::sync::{Arc, OnceLock}; use std::time::Duration; use forge_core::password::{hash_password, verify_password}; -use forge_core::time::stamp_after; +use forge_core::time::{stamp_after, unix_now}; use forge_core::token::{constant_time_eq, hash_token, random_b64url}; use forge_core::{Session, Store, User, secret, totp}; use tokio::sync::Semaphore; @@ -20,35 +15,21 @@ use topcoat::router::request::{headers, uri}; use crate::client_ip::client_addr; use crate::state::AppState; -/// Logical cookie name. `override_prefix_host()` stores it as `__Host-forge_session`. pub const SESSION_COOKIE: &str = "forge_session"; -/// Lifetime of a web session, both in the database and on the cookie. pub const SESSION_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60); -/// Logical name of the pre-session CSRF cookie, used by `/login` and `/setup` before any -/// session exists. Stored as `__Host-forge_precsrf`. pub const PRE_CSRF_COOKIE: &str = "forge_precsrf"; -/// Lifetime of the pre-session CSRF cookie. const PRE_CSRF_TTL: Duration = Duration::from_secs(60 * 60); -/// Logical name of the pending-login cookie set between the password and the second factor. -/// Stored as `__Host-forge_2fa`. Its value is sealed with the instance key. pub const PENDING_2FA_COOKIE: &str = "forge_2fa"; -/// How long a password-verified login may wait for its second factor. pub const PENDING_2FA_TTL: Duration = Duration::from_secs(5 * 60); -/// Maximum accepted length of a `next` redirect target. const MAX_NEXT_LEN: usize = 2048; -/// Cookie jar that forces the `__Host-` prefix (Secure, Path=/, no Domain). fn session_jar(cx: &Cx) -> impl Cookies + '_ { cookies(cx).override_prefix_host() } -/// Resolves the signed-in user from the session cookie. -/// -/// Returns `None` when there is no cookie, the session is unknown or expired, or its -/// user no longer exists. Every successful lookup refreshes `last_seen`. pub async fn current_user(cx: &Cx) -> forge_core::Result> { let Some(cookie) = session_jar(cx).get(SESSION_COOKIE) else { return Ok(None); @@ -60,7 +41,6 @@ pub async fn current_user(cx: &Cx) -> forge_core::Result else { return Ok(None); }; - // An organization never signs in, even if a session row names one. let Some(user) = store .user_by_id(&session.user_id) .await? @@ -73,7 +53,6 @@ pub async fn current_user(cx: &Cx) -> forge_core::Result Ok(Some((user, session))) } -/// Creates a session for `user` and sets the session cookie on the response. pub async fn login(cx: &Cx, user: &User) -> forge_core::Result { let store = &context::(cx).store; let token = random_b64url(); @@ -88,7 +67,6 @@ pub async fn login(cx: &Cx, user: &User) -> forge_core::Result { Some(&addr), ) .await?; - // A new sign-in shows up in the user's session list in their other open tabs. context::(cx) .live .bump(&crate::live::Topic::Account(user.id.clone())); @@ -105,27 +83,19 @@ pub async fn login(cx: &Cx, user: &User) -> forge_core::Result { Ok(session) } -/// Deletes the session row and clears the cookie. pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> { let state = context::(cx); state.store.delete_session(&session.id).await?; - // The user's other tabs may show this session (a page that now leaves for the login page). crate::live::bump_account(state, &session.user_id); session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); Ok(()) } -/// Constant-time comparison of the submitted CSRF token with the session's token. pub fn check_csrf(session: &Session, submitted: &str) -> bool { - // An empty stored token must never match, even an empty submission. !session.csrf_token.is_empty() && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) } -/// Returns the pre-session CSRF token for a form, issuing one when the browser has none. -/// -/// The existing cookie is reused so that two open login tabs keep working. The same value -/// goes into a hidden `precsrf` field; the POST must echo it back. pub fn pre_csrf_token(cx: &Cx) -> String { if let Some(cookie) = session_jar(cx).get(PRE_CSRF_COOKIE) { let value = cookie.value(); @@ -138,7 +108,6 @@ pub fn pre_csrf_token(cx: &Cx) -> String { token } -/// True only when the submitted `precsrf` equals the cookie, compared in constant time. pub fn check_pre_csrf(cx: &Cx, submitted: &str) -> bool { let Some(cookie) = session_jar(cx).get(PRE_CSRF_COOKIE) else { return false; @@ -146,7 +115,6 @@ pub fn check_pre_csrf(cx: &Cx, submitted: &str) -> bool { !cookie.value().is_empty() && constant_time_eq(cookie.value().as_bytes(), submitted.as_bytes()) } -/// Removes the pre-session CSRF cookie. Called after a successful login or setup. pub fn clear_pre_csrf(cx: &Cx) { session_jar(cx).remove(Cookie::build((PRE_CSRF_COOKIE, "")).path("/")); } @@ -163,17 +131,13 @@ fn pre_csrf_cookie(token: String) -> Cookie<'static> { .build() } -/// Argon2 runs at once, server-wide. Each hash or verify allocates about 19 MiB, so a burst of -/// logins would otherwise pile that memory up on the blocking pool. const MAX_CONCURRENT_PASSWORD_HASHES: usize = 4; -/// Permits for argon2 work. A permit is held until the hash or verify finishes. fn password_slots() -> &'static Arc { static SLOTS: OnceLock> = OnceLock::new(); SLOTS.get_or_init(|| Arc::new(Semaphore::new(MAX_CONCURRENT_PASSWORD_HASHES))) } -/// Hashes a password with argon2 on the blocking pool, keeping the async runtime free. pub async fn hash_password_async(password: String) -> forge_core::Result { let _permit = password_slots() .acquire() @@ -184,7 +148,6 @@ pub async fn hash_password_async(password: String) -> forge_core::Result .map_err(|_| forge_core::Error::Crypto("password hashing task failed".into()))? } -/// Verifies a password with argon2 on the blocking pool. pub async fn verify_password_async(password: String, hash: String) -> forge_core::Result { let _permit = password_slots() .acquire() @@ -195,7 +158,6 @@ pub async fn verify_password_async(password: String, hash: String) -> forge_core .map_err(|_| forge_core::Error::Crypto("password verification task failed".into())) } -/// Returns the signed-in user, or a 303 redirect to `/login?next=`. pub async fn require_user(cx: &Cx) -> Result<(User, Session)> { match current_user(cx).await? { Some(viewer) => Ok(viewer), @@ -207,7 +169,6 @@ pub async fn require_user(cx: &Cx) -> Result<(User, Session)> { } } -/// Requires a signed-in user and a valid `csrf` form field. Returns 403 on a bad token. pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<(User, Session)> { let (user, session) = require_user(cx).await?; if check_csrf(&session, submitted) { @@ -217,21 +178,11 @@ pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<(User, Session)> { } } -/// A login that has passed its password and waits for the second factor. pub struct PendingLogin { pub user_id: String, pub next: String, } -/// Seconds since the Unix epoch, or 0 if the clock is before it. -pub fn unix_now() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_secs()) -} - -/// Sets the pending-login cookie. Its payload is `expires|user_id|next`, sealed so the browser -/// cannot change the user or the expiry. pub fn set_pending_login( cx: &Cx, key: &[u8; 32], @@ -253,8 +204,6 @@ pub fn set_pending_login( Ok(()) } -/// The pending login from the cookie, or `None` when the cookie is missing, tampered with, -/// malformed or past its expiry. pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option { let cookie = session_jar(cx).get(PENDING_2FA_COOKIE)?; let plain = secret::open(key, cookie.value()).ok()?; @@ -272,12 +221,10 @@ pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option { }) } -/// Removes the pending-login cookie. pub fn clear_pending_login(cx: &Cx) { session_jar(cx).remove(Cookie::build((PENDING_2FA_COOKIE, "")).path("/")); } -/// True when the user has confirmed two-factor authentication. pub async fn two_factor_enabled(store: &Store, user_id: &str) -> forge_core::Result { Ok(store .totp_state(user_id) @@ -285,9 +232,6 @@ pub async fn two_factor_enabled(store: &Store, user_id: &str) -> forge_core::Res .is_some_and(|state| state.enabled)) } -/// Checks a second-factor input for a user with two-factor on. A six-digit input is a TOTP -/// code, checked with replay protection. Anything else is a recovery code, which is used up -/// on success. Returns false for any wrong or spent input. pub async fn verify_second_factor( store: &Store, key: &[u8; 32], @@ -295,7 +239,6 @@ pub async fn verify_second_factor( input: &str, ) -> forge_core::Result { let input = input.trim(); - // An organization has no second factor and never passes one. if store .user_by_id(user_id) .await? @@ -325,10 +268,6 @@ pub async fn verify_second_factor( .await } -/// Returns `next` only when it is a same-site relative path; otherwise `/`. -/// -/// Accepts a single leading `/`, rejects `//` and `/\` (protocol-relative or browser -/// backslash tricks), rejects control characters and caps the length. pub fn safe_next(next: Option<&str>) -> &str { match next { Some(n) if is_local_path(n) => n, @@ -344,7 +283,6 @@ fn is_local_path(path: &str) -> bool { && path.chars().all(|c| !c.is_control()) } -/// Percent-encodes everything except unreserved characters and `/`. pub fn percent_encode(input: &str) -> String { let mut out = String::with_capacity(input.len()); for b in input.bytes() { @@ -358,7 +296,6 @@ pub fn percent_encode(input: &str) -> String { out } -/// The request's `User-Agent`, truncated to 512 characters. pub fn user_agent(cx: &Cx) -> Option { headers(cx) .get(http::header::USER_AGENT) @@ -437,8 +374,6 @@ mod tests { assert_eq!(percent_encode("/a b"), "/a%20b"); } - /// An organization has no second factor and never passes one, even with a valid TOTP code or - /// a recovery code on its row. A person with the same setup does pass. #[tokio::test] async fn an_org_never_passes_a_second_factor() { let dir = tempfile::tempdir().unwrap(); @@ -471,7 +406,6 @@ mod tests { .await .unwrap() ); - // The same setup on a person works, so the refusal is the org rule. assert!( verify_second_factor(&store, &key, &tahinli.id, "aaaa-bbbb") .await diff --git a/crates/forge-web-app/src/automerge.rs b/crates/forge-web-app/src/automerge.rs index d3ac679..0517ef3 100644 --- a/crates/forge-web-app/src/automerge.rs +++ b/crates/forge-web-app/src/automerge.rs @@ -63,7 +63,7 @@ async fn evaluate_logged(state: &AppState, repo: &Repo, pr: &PullRequest) { /// The merge runs as the user who enabled auto-merge, and only while that user still has Write on /// the repo; otherwise auto-merge is switched off with a timeline notice. A merge the repository /// refuses (a conflict, a moved base) also switches it off, so it never retries forever. -pub async fn evaluate(state: &AppState, repo: &Repo, pr: &PullRequest) -> forge_core::Result { +async fn evaluate(state: &AppState, repo: &Repo, pr: &PullRequest) -> forge_core::Result { let Some(auto) = pr.auto_merge.as_ref() else { return Ok(false); }; @@ -87,11 +87,7 @@ pub async fn evaluate(state: &AppState, repo: &Repo, pr: &PullRequest) -> forge_ .await?; return Ok(false); }; - let collaborator = state.store.collaborator_role(&repo.id, &user.id).await?; - let org = state - .store - .org_repo_role(&repo.owner_id, &user.id, &repo.id) - .await?; + let (collaborator, org) = state.store.user_roles(repo, Some(&user)).await?; if authorize(Some(&user), repo, collaborator, org, Action::Write).is_err() { state .store diff --git a/crates/forge-web-app/src/backup/mod.rs b/crates/forge-web-app/src/backup/mod.rs index fdef9e5..706dcef 100644 --- a/crates/forge-web-app/src/backup/mod.rs +++ b/crates/forge-web-app/src/backup/mod.rs @@ -14,11 +14,11 @@ pub mod scheduler; mod verify; use std::fs::{DirBuilder, File}; -use std::io::Read; use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt}; use std::path::{Path, PathBuf}; use forge_core::{Error, Result, Store}; +use forge_core::token::sha256_reader; use forge_git::GitEnv; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -36,7 +36,6 @@ pub const DB_FILE: &str = "db/forge.db"; pub const KEY_FILE: &str = "keys/forge.key"; const BACKUP_DIR_PREFIX: &str = "forge-backup-"; const PARTIAL_PREFIX: &str = ".partial-"; -const COPY_BUF: usize = 64 * 1024; /// What a backup set contains. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -190,44 +189,29 @@ fn fsync_dir(path: &Path) -> Result<()> { /// Streams the file through sha256. Returns its size and lowercase hex digest. fn hash_file(path: &Path) -> Result<(u64, String)> { - let mut f = File::open(path).map_err(io_err)?; - let mut hasher = Sha256::new(); - let mut buf = vec![0u8; COPY_BUF]; - let mut total = 0u64; - loop { - let n = f.read(&mut buf).map_err(io_err)?; - if n == 0 { - break; - } - hasher.update(&buf[..n]); - total += n as u64; - } - Ok((total, hex::encode(hasher.finalize()))) + sha256_reader(File::open(path).map_err(io_err)?).map_err(io_err) } /// `20260102T030405Z`, the UTC stamp used in set names. fn name_stamp(t: time::OffsetDateTime) -> String { - format!( - "{:04}{:02}{:02}T{:02}{:02}{:02}Z", - t.year(), - u8::from(t.month()), - t.day(), - t.hour(), - t.minute(), - t.second() - ) + stamp(t, "", "") } -/// RFC 3339 UTC, used in the manifest. fn manifest_stamp(t: time::OffsetDateTime) -> String { + stamp(t, "-", ":") +} + +fn stamp(t: time::OffsetDateTime, date_sep: &str, time_sep: &str) -> String { format!( - "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", + "{:04}{d}{:02}{d}{:02}T{:02}{s}{:02}{s}{:02}Z", t.year(), u8::from(t.month()), t.day(), t.hour(), t.minute(), - t.second() + t.second(), + d = date_sep, + s = time_sep, ) } diff --git a/crates/forge-web-app/src/backup/restore.rs b/crates/forge-web-app/src/backup/restore.rs index d68fee9..1888ddd 100644 --- a/crates/forge-web-app/src/backup/restore.rs +++ b/crates/forge-web-app/src/backup/restore.rs @@ -106,22 +106,11 @@ pub async fn restore_backup( init_bare(&git, &path, &default_branch).await?; dirs_to_lock.push(path.clone()); - match &entry.bundle { - Some(rel) => { - let bundle = set.join(rel); - let bundle_str = bundle - .to_str() - .ok_or_else(|| Error::Invalid("bundle path is not UTF-8".into()))?; - GitCommand::new(&git, "fetch") - .git_dir(&path) - .arg("--quiet") - .user_arg(bundle_str)? - .user_arg("+refs/*:refs/*")? - .status() - .await?; - repos += 1; - } - None => empty_repos += 1, + let bundle = entry.bundle.as_ref().map(|rel| set.join(rel)); + if bundle.is_some() { + repos += 1; + } else { + empty_repos += 1; } let head = format!("refs/heads/{default_branch}"); @@ -131,50 +120,28 @@ pub async fn restore_backup( .user_arg(&head)? .status() .await?; + restore_git( + &git, + &path, + bundle.as_deref(), + &entry.refs_sha256, + &format!("repo {}", entry.id), + ) + .await?; - let refs = forge_git::backup::refs_checksum(&git, &path).await?; - if refs != entry.refs_sha256 { - return Err(Error::Conflict(format!( - "repo {}: refs after restore ({refs}) do not match the manifest ({})", - entry.id, entry.refs_sha256 - ))); - } - GitCommand::new(&git, "fsck") - .git_dir(&path) - .arg("--full") - .status() - .await?; - - // The wiki comes back the same way as the repo, from its own bundle, if the set has one. if let Some(wiki) = &entry.wiki { let wiki_repo = forge_git::repo::wiki_path(&target, &entry.id)?; init_bare(&git, &wiki_repo, forge_git::wiki::WIKI_BRANCH).await?; dirs_to_lock.push(wiki_repo.clone()); - if let Some(rel) = &wiki.bundle { - let bundle = set.join(rel); - let bundle_str = bundle - .to_str() - .ok_or_else(|| Error::Invalid("bundle path is not UTF-8".into()))?; - GitCommand::new(&git, "fetch") - .git_dir(&wiki_repo) - .arg("--quiet") - .user_arg(bundle_str)? - .user_arg("+refs/*:refs/*")? - .status() - .await?; - } - let refs = forge_git::backup::refs_checksum(&git, &wiki_repo).await?; - if refs != wiki.refs_sha256 { - return Err(Error::Conflict(format!( - "repo {} wiki: refs after restore ({refs}) do not match the manifest ({})", - entry.id, wiki.refs_sha256 - ))); - } - GitCommand::new(&git, "fsck") - .git_dir(&wiki_repo) - .arg("--full") - .status() - .await?; + let bundle = wiki.bundle.as_ref().map(|rel| set.join(rel)); + restore_git( + &git, + &wiki_repo, + bundle.as_deref(), + &wiki.refs_sha256, + &format!("repo {} wiki", entry.id), + ) + .await?; } } drop(store); @@ -214,6 +181,39 @@ pub async fn restore_backup( }) } +async fn restore_git( + git: &GitEnv, + dir: &Path, + bundle: Option<&Path>, + expected_refs: &str, + label: &str, +) -> Result<()> { + if let Some(bundle) = bundle { + let bundle_str = bundle + .to_str() + .ok_or_else(|| Error::Invalid("bundle path is not UTF-8".into()))?; + GitCommand::new(git, "fetch") + .git_dir(dir) + .arg("--quiet") + .user_arg(bundle_str)? + .user_arg("+refs/*:refs/*")? + .status() + .await?; + } + let refs = forge_git::backup::refs_checksum(git, dir).await?; + if refs != expected_refs { + return Err(Error::Conflict(format!( + "{label}: refs after restore ({refs}) do not match the manifest ({expected_refs})" + ))); + } + GitCommand::new(git, "fsck") + .git_dir(dir) + .arg("--full") + .status() + .await?; + Ok(()) +} + /// The target must not be inside the set, and must be missing or an empty directory. fn check_target(set: &Path, target: &Path) -> Result<()> { if target.starts_with(set) { @@ -299,30 +299,34 @@ fn lock_down_dirs(target: &Path, repo_dirs: &[PathBuf]) -> Result<()> { #[cfg(test)] mod tests { use super::*; - use crate::backup::{BackupOptions, BackupSource, create_backup}; - use forge_core::model::Visibility; + use crate::backup::BackupOptions; + use crate::backup::create_backup; + use crate::backup::tests::{Fixture, fixture, git_in, opts}; use std::os::unix::fs::PermissionsExt; use std::process::Command; - struct Source { - dir: tempfile::TempDir, - data_dir: PathBuf, - source: BackupSource, - demo_id: String, - empty_id: String, + async fn source() -> Fixture { + let fx = fixture().await; + let tahinli = fx + .source + .store + .user_by_username("tahinli") + .await + .expect("query") + .expect("user"); + fx.source + .store + .create_issue(&fx.demo_id, &tahinli.id, "First issue", "body") + .await + .expect("issue"); + let key = fx.data_dir.join("forge.key"); + std::fs::write(&key, [7u8; 32]).expect("key"); + std::fs::set_permissions(&key, std::fs::Permissions::from_mode(0o600)).expect("key mode"); + fx } - fn git_in(dir: &Path, args: &[&str]) { - let out = Command::new("git") - .current_dir(dir) - .env("GIT_AUTHOR_NAME", "t") - .env("GIT_AUTHOR_EMAIL", "t@example.invalid") - .env("GIT_COMMITTER_NAME", "t") - .env("GIT_COMMITTER_EMAIL", "t@example.invalid") - .args(args) - .output() - .expect("run git"); - assert!(out.status.success(), "git {args:?}: {out:?}"); + fn git_bin() -> PathBuf { + PathBuf::from("git") } fn git_out(dir: &Path, args: &[&str]) -> String { @@ -335,92 +339,6 @@ mod tests { String::from_utf8(out.stdout).expect("utf8") } - /// A data dir with a user, an issue, a repo with commits/branch/tag, and an empty repo. - async fn source() -> Source { - let dir = tempfile::tempdir().expect("tempdir"); - let data_dir = dir.path().join("data"); - std::fs::create_dir_all(&data_dir).expect("data dir"); - let store = Store::open(&data_dir.join("forge.db")).await.expect("open"); - let tahinli = store - .create_user("Tahinli", None, "hash", false) - .await - .expect("user"); - let git = GitEnv { - git_bin: "git".into(), - data_dir: data_dir.clone(), - }; - let demo = store - .create_repo(&tahinli.id, "demo", "", Visibility::Private, "main") - .await - .expect("demo"); - let demo_path = repo_path(&data_dir, &demo.id).expect("path"); - let work = dir.path().join("work"); - std::fs::create_dir_all(&work).expect("work"); - git_in(&work, &["init", "-q", "-b", "main"]); - git_in(&work, &["commit", "-q", "--allow-empty", "-m", "one"]); - git_in(&work, &["commit", "-q", "--allow-empty", "-m", "two"]); - git_in(&work, &["branch", "feature"]); - git_in(&work, &["tag", "v1"]); - std::fs::create_dir_all(demo_path.parent().expect("parent")).expect("mkdir"); - let dest = demo_path.to_str().expect("utf8").to_string(); - git_in( - dir.path(), - &[ - "clone", - "-q", - "--bare", - "--no-hardlinks", - work.to_str().expect("utf8"), - &dest, - ], - ); - let empty = store - .create_repo(&tahinli.id, "empty", "", Visibility::Private, "main") - .await - .expect("empty"); - init_bare( - &git, - &repo_path(&data_dir, &empty.id).expect("path"), - "main", - ) - .await - .expect("init empty"); - store - .create_issue(&demo.id, &tahinli.id, "First issue", "body") - .await - .expect("issue"); - std::fs::write(data_dir.join("forge.key"), [7u8; 32]).expect("key"); - std::fs::set_permissions( - data_dir.join("forge.key"), - std::fs::Permissions::from_mode(0o600), - ) - .expect("key mode"); - - Source { - source: BackupSource { - store, - git, - base_url: "https://forge.example.invalid".into(), - }, - data_dir, - demo_id: demo.id, - empty_id: empty.id, - dir, - } - } - - fn git_bin() -> PathBuf { - PathBuf::from("git") - } - - fn opts(out: &Path, include_key: bool) -> BackupOptions { - BackupOptions { - out: out.to_path_buf(), - include_key, - scope: Scope::All, - } - } - fn for_each_ref(dir: &Path) -> String { git_out(dir, &["for-each-ref", "--format=%(objectname) %(refname)"]) } @@ -429,7 +347,7 @@ mod tests { async fn round_trip_restores_store_repos_hooks_and_config() { let src = source().await; let out = src.dir.path().join("out"); - let summary = create_backup(&src.source, &opts(&out, true)) + let summary = create_backup(&src.source, &opts(&out, true, Scope::All)) .await .expect("backup"); let target = src.dir.path().join("fresh"); @@ -517,7 +435,7 @@ mod tests { .expect("commit page"); let out = src.dir.path().join("out"); - let summary = create_backup(&src.source, &opts(&out, true)) + let summary = create_backup(&src.source, &opts(&out, true, Scope::All)) .await .expect("backup"); let manifest = std::fs::read(summary.path.join(MANIFEST_FILE)).expect("manifest"); @@ -549,7 +467,7 @@ mod tests { async fn restore_refuses_a_non_empty_target() { let src = source().await; let out = src.dir.path().join("out"); - let summary = create_backup(&src.source, &opts(&out, false)) + let summary = create_backup(&src.source, &opts(&out, false, Scope::All)) .await .expect("backup"); let target = src.dir.path().join("busy"); @@ -568,7 +486,7 @@ mod tests { async fn restore_refuses_a_tampered_set_and_writes_nothing() { let src = source().await; let out = src.dir.path().join("out"); - let summary = create_backup(&src.source, &opts(&out, false)) + let summary = create_backup(&src.source, &opts(&out, false, Scope::All)) .await .expect("backup"); let bundle = summary.path.join(format!("repos/{}.bundle", src.demo_id)); @@ -590,7 +508,7 @@ mod tests { async fn restore_without_key_warns() { let src = source().await; let out = src.dir.path().join("out"); - let summary = create_backup(&src.source, &opts(&out, false)) + let summary = create_backup(&src.source, &opts(&out, false, Scope::All)) .await .expect("backup"); let target = src.dir.path().join("fresh"); diff --git a/crates/forge-web-app/src/backup/scheduler.rs b/crates/forge-web-app/src/backup/scheduler.rs index f19f288..94cca6c 100644 --- a/crates/forge-web-app/src/backup/scheduler.rs +++ b/crates/forge-web-app/src/backup/scheduler.rs @@ -214,12 +214,16 @@ pub fn configured_dir(state: &AppState) -> Result { std::path::absolute(&state.config.backup.dir).map_err(Error::Io) } -async fn scheduled_backup(state: &AppState) -> Result { - let opts = BackupOptions { +fn full_set_options(state: &AppState) -> Result { + Ok(BackupOptions { out: configured_dir(state)?, include_key: false, scope: super::Scope::All, - }; + }) +} + +async fn scheduled_backup(state: &AppState) -> Result { + let opts = full_set_options(state)?; backup_job(state, RunTrigger::Schedule, opts, true).await } @@ -296,23 +300,13 @@ pub async fn fsck_job(state: &AppState, trigger: RunTrigger, full: bool) -> Resu let run_id = state.store.start_run(RunKind::Fsck, trigger).await?; runs_changed(); let outcome = run_fsck(&state.store, &state.git, full).await; - match &outcome { - Ok(summary) if summary.is_ok() => crate::alerts::fsck_finished(state, Ok(())).await, - Ok(summary) => crate::alerts::fsck_finished(state, Err(&summary.problems.join("\n"))).await, - Err(e) => crate::alerts::fsck_finished(state, Err(&e.to_string())).await, - } - match &outcome { - Ok(summary) if summary.is_ok() => { - record_finish(state, &run_id, true, None, None, None).await; - } - Ok(summary) => { - let text = summary.problems.join("\n"); - record_finish(state, &run_id, false, None, None, Some(&text)).await; - } - Err(e) => { - record_finish(state, &run_id, false, None, None, Some(&e.to_string())).await; - } - } + let problem: Option = match &outcome { + Ok(summary) if summary.is_ok() => None, + Ok(summary) => Some(summary.problems.join("\n")), + Err(e) => Some(e.to_string()), + }; + crate::alerts::fsck_finished(state, problem.as_deref().map_or(Ok(()), Err)).await; + record_finish(state, &run_id, problem.is_none(), None, None, problem.as_deref()).await; outcome } @@ -346,19 +340,10 @@ pub fn start_manual(state: &AppState, guard: JobGuard) -> Result<()> { tokio::spawn(async move { let _guard = guard; let outcome: Result<()> = match kind { - RunKind::Backup => match configured_dir(&state) { - Ok(out) => backup_job( - &state, - RunTrigger::Manual, - BackupOptions { - out, - include_key: false, - scope: super::Scope::All, - }, - true, - ) - .await - .map(|_| ()), + RunKind::Backup => match full_set_options(&state) { + Ok(opts) => backup_job(&state, RunTrigger::Manual, opts, true) + .await + .map(|_| ()), Err(e) => Err(e), }, RunKind::Fsck => fsck_job(&state, RunTrigger::Manual, false) diff --git a/crates/forge-web-app/src/backup/tests.rs b/crates/forge-web-app/src/backup/tests.rs index a18f29c..2c1435a 100644 --- a/crates/forge-web-app/src/backup/tests.rs +++ b/crates/forge-web-app/src/backup/tests.rs @@ -15,16 +15,16 @@ use super::{ verify_backup, }; -struct Fixture { - dir: tempfile::TempDir, - source: BackupSource, - git: GitEnv, - data_dir: PathBuf, - demo_id: String, - empty_id: String, +pub(super) struct Fixture { + pub(super) dir: tempfile::TempDir, + pub(super) source: BackupSource, + pub(super) git: GitEnv, + pub(super) data_dir: PathBuf, + pub(super) demo_id: String, + pub(super) empty_id: String, } -fn git_in(dir: &Path, args: &[&str]) { +pub(super) fn git_in(dir: &Path, args: &[&str]) { let out = Command::new("git") .current_dir(dir) .env("GIT_AUTHOR_NAME", "t") @@ -39,7 +39,7 @@ fn git_in(dir: &Path, args: &[&str]) { /// A store with one user, a repo that has commits, a branch and a tag, and an empty repo. The /// repos are laid out where the server would put them. -async fn fixture() -> Fixture { +pub(super) async fn fixture() -> Fixture { let dir = tempfile::tempdir().expect("tempdir"); let data_dir = dir.path().join("data"); std::fs::create_dir_all(&data_dir).expect("data dir"); @@ -105,7 +105,7 @@ async fn fixture() -> Fixture { } } -fn opts(out: &Path, include_key: bool, scope: Scope) -> BackupOptions { +pub(super) fn opts(out: &Path, include_key: bool, scope: Scope) -> BackupOptions { BackupOptions { out: out.to_path_buf(), include_key, diff --git a/crates/forge-web-app/src/backup/verify.rs b/crates/forge-web-app/src/backup/verify.rs index 91663c1..639a546 100644 --- a/crates/forge-web-app/src/backup/verify.rs +++ b/crates/forge-web-app/src/backup/verify.rs @@ -100,49 +100,55 @@ fn check_layout(root: &Path, manifest: &Manifest, problems: &mut Vec) -> if !ids.insert(repo.id.as_str()) { problems.push(format!("repo {} is listed twice", repo.id)); } - match &repo.bundle { - Some(b) => { - if *b != format!("repos/{}.bundle", repo.id) || !listed.contains(b.as_str()) { - problems.push(format!( - "repo {}: bundle {b} is not listed as a file", - repo.id - )); - } - } - None => { - if repo.refs_sha256 != empty_sha256() { - problems.push(format!( - "repo {} has no bundle but its refs are not empty", - repo.id - )); - } + check_bundle( + problems, + &listed, + &repo.id, + "", + repo.bundle.as_deref(), + &repo.refs_sha256, + format!("repos/{}.bundle", repo.id), + ); + if let Some(wiki) = &repo.wiki { + check_bundle( + problems, + &listed, + &repo.id, + "wiki ", + wiki.bundle.as_deref(), + &wiki.refs_sha256, + format!("repos/{}.wiki.bundle", repo.id), + ); + } + } + Ok(()) +} + +fn check_bundle( + problems: &mut Vec, + listed: &BTreeSet<&str>, + repo_id: &str, + label: &str, + bundle: Option<&str>, + refs_sha256: &str, + expected_path: String, +) { + match bundle { + Some(b) => { + if b != expected_path || !listed.contains(b) { + problems.push(format!( + "repo {repo_id}: {label}bundle {b} is not listed as a file" + )); } } - // The wiki, when the set has one, follows the same rules under its own file name. - if let Some(wiki) = &repo.wiki { - match &wiki.bundle { - Some(b) => { - if *b != format!("repos/{}.wiki.bundle", repo.id) - || !listed.contains(b.as_str()) - { - problems.push(format!( - "repo {}: wiki bundle {b} is not listed as a file", - repo.id - )); - } - } - None => { - if wiki.refs_sha256 != empty_sha256() { - problems.push(format!( - "repo {} has no wiki bundle but its wiki refs are not empty", - repo.id - )); - } - } + None => { + if refs_sha256 != empty_sha256() { + problems.push(format!( + "repo {repo_id} has no {label}bundle but its {label}refs are not empty" + )); } } } - Ok(()) } /// Collects regular files under `dir` as paths relative to `root`. Unexpected directories and @@ -259,28 +265,28 @@ async fn check_bundles( git: &GitEnv, problems: &mut Vec, ) -> Result { - let bundles: Vec<(usize, &super::RepoEntry, &str)> = manifest - .repos - .iter() - .enumerate() - .filter_map(|(i, r)| r.bundle.as_deref().map(|b| (i, r, b))) - .collect(); + let mut bundles: Vec<(String, &str, &str)> = Vec::new(); + for repo in &manifest.repos { + if let Some(b) = &repo.bundle { + bundles.push((format!("repo {}", repo.id), b, &repo.refs_sha256)); + } + if let Some(wiki) = &repo.wiki + && let Some(b) = &wiki.bundle + { + bundles.push((format!("repo {} wiki", repo.id), b, &wiki.refs_sha256)); + } + } if bundles.is_empty() { return Ok(0); } let parent = root .parent() .ok_or_else(|| Error::Invalid("the backup set has no parent directory".into()))?; - let suffix = format!( - "{}-{}", - std::process::id(), - time::OffsetDateTime::now_utc().unix_timestamp_nanos() - ); - let scratch_root: PathBuf = parent.join(format!(".partial-verify-{suffix}")); + let scratch_root: PathBuf = parent.join(format!(".partial-verify-{}", super::unique_suffix())); create_private_dir(&scratch_root)?; let mut passed = 0; - for (idx, repo, bundle) in bundles { + for (idx, (name, bundle, expected)) in bundles.into_iter().enumerate() { let scratch = scratch_root.join(format!("{idx}.git")); let outcome = async { forge_git::repo::init_bare(git, &scratch, "main").await?; @@ -288,12 +294,11 @@ async fn check_bundles( } .await; match outcome { - Ok(imported) if imported == repo.refs_sha256 => passed += 1, + Ok(imported) if imported == expected => passed += 1, Ok(imported) => problems.push(format!( - "repo {}: bundle refs {imported} do not match the manifest {}", - repo.id, repo.refs_sha256 + "{name}: bundle refs {imported} do not match the manifest {expected}" )), - Err(e) => problems.push(format!("repo {}: bundle failed verification: {e}", repo.id)), + Err(e) => problems.push(format!("{name}: bundle failed verification: {e}")), } } if let Err(e) = std::fs::remove_dir_all(&scratch_root) { diff --git a/crates/forge-web-app/src/ci/api.rs b/crates/forge-web-app/src/ci/api.rs index 8081ab2..c9222a8 100644 --- a/crates/forge-web-app/src/ci/api.rs +++ b/crates/forge-web-app/src/ci/api.rs @@ -18,6 +18,7 @@ use forge_core::Error as CoreError; use forge_core::ci::{ CiJob, CiRun, CiRunner, JobState, MemoryOffer, QueueSkips, RestartMode, RunState, RunnerReport, }; +use forge_core::pulls::PullRequest; use futures_util::StreamExt; use http::header::HeaderValue; use serde_json::json; @@ -62,6 +63,7 @@ const MAX_LABELS: usize = 32; /// Text appended once when the log cap is reached. const TRUNCATED_MARKER: &[u8] = b"\n[log truncated]\n"; const MIB: u64 = 1024 * 1024; +static LOG_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); /// Bearer token from the `Authorization` header, or `None`. fn bearer_token(headers: &HeaderMap) -> Option<&str> { @@ -114,9 +116,8 @@ async fn job_from(state: &AppState, headers: &HeaderMap, job_id: &str) -> Result } } -/// Parses a JSON body of at most [`MAX_JSON_BODY`] bytes. -async fn json_body(body: Body) -> Result { - let bytes = api::read_body(body, MAX_JSON_BODY).await?; +async fn json_body(body: Body, limit: usize) -> Result { + let bytes = api::read_body(body, limit).await?; serde_json::from_slice(&bytes).map_err(|e| { Box::new(api::error( StatusCode::BAD_REQUEST, @@ -146,17 +147,14 @@ pub fn valid_artifact_name(name: &str) -> bool { #[route(POST "/api/v1/ci/runners/register")] async fn register(cx: &Cx, body: Body) -> topcoat::Result { let state = context::(cx); - let request: RegisterRequest = match json_body(body).await { + let request: RegisterRequest = match json_body(body, MAX_JSON_BODY).await { Ok(request) => request, Err(res) => return Ok(*res), }; - if !valid_name(&request.name) || request.labels.len() > MAX_LABELS { - return Ok(api::error( - StatusCode::UNPROCESSABLE_ENTITY, - "the runner name or labels are invalid", - )); - } - if request.labels.iter().any(|label| !valid_name(label)) { + if !valid_name(&request.name) + || request.labels.len() > MAX_LABELS + || request.labels.iter().any(|label| !valid_name(label)) + { return Ok(api::error( StatusCode::UNPROCESSABLE_ENTITY, "the runner name or labels are invalid", @@ -173,10 +171,7 @@ async fn register(cx: &Cx, body: Body) -> topcoat::Result { runner_id: runner.id, runner_secret: secret, }; - Ok(api::json( - StatusCode::CREATED, - &serde_json::to_value(&body).unwrap_or_default(), - )) + Ok(api::json(StatusCode::CREATED, &body)) } Err(CoreError::Invalid(_)) => Ok(api::error( StatusCode::UNAUTHORIZED, @@ -239,9 +234,7 @@ async fn claim(cx: &Cx, body: Body) -> topcoat::Result { .await; let mut res = claim_work(state, &runner, offer).await?; // The override can change during the long poll, so it is read at answer time. - set_concurrency_header(state, &runner.id, &mut res).await; - set_memory_headers(state, &runner.id, &mut res).await; - set_restart_header(state, &runner.id, &mut res).await; + set_claim_headers(state, &runner.id, &mut res).await; // Advertises the binary sha256 when self-update is on and the runner asked for this target. self_update::advertise(state, headers(cx), &mut res); Ok(res) @@ -277,8 +270,7 @@ async fn note_report(state: &AppState, runner_id: &str, report: &RunnerReport) { } } -/// Adds the admin's concurrency override to a claim answer. No header means no override. -async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Response) { +async fn set_claim_headers(state: &AppState, runner_id: &str, res: &mut Response) { if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) { return; } @@ -287,36 +279,21 @@ async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Res { res.headers_mut().insert(CONCURRENCY_HEADER, value); } -} - -/// Adds the admin's memory budget and default reservation to a claim answer. No header means no -/// override. An older runner ignores both. -async fn set_memory_headers(state: &AppState, runner_id: &str, res: &mut Response) { - if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) { - return; - } - for (key, header) in [ - ("limits.memory_budget", MEMORY_BUDGET_HEADER), - ("limits.reserve_memory", RESERVE_MEMORY_HEADER), - ] { - if let Ok(Some(text)) = state.store.runner_field_override(runner_id, key).await - && let Ok(value) = HeaderValue::from_str(&text) - { - res.headers_mut().insert(header, value); - } + if let Ok(Some(text)) = state + .store + .runner_field_override(runner_id, "limits.memory_budget") + .await + && let Ok(value) = HeaderValue::from_str(&text) + { + res.headers_mut().insert(MEMORY_BUDGET_HEADER, value); } -} - -/// The restart an admin asked for, in the wire type. `None` when nothing is pending. -async fn pending_restart(state: &AppState, runner_id: &str) -> Option { - state.store.runner_restart(runner_id).await.ok().flatten() -} - -/// Adds the pending restart request to a claim answer. Sent on every answer until the runner -/// comes back with a new boot id. An older runner ignores the header. -async fn set_restart_header(state: &AppState, runner_id: &str, res: &mut Response) { - if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) { - return; + if let Ok(Some(text)) = state + .store + .runner_field_override(runner_id, "limits.reserve_memory") + .await + && let Ok(value) = HeaderValue::from_str(&text) + { + res.headers_mut().insert(RESERVE_MEMORY_HEADER, value); } if let Some(mode) = pending_restart(state, runner_id).await { res.headers_mut() @@ -324,6 +301,10 @@ async fn set_restart_header(state: &AppState, runner_id: &str, res: &mut Respons } } +async fn pending_restart(state: &AppState, runner_id: &str) -> Option { + state.store.runner_restart(runner_id).await.ok().flatten() +} + /// `POST /api/v1/ci/runners/log`: a batch of the runner's own log lines. Answers the next line /// number the forge wants for this boot id, so the runner resends what was lost. #[route(POST "/api/v1/ci/runners/log")] @@ -333,18 +314,9 @@ async fn runner_log(cx: &Cx, body: Body) -> topcoat::Result { Ok(runner) => runner, Err(res) => return Ok(*res), }; - let bytes = match api::read_body(body, MAX_LOG_BATCH).await { - Ok(bytes) => bytes, - Err(res) => return Ok(*res), - }; - let batch: RunnerLogBatch = match serde_json::from_slice(&bytes) { + let batch: RunnerLogBatch = match json_body(body, MAX_LOG_BATCH).await { Ok(batch) => batch, - Err(e) => { - return Ok(api::error( - StatusCode::BAD_REQUEST, - &format!("invalid JSON body: {e}"), - )); - } + Err(res) => return Ok(*res), }; if batch.boot_id.is_empty() || batch.boot_id.len() > 64 { return Ok(api::error( @@ -354,8 +326,7 @@ async fn runner_log(cx: &Cx, body: Body) -> topcoat::Result { } let next_seq = state.runner_logs.ingest(&runner.id, &batch); state.ci_live.bump_runners(); - let ack = serde_json::to_value(RunnerLogAck { next_seq }).unwrap_or_default(); - Ok(api::json(StatusCode::OK, &ack)) + Ok(api::json(StatusCode::OK, &RunnerLogAck { next_seq })) } /// `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 { Ok(runner) => runner, Err(res) => return Ok(*res), }; - let bytes = match api::read_body(body, MAX_METRICS_BATCH).await { - Ok(bytes) => bytes, - Err(res) => return Ok(*res), - }; - let batch: RunnerMetricsBatch = match serde_json::from_slice(&bytes) { + let batch: RunnerMetricsBatch = match json_body(body, MAX_METRICS_BATCH).await { Ok(batch) => batch, - Err(e) => { - return Ok(api::error( - StatusCode::BAD_REQUEST, - &format!("invalid JSON body: {e}"), - )); - } + Err(res) => return Ok(*res), }; if batch.samples.len() > MAX_METRICS_SAMPLES { return Ok(api::error( @@ -410,7 +372,7 @@ async fn runner_config_put(cx: &Cx, body: Body) -> topcoat::Result { Ok(runner) => runner, Err(res) => return Ok(*res), }; - let report: RunnerConfigReport = match json_body(body).await { + let report: RunnerConfigReport = match json_body(body, MAX_JSON_BODY).await { Ok(report) => report, Err(res) => return Ok(*res), }; @@ -431,12 +393,11 @@ async fn runner_config_put(cx: &Cx, body: Body) -> topcoat::Result { } fn overrides_response(runner: &CiRunner) -> Response { - let reply = RunnerConfigOverrides { - overrides: runner.config_overrides.clone(), - }; api::json( StatusCode::OK, - &serde_json::to_value(reply).unwrap_or_default(), + &RunnerConfigOverrides { + overrides: runner.config_overrides.clone(), + }, ) } @@ -462,7 +423,7 @@ async fn claim_work( return Ok(empty(StatusCode::NO_CONTENT)); } match try_claim(state, runner, offer).await { - Ok(Some(assignment)) => return Ok(assignment_response(&assignment)), + Ok(Some(assignment)) => return Ok(api::json(StatusCode::OK, &assignment)), Ok(None) => {} Err(res) => return Ok(*res), } @@ -574,13 +535,6 @@ async fn runner_binary(cx: &Cx) -> topcoat::Result { } } -fn assignment_response(assignment: &JobAssignment) -> Response { - api::json( - StatusCode::OK, - &serde_json::to_value(assignment).unwrap_or_default(), - ) -} - fn empty(status: StatusCode) -> Response { let mut res = Response::new(topcoat::router::Body::empty()); *res.status_mut() = status; @@ -605,13 +559,30 @@ async fn try_claim( state.ci_live.bump_run(&run.id); state.ci_live.bump_repo(&run.repo_id); state.ci_live.bump_runners(); - // The next refusal is written again, and this job is written now. state.runner_logs.clear_note(&runner.id); note_runner( state, &runner.id, &format!("took job {} of run #{}", job.name, run.number), ); + let job_id = job.id.clone(); + match build_assignment(state, job, run, job_token).await { + Ok(assignment) => Ok(Some(assignment)), + Err(e) => { + if let Err(err) = state.store.requeue_job(&job_id).await { + tracing::warn!(error = %err, job = %job_id, "ci: failed claim not requeued"); + } + Err(e) + } + } +} + +async fn build_assignment( + state: &AppState, + job: CiJob, + run: CiRun, + job_token: String, +) -> Result { let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?; let repo = state .store @@ -619,8 +590,15 @@ async fn try_claim( .await .map_err(api::internal)? .ok_or_else(|| api::internal("claimed job belongs to a missing repo"))?; - - let secrets = if is_fork_run(state, &run).await? { + let pull = match (run.trigger.as_str(), run.pull_number) { + ("pull_request", Some(number)) => state + .store + .pull_by_number(&run.repo_id, number) + .await + .map_err(api::internal)?, + _ => None, + }; + let secrets = if is_fork_run(&run, pull.as_ref()) { BTreeMap::new() } else { state @@ -629,11 +607,9 @@ async fn try_claim( .await .map_err(api::internal)? }; - let (cache_key, cache_restore_keys) = - cache_scopes(state, &run, &repo.default_branch, &spec.cache).await?; - - Ok(Some(JobAssignment { + cache_scopes(&run, &repo.default_branch, &spec.cache, pull.as_ref()); + Ok(JobAssignment { job_id: job.id, job_token, repo: format!("{}/{}", repo.owner_name, repo.name), @@ -652,41 +628,29 @@ async fn try_claim( cache_key, cache_restore_keys, memory_bytes: spec.memory, - })) + }) } -/// The cache scopes of a job's run. A job without `cache` gets none. A pull request run's base -/// branch comes from its pull request record. -async fn cache_scopes( - state: &AppState, +fn cache_scopes( run: &CiRun, default_branch: &str, cache: &[String], -) -> Result<(String, Vec), Refusal> { + pull: Option<&PullRequest>, +) -> (String, Vec) { if cache.is_empty() { - return Ok((String::new(), Vec::new())); + return (String::new(), Vec::new()); } - let pull_base = match (run.trigger.as_str(), run.pull_number) { - ("pull_request", Some(number)) => state - .store - .pull_by_number(&run.repo_id, number) - .await - .map_err(api::internal)? - .map(|pull| pull.base_branch), - _ => None, - }; let scope = cache_scope( &run.trigger, &run.git_ref, run.pull_number, - pull_base.as_deref(), + pull.map(|pull| pull.base_branch.as_str()), default_branch, ); - Ok(match scope { + match scope { Some(scope) => (scope.key, scope.restore_keys), - // A run whose scope cannot be derived gets no key, so the runner neither restores nor saves. None => (String::new(), Vec::new()), - }) + } } /// The cache scope a run may write, and the read-only scopes it may restore from. @@ -740,24 +704,9 @@ fn cache_scope( } } -/// True for a pull-request run whose head is not this repo, or whose pull request is gone. Such -/// runs get no secrets. Missing data counts as a fork, so the answer errs on the safe side. -async fn is_fork_run(state: &AppState, run: &CiRun) -> Result { - if run.trigger != "pull_request" { - return Ok(false); - } - let Some(number) = run.pull_number else { - return Ok(true); - }; - match state - .store - .pull_by_number(&run.repo_id, number) - .await - .map_err(api::internal)? - { - Some(pull) => Ok(pull.head_repo_id.as_deref() != Some(run.repo_id.as_str())), - None => Ok(true), - } +fn is_fork_run(run: &CiRun, pull: Option<&PullRequest>) -> bool { + run.trigger == "pull_request" + && pull.is_none_or(|pull| pull.head_repo_id.as_deref() != Some(run.repo_id.as_str())) } // --------------------------------------------------------------------------------------------- @@ -819,25 +768,19 @@ async fn heartbeat(cx: &Cx) -> topcoat::Result { } Ok(api::json( StatusCode::OK, - &serde_json::to_value(HeartbeatResponse { + &HeartbeatResponse { cancel, concurrency, restart, - }) - .unwrap_or_default(), + }, )) } Err(e) => Ok(*api::internal(e)), } } -/// Outcome of a log append. enum LogWrite { - /// The chunk is stored (or was dropped by the cap); the size is the new byte count. Stored(u64), - /// This exact chunk was already stored: a retry. The size is unchanged. - Duplicate(u64), - /// The offset does not match the stored size. Mismatch(u64), } @@ -864,7 +807,7 @@ async fn append_log(cx: &Cx, body: Body) -> topcoat::Result { Err(res) => return Ok(*res), }; match write_log(state, &job, offset, &chunk).await { - Ok(LogWrite::Stored(size) | LogWrite::Duplicate(size)) => { + Ok(LogWrite::Stored(size)) => { Ok(api::json(StatusCode::OK, &json!({ "size": size }))) } Ok(LogWrite::Mismatch(size)) => { @@ -887,11 +830,15 @@ async fn write_log( offset: u64, chunk: &[u8], ) -> Result { - let size = u64::try_from(job.log_bytes).unwrap_or(0); + let _guard = LOG_LOCK.lock().await; + let size = match state.store.job_by_id(&job.id).await.map_err(api::internal)? { + Some(fresh) => u64::try_from(fresh.log_bytes).unwrap_or(0), + None => return Err(api::internal("log for a job that is gone")), + }; let len = chunk.len() as u64; if offset != size { return Ok(if offset.checked_add(len) == Some(size) { - LogWrite::Duplicate(size) + LogWrite::Stored(size) } else { LogWrite::Mismatch(size) }); @@ -1190,7 +1137,7 @@ async fn finish(cx: &Cx, body: Body) -> topcoat::Result { Ok(job) => job, Err(res) => return Ok(*res), }; - let request: FinishRequest = match json_body(body).await { + let request: FinishRequest = match json_body(body, MAX_JSON_BODY).await { Ok(request) => request, Err(res) => return Ok(*res), }; @@ -1213,7 +1160,7 @@ async fn requeue(cx: &Cx, body: Body) -> topcoat::Result { Ok(job) => job, Err(res) => return Ok(*res), }; - let request: RequeueRequest = match json_body(body).await { + let request: RequeueRequest = match json_body(body, MAX_JSON_BODY).await { Ok(request) => request, Err(res) => return Ok(*res), }; diff --git a/crates/forge-web-app/src/ci/metrics_chart.rs b/crates/forge-web-app/src/ci/metrics_chart.rs index f9d5884..a9a2e6b 100644 --- a/crates/forge-web-app/src/ci/metrics_chart.rs +++ b/crates/forge-web-app/src/ci/metrics_chart.rs @@ -140,14 +140,16 @@ pub fn nice_max(value: u64) -> u64 { if value <= 1 { return 1; } - let mut unit = 1u64; - while unit.saturating_mul(10) <= value { + let value = u128::from(value); + let mut unit = 1u128; + while unit * 10 <= value { unit *= 10; } - [unit, unit * 2, unit * 5 / 2, unit * 5, unit * 10] + let nice = [unit, unit * 2, unit * 5 / 2, unit * 5, unit * 10] .into_iter() .find(|candidate| *candidate >= value) - .unwrap_or(unit * 10) + .unwrap_or(unit * 10); + u64::try_from(nice).unwrap_or(u64::MAX) } /// 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 { assert_eq!(nice_max(1500), 2000); assert_eq!(nice_max(2400), 2500); assert_eq!(nice_max(3_145_728), 5_000_000); + assert_eq!(nice_max(15_000_000_000_000_000_000), u64::MAX); } } diff --git a/crates/forge-web-app/src/ci/reaper.rs b/crates/forge-web-app/src/ci/reaper.rs index 7c88bec..5213328 100644 --- a/crates/forge-web-app/src/ci/reaper.rs +++ b/crates/forge-web-app/src/ci/reaper.rs @@ -44,9 +44,9 @@ async fn run(state: AppState) { loop { tick.tick().await; if booted.elapsed() >= LOST_AFTER { - reap_once(&state).await; + reap_before(&state, &stamp_ago(LOST_AFTER)).await; } - crate::alerts::check_runners(&state).await; + crate::alerts::check_runners(&state, crate::views::now_unix()).await; if Instant::now() >= next_health { crate::live::admin().bump(&crate::live::Topic::AdminHealth); next_health = Instant::now() + HEALTH_EVERY; @@ -62,14 +62,8 @@ async fn run(state: AppState) { } } -/// Marks lost jobs as Error and syncs the statuses of every run they belong to. Returns how many -/// jobs were reaped. -pub async fn reap_once(state: &AppState) -> usize { - reap_before(state, &stamp_ago(LOST_AFTER)).await -} - -/// [`reap_once`] with an explicit cutoff: running jobs whose heartbeat is older than `older_than` -/// are lost. +/// Marks running jobs whose heartbeat is older than `older_than` as Error and syncs the statuses of +/// every run they belong to. Returns how many jobs were reaped. pub async fn reap_before(state: &AppState, older_than: &str) -> usize { let jobs = match state.store.reap_lost_jobs(older_than).await { Ok(jobs) => jobs, diff --git a/crates/forge-web-app/src/ci/release.rs b/crates/forge-web-app/src/ci/release.rs index d04775e..17a7968 100644 --- a/crates/forge-web-app/src/ci/release.rs +++ b/crates/forge-web-app/src/ci/release.rs @@ -1,16 +1,3 @@ -//! Publishes a release when a tag run finishes with every job succeeded and the workflow at the -//! run's commit has a `[release]` table (see docs/ci.md, Releases). The finish handler spawns -//! [`on_run_finished`], so the runner's request is not slowed down. -//! -//! The run is idempotent. A release that already exists keeps its title, notes and draft state and -//! only gets the selected artifacts; an asset with the same name is replaced. -//! -//! The release is made as the run's actor. A system run has no actor, and an organization never -//! acts, so those fall back to the repo owner, then to the ghost account (`status_creator`). -//! -//! The outcome is written as one `[forge]` line at the end of the log of the run's last finished -//! job, so it shows on the run's job pages with the rest of the output. - use forge_ci::config::{Event, ReleaseNotes, ReleaseSpec}; use forge_core::ci::{CiJob, CiRun, RunState}; use forge_core::releases::{MAX_BODY_CHARS, MAX_TITLE_CHARS, Release}; @@ -28,13 +15,9 @@ use crate::release_ops::{self, CreateRelease, ReleaseError}; use crate::render::commit_message::CommitMessage; use crate::state::AppState; -/// Most commits listed in the notes. Older commits are left out. const MAX_NOTE_COMMITS: usize = 200; const MIB: u64 = 1024 * 1024; -/// Runs after a run finished. Does nothing unless the run is a successful tag run and the workflow -/// at its commit asks for a release for this tag. Failures are logged and written to the job log; -/// they never fail the caller. pub async fn on_run_finished(state: &AppState, run: &CiRun) { if run.state != RunState::Success { return; @@ -74,7 +57,6 @@ pub async fn on_run_finished(state: &AppState, run: &CiRun) { } } -/// Creates or finds the release, attaches the selected artifacts, and describes the outcome. async fn publish( state: &AppState, repo: &Repo, @@ -140,7 +122,6 @@ async fn publish( text } -/// The person the release is made as: the run's actor, or the fallback of `status_creator`. async fn actor_of(state: &AppState, repo: &Repo, run: &CiRun) -> Option { let id = status_creator(state, repo, &run.actor_id).await?; match state.store.user_by_id(&id).await { @@ -152,8 +133,6 @@ async fn actor_of(state: &AppState, repo: &Repo, run: &CiRun) -> Option { } } -/// The existing release for `tag`, or a new one made from the spec. A release made by another run -/// in the meantime (a `Conflict`) is read back instead. async fn release_for( state: &AppState, repo: &Repo, @@ -195,10 +174,6 @@ async fn release_for( } } -/// An existing release whose tag now names the run's commit (the tag was deleted and pushed -/// again elsewhere) follows it: its target becomes that commit, and notes the forge wrote for the -/// old target, unedited, are written again for the new one. Hand-written notes and the title are -/// kept. A failure is logged and the release is used as it is. async fn follow_tag( state: &AppState, repo: &Repo, @@ -229,7 +204,6 @@ async fn follow_tag( } } -/// Stores one artifact as an asset of `release`, replacing an asset with the same name. async fn attach( state: &AppState, repo: &Repo, @@ -265,8 +239,6 @@ async fn attach( }) } -/// The notes for a new release, or an empty string when the spec turns them off. A git failure -/// leaves the notes empty and is logged; the release is still made. async fn notes( state: &AppState, repo: &Repo, @@ -286,9 +258,6 @@ async fn notes( } } -/// The commit list since the previous release. The previous release is the newest other -/// published release whose target is an ancestor of this commit. Without one, it is the closest -/// git tag reachable from the commit. Without either, the list is capped at the newest commits. async fn changelog( state: &AppState, repo: &Repo, @@ -337,7 +306,6 @@ async fn changelog( Ok(bullets(&commits, footer.as_deref())) } -/// Note sections in output order. Commit kinds map to them through `section_of`. const SECTIONS: [&str; 7] = [ "Features", "Fixes", @@ -348,7 +316,6 @@ const SECTIONS: [&str; 7] = [ "Other", ]; -/// The index in `SECTIONS` for a commit kind. Unknown kinds go to `Other`. fn section_of(kind: &str) -> usize { match kind { "feat" => 0, @@ -361,9 +328,6 @@ fn section_of(kind: &str) -> usize { } } -/// The notes body. When at least one subject is structured, the clauses are grouped under -/// `SECTIONS`; otherwise one `- subject (shortsha)` line per commit, newest first. Commits that -/// would push the notes past the body limit are left out, and the footer is kept in the count. fn bullets(commits: &[CommitInfo], footer: Option<&str>) -> String { let footer_len = footer.map_or(0, |f| f.chars().count() + 2); let structured = commits @@ -377,7 +341,6 @@ fn bullets(commits: &[CommitInfo], footer: Option<&str>) -> String { with_footer(&body, footer) } -/// One `- subject (shortsha)` line per commit, newest first. fn flat_bullets(commits: &[CommitInfo], footer_len: usize) -> String { let mut body = String::new(); let mut used = 0usize; @@ -394,8 +357,6 @@ fn flat_bullets(commits: &[CommitInfo], footer_len: usize) -> String { body } -/// Lines grouped under `SECTIONS`, in commit order within each section. A heading costs its -/// `### name` line and the blank line after the section, and is counted once per section. fn grouped_bullets(commits: &[CommitInfo], footer_len: usize) -> String { let mut sections: Vec> = vec![Vec::new(); SECTIONS.len()]; let mut used = 0usize; @@ -444,7 +405,6 @@ fn grouped_bullets(commits: &[CommitInfo], footer_len: usize) -> String { body } -/// The body without trailing whitespace, then the footer after a blank line. fn with_footer(body: &str, footer: Option<&str>) -> String { let mut body = body.trim_end().to_owned(); if let Some(footer) = footer { @@ -456,8 +416,6 @@ fn with_footer(body: &str, footer: Option<&str>) -> String { body } -/// Appends one `[forge]` line to the log of `job`. Respects the log size cap. A failure is logged; -/// the outcome is not lost, it is also in the tracing output. async fn note(state: &AppState, job: &CiJob, text: &str) { let line = format!("[forge] {text}\n"); let cap = state.live().ci.max_log_mb.saturating_mul(MIB); @@ -507,7 +465,6 @@ mod tests { use crate::ci::schedule::tests::{Fixture, ZERO, fixture, git, land, push}; use crate::post_update::after_ref_update; - /// A tag release workflow with two jobs. Only `build` feeds the release, through `dist_*`. const RELEASE: &str = r#" [on] push = ["main"] @@ -528,7 +485,6 @@ assets = ["build:dist_*"] title = "forge {tag}" "#; - /// Finishes the jobs of `run_id` in order. The job named `failing` fails; the others succeed. async fn finish_all(fx: &Fixture, run_id: &str, failing: Option<&str>) { loop { let jobs = fx.state.store.jobs_for_run(run_id).await.expect("jobs"); @@ -569,7 +525,6 @@ title = "forge {tag}" .expect("job") } - /// Stores `body` as an artifact of `job`, the way the upload handler does. async fn add_artifact(fx: &Fixture, job: &CiJob, name: &str, body: &[u8]) -> CiArtifact { let tmp = format!("ci/tmp/{}", ulid::Ulid::generate()); let mut writer = fx.state.blobs.begin(&tmp, 1 << 30).await.expect("begin"); @@ -589,7 +544,6 @@ title = "forge {tag}" artifact } - /// Commits an empty change with `message` and returns the commit. fn commit_message(work: &std::path::Path, message: &str) -> String { git(work, &["commit", "--allow-empty", "-m", message]); git(work, &["rev-parse", "HEAD"]) @@ -766,16 +720,10 @@ title = "forge {tag}" assert_eq!(asset_names(&fx, &release).await.len(), 1); } - /// Failed runs never publish. Each scenario has its own tag, so its run is number 1, 2 and 3. - /// Scenario 1: `docs` fails after the jobs run in order. Scenario 2: `build` finishes green - /// while `docs` still runs, then `docs` fails. Scenario 3: `docs` fails fast while `build` - /// has not finished, so `build` is cancelled at once (the running-job path is covered in the - /// store tests). No release is created in any scenario. #[tokio::test] async fn failed_runs_create_no_release() { let fx = fixture().await; - // Scenario 1. push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; let run = run_of(&fx, 1).await; let build = job_of(&fx, &run, "build").await; @@ -786,7 +734,6 @@ title = "forge {tag}" on_run_finished(&fx.state, &run).await; assert!(release_named(&fx, "v1.0").await.is_none(), "in order"); - // Scenario 2. push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v2.0").await; let run = run_of(&fx, 2).await; let build = job_of(&fx, &run, "build").await; @@ -813,7 +760,6 @@ title = "forge {tag}" on_run_finished(&fx.state, &after_docs).await; assert!(release_named(&fx, "v2.0").await.is_none(), "parallel"); - // Scenario 3. push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v3.0").await; let run = run_of(&fx, 3).await; let build = job_of(&fx, &run, "build").await; @@ -873,7 +819,6 @@ title = "forge {tag}" ); } - /// No release exists for the earlier tag, so the notes start from the closest git tag. #[tokio::test] async fn notes_fall_back_to_the_previous_git_tag() { let fx = fixture().await; diff --git a/crates/forge-web-app/src/ci/runner_log.rs b/crates/forge-web-app/src/ci/runner_log.rs index f5d4ecb..27766dc 100644 --- a/crates/forge-web-app/src/ci/runner_log.rs +++ b/crates/forge-web-app/src/ci/runner_log.rs @@ -15,8 +15,6 @@ use forge_ci::proto::{RUNNER_LOG_MAX_TEXT, RunnerLogBatch, truncate_text}; const MAX_LINES: usize = 2000; /// Most lines taken from one batch. The rest are left for the runner to resend. const MAX_BATCH_LINES: usize = 1000; -/// Longest boot id kept, in bytes. -const MAX_BOOT_ID_BYTES: usize = 64; /// The levels a runner may send. Any other level is stored as `info`. const LEVELS: [&str; 5] = ["error", "warn", "info", "debug", "trace"]; @@ -54,9 +52,6 @@ impl RunnerLogs { /// starts a fresh numbering, and the lines already in `lines` are kept. Lines before the /// wanted number are skipped, so a resent batch adds only what is new. pub fn ingest(&self, runner_id: &str, batch: &RunnerLogBatch) -> u64 { - if batch.boot_id.is_empty() || batch.boot_id.len() > MAX_BOOT_ID_BYTES { - return self.next_seq(runner_id); - } let mut runners = self.lock(); let entry = runners.entry(runner_id.to_owned()).or_default(); if entry.boot_id != batch.boot_id { @@ -118,10 +113,6 @@ impl RunnerLogs { .unwrap_or_default() } - fn next_seq(&self, runner_id: &str) -> u64 { - self.lock().get(runner_id).map_or(0, |entry| entry.next_seq) - } - fn lock(&self) -> MutexGuard<'_, HashMap> { // A panic while the lock was held leaves the map usable, so a poisoned lock is taken as is. self.runners.lock().unwrap_or_else(|e| e.into_inner()) diff --git a/crates/forge-web-app/src/ci/runner_metrics.rs b/crates/forge-web-app/src/ci/runner_metrics.rs index d400607..bb0319b 100644 --- a/crates/forge-web-app/src/ci/runner_metrics.rs +++ b/crates/forge-web-app/src/ci/runner_metrics.rs @@ -9,7 +9,7 @@ use std::sync::{Mutex, MutexGuard}; use forge_ci::proto::{RunnerMetricsBatch, RunnerSample}; /// How far back samples are kept, in milliseconds, counted from the newest sample. -pub const KEEP_MS: i64 = 3_600_000; +const KEEP_MS: i64 = 3_600_000; /// Most samples kept per runner. The oldest go first. const MAX_SAMPLES: usize = 800; diff --git a/crates/forge-web-app/src/ci/schedule.rs b/crates/forge-web-app/src/ci/schedule.rs index d6f5b6a..c69f43a 100644 --- a/crates/forge-web-app/src/ci/schedule.rs +++ b/crates/forge-web-app/src/ci/schedule.rs @@ -9,7 +9,7 @@ use forge_core::authz::{Action, authorize}; use forge_core::ci::{CiRun, NewJob, NewRun}; use forge_core::store::commit_status::StatusState; use forge_core::{PullRequest, Repo}; -use forge_git::browse::{peel_to_commit, read_blob, resolve_commit}; +use forge_git::browse::{BlobData, peel_to_commit, read_blob, resolve_commit}; use tokio::io::AsyncWriteExt; use super::api::fit_to_cap; @@ -35,21 +35,13 @@ pub(super) enum Loaded { Valid(CiConfig), } -/// What a request should do with the loaded config. -enum Plan { - /// No workflow file at this commit. - Missing, - /// The file is valid but this event does not trigger it. - NotTriggered, - /// Create a run with these jobs, or an Error run when `config_error` is set. `warnings` are the - /// config's ignored keys, written to the start of every job log. - Run { - jobs: Vec, - config_error: Option, - warnings: Vec, - /// `[on] cancel_superseded`: a push cancels the older live runs on its branch. - cancel_superseded: bool, - }, +/// A run to create. `config_error` makes it an Error run. `warnings` are the config's ignored keys, +/// written to the start of every job log. `cancel_superseded` is `[on] cancel_superseded`. +struct Planned { + jobs: Vec, + config_error: Option, + warnings: Vec, + cancel_superseded: bool, } /// The inputs of one run to create. @@ -83,49 +75,49 @@ pub async fn on_ref_update( } else { return; }; - let result = async { - // An annotated tag's ref names a tag object: the run, its statuses and any release are - // for the commit it points at. - let Some(commit) = peeled_commit(state, &repo.id, new_oid).await else { - return forge_core::Result::Ok(()); - }; - let new_oid = commit.as_str(); - let loaded = load(state, &repo.id, new_oid).await; - if let Plan::Run { - jobs, - config_error, - warnings, - cancel_superseded, - } = plan_for(loaded, &event)? - { - let run = create( - state, - Request { - repo, - trigger, - git_ref: refname, - commit: new_oid, - pull_number: None, - actor_id, - needs_approval: false, - }, - jobs, - config_error.as_deref(), - &warnings, - ) - .await?; - if cancel_superseded && trigger == "push" { - cancel_superseded_runs(state, &run).await?; - } - } - forge_core::Result::Ok(()) - } - .await; - if let Err(e) = result { + if let Err(e) = schedule_ref(state, repo, actor_id, trigger, refname, &event, new_oid).await { tracing::error!(error = %e, repo_id = %repo.id, refname, "ci: scheduling a push failed"); } } +async fn schedule_ref( + state: &AppState, + repo: &Repo, + actor_id: &str, + trigger: &'static str, + refname: &str, + event: &Event<'_>, + new_oid: &str, +) -> forge_core::Result<()> { + // An annotated tag's ref names a tag object: the run, its statuses and any release are + // for the commit it points at. + let Some(commit) = peeled_commit(state, &repo.id, new_oid).await else { + return Ok(()); + }; + let loaded = load(state, &repo.id, &commit).await; + let Some(planned) = plan_for(loaded, event)? else { + return Ok(()); + }; + let run = create( + state, + Request { + repo, + trigger, + git_ref: refname, + commit: &commit, + pull_number: None, + actor_id, + needs_approval: false, + }, + &planned, + ) + .await?; + if planned.cancel_superseded && trigger == "push" { + cancel_superseded_runs(state, &run).await?; + } + Ok(()) +} + /// A pull request was opened, synchronized (its head moved) or reopened. The config is read at /// the head commit. A fork head, or an author without Write on the base repo, creates the run in /// WaitingApproval: its jobs wait until someone approves it. @@ -145,13 +137,7 @@ async fn pull_run( actor_id: &str, ) -> forge_core::Result<()> { let loaded = load(state, &repo.id, &pull.head_oid).await; - let Plan::Run { - jobs, - config_error, - warnings, - .. - } = plan_for(loaded, &Event::PullRequest)? - else { + let Some(planned) = plan_for(loaded, &Event::PullRequest)? else { return Ok(()); }; let needs_approval = needs_approval(state, repo, pull).await?; @@ -167,9 +153,7 @@ async fn pull_run( actor_id, needs_approval, }, - jobs, - config_error.as_deref(), - &warnings, + &planned, ) .await?; Ok(()) @@ -198,37 +182,30 @@ pub async fn manual_run( return Err(forge_core::Error::NotFound); }; let loaded = load(state, &repo.id, &commit).await; - match plan_for(loaded, &Event::Manual)? { - Plan::Run { - jobs, - config_error, - warnings, - .. - } => { - create( - state, - Request { - repo, - trigger: "manual", - git_ref: &git_ref, - commit: &commit, - pull_number: None, - actor_id, - needs_approval: false, - }, - jobs, - config_error.as_deref(), - &warnings, - ) - .await - } - Plan::NotTriggered => Err(forge_core::Error::Invalid( - "manual runs are not enabled in .forge/ci.toml".into(), - )), - Plan::Missing => Err(forge_core::Error::Invalid( + if matches!(loaded, Loaded::Missing) { + return Err(forge_core::Error::Invalid( "this branch has no .forge/ci.toml".into(), - )), + )); } + let Some(planned) = plan_for(loaded, &Event::Manual)? else { + return Err(forge_core::Error::Invalid( + "manual runs are not enabled in .forge/ci.toml".into(), + )); + }; + create( + state, + Request { + repo, + trigger: "manual", + git_ref: &git_ref, + commit: &commit, + pull_number: None, + actor_id, + needs_approval: false, + }, + &planned, + ) + .await } /// 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 } /// The `[on] schedule` entries of the workflow on the repo's default branch. Empty when there is -/// no valid workflow. +/// no valid workflow or it cannot be read. pub async fn schedules_of(state: &AppState, repo: &Repo) -> Vec { match default_head_config(state, repo).await { Some((_, Loaded::Valid(cfg))) => cfg.on.schedule, @@ -264,13 +241,7 @@ pub(super) async fn scheduled_run( commit: &str, loaded: Loaded, ) -> forge_core::Result> { - let Plan::Run { - jobs, - config_error, - warnings, - .. - } = plan_for(loaded, &Event::Schedule)? - else { + let Some(planned) = plan_for(loaded, &Event::Schedule)? else { return Ok(None); }; let git_ref = format!("refs/heads/{}", repo.default_branch); @@ -286,9 +257,7 @@ pub(super) async fn scheduled_run( actor_id: &repo.owner_id, needs_approval: false, }, - jobs, - config_error.as_deref(), - &warnings, + &planned, ) .await?; Ok(Some(run)) @@ -310,13 +279,7 @@ pub async fn merge_queue_run( return Ok(None); } let loaded = load(state, &repo.id, commit).await; - let Plan::Run { - jobs, - config_error, - warnings, - .. - } = plan_for(loaded, &Event::MergeQueue { branch })? - else { + let Some(planned) = plan_for(loaded, &Event::MergeQueue { branch })? else { return Ok(None); }; let run = create( @@ -330,9 +293,7 @@ pub async fn merge_queue_run( actor_id, needs_approval: false, }, - jobs, - config_error.as_deref(), - &warnings, + &planned, ) .await?; Ok(Some(run)) @@ -343,11 +304,12 @@ pub async fn merge_queue_run( async fn create( state: &AppState, req: Request<'_>, - jobs: Vec, - config_error: Option<&str>, - warnings: &[String], + planned: &Planned, ) -> forge_core::Result { - let new_jobs: Vec> = jobs + let config_error = planned.config_error.as_deref(); + let warnings = planned.warnings.as_slice(); + let new_jobs: Vec> = planned + .jobs .iter() .map(|(name, spec_json, needs)| NewJob { name, @@ -476,25 +438,25 @@ async fn note_warnings( } /// Decides what a request does, given the loaded config and the event. -fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result { +fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result> { match loaded { - Loaded::Missing => Ok(Plan::Missing), - Loaded::Invalid(message) => Ok(Plan::Run { + Loaded::Missing => Ok(None), + Loaded::Invalid(message) => Ok(Some(Planned { jobs: Vec::new(), config_error: Some(message), warnings: Vec::new(), cancel_superseded: false, - }), + })), Loaded::Valid(cfg) => { if !cfg.triggered_by(event) { - return Ok(Plan::NotTriggered); + return Ok(None); } - Ok(Plan::Run { + Ok(Some(Planned { jobs: plan_jobs(&cfg)?, config_error: None, warnings: cfg.warnings.clone(), cancel_superseded: cfg.on.cancel_superseded, - }) + })) } } } @@ -513,7 +475,6 @@ fn plan_jobs(cfg: &CiConfig) -> forge_core::Result> { Ok(jobs) } -/// Reads and parses `.forge/ci.toml` at `commit` from the repo `repo_id`. /// The workflow at `commit`, when it is a valid file. Used by the release hook, which reads the /// config the run itself was made from. pub(super) async fn config_at(state: &AppState, repo_id: &str, commit: &str) -> Option { @@ -543,22 +504,28 @@ async fn peeled_commit(state: &AppState, repo_id: &str, oid: &str) -> Option Loaded { - let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, repo_id) { - Ok(path) => path, - Err(e) => { - tracing::error!(error = %e, repo_id, "ci: bad repo path"); - return Loaded::Invalid(format!("could not read {CONFIG_PATH}")); - } - }; +async fn read_config( + state: &AppState, + repo_id: &str, + commit: &str, +) -> forge_core::Result> { + let repo_dir = forge_git::repo::repo_path(&state.git.data_dir, repo_id) + .map_err(|e| forge_core::Error::Git(e.to_string()))?; let (dir, rev) = (repo_dir, commit.to_owned()); - let blob = match blocking(move || read_blob(&dir, &rev, CONFIG_PATH, MAX_CONFIG_BYTES)).await { - Ok(blob) => blob, + blocking(move || read_blob(&dir, &rev, CONFIG_PATH, MAX_CONFIG_BYTES)).await +} + +async fn load(state: &AppState, repo_id: &str, commit: &str) -> Loaded { + match read_config(state, repo_id, commit).await { + Ok(blob) => loaded_from(blob), Err(e) => { tracing::error!(error = %e, repo_id, commit, "ci: reading the workflow failed"); - return Loaded::Invalid(format!("could not read {CONFIG_PATH}")); + Loaded::Invalid(format!("could not read {CONFIG_PATH}")) } - }; + } +} + +fn loaded_from(blob: Option) -> Loaded { let Some(blob) = blob else { return Loaded::Missing; }; diff --git a/crates/forge-web-app/src/client_ip.rs b/crates/forge-web-app/src/client_ip.rs index 2a71997..09abb6a 100644 --- a/crates/forge-web-app/src/client_ip.rs +++ b/crates/forge-web-app/src/client_ip.rs @@ -36,14 +36,7 @@ pub fn client_addr(cx: &Cx) -> IpAddr { resolve_addr(peer, &forwarded, trusted) } -/// Pure form of [`client_ip`]: `forwarded` is the combined `X-Forwarded-For` value, or empty. -/// Only the tests use the bucketed form; the server takes [`client_ip`], which buckets itself. -#[cfg(any(test, feature = "test-support"))] -pub fn resolve(peer: Option, forwarded: &str, trusted: &[IpNet]) -> IpAddr { - bucket(resolve_addr(peer, forwarded, trusted)) -} - -/// Pure form of [`client_addr`]: the exact client address, normalized but not bucketed. +/// Pure form of [`client_addr`]: `forwarded` is the combined `X-Forwarded-For` value, or empty. pub fn resolve_addr(peer: Option, forwarded: &str, trusted: &[IpNet]) -> IpAddr { let Some(peer) = peer.map(normalize) else { return IpAddr::V4(Ipv4Addr::UNSPECIFIED); @@ -102,14 +95,14 @@ mod tests { #[test] fn forwarded_for_is_ignored_from_untrusted_peer() { let trusted = [net("10.0.0.0/8")]; - let got = resolve(Some(ip("203.0.113.9")), "198.51.100.7", &trusted); + let got = resolve_addr(Some(ip("203.0.113.9")), "198.51.100.7", &trusted); assert_eq!(got, ip("203.0.113.9")); } #[test] fn forwarded_for_is_honored_from_trusted_peer() { let trusted = [net("127.0.0.1/32")]; - let got = resolve(Some(ip("127.0.0.1")), "198.51.100.7", &trusted); + let got = resolve_addr(Some(ip("127.0.0.1")), "198.51.100.7", &trusted); assert_eq!(got, ip("198.51.100.7")); } @@ -117,7 +110,7 @@ mod tests { fn right_most_untrusted_entry_wins() { let trusted = [net("127.0.0.1/32"), net("10.0.0.0/8")]; // The client may prepend anything; the proxy appends the address it saw. - let got = resolve( + let got = resolve_addr( Some(ip("127.0.0.1")), "1.2.3.4, 198.51.100.7, 10.0.0.5", &trusted, @@ -129,15 +122,15 @@ mod tests { fn unusable_header_falls_back_to_peer() { let trusted = [net("127.0.0.1/32")]; assert_eq!( - resolve(Some(ip("127.0.0.1")), "", &trusted), + resolve_addr(Some(ip("127.0.0.1")), "", &trusted), ip("127.0.0.1") ); assert_eq!( - resolve(Some(ip("127.0.0.1")), "garbage", &trusted), + resolve_addr(Some(ip("127.0.0.1")), "garbage", &trusted), ip("127.0.0.1") ); assert_eq!( - resolve(Some(ip("127.0.0.1")), "127.0.0.1", &trusted), + resolve_addr(Some(ip("127.0.0.1")), "127.0.0.1", &trusted), ip("127.0.0.1") ); } @@ -145,9 +138,9 @@ mod tests { #[test] fn ipv6_is_bucketed_by_slash_64() { let trusted: [IpNet; 0] = []; - let a = resolve(Some(ip("2001:db8:1:2:aaaa::1")), "", &trusted); - let b = resolve(Some(ip("2001:db8:1:2:bbbb::9")), "", &trusted); - let c = resolve(Some(ip("2001:db8:1:3::1")), "", &trusted); + let a = bucket(resolve_addr(Some(ip("2001:db8:1:2:aaaa::1")), "", &trusted)); + let b = bucket(resolve_addr(Some(ip("2001:db8:1:2:bbbb::9")), "", &trusted)); + let c = bucket(resolve_addr(Some(ip("2001:db8:1:3::1")), "", &trusted)); assert_eq!(a, b); assert_ne!(a, c); assert_eq!(a, ip("2001:db8:1:2::")); @@ -157,7 +150,7 @@ mod tests { fn ipv4_mapped_peer_is_reported_as_ipv4() { let trusted: [IpNet; 0] = []; assert_eq!( - resolve(Some(ip("::ffff:192.0.2.5")), "", &trusted), + resolve_addr(Some(ip("::ffff:192.0.2.5")), "", &trusted), ip("192.0.2.5") ); } @@ -165,6 +158,6 @@ mod tests { #[test] fn unknown_peer_maps_to_unspecified() { let trusted: [IpNet; 0] = []; - assert_eq!(resolve(None, "1.2.3.4", &trusted), ip("0.0.0.0")); + assert_eq!(resolve_addr(None, "1.2.3.4", &trusted), ip("0.0.0.0")); } } diff --git a/crates/forge-web-app/src/exporter.rs b/crates/forge-web-app/src/exporter.rs index 4017cc6..87599d7 100644 --- a/crates/forge-web-app/src/exporter.rs +++ b/crates/forge-web-app/src/exporter.rs @@ -27,14 +27,15 @@ use tokio::sync::watch; use crate::state::AppState; -/// How long a finished export stays downloadable. -pub const EXPORT_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60); -/// How many days that is, for the page text. +/// How many days a finished export stays downloadable, for the page text. pub const EXPORT_TTL_DAYS: u64 = 7; +/// How long a finished export stays downloadable. +pub const EXPORT_TTL: Duration = Duration::from_secs(EXPORT_TTL_DAYS * 24 * 60 * 60); const PAGE: u32 = 100; static HUB: LazyLock>>> = LazyLock::new(|| Mutex::new(HashMap::new())); +static START: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); /// Follows a user's exports. Subscribe before reading their state. pub fn subscribe(user_id: &str) -> watch::Receiver { @@ -56,7 +57,7 @@ fn bump(user_id: &str) { } } -pub fn export_dir(state: &AppState) -> PathBuf { +fn export_dir(state: &AppState) -> PathBuf { state.config.data_dir.join("exports") } @@ -64,10 +65,26 @@ pub fn archive_path(state: &AppState, id: &str) -> PathBuf { export_dir(state).join(format!("{id}.tar.gz")) } +fn partial_path(state: &AppState, id: &str) -> PathBuf { + export_dir(state).join(format!("{id}.tar.part")) +} + +async fn remove_archive(state: &AppState, id: &str) -> std::io::Result<()> { + for path in [archive_path(state, id), partial_path(state, id)] { + match tokio::fs::remove_file(&path).await { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + } + Ok(()) +} + /// Starts an export for `user` and returns its row. At most one runs per user: a second request /// while one is building returns that one. pub async fn start(state: &AppState, user: &User) -> forge_core::Result { sweep_expired(state).await; + let _guard = START.lock().await; if let Some(running) = state .store .list_exports(&user.id) @@ -102,7 +119,7 @@ async fn run(state: &AppState, user: &User, id: &str) { } Err(message) => { tracing::error!(error = %message, export_id = id, "export failed"); - let _ = tokio::fs::remove_file(archive_path(state, id)).await; + let _ = remove_archive(state, id).await; if let Err(e) = state.store.mark_export_failed(id, &message).await { tracing::error!(error = %e, "export: could not record a failure"); } @@ -171,7 +188,7 @@ async fn stage_and_pack( stage_repo(state, repo, &repo_dir).await?; } let target = archive_path(state, id); - let partial = target.with_extension("part"); + let partial = partial_path(state, id); let (work_buf, partial_buf, name) = ( work.to_path_buf(), partial.clone(), @@ -230,7 +247,7 @@ fn write_array_item( } /// The account fields worth taking along. Never the password hash. -pub fn profile_json(user: &User) -> Value { +fn profile_json(user: &User) -> Value { json!({ "username": user.username, "display_name": user.display_name, @@ -389,14 +406,9 @@ pub async fn sweep_expired(state: &AppState) { } }; for export in expired { - let path = archive_path(state, &export.id); - match tokio::fs::remove_file(&path).await { - Ok(()) => {} - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => { - tracing::warn!(error = %e, "export: could not remove an expired archive"); - continue; - } + if let Err(e) = remove_archive(state, &export.id).await { + tracing::warn!(error = %e, "export: could not remove an expired archive"); + continue; } if let Err(e) = state.store.delete_export(&export.id).await { tracing::warn!(error = %e, "export: could not delete an expired export row"); @@ -407,13 +419,9 @@ pub async fn sweep_expired(state: &AppState) { /// Deletes one export by hand, its archive and its row. A missing archive is not an error. pub async fn delete_one(state: &AppState, export: &DataExport) -> forge_core::Result<()> { - match tokio::fs::remove_file(archive_path(state, &export.id)).await { - Ok(()) => {} - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => { - tracing::warn!(error = %e, "export: could not remove an archive"); - return Err(e.into()); - } + if let Err(e) = remove_archive(state, &export.id).await { + tracing::warn!(error = %e, "export: could not remove an archive"); + return Err(e.into()); } state.store.delete_export(&export.id).await?; bump(&export.user_id); diff --git a/crates/forge-web-app/src/git_http.rs b/crates/forge-web-app/src/git_http.rs index 65a970e..45ca096 100644 --- a/crates/forge-web-app/src/git_http.rs +++ b/crates/forge-web-app/src/git_http.rs @@ -361,6 +361,7 @@ pub async fn job_token_read( if !username.eq_ignore_ascii_case(JOB_GIT_USERNAME) { return None; } + let (job_id, token) = password.split_once(':')?; let key = throttle::ip_key("git-ip", ip); let now = Instant::now(); if let Some(retry) = state.throttle.check(&key, GIT_IP_LIMIT, now) { @@ -378,31 +379,13 @@ pub async fn job_token_read( "CI job tokens are read-only", )))); } - let job_token = match password.split_once(':') { - Some((job_id, token)) => state - .store - .job_by_token(job_id, token) - .await - .map_err(|e| internal_error_for(&e)), - None => Ok(None), - }; - let run_repo = match job_token { - Ok(Some(job)) => state - .store - .run_by_id(&job.run_id) - .await - .map_err(|e| internal_error_for(&e)) - .map(|run| run.map(|run| run.repo_id)), - Ok(None) => Ok(None), - Err(response) => Err(response), - }; - let run_repo = match run_repo { - Ok(run_repo) => run_repo, - Err(response) => return Some(Err(Box::new(response))), - }; - let Some(job_repo_id) = run_repo else { - state.throttle.record_failure(&key, now); - return Some(Err(Box::new(access_error(AccessError::Unauthorized)))); + let job_repo_id = match job_repo_id(state, job_id, token).await { + Ok(Some(id)) => id, + Ok(None) => { + state.throttle.record_failure(&key, now); + return Some(Err(job_unauthorized())); + } + Err(response) => return Some(Err(response)), }; // `.wiki` names the job's repo's wiki. It is hidden while the wiki is off, as for users. let (repo_name, wiki) = match forge_core::names::wiki_base(name) { @@ -411,13 +394,13 @@ pub async fn job_token_read( }; let repo = match find_repo(state, owner, repo_name).await { Ok(Some(repo)) if repo.id == job_repo_id => repo, - Ok(_) => return Some(Err(Box::new(access_error(AccessError::Unauthorized)))), + Ok(_) => return Some(Err(job_unauthorized())), Err(e) => return Some(Err(Box::new(access_error(e)))), }; if wiki { match state.store.wiki_enabled(&repo.id).await { Ok(true) => {} - Ok(false) => return Some(Err(Box::new(access_error(AccessError::Unauthorized)))), + Ok(false) => return Some(Err(job_unauthorized())), Err(e) => return Some(Err(Box::new(internal_error_for(&e)))), } return match forge_git::repo::wiki_path(&state.config.data_dir, &repo.id) { @@ -431,6 +414,31 @@ pub async fn job_token_read( } } +async fn job_repo_id( + state: &AppState, + job_id: &str, + token: &str, +) -> Result, Box> { + let Some(job) = state + .store + .job_by_token(job_id, token) + .await + .map_err(|e| Box::new(internal_error_for(&e)))? + else { + return Ok(None); + }; + let run = state + .store + .run_by_id(&job.run_id) + .await + .map_err(|e| Box::new(internal_error_for(&e)))?; + Ok(run.map(|run| run.repo_id)) +} + +fn job_unauthorized() -> Box { + Box::new(access_error(AccessError::Unauthorized)) +} + fn internal_error_for(error: &forge_core::Error) -> Response { tracing::error!(error = %error, "ci job token check failed"); internal_error() diff --git a/crates/forge-web-app/src/importer/api.rs b/crates/forge-web-app/src/importer/api.rs index c780a5c..c1d78b0 100644 --- a/crates/forge-web-app/src/importer/api.rs +++ b/crates/forge-web-app/src/importer/api.rs @@ -1,8 +1,3 @@ -//! Remote forge APIs for imports. [`RemoteApi`] is the seam: the import job talks only to the -//! trait, so tests use a fake and CI never needs the network. [`GitHub`] and [`GitLab`] are the real -//! clients over REST. They paginate, wait out rate limits (and say so through the notice callback), -//! and send the token only to the API host, never to a redirect target. - use std::fmt; use std::future::Future; use std::io; @@ -17,17 +12,12 @@ use serde::de::DeserializeOwned; use crate::webhooks::client::{WebhookPolicy, validate_url}; -/// A release asset's bytes as they arrive from the server, ready for the blob writer. pub type AssetStream = BoxStream<'static, io::Result>; const PER_PAGE: usize = 100; -/// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever. -/// Forgejo and Gitea cap `limit` at 50 by default. const FORGEJO_LIMIT: usize = 50; const MAX_PAGES: usize = 500; -/// Longest rate-limit wait a job sits through. A longer reset fails the job; a retry continues. const MAX_RATE_WAIT: u64 = 15 * 60; -/// Largest JSON page read. const MAX_JSON_BYTES: usize = 32 * 1024 * 1024; const MAX_REDIRECTS: usize = 5; @@ -58,7 +48,6 @@ impl fmt::Display for ApiError { } } -/// `secs` as a reader would say it, rounded up to the minute so a retry at that time is not early. fn wait_text(secs: u64) -> String { let plural = |n: u64| if n == 1 { "" } else { "s" }; if secs < 60 { @@ -88,7 +77,6 @@ pub struct ExtMilestone { pub title: String, pub description: String, pub closed: bool, - /// `YYYY-MM-DD`. pub due_on: Option, } @@ -143,7 +131,6 @@ pub struct ExtRelease { #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct ExtRepo { pub name: String, - /// `owner/name`, or the GitLab project path. pub full_name: String, pub description: String, pub private: bool, @@ -153,13 +140,10 @@ pub struct ExtRepo { pub web_url: String, } -/// What an import needs from a remote forge. `repo` is `owner/name` for GitHub and the full -/// project path for GitLab. pub trait RemoteApi: Send + Sync { fn list_repos(&self, owner: &str) -> impl Future>> + Send; fn labels(&self, repo: &str) -> impl Future>> + Send; fn milestones(&self, repo: &str) -> impl Future>> + Send; - /// Issues and pull (merge) requests, every state, with `is_pr` set on the latter. fn issues(&self, repo: &str) -> impl Future>> + Send; fn comments( &self, @@ -167,7 +151,6 @@ pub trait RemoteApi: Send + Sync { issue: &ExtIssue, ) -> impl Future>> + Send; fn releases(&self, repo: &str) -> impl Future>> + Send; - /// The bytes of a release asset, at most `max_bytes`, streamed as they arrive. fn download( &self, asset: &ExtAsset, @@ -175,7 +158,6 @@ pub trait RemoteApi: Send + Sync { ) -> impl Future> + Send; } -/// True for one URL path segment of an owner, repo or group name. pub fn valid_segment(s: &str) -> bool { !s.is_empty() && s.len() <= 100 @@ -185,13 +167,11 @@ pub fn valid_segment(s: &str) -> bool { .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) } -/// `owner/name` made of valid segments, `min..=max` of them. pub fn valid_path(path: &str, min: usize, max: usize) -> bool { let parts: Vec<&str> = path.split('/').collect(); (min..=max).contains(&parts.len()) && parts.iter().all(|p| valid_segment(p)) } -/// How long to wait after a 403 or 429. `None` when the response is not a rate limit. pub fn rate_wait( retry_after: Option<&str>, remaining: Option<&str>, @@ -210,18 +190,13 @@ pub fn rate_wait( pub type Notice = Arc; -/// How the token is presented to the API host. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Auth { - /// `Authorization: Bearer`. GitHub, - /// `PRIVATE-TOKEN`. GitLab, - /// `Authorization: token`. Forgejo, } -/// A client under the outbound policy, with the token kept private to the API host. pub struct Http { client: reqwest::Client, policy: WebhookPolicy, @@ -282,10 +257,7 @@ impl Http { .map(str::to_owned) } - /// One GET with retries: waits out a rate limit, backs off on a 5xx. Returns a 2xx or 3xx. async fn send(&self, url: &str, accept: &str, authed: bool) -> ApiResult { - // Every URL, including one taken from an API answer or a redirect: the client's resolver - // filters host names, but an address literal never reaches it. validate_url(url, &self.policy) .map_err(|e| ApiError::Http(format!("address refused: {e}")))?; let mut attempt = 0u32; @@ -354,7 +326,6 @@ impl Http { serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string())) } - /// Every page of a list endpoint, 100 per page, stopping at the first short page. pub async fn pages(&self, base: &str) -> ApiResult> { let sep = if base.contains('?') { '&' } else { '?' }; let mut out = Vec::new(); @@ -364,14 +335,12 @@ impl Http { let short = items.len() < PER_PAGE; out.extend(items); if short { - break; + return Ok(out); } } - Ok(out) + Err(ApiError::TooLarge) } - /// Every page of a Forgejo/Gitea list endpoint (`limit`, `page`). The `Link` header decides - /// when it ends; without one, `X-Total-Count`; without either, the first short page. pub async fn limit_pages(&self, base: &str) -> ApiResult> { let sep = if base.contains('?') { '&' } else { '?' }; let mut out: Vec = Vec::new(); @@ -393,15 +362,12 @@ impl Http { (None, None) => got < FORGEJO_LIMIT, }; if done { - break; + return Ok(out); } } - Ok(out) + Err(ApiError::TooLarge) } - /// Downloads a file, following redirects by hand: the token goes to the API host only, and - /// each hop is fetched under the same address policy as every other request. The body is - /// streamed, so a large asset is never held in memory whole. pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult { let mut current = url.to_owned(); for _ in 0..=MAX_REDIRECTS { @@ -435,8 +401,6 @@ impl Http { Err(ApiError::Http("too many redirects".into())) } - /// The body as it arrives. Counting happens here, so the stream fails with `InvalidData` as - /// soon as more than `max` bytes have come, whether or not the server sent a length. fn stream(resp: reqwest::Response, max: u64) -> AssetStream { let mut seen: u64 = 0; Box::pin(resp.bytes_stream().map(move |chunk| { @@ -467,8 +431,6 @@ fn s(v: Option) -> String { v.unwrap_or_default() } -// ---- GitHub ---- - pub struct GitHub { http: Http, base: String, @@ -584,8 +546,23 @@ fn login(u: Option) -> String { u.and_then(|u| u.login).unwrap_or_default() } -#[cfg(any(test, feature = "test-support"))] -pub fn parse_github_labels(json: &[u8]) -> ApiResult> { +fn release_title(name: Option, tag: &str) -> String { + name.filter(|n| !n.is_empty()) + .unwrap_or_else(|| tag.to_owned()) +} + +async fn or_user( + org: ApiResult>, + user: impl Future>>, +) -> ApiResult> { + match org { + Err(ApiError::NotFound(_)) => user.await, + other => other, + } +} + +#[cfg(test)] +fn parse_github_labels(json: &[u8]) -> ApiResult> { let raw: Vec = from_json(json)?; Ok(raw.into_iter().map(label_of).collect()) } @@ -598,13 +575,13 @@ fn label_of(l: GhLabel) -> ExtLabel { } } -#[cfg(any(test, feature = "test-support"))] +#[cfg(test)] fn from_json(json: &[u8]) -> ApiResult { serde_json::from_slice(json).map_err(|e| ApiError::Parse(e.to_string())) } -#[cfg(any(test, feature = "test-support"))] -pub fn parse_github_issues(json: &[u8]) -> ApiResult> { +#[cfg(test)] +fn parse_github_issues(json: &[u8]) -> ApiResult> { let raw: Vec = from_json(json)?; Ok(raw.into_iter().map(gh_issue).collect()) } @@ -630,8 +607,8 @@ fn gh_issue(i: GhIssue) -> ExtIssue { } } -#[cfg(any(test, feature = "test-support"))] -pub fn parse_github_releases(json: &[u8]) -> ApiResult> { +#[cfg(test)] +fn parse_github_releases(json: &[u8]) -> ApiResult> { let raw: Vec = from_json(json)?; Ok(raw .into_iter() @@ -672,15 +649,12 @@ impl RemoteApi for GitHub { .http .pages(&format!("{}/orgs/{owner}/repos?type=all", self.base)) .await; - let raw = match org { - Ok(raw) => raw, - Err(ApiError::NotFound(_)) => { - self.http - .pages(&format!("{}/users/{owner}/repos?type=owner", self.base)) - .await? - } - Err(e) => return Err(e), - }; + let raw = or_user( + org, + self.http + .pages(&format!("{}/users/{owner}/repos?type=owner", self.base)), + ) + .await?; Ok(raw .into_iter() .map(|r| ExtRepo { @@ -762,7 +736,6 @@ impl RemoteApi for GitHub { .http .pages(&format!("{}/repos/{repo}/releases", self.base)) .await?; - // Reuse the one conversion by round-tripping through the parser's mapping. Ok(raw.into_iter().map(gh_release).collect()) } @@ -777,10 +750,7 @@ impl RemoteApi for GitHub { fn gh_release(r: GhRelease) -> ExtRelease { ExtRelease { id: r.id.to_string(), - title: r - .name - .filter(|n| !n.is_empty()) - .unwrap_or_else(|| r.tag_name.clone()), + title: release_title(r.name, &r.tag_name), tag: r.tag_name, body: s(r.body), draft: r.draft, @@ -810,16 +780,12 @@ fn check_repo(repo: &str, min: usize, max: usize) -> ApiResult<()> { } } -// ---- GitLab ---- - pub struct GitLab { http: Http, - /// `https://host/api/v4`. base: String, } impl GitLab { - /// `instance` is the instance's web address, e.g. `https://gitlab.com`. pub fn new(http: Http, instance: &str) -> Self { GitLab { http, @@ -952,14 +918,14 @@ fn gl_issue(i: GlIssue, is_pr: bool) -> ExtIssue { } } -#[cfg(any(test, feature = "test-support"))] -pub fn parse_gitlab_issues(json: &[u8], is_pr: bool) -> ApiResult> { +#[cfg(test)] +fn parse_gitlab_issues(json: &[u8], is_pr: bool) -> ApiResult> { let raw: Vec = from_json(json)?; Ok(raw.into_iter().map(|i| gl_issue(i, is_pr)).collect()) } -#[cfg(any(test, feature = "test-support"))] -pub fn parse_gitlab_releases(json: &[u8]) -> ApiResult> { +#[cfg(test)] +fn parse_gitlab_releases(json: &[u8]) -> ApiResult> { let raw: Vec = from_json(json)?; Ok(raw.into_iter().map(gl_release).collect()) } @@ -967,10 +933,7 @@ pub fn parse_gitlab_releases(json: &[u8]) -> ApiResult> { fn gl_release(r: GlRelease) -> ExtRelease { ExtRelease { id: r.tag_name.clone(), - title: r - .name - .filter(|n| !n.is_empty()) - .unwrap_or_else(|| r.tag_name.clone()), + title: release_title(r.name, &r.tag_name), tag: r.tag_name, body: s(r.description), draft: r.upcoming_release, @@ -1007,15 +970,12 @@ impl RemoteApi for GitLab { self.base )) .await; - let raw = match group { - Ok(raw) => raw, - Err(ApiError::NotFound(_)) => { - self.http - .pages(&format!("{}/users/{enc}/projects", self.base)) - .await? - } - Err(e) => return Err(e), - }; + let raw = or_user( + group, + self.http + .pages(&format!("{}/users/{enc}/projects", self.base)), + ) + .await?; Ok(raw .into_iter() .map(|p| ExtRepo { @@ -1125,19 +1085,13 @@ impl RemoteApi for GitLab { } } -// ---- Forgejo and Gitea ---- - -/// A Forgejo or Gitea instance (Codeberg among them), over `/api/v1`. pub struct Forgejo { http: Http, - /// `https://host`, the web address the asset links must start with. origin: String, - /// `https://host/api/v1`. base: String, } impl Forgejo { - /// `instance` is the instance's web address, e.g. `https://codeberg.org`. pub fn new(http: Http, instance: &str) -> Self { let origin = instance.trim_end_matches('/').to_owned(); Forgejo { @@ -1192,7 +1146,6 @@ struct FjIssue { milestone: Option, created_at: Option, html_url: Option, - /// Set on `/pulls` items. #[serde(default)] merged: bool, } @@ -1266,10 +1219,7 @@ fn fj_issue(i: FjIssue, is_pr: bool) -> ExtIssue { fn fj_release(r: FjRelease) -> ExtRelease { ExtRelease { id: r.id.to_string(), - title: r - .name - .filter(|n| !n.is_empty()) - .unwrap_or_else(|| r.tag_name.clone()), + title: release_title(r.name, &r.tag_name), tag: r.tag_name, body: s(r.body), draft: r.draft, @@ -1293,7 +1243,6 @@ fn fj_release(r: FjRelease) -> ExtRelease { impl RemoteApi for Forgejo { async fn list_repos(&self, owner: &str) -> ApiResult> { - // An empty owner means "mine", which needs a token. let raw: Vec = if owner.is_empty() { self.http .limit_pages(&format!("{}/user/repos", self.base)) @@ -1306,15 +1255,12 @@ impl RemoteApi for Forgejo { .http .limit_pages(&format!("{}/orgs/{owner}/repos", self.base)) .await; - match org { - Ok(raw) => raw, - Err(ApiError::NotFound(_)) => { - self.http - .limit_pages(&format!("{}/users/{owner}/repos", self.base)) - .await? - } - Err(e) => return Err(e), - } + or_user( + org, + self.http + .limit_pages(&format!("{}/users/{owner}/repos", self.base)), + ) + .await? }; Ok(raw .into_iter() @@ -1413,7 +1359,6 @@ impl RemoteApi for Forgejo { .http .limit_pages(&format!("{}/repos/{repo}/releases", self.base)) .await?; - // The list embeds each release's assets, so `/releases/{id}/assets` is not needed. Ok(raw.into_iter().map(fj_release).collect()) } diff --git a/crates/forge-web-app/src/importer/mod.rs b/crates/forge-web-app/src/importer/mod.rs index a2577f1..15b5c40 100644 --- a/crates/forge-web-app/src/importer/mod.rs +++ b/crates/forge-web-app/src/importer/mod.rs @@ -288,7 +288,7 @@ fn clip_title(title: &str) -> String { /// An asset file name the release store accepts. pub fn asset_name(name: &str) -> String { - let mut out: String = name + let cleaned: String = name .chars() .map(|c| { if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+') { @@ -298,9 +298,7 @@ pub fn asset_name(name: &str) -> String { } }) .collect(); - while out.starts_with('.') { - out.remove(0); - } + let mut out = cleaned.trim_start_matches('.').to_owned(); out.truncate(MAX_ASSET_NAME_LEN); if out.is_empty() { "asset".to_owned() @@ -354,7 +352,7 @@ async fn run_production(state: &AppState, job: &ImportJob, spec: &JobSpec) { Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, Err(e) => fail(state, &rep, &e).await, }, - Source::Git => {} + Source::Git => run_job::(state, job, spec, None, &Transport::Net).await, } } @@ -566,10 +564,6 @@ struct Totals { skipped: usize, } -fn api_err(e: ApiError) -> String { - e.to_string() -} - struct Run<'a, A> { state: &'a AppState, rep: &'a Reporter, @@ -614,7 +608,11 @@ impl Run<'_, A> { async fn labels(&self, totals: &mut Totals) -> Result<(), String> { self.rep.stage("labels", 0, 0).await; - let labels = self.api.labels(&self.spec.remote).await.map_err(api_err)?; + let labels = self + .api + .labels(&self.spec.remote) + .await + .map_err(|e| e.to_string())?; let total = labels.len(); for (i, label) in labels.into_iter().enumerate() { self.rep.stage("labels", i, total).await; @@ -656,7 +654,7 @@ impl Run<'_, A> { .api .milestones(&self.spec.remote) .await - .map_err(api_err)?; + .map_err(|e| e.to_string())?; let total = items.len(); for (i, m) in items.into_iter().enumerate() { self.rep.stage("milestones", i, total).await; @@ -721,7 +719,12 @@ impl Run<'_, A> { cache.insert(key, label.id.clone()); Some(label.id) } - Err(_) => None, + Err(e) => { + self.rep + .log("warn", format!("label `{name}` not set: {e}")) + .await; + None + } } } @@ -731,7 +734,7 @@ impl Run<'_, A> { .api .issues(&self.spec.remote) .await - .map_err(api_err)? + .map_err(|e| e.to_string())? .into_iter() .filter(|i| { if i.is_pr { @@ -741,11 +744,10 @@ impl Run<'_, A> { } }) .collect(); - items.sort_by_key(|i| (i.is_pr, i.number)); - // GitHub and Forgejo number issues and pull requests together; GitLab keeps two sequences. Sorting - // by number alone keeps GitHub numbers aligned, so do that for them. if matches!(self.spec.source, Source::GitHub | Source::Forgejo) { items.sort_by_key(|i| i.number); + } else { + items.sort_by_key(|i| (i.is_pr, i.number)); } let total = items.len(); let mut labels: HashMap = self @@ -779,7 +781,6 @@ impl Run<'_, A> { Some(o) => o.local_id, None => match self.create_item(item, &mut labels, &milestones).await { Ok(id) => { - self.record(kind, &ext, &id, &item.author, &item.url).await; created_since_bump += 1; if created_since_bump == IMPORT_BUMP_BATCH { created_since_bump = 0; @@ -801,47 +802,58 @@ impl Run<'_, A> { } }, }; - let comments = self - .api - .comments(&self.spec.remote, item) - .await - .map_err(api_err)?; - for c in comments { - if self - .mapped("comment", &format!("{kind}:{}", c.id)) - .await? - .is_some() - { - continue; + self.import_comments(kind, &local, item, totals).await?; + } + self.rep.stage("issues", total, total).await; + self.bump_issues(); + Ok(()) + } + + async fn import_comments( + &self, + kind: &str, + local: &str, + item: &ExtIssue, + totals: &mut Totals, + ) -> Result<(), String> { + let comments = self + .api + .comments(&self.spec.remote, item) + .await + .map_err(|e| e.to_string())?; + for c in comments { + if self + .mapped("comment", &format!("{kind}:{}", c.id)) + .await? + .is_some() + { + continue; + } + let note = origin_note(self.spec.source.label(), &c.author, &c.created_at, &c.url); + let body = with_note(¬e, &c.body); + match self.store().add_comment(local, &self.user.id, &body).await { + Ok(created) => { + self.record( + "comment", + &format!("{kind}:{}", c.id), + &created.id, + &c.author, + &c.url, + ) + .await; + totals.comments += 1; } - let note = origin_note(self.spec.source.label(), &c.author, &c.created_at, &c.url); - let body = with_note(¬e, &c.body); - match self.store().add_comment(&local, &self.user.id, &body).await { - Ok(created) => { - self.record( - "comment", - &format!("{kind}:{}", c.id), - &created.id, - &c.author, - &c.url, + Err(e) => { + totals.skipped += 1; + self.rep + .log( + "warn", + format!("a comment on #{} skipped: {e}", item.number), ) .await; - totals.comments += 1; - } - Err(e) => { - totals.skipped += 1; - self.rep - .log( - "warn", - format!("a comment on #{} skipped: {e}", item.number), - ) - .await; - } } } } - self.rep.stage("issues", total, total).await; - self.bump_issues(); Ok(()) } @@ -876,6 +888,9 @@ impl Run<'_, A> { &body, ) .await?; + let kind = if item.is_pr { "pull" } else { "issue" }; + self.record(kind, &item.number.to_string(), &issue.id, &item.author, &item.url) + .await; let mut ids = Vec::new(); for name in &item.labels { if let Some(id) = self.label_id(labels, name, FALLBACK_LABEL_COLOR).await { @@ -889,7 +904,6 @@ impl Run<'_, A> { { ids.push(id); } - ids.dedup(); if !ids.is_empty() { self.store() .set_issue_labels(&issue.id, &self.user.id, &ids) @@ -929,7 +943,7 @@ impl Run<'_, A> { .api .releases(&self.spec.remote) .await - .map_err(api_err)?; + .map_err(|e| e.to_string())?; let repo_dir = forge_git::repo::repo_path(&self.state.git.data_dir, &self.repo.id) .map_err(|e| e.to_string())?; let refs = ref_snapshot(self.state, &repo_dir).await?; @@ -957,11 +971,21 @@ impl Run<'_, A> { totals: &mut Totals, ) -> Result, String> { if let Some(o) = self.mapped("release", &rel.id).await? { - return self + let found = self .store() .release(&o.local_id) .await - .map_err(|e| e.to_string()); + .map_err(|e| e.to_string())?; + if found.is_none() { + totals.skipped += 1; + self.rep + .log( + "warn", + format!("release `{}` skipped: it was deleted here", rel.tag), + ) + .await; + } + return Ok(found); } let Some(oid) = refs.get(&format!("refs/tags/{}", rel.tag)) else { totals.skipped += 1; diff --git a/crates/forge-web-app/src/importer/remote.rs b/crates/forge-web-app/src/importer/remote.rs index e6a9dc2..3a6303e 100644 --- a/crates/forge-web-app/src/importer/remote.rs +++ b/crates/forge-web-app/src/importer/remote.rs @@ -8,14 +8,28 @@ use crate::mirrors::policy; use crate::state::AppState; use crate::webhooks::client::{policy_client, validate_url}; +fn client(state: &AppState) -> Result { + policy_client(policy(state), Duration::from_secs(60), "forge-import/1") + .map_err(|e| format!("could not build the HTTP client: {e}")) +} + +fn instance_host<'a>(state: &AppState, instance: &'a str) -> Result<(&'a str, String), String> { + let instance = instance.trim_end_matches('/'); + let host = validate_url(instance, &policy(state)) + .map_err(|e| format!("instance address refused: {e}"))? + .host_str() + .unwrap_or_default() + .to_ascii_lowercase(); + Ok((instance, host)) +} + /// A GitHub client under the outbound policy. pub fn make_github( state: &AppState, token: Option, notice: Notice, ) -> Result { - let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1") - .map_err(|e| format!("could not build the HTTP client: {e}"))?; + let client = client(state)?; Ok(GitHub::new(Http::new( client, policy(state), @@ -33,14 +47,8 @@ pub fn make_gitlab( token: Option, notice: Notice, ) -> Result { - let instance = instance.trim_end_matches('/'); - let host = validate_url(instance, &policy(state)) - .map_err(|e| format!("instance address refused: {e}"))? - .host_str() - .unwrap_or_default() - .to_ascii_lowercase(); - let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1") - .map_err(|e| format!("could not build the HTTP client: {e}"))?; + let (instance, host) = instance_host(state, instance)?; + let client = client(state)?; Ok(GitLab::new( Http::new(client, policy(state), token, Auth::GitLab, host, notice), instance, @@ -54,14 +62,8 @@ pub fn make_forgejo( token: Option, notice: Notice, ) -> Result { - let instance = instance.trim_end_matches('/'); - let host = validate_url(instance, &policy(state)) - .map_err(|e| format!("instance address refused: {e}"))? - .host_str() - .unwrap_or_default() - .to_ascii_lowercase(); - let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1") - .map_err(|e| format!("could not build the HTTP client: {e}"))?; + let (instance, host) = instance_host(state, instance)?; + let client = client(state)?; Ok(Forgejo::new( Http::new(client, policy(state), token, Auth::Forgejo, host, notice), instance, diff --git a/crates/forge-web-app/src/internal.rs b/crates/forge-web-app/src/internal.rs index a0843b9..c65830d 100644 --- a/crates/forge-web-app/src/internal.rs +++ b/crates/forge-web-app/src/internal.rs @@ -161,14 +161,11 @@ async fn hook_endpoint( Stage::PreReceive => match evaluate_pre_receive(&state.store, &state.git, &req).await { Ok(verdict) => verdict, Err(e) => { - // Fail closed: an internal error rejects the push. tracing::error!(error = %e, repo_id = %req.repo_id, "pre-receive check failed"); HookResponse::deny("internal error while checking the push") } }, Stage::PostReceive if req.wiki => { - // A wiki push changes neither the code repo's refs nor its CI, pull requests or events. - // It still goes to the standby. record_wiki_push(&state.store, &req).await; crate::live::bump_wiki(state, &req.repo_id); crate::replication::enqueue_repo(state, &req.repo_id); @@ -431,7 +428,6 @@ async fn record_events(store: &Store, req: &HookRequest) -> HookResponse { )); } } - // post-receive cannot reject a push, so the verdict is always allow. HookResponse { allow: true, message: failures.join("\n"), @@ -599,7 +595,7 @@ async fn record_wiki_push(store: &Store, req: &HookRequest) { /// Decides whether a push may proceed. `Ok(deny)` is a policy decision; `Err` is an /// internal failure (the caller turns it into a deny). -pub async fn evaluate_pre_receive( +async fn evaluate_pre_receive( store: &Store, git: &GitEnv, req: &HookRequest, @@ -615,8 +611,6 @@ pub async fn evaluate_pre_receive( return Ok(HookResponse::deny("the wiki is disabled")); } } else if store.pull_mirror(&repo.id).await?.is_some() { - // A pull mirror's refs come from its remote; a push here would be overwritten by the next sync. - // Mirrors do not mirror wikis, so wiki pushes are not refused for this. return Ok(HookResponse::deny("this repository is a pull mirror")); } let repo_dir = if req.wiki { @@ -624,8 +618,6 @@ pub async fn evaluate_pre_receive( } else { forge_git::repo::repo_path(&git.data_dir, &repo.id)? }; - // Loaded once per push; every branch update below is checked against the same rules. Wiki - // pushes skip the rules: the wiki has no protected branches, only its main branch. let rules = if req.wiki { Vec::new() } else { @@ -639,7 +631,7 @@ pub async fn evaluate_pre_receive( update.ref_name ))); } - if !is_valid_oid(&update.old) || !is_valid_oid(&update.new) { + if !is_git_oid(&update.old) || !is_git_oid(&update.new) { return Ok(HookResponse::deny(format!( "invalid object id in update to {:?}", update.ref_name @@ -758,7 +750,7 @@ pub fn is_zero_oid(oid: &str) -> bool { } /// True for a SHA-1 or SHA-256 object id: 40 or 64 hex digits. -pub fn is_valid_oid(oid: &str) -> bool { +pub fn is_git_oid(oid: &str) -> bool { matches!(oid.len(), 40 | 64) && oid.bytes().all(|b| b.is_ascii_hexdigit()) } @@ -771,7 +763,6 @@ mod tests { #[test] fn ref_name_validity_cases() { - // (ref name, expected validity): must live under refs/, no dotdot or leading dash, no control chars. let cases: [(&str, bool); 12] = [ ("refs/heads/main", true), ("refs/tags/v1.0", true), @@ -802,24 +793,21 @@ mod tests { #[test] fn oid_validation() { - assert!(is_valid_oid(&"a".repeat(40))); - assert!(is_valid_oid(&"F".repeat(64))); - assert!(is_valid_oid(&"0".repeat(40))); - assert!(!is_valid_oid(&"g".repeat(40))); - assert!(!is_valid_oid(&"a".repeat(41))); - assert!(!is_valid_oid("--all")); + assert!(is_git_oid(&"a".repeat(40))); + assert!(is_git_oid(&"F".repeat(64))); + assert!(is_git_oid(&"0".repeat(40))); + assert!(!is_git_oid(&"g".repeat(40))); + assert!(!is_git_oid(&"a".repeat(41))); + assert!(!is_git_oid("--all")); } #[test] fn maintenance_claims_coalesce_per_repo() { let mut map = HashMap::new(); - // First push starts a worker; pushes during the run only flag a rerun. assert!(claim_maintenance(&mut map, "r1")); assert!(!claim_maintenance(&mut map, "r1")); assert!(!claim_maintenance(&mut map, "r1")); - // Other repos are independent. assert!(claim_maintenance(&mut map, "r2")); - // One rerun is due after the first run, then the repo is released. assert!(finish_maintenance(&mut map, "r1")); assert!(!finish_maintenance(&mut map, "r1")); assert!(!map.contains_key("r1")); @@ -874,7 +862,6 @@ mod tests { assert_eq!(res.status(), 403, "{path} with token {token:?}"); } } - // The right token gets through: an fsck of an instance with no repos is clean. let req = topcoat::router::request::Request::builder() .method("POST") .uri("/internal/admin/fsck") @@ -919,7 +906,6 @@ mod tests { #[tokio::test] async fn hook_routes_are_not_collected_by_discover() { - // The public router uses `.discover()`. Hook routes are plain RouteFns and must not be in it. let public = Router::builder().discover().build(); for path in ["/hook/pre-receive", "/hook/post-receive"] { let req = topcoat::router::request::Request::builder() @@ -1013,7 +999,6 @@ mod tests { quarantine_env: BTreeMap::new(), }; - // A Write collaborator's direct fast-forward is refused. let refused = evaluate_pre_receive(&store, &git_env, &request(&writer.id, &first, &second)) .await .expect("evaluate"); @@ -1022,7 +1007,6 @@ mod tests { refused.message, "branch 'main' only accepts changes through pull requests" ); - // So is creating the branch. let created = evaluate_pre_receive( &store, &git_env, @@ -1032,7 +1016,6 @@ mod tests { .expect("evaluate"); assert!(!created.allow); - // Repo admins (Admin collaborators and the owner) may still push. for actor in [&admin.id, &owner.id] { let ok = evaluate_pre_receive(&store, &git_env, &request(actor, &first, &second)) .await @@ -1081,7 +1064,6 @@ mod tests { }], quarantine_env: BTreeMap::new(), }; - // Before the pull mirror exists, the push is not refused for that reason. let before = evaluate_pre_receive(&store, &git_env, &request) .await .expect("evaluate"); @@ -1130,14 +1112,12 @@ mod tests { data_dir: tmp.path().to_path_buf(), }; - // Bare repo at the path forge would use for this repo id. let bare = forge_git::repo::repo_path(&git_env.data_dir, &repo.id).expect("repo path"); forge_git::repo::init_bare(&git_env, &bare, "main") .await .expect("init bare"); let bare_str = bare.to_str().expect("utf8 path"); - // Two commits on main, then a divergent commit on a side branch. let work = tmp.path().join("work"); git(tmp.path(), &["init", "-b", "main", "work"]); let first = commit(&work, "one"); @@ -1164,13 +1144,11 @@ mod tests { quarantine_env: BTreeMap::new(), }; - // Fast-forward: allowed. let ff = evaluate_pre_receive(&store, &git_env, &request(&first, &second)) .await .expect("evaluate"); assert_eq!(ff, HookResponse::allow()); - // Non-fast-forward: denied. let forced = evaluate_pre_receive(&store, &git_env, &request(&second, &divergent)) .await .expect("evaluate"); @@ -1180,7 +1158,6 @@ mod tests { "force-push to protected branch 'main' is not allowed" ); - // Deleting the default branch: denied. let deleted = evaluate_pre_receive(&store, &git_env, &request(&second, &"0".repeat(40))) .await .expect("evaluate"); @@ -1190,7 +1167,6 @@ mod tests { "deleting protected branch 'main' is not allowed" ); - // A rule that allows force pushes lifts only that check; deletion stays denied. store .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(true, false)) .await diff --git a/crates/forge-web-app/src/layers.rs b/crates/forge-web-app/src/layers.rs index b7091ee..a141313 100644 --- a/crates/forge-web-app/src/layers.rs +++ b/crates/forge-web-app/src/layers.rs @@ -1,5 +1,9 @@ use std::fmt; +use topcoat::context::Cx; +use topcoat::router::request::{method, uri}; +use topcoat::router::Method; + use crate::live::Topic; use crate::state::AppState; @@ -69,6 +73,13 @@ pub async fn bump_pending_reviewers(state: &AppState, issue_id: &str) { } } +fn post_segments(cx: &Cx) -> Option> { + if *method(cx) != Method::POST { + return None; + } + Some(uri(cx).path().trim_start_matches('/').split('/').collect()) +} + mod settings_write { use topcoat::Result; use topcoat::context::{Cx, context}; @@ -201,11 +212,10 @@ mod repo_moved { mod pull_write { use topcoat::context::{Cx, context}; - use topcoat::router::request::{method, uri}; use topcoat::router::response::Response; - use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; + use topcoat::router::{Body, Layer, LayerFuture, Next, Path}; - use super::bump_pending_reviewers; + use super::{bump_pending_reviewers, post_segments}; use crate::live::{bump_list, bump_pull, bump_repo_pulls}; use crate::state::AppState; @@ -225,11 +235,7 @@ mod pull_write { /// The write a request makes to the pull side, when it is a POST that can change one. fn written(cx: &Cx) -> Option { - if *method(cx) != Method::POST { - return None; - } - let path = uri(cx).path().to_owned(); - let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); + let parts = post_segments(cx)?; let [owner, repo, kind, rest @ ..] = parts.as_slice() else { return None; }; @@ -310,10 +316,10 @@ mod pull_write { mod discussion_write { use topcoat::context::{Cx, context}; - use topcoat::router::request::{method, uri}; use topcoat::router::response::Response; - use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; + use topcoat::router::{Body, Layer, LayerFuture, Next, Path}; + use super::post_segments; use crate::live::Topic; use crate::state::AppState; @@ -331,11 +337,7 @@ mod discussion_write { /// The write a request makes to the discussion side, when it is a POST that can change one. fn written(cx: &Cx) -> Option { - if *method(cx) != Method::POST { - return None; - } - let path = uri(cx).path().to_owned(); - let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); + let parts = post_segments(cx)?; let [owner, repo, kind, rest @ ..] = parts.as_slice() else { return None; }; @@ -416,20 +418,16 @@ mod discussion_write { mod org_write { use topcoat::context::{Cx, context}; - use topcoat::router::request::{method, uri}; use topcoat::router::response::Response; - use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; + use topcoat::router::{Body, Layer, LayerFuture, Next, Path}; + use super::post_segments; use crate::live::Topic; use crate::state::AppState; /// The org a POST under `/org/{org}/{members|teams|settings}` writes to, by its name. fn written_org(cx: &Cx) -> Option { - if *method(cx) != Method::POST { - return None; - } - let path = uri(cx).path().to_owned(); - let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); + let parts = post_segments(cx)?; let ["org", name, kind, ..] = parts.as_slice() else { return None; }; @@ -478,10 +476,10 @@ mod org_write { mod repo_settings_write { use topcoat::Result; use topcoat::context::{Cx, context}; - use topcoat::router::request::{method, uri}; use topcoat::router::response::Response; - use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; + use topcoat::router::{Body, Layer, LayerFuture, Next, Path}; + use super::post_segments; use crate::live::{Topic, bump_repo_pulls, bump_settings}; use crate::state::AppState; @@ -501,11 +499,7 @@ mod repo_settings_write { /// The `(owner, name)` of a POST under `/{o}/{r}/settings/...` or `/{o}/{r}/security/...`. fn written(cx: &Cx) -> Option<(String, String)> { - if *method(cx) != Method::POST { - return None; - } - let path = uri(cx).path().to_owned(); - let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); + let parts = post_segments(cx)?; match parts.as_slice() { [owner, name, "settings" | "security", ..] => { Some(((*owner).to_owned(), (*name).to_owned())) diff --git a/crates/forge-web-app/src/lfs/gc.rs b/crates/forge-web-app/src/lfs/gc.rs index b9e3d15..01484d9 100644 --- a/crates/forge-web-app/src/lfs/gc.rs +++ b/crates/forge-web-app/src/lfs/gc.rs @@ -9,7 +9,7 @@ use std::time::{Duration, SystemTime}; use forge_core::Store; use serde::{Deserialize, Serialize}; -use super::{is_valid_oid, lfs_root, tmp_dir}; +use super::{is_sha256_hex, lfs_root, tmp_dir}; /// The age an unlinked file must reach before it is deleted. pub const GC_MIN_AGE: Duration = Duration::from_secs(24 * 60 * 60); @@ -68,7 +68,11 @@ pub async fn gc( } // Look again just before deleting: an upload may have renamed the file into place and // linked it since the listing was taken. - let fresh = tokio::fs::metadata(&candidate.path).await?; + let fresh = match tokio::fs::metadata(&candidate.path).await { + Ok(fresh) => fresh, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + Err(e) => return Err(e.into()), + }; if !is_older_than(fresh.modified()?, now, min_age) || store.lfs_oid_is_linked(&candidate.oid).await? { @@ -105,7 +109,11 @@ fn list_files(dir: &Path) -> forge_core::Result> { }; for entry in entries { let entry = entry?; - let meta = entry.metadata()?; + let meta = match entry.metadata() { + Ok(meta) => meta, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + Err(e) => return Err(e.into()), + }; if meta.is_file() { found.push((entry.path(), meta.modified()?)); } @@ -132,12 +140,16 @@ fn collect_objects(root: &Path) -> forge_core::Result> { }; for file in std::fs::read_dir(b.path())? { let file = file?; - let meta = file.metadata()?; + let meta = match file.metadata() { + Ok(meta) => meta, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + Err(e) => return Err(e.into()), + }; let Some(oid) = file.file_name().to_str().map(str::to_owned) else { continue; }; if !meta.is_file() - || !is_valid_oid(&oid) + || !is_sha256_hex(&oid) || !oid.starts_with(&format!("{a_name}{b_name}")) { continue; diff --git a/crates/forge-web-app/src/lfs/mod.rs b/crates/forge-web-app/src/lfs/mod.rs index 4edb301..41ce18c 100644 --- a/crates/forge-web-app/src/lfs/mod.rs +++ b/crates/forge-web-app/src/lfs/mod.rs @@ -17,7 +17,7 @@ use forge_core::Result; use crate::state::AppState; /// True for a 64-character lowercase hex SHA-256. -pub fn is_valid_oid(oid: &str) -> bool { +pub fn is_sha256_hex(oid: &str) -> bool { oid.len() == 64 && oid .bytes() @@ -34,7 +34,7 @@ pub fn tmp_dir(data_dir: &Path) -> PathBuf { lfs_root(data_dir).join("tmp") } -/// The on-disk path of object `oid`. Callers pass a validated oid (see [`is_valid_oid`]); for any +/// The on-disk path of object `oid`. Callers pass a validated oid (see [`is_sha256_hex`]); for any /// other input the path is still inside the store, just not in a fan-out directory. pub fn object_path(data_dir: &Path, oid: &str) -> PathBuf { match (oid.get(0..2), oid.get(2..4)) { @@ -56,12 +56,12 @@ mod tests { #[test] fn oid_must_be_64_lowercase_hex() { let good = "4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393"; - assert!(is_valid_oid(good)); - assert!(!is_valid_oid(&good[..63])); - assert!(!is_valid_oid(&format!("{good}0"))); - assert!(!is_valid_oid(&good.to_uppercase())); - assert!(!is_valid_oid(&format!("{}g", &good[..63]))); - assert!(!is_valid_oid("")); + assert!(is_sha256_hex(good)); + assert!(!is_sha256_hex(&good[..63])); + assert!(!is_sha256_hex(&format!("{good}0"))); + assert!(!is_sha256_hex(&good.to_uppercase())); + assert!(!is_sha256_hex(&format!("{}g", &good[..63]))); + assert!(!is_sha256_hex("")); } #[test] diff --git a/crates/forge-web-app/src/lfs/routes.rs b/crates/forge-web-app/src/lfs/routes.rs index cf52a6b..f66cede 100644 --- a/crates/forge-web-app/src/lfs/routes.rs +++ b/crates/forge-web-app/src/lfs/routes.rs @@ -8,10 +8,10 @@ use std::net::IpAddr; use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; -use std::time::{SystemTime, UNIX_EPOCH}; use forge_core::Action; use forge_core::lfs_token::{self, LfsOp}; +use forge_core::time::now_unix; use futures_util::{StreamExt, TryStreamExt}; use http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; use http_body::Frame; @@ -26,7 +26,7 @@ use topcoat::router::request::headers; use topcoat::router::response::Response; use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route, to_bytes}; -use super::{is_valid_oid, object_path, tmp_dir}; +use super::{is_sha256_hex, object_path, tmp_dir}; use crate::access::{AccessError, find_repo, resolve_repo_for}; use crate::client_ip::client_ip; use crate::git_http::{access_error, authenticate}; @@ -86,7 +86,7 @@ async fn batch(cx: &Cx, body: Body) -> topcoat::Result { }; let max = state.live().lfs.max_object_bytes(); for object in &request.objects { - if !is_valid_oid(&object.oid) { + if !is_sha256_hex(&object.oid) { return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid")); } if object.size > max { @@ -199,7 +199,7 @@ async fn get_object(cx: &Cx) -> topcoat::Result { let owner = owner(cx); let name = repo(cx); let oid = oid(cx); - if !is_valid_oid(oid) { + if !is_sha256_hex(oid) { return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid")); } @@ -239,7 +239,7 @@ async fn put_object(cx: &Cx, body: Body) -> topcoat::Result { let owner = owner(cx); let name = repo(cx); let oid = oid(cx); - if !is_valid_oid(oid) { + if !is_sha256_hex(oid) { return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid")); } @@ -298,7 +298,7 @@ async fn verify(cx: &Cx, body: Body) -> topcoat::Result { )); } }; - if !is_valid_oid(&request.oid) { + if !is_sha256_hex(&request.oid) { return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid")); } Ok( @@ -504,9 +504,3 @@ fn lfs_json(status: StatusCode, value: Value) -> Response { fn message(status: StatusCode, text: impl Into) -> Response { lfs_json(status, json!({ "message": text.into() })) } - -fn now_unix() -> i64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) -} diff --git a/crates/forge-web-app/src/lfs_pointer.rs b/crates/forge-web-app/src/lfs_pointer.rs index d284a2e..6d5f06d 100644 --- a/crates/forge-web-app/src/lfs_pointer.rs +++ b/crates/forge-web-app/src/lfs_pointer.rs @@ -9,10 +9,10 @@ //! //! Extra `key value` lines are allowed. The parser is pure and accepts nothing else. -use crate::lfs::is_valid_oid; +use crate::lfs::is_sha256_hex; /// Pointer files are about 130 bytes. Anything larger is never treated as a pointer. -pub const MAX_POINTER_BYTES: usize = 1024; +const MAX_POINTER_BYTES: usize = 1024; const VERSION_LINE: &str = "version https://git-lfs.github.com/spec/v1"; @@ -42,7 +42,7 @@ pub fn parse(data: &[u8]) -> Option { match key { "oid" => { let hex = value.strip_prefix("sha256:")?; - if oid.is_some() || !is_valid_oid(hex) { + if oid.is_some() || !is_sha256_hex(hex) { return None; } oid = Some(hex.to_owned()); diff --git a/crates/forge-web-app/src/live.rs b/crates/forge-web-app/src/live.rs index 0fcde9a..2b756cb 100644 --- a/crates/forge-web-app/src/live.rs +++ b/crates/forge-web-app/src/live.rs @@ -277,9 +277,8 @@ where events_response(cx, events) } -/// The events of [`stream_changes_with`] as a stream, each named `name`, for a caller that merges -/// several streams into one response (see `pages::shell_events`). -pub async fn named_changes( +/// The events of [`stream_changes_with`] as a stream, each named `name`. +async fn named_changes( hub: &LiveHub, topics: Vec, extra: Vec>, @@ -479,14 +478,12 @@ impl StreamSlot { let ip = crate::client_ip::client_ip(cx); let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner()); let (total, per_client) = &mut *open; - let count = per_client - .get_or_insert_with(HashMap::new) - .entry(ip) - .or_insert(0); - if *total >= MAX_STREAMS || *count >= MAX_STREAMS_PER_CLIENT { + let map = per_client.get_or_insert_with(HashMap::new); + let count = map.get(&ip).copied().unwrap_or(0); + if *total >= MAX_STREAMS || count >= MAX_STREAMS_PER_CLIENT { return None; } - *count += 1; + *map.entry(ip).or_insert(0) += 1; *total += 1; Some(StreamSlot { ip: Some(ip) }) } @@ -513,7 +510,7 @@ impl Drop for StreamSlot { /// How long the browser waits before it reconnects a dropped event stream. The browser's default is /// a few seconds; one second makes a page come back as soon as a server restart is done. -pub const STREAM_RETRY: Duration = Duration::from_secs(1); +const STREAM_RETRY: Duration = Duration::from_secs(1); /// The response of an event stream: keep-alive comments while idle, no buffering by a reverse /// proxy, and a `retry` field first so every stream reconnects after `STREAM_RETRY`. diff --git a/crates/forge-web-app/src/mail/smtp.rs b/crates/forge-web-app/src/mail/smtp.rs index 49cb999..268963b 100644 --- a/crates/forge-web-app/src/mail/smtp.rs +++ b/crates/forge-web-app/src/mail/smtp.rs @@ -31,8 +31,11 @@ impl SmtpMailer { .mail_settings() .await .map_err(|e| MailError::Transient(format!("cannot read the mail settings: {e}")))?; - let password = self.store.mail_password().await.map_err(|e| { - MailError::Permanent(format!("cannot open the stored SMTP password: {e}")) + let password = self.store.mail_password().await.map_err(|e| match e { + forge_core::Error::Database(_) => { + MailError::Transient(format!("cannot read the stored SMTP password: {e}")) + } + _ => MailError::Permanent(format!("cannot open the stored SMTP password: {e}")), })?; let message = build_message(&settings, mail)?; let transport = build_transport(&settings, password.as_ref().map(|p| p.expose()))?; diff --git a/crates/forge-web-app/src/mail/worker.rs b/crates/forge-web-app/src/mail/worker.rs index 0a216c8..d128632 100644 --- a/crates/forge-web-app/src/mail/worker.rs +++ b/crates/forge-web-app/src/mail/worker.rs @@ -7,17 +7,14 @@ use std::time::Duration; use forge_core::mail::{MailError, OutboxEntry, OutgoingMail, retry_delay}; -use forge_core::time::{now_stamp, stamp_after}; +use forge_core::time::{now_stamp, sleep_until, stamp_after}; use time::OffsetDateTime; -use time::format_description::well_known::Rfc3339; use crate::mail::live; use crate::state::AppState; /// The longest the worker sleeps. It guards against a missed wake, not polling. const BACKSTOP: Duration = Duration::from_secs(15 * 60); -/// The shortest sleep, so a due time that has already passed does not spin the loop. -const MIN_SLEEP: Duration = Duration::from_secs(1); /// Messages leased per pass. const BATCH: u32 = 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 { deliver(state, &entry).await; } let next = state.store.next_mail_due().await?; - Ok(sleep_for(next.as_deref(), OffsetDateTime::now_utc())) + Ok(sleep_until(next.as_deref(), OffsetDateTime::now_utc(), BACKSTOP)) } /// Sends one leased message and records the outcome. @@ -117,16 +114,6 @@ async fn deliver(state: &AppState, entry: &OutboxEntry) { live::bump(); } -/// How long the worker sleeps: until `next_due` (an RFC 3339 stamp), clamped to -/// `MIN_SLEEP..=BACKSTOP`. `None` (nothing queued) or an unparsable stamp gives `BACKSTOP`. -pub fn sleep_for(next_due: Option<&str>, now: OffsetDateTime) -> Duration { - let Some(due) = next_due.and_then(|s| OffsetDateTime::parse(s, &Rfc3339).ok()) else { - return BACKSTOP; - }; - let until = Duration::try_from(due - now).unwrap_or(Duration::ZERO); - until.clamp(MIN_SLEEP, BACKSTOP) -} - #[cfg(test)] mod tests { use std::sync::Arc; @@ -159,22 +146,6 @@ mod tests { (state, fake) } - #[test] - fn sleep_stops_at_the_next_due_time_and_is_clamped() { - use time::macros::datetime; - - let now = datetime!(2026-10-15 12:00:00 UTC); - let stamp = |t: OffsetDateTime| t.format(&Rfc3339).expect("stamp"); - assert_eq!(sleep_for(None, now), BACKSTOP); - let in_10s = stamp(now + time::Duration::seconds(10)); - assert_eq!(sleep_for(Some(&in_10s), now), Duration::from_secs(10)); - let in_1h = stamp(now + time::Duration::hours(1)); - assert_eq!(sleep_for(Some(&in_1h), now), BACKSTOP); - let past = stamp(now - time::Duration::seconds(5)); - assert_eq!(sleep_for(Some(&past), now), MIN_SLEEP); - assert_eq!(sleep_for(Some("soon"), now), BACKSTOP); - } - #[tokio::test] async fn a_row_leased_before_a_restart_is_sent_by_the_first_pass_after_boot() { let dir = tempfile::tempdir().expect("tempdir"); diff --git a/crates/forge-web-app/src/merge.rs b/crates/forge-web-app/src/merge.rs index 1371a63..aeb630e 100644 --- a/crates/forge-web-app/src/merge.rs +++ b/crates/forge-web-app/src/merge.rs @@ -1,6 +1,3 @@ -//! Merging a pull request: the merge gate, the merge itself and what follows it, shared by the -//! merge page, auto-merge and the merge queue. - use forge_core::protection::{RuleFlags, effective}; use forge_core::store::commit_status::StatusState; use forge_core::{MergeStyle, PullRequest, ReviewState, Role, User}; @@ -19,11 +16,8 @@ use crate::state::AppState; use crate::views::now_unix; use crate::webhooks::emit::{Sender, emit_item_action}; -/// Commits listed in a squash message. pub const MAX_SQUASH_COMMITS: usize = 250; -/// Refusal codes, sent as `?merge_error=` on the pull request page. The page owns the -/// wording for each code; a code outside this set is never echoed back. pub const ERR_CONFLICT: &str = "conflict"; pub const ERR_UP_TO_DATE: &str = "up_to_date"; pub const ERR_FF_IMPOSSIBLE: &str = "ff_impossible"; @@ -57,15 +51,12 @@ pub const HEAD_MISSING_MSG: &str = "The head repository was deleted, so this pull request cannot be merged."; pub const BASE_MISSING_MSG: &str = "The base branch does not exist."; -/// What a merge attempt did: the base branch now points at `commit`, or the attempt was refused -/// with an HTTP status and a message for the viewer. #[derive(Debug, PartialEq, Eq)] pub enum MergeOutcome { Merged { commit: String }, Refused { status: StatusCode, message: String }, } -/// The refusal code for a message `perform_merge` returns, if it has one. pub fn refusal_code(message: &str) -> Option<&'static str> { Some(match message { CONFLICTS_MSG => ERR_CONFLICT, @@ -81,6 +72,18 @@ pub fn refusal_code(message: &str) -> Option<&'static str> { }) } +pub struct MergeRefusal { + pub status: StatusCode, + pub message: String, +} + +fn refusal(message: &str) -> MergeRefusal { + MergeRefusal { + status: StatusCode::CONFLICT, + message: message.to_owned(), + } +} + pub fn refused(status: StatusCode, message: &str) -> MergeOutcome { MergeOutcome::Refused { status, @@ -88,31 +91,22 @@ pub fn refused(status: StatusCode, message: &str) -> MergeOutcome { } } -/// Whether `user` is a reviewer whose approvals and change requests count under merge rules: -/// the repo owner, an instance admin, or a collaborator with Write, Maintain or Admin. pub fn counts_for_merge_rules(repo: &forge_core::Repo, user: &User, role: Option) -> bool { user.is_admin || user.id == repo.owner_id || matches!(role, Some(Role::Write | Role::Maintain | Role::Admin)) } -/// The base branch's merge rule for a pull request, with the facts that rule checks. #[derive(Debug, Clone, PartialEq, Eq)] pub struct MergeGate { pub rule: RuleFlags, - /// Distinct counting reviewers whose latest submitted review is an approval. pub approvals: u32, - /// Some counting reviewer's latest submitted review requests changes. pub changes_requested: bool, - /// The head contains the current base tip. Always true when the rule does not require it. pub up_to_date: bool, - /// The pull request is a draft. pub draft: bool, - /// Each required check context with its state on the head commit (`None`: not reported). pub required: Vec, } -/// One required status check and where it stands on the pull request head. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RequiredCheck { pub context: String, @@ -120,7 +114,6 @@ pub struct RequiredCheck { } impl MergeGate { - /// Every refusal code that currently blocks the merge, in the order they are reported. pub fn blockers(&self) -> Vec<&'static str> { let mut out = Vec::new(); if self.draft { @@ -145,13 +138,10 @@ impl MergeGate { out } - /// The refusal code for the first rule that blocks the merge, if any. pub fn blocked(&self) -> Option<&'static str> { self.blockers().first().copied() } - /// Whether waiting could clear every blocker: only missing approvals or checks that are not - /// green yet. Auto-merge may be enabled only then (or when nothing blocks). pub fn waiting_only(&self) -> bool { self.blockers() .iter() @@ -159,11 +149,6 @@ impl MergeGate { } } -/// Evaluates the effective rule for the pull request's base branch. Approvals and change requests -/// count only from `counts_for_merge_rules` reviewers, using each reviewer's latest review; an -/// approval counts only while the head is the commit it was given on. -/// Repo admins are not exempt. A base branch that does not exist counts as up to date; the merge -/// itself reports that. pub async fn merge_gate( state: &AppState, repo: &forge_core::Repo, @@ -174,8 +159,6 @@ pub async fn merge_gate( let mut approvals = 0u32; let mut changes_requested = false; for (author_id, _, review, commit) in state.store.latest_review_states(&pr.issue.id).await? { - // An approval is of the commits the reviewer saw: a push after it leaves it uncounted - // until they approve again. A change request stands until it is dismissed or replaced. if review == ReviewState::Approved && commit != pr.head_oid { continue; } @@ -230,12 +213,6 @@ pub async fn merge_gate( }) } -/// Merges `pr` into its base branch in `repo` as `viewer`. -/// -/// The base tip is `expected_base` when given, otherwise the current tip of the base branch. The -/// merge is checked and built against that tip, and the ref moves only if it still points there. -/// `message` replaces the default commit message (not used by fast-forward). Refusals that the -/// viewer can act on come back as `MergeOutcome::Refused`; git and database failures are errors. pub async fn perform_merge( state: &AppState, repo: &forge_core::Repo, @@ -258,7 +235,12 @@ pub async fn perform_merge( }; let new = match merge_commit(state, repo, pr, viewer, style, message, &base_tip).await? { Ok(new) => new, - Err(refusal) => return Ok(refusal), + Err(refusal) => { + return Ok(MergeOutcome::Refused { + status: refusal.status, + message: refusal.message, + }); + } }; match update_ref_cas(&state.git, &base_path, &refname, &new, &base_tip).await { @@ -273,9 +255,6 @@ pub async fn perform_merge( Ok(MergeOutcome::Merged { commit: new }) } -/// The commit that merging `pr` into `base_tip` makes in `style`, committed as `committer`. No ref -/// moves. A refusal the caller can act on comes back as the inner `Err`. Fast-forward returns the -/// head itself. pub async fn merge_commit( state: &AppState, repo: &forge_core::Repo, @@ -284,7 +263,7 @@ pub async fn merge_commit( style: MergeStyle, message: Option<&str>, base_tip: &str, -) -> forge_core::Result> { +) -> forge_core::Result> { let base_path = repo_path(&state.git.data_dir, &repo.id)?; let base_tip = base_tip.to_owned(); let viewer = committer; @@ -292,9 +271,9 @@ pub async fn merge_commit( let tree = match check_merge(&state.git, &base_path, &base_tip, head).await? { MergeCheck::Clean { tree } => tree, MergeCheck::Conflict { .. } => { - return Ok(Err(refused(StatusCode::CONFLICT, CONFLICTS_MSG))); + return Ok(Err(refusal(CONFLICTS_MSG))); } - MergeCheck::UpToDate => return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG))), + MergeCheck::UpToDate => return Ok(Err(refusal(UP_TO_DATE_MSG))), }; let now = now_unix(); @@ -306,7 +285,7 @@ pub async fn merge_commit( let new = match style { MergeStyle::FastForward => { if !is_ancestor(&state.git, &base_path, &base_tip, head).await? { - return Ok(Err(refused(StatusCode::CONFLICT, FF_MSG))); + return Ok(Err(refusal(FF_MSG))); } head.to_owned() } @@ -314,10 +293,10 @@ pub async fn merge_commit( match rebase_commits(&state.git, &base_path, &base_tip, head, &committer).await? { RebaseResult::Clean { tip, count } if count > 0 => tip, RebaseResult::Clean { .. } => { - return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG))); + return Ok(Err(refusal(UP_TO_DATE_MSG))); } RebaseResult::Conflict { .. } => { - return Ok(Err(refused(StatusCode::CONFLICT, REBASE_CONFLICT_MSG))); + return Ok(Err(refusal(REBASE_CONFLICT_MSG))); } } } @@ -370,9 +349,6 @@ pub async fn merge_commit( Ok(Ok(new)) } -/// The work after a merge moved `refname` from `base_tip` to `new`: the pull request is marked -/// merged, its events and notifications go out, and the ref update runs its post-update work. -/// Failures here are logged, not reported: the merge is already in place. pub async fn finish_merge( state: &AppState, repo: &forge_core::Repo, @@ -393,7 +369,6 @@ pub async fn finish_merge( } } trigger_maintenance(&state.git, &repo.id); - // Boxed: the queue lands through this path, and the post-update work can reach the queue again. if let Err(e) = Box::pin(after_ref_update( state, repo, &viewer.id, refname, base_tip, new, )) @@ -403,8 +378,6 @@ pub async fn finish_merge( } } -/// The address written into a commit for `user`: their email, or a noreply address on this -/// instance's host when they have none. pub fn contact_email(base_url: &str, user: &User) -> String { match user .email @@ -429,7 +402,6 @@ pub fn base_url_host(base_url: &str) -> String { .unwrap_or_else(|| "localhost".to_owned()) } -/// `Merge pull request #N from owner/branch`, a blank line, then the pull request title. pub async fn default_merge_message( state: &AppState, pr: &PullRequest, @@ -452,7 +424,6 @@ pub async fn default_merge_message( )) } -/// ` (#N)`, a blank line, then one `- <summary>` line per commit, oldest first. pub fn squash_message(pr: &PullRequest, commits: &[CommitInfo]) -> String { let mut text = format!("{} (#{})\n\n", pr.issue.title, pr.issue.number); for commit in commits { diff --git a/crates/forge-web-app/src/merge_queue.rs b/crates/forge-web-app/src/merge_queue.rs index 520b8d9..bad22e4 100644 --- a/crates/forge-web-app/src/merge_queue.rs +++ b/crates/forge-web-app/src/merge_queue.rs @@ -23,7 +23,7 @@ use forge_git::repo::repo_path; use crate::ci::schedule::merge_queue_run; use crate::merge::{ ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE, - ERR_QUEUE_ALREADY, MergeOutcome, finish_merge, merge_commit, merge_gate, + ERR_QUEUE_ALREADY, finish_merge, merge_commit, merge_gate, }; use crate::notify::{self, Activity}; use crate::state::AppState; @@ -86,17 +86,25 @@ pub async fn enqueue( /// Takes a waiting entry out of the queue, with `reason`. The caller starts the queue again with /// `advance`. A candidate that is already testing keeps its CI run; its result is then ignored. pub async fn remove(state: &AppState, repo: &Repo, entry: &QueueEntry, reason: &str) { - match state + if let Err(e) = remove_entry(state, repo, entry, reason).await { + tracing::error!(error = %e, repo_id = %repo.id, "merge queue: removing an entry failed"); + } +} + +async fn remove_entry( + state: &AppState, + repo: &Repo, + entry: &QueueEntry, + reason: &str, +) -> forge_core::Result<()> { + if state .store .queue_finish(&entry.id, QueueState::Removed, reason) - .await + .await? { - Ok(true) => notify_entry(state, repo, entry), - Ok(false) => {} - Err(e) => { - tracing::error!(error = %e, repo_id = %repo.id, "merge queue: removing an entry failed"); - } + notify_entry(state, repo, entry); } + Ok(()) } /// 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( let tested = match merge_commit(state, repo, pr, &user, entry.merge_style, None, &base_tip).await? { Ok(oid) => oid, - Err(MergeOutcome::Refused { message, .. }) => { - let text = format!("could not build the merge with the target branch: {message}."); + Err(refusal) => { + let text = format!( + "could not build the merge with the target branch: {}.", + refusal.message + ); fail(state, repo, entry, pr, "conflict", &text).await?; return Ok(false); } - Err(MergeOutcome::Merged { .. }) => return Ok(false), }; let test_ref = test_ref_name(&entry.branch, entry.pull_number); set_ref(&state.git, &base_path, &test_ref, &tested).await?; @@ -335,7 +345,7 @@ async fn land( let tested = entry.tested_oid.clone().unwrap_or_default(); let base = entry.base_oid.clone().unwrap_or_default(); let Some(user) = state.store.user_by_id(&entry.enqueued_by).await? else { - finish_removed(state, repo, entry, "removed").await?; + remove_entry(state, repo, entry, "removed").await?; return Ok(true); }; let collaborator = state.store.collaborator_role(&repo.id, &user.id).await?; @@ -344,13 +354,13 @@ async fn land( .org_repo_role(&repo.owner_id, &user.id, &repo.id) .await?; if authorize(Some(&user), repo, collaborator, org, Action::Write).is_err() { - finish_removed(state, repo, entry, "permission").await?; + remove_entry(state, repo, entry, "permission").await?; return Ok(true); } // Reviews may have changed while the candidate was tested (a change request, a dismissed // approval): the same readiness test as before testing, now right before the target moves. if let Some(reason) = unready(state, repo, pr).await? { - finish_removed(state, repo, entry, reason).await?; + remove_entry(state, repo, entry, reason).await?; return Ok(true); } let refname = format!("refs/heads/{}", entry.branch); @@ -370,25 +380,10 @@ async fn land( } } finish_merge(state, repo, pr, &user, &refname, &base, &tested).await; - finish_removed(state, repo, entry, "merged").await?; + remove_entry(state, repo, entry, "merged").await?; Ok(true) } -/// Ends a merging entry as removed with `reason`. -async fn finish_removed( - state: &AppState, - repo: &Repo, - entry: &QueueEntry, - reason: &str, -) -> forge_core::Result<()> { - state - .store - .queue_finish(&entry.id, QueueState::Removed, reason) - .await?; - notify_entry(state, repo, entry); - Ok(()) -} - /// Ends an entry as failed and comments on its pull request, mentioning the person who queued it. async fn fail( state: &AppState, diff --git a/crates/forge-web-app/src/mirrors/worker.rs b/crates/forge-web-app/src/mirrors/worker.rs index 1d90c9d..eb97e62 100644 --- a/crates/forge-web-app/src/mirrors/worker.rs +++ b/crates/forge-web-app/src/mirrors/worker.rs @@ -5,9 +5,8 @@ use std::collections::HashSet; use std::time::Duration; -use forge_core::time::now_stamp; +use forge_core::time::{now_stamp, sleep_until}; use time::OffsetDateTime; -use time::format_description::well_known::Rfc3339; use tokio::sync::mpsc; use super::{policy, run_one}; @@ -16,8 +15,6 @@ use crate::webhooks::client::WebhookPolicy; /// The longest the worker sleeps. It guards against a missed wake, not polling. const BACKSTOP: Duration = Duration::from_secs(15 * 60); -/// The shortest sleep, so a due time that has already passed does not spin the loop. -const MIN_SLEEP: Duration = Duration::from_secs(1); /// Runs in flight at once. const MAX_RUNNING: usize = 2; /// Due mirrors read per pass. @@ -45,7 +42,7 @@ async fn run(state: AppState) { // Wake when the earliest enabled mirror is due, so a push mirror queued with a short // debounce runs on time instead of waiting for the next poll. let nap = match state.store.next_mirror_due().await { - Ok(next) => sleep_for(next.as_deref(), OffsetDateTime::now_utc()), + Ok(next) => sleep_until(next.as_deref(), OffsetDateTime::now_utc(), BACKSTOP), Err(e) => { tracing::error!(error = %e, "mirrors: could not read the next due time"); BACKSTOP @@ -62,17 +59,6 @@ async fn run(state: AppState) { } } -/// How long the worker sleeps before its next pass: until `next_due` (an RFC 3339 stamp, the -/// earliest enabled mirror), clamped to `MIN_SLEEP..=BACKSTOP`. `None` (nothing enabled) or an -/// unparsable stamp gives `BACKSTOP`. -pub fn sleep_for(next_due: Option<&str>, now: OffsetDateTime) -> Duration { - let Some(due) = next_due.and_then(|s| OffsetDateTime::parse(s, &Rfc3339).ok()) else { - return BACKSTOP; - }; - let until = Duration::try_from(due - now).unwrap_or(Duration::ZERO); - until.clamp(MIN_SLEEP, BACKSTOP) -} - /// Starts runs for due mirrors until the concurrency limit, skipping mirrors and repos already /// in flight. async fn claim( @@ -119,34 +105,6 @@ mod tests { use super::super::pull_refs; use crate::test_support::test_state; - #[test] - fn sleep_stops_at_the_next_due_time_and_is_clamped() { - use std::time::Duration; - - use time::OffsetDateTime; - use time::format_description::well_known::Rfc3339; - use time::macros::datetime; - - let now = datetime!(2026-10-15 12:00:00 UTC); - let stamp = |t: OffsetDateTime| t.format(&Rfc3339).expect("stamp"); - // Nothing enabled: the backstop. - assert_eq!(super::sleep_for(None, now), super::BACKSTOP); - // A push queued with a 10 s debounce: sleep until it is due. - let in_10s = stamp(now + time::Duration::seconds(10)); - assert_eq!( - super::sleep_for(Some(&in_10s), now), - Duration::from_secs(10) - ); - // Due later than the backstop: wake at the backstop. - let in_1h = stamp(now + time::Duration::hours(1)); - assert_eq!(super::sleep_for(Some(&in_1h), now), super::BACKSTOP); - // Already due (or in flight and still due): do not spin, wait the minimum. - let past = stamp(now - time::Duration::seconds(5)); - assert_eq!(super::sleep_for(Some(&past), now), super::MIN_SLEEP); - // A stamp that does not parse falls back to the backstop. - assert_eq!(super::sleep_for(Some("soon"), now), super::BACKSTOP); - } - /// Plain git against a bare repo, for setting up the fake upstream. fn plumbing(git_dir: &Path, args: &[&str]) -> String { let out = std::process::Command::new("git") diff --git a/crates/forge-web-app/src/notify.rs b/crates/forge-web-app/src/notify.rs index beab2f5..0ae6e72 100644 --- a/crates/forge-web-app/src/notify.rs +++ b/crates/forge-web-app/src/notify.rs @@ -238,12 +238,10 @@ async fn fan_out( /// Keeps the stronger of the reasons already recorded for a user and `reason`. fn add(candidates: &mut BTreeMap<String, Reason>, user_id: String, reason: Reason) { - match candidates.get(&user_id) { - Some(prev) if prev.rank() >= reason.rank() => {} - _ => { - candidates.insert(user_id, reason); - } - } + candidates + .entry(user_id) + .and_modify(|r| *r = strongest(*r, reason)) + .or_insert(reason); } fn strongest(a: Reason, b: Reason) -> Reason { diff --git a/crates/forge-web-app/src/oci/auth.rs b/crates/forge-web-app/src/oci/auth.rs index 5fc7ffc..08d84ad 100644 --- a/crates/forge-web-app/src/oci/auth.rs +++ b/crates/forge-web-app/src/oci/auth.rs @@ -8,13 +8,14 @@ use forge_core::User; use forge_core::oci as rules; use forge_core::packages::{KIND_OCI, Package}; +use forge_core::time::unix_now; use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE}; use topcoat::context::{Cx, context}; use topcoat::router::StatusCode; use topcoat::router::request::headers; use topcoat::router::response::Response; -use super::oci_error; +use super::{name_unknown, oci_error}; use crate::api::{self, Refusal}; use crate::client_ip::client_ip; use crate::package_ops::{self, PackageError}; @@ -50,7 +51,7 @@ pub async fn caller(cx: &Cx) -> Result<Caller, Refusal> { if let Some(bearer) = value.strip_prefix("Bearer ").map(str::trim) && !bearer.starts_with("forge_") { - let now = unix_now(); + let now = unix_now() as i64; return match rules::verify_token(&state.key, bearer, now) { Some(Some(user_id)) => match state.store.user_by_id(&user_id).await { Ok(Some(user)) if !user.is_org() => Ok(Caller { user: Some(user) }), @@ -155,14 +156,6 @@ pub async fn authorize( } } -fn name_unknown() -> Response { - oci_error( - StatusCode::NOT_FOUND, - "NAME_UNKNOWN", - "repository name not known to registry", - ) -} - /// The 401 that asks for credentials. It names the token endpoint, and the repository's scope when /// the request names one. pub fn challenge(state: &AppState, name: Option<&str>) -> Response { @@ -214,10 +207,3 @@ pub fn package_failure(error: PackageError) -> Refusal { pub fn internal_refusal(error: impl std::fmt::Display) -> Refusal { Box::new(internal(error)) } - -/// The current time in seconds since the epoch. -pub fn unix_now() -> i64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) -} diff --git a/crates/forge-web-app/src/oci/blobs.rs b/crates/forge-web-app/src/oci/blobs.rs index c5e9511..6cbf78b 100644 --- a/crates/forge-web-app/src/oci/blobs.rs +++ b/crates/forge-web-app/src/oci/blobs.rs @@ -13,11 +13,11 @@ use std::time::{Duration, SystemTime}; use forge_core::oci as rules; use forge_core::packages::{KIND_OCI, Package}; +use forge_core::token::sha256_reader; use futures_util::StreamExt; use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; use http_body::Frame; use http_body_util::StreamBody; -use sha2::{Digest, Sha256}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use topcoat::router::response::Response; use topcoat::router::{Body, StatusCode}; @@ -46,7 +46,7 @@ pub fn blob_key(hex: &str) -> String { /// A session id as this module makes them: 26 ASCII letters or digits. Anything else is not a /// session, so no id can name a path outside the uploads directory. -pub fn valid_session_id(id: &str) -> bool { +fn valid_session_id(id: &str) -> bool { id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) } @@ -172,17 +172,12 @@ pub async fn append( /// The sha256 of a file, hex. pub async fn file_sha256(path: &Path) -> std::io::Result<String> { - let mut file = tokio::fs::File::open(path).await?; - let mut hasher = Sha256::new(); - let mut buf = vec![0u8; CHUNK]; - loop { - let read = file.read(&mut buf).await?; - if read == 0 { - break; - } - hasher.update(&buf[..read]); - } - Ok(hex::encode(hasher.finalize())) + let path = path.to_owned(); + tokio::task::spawn_blocking(move || { + sha256_reader(std::fs::File::open(path)?).map(|(_, hex)| hex) + }) + .await + .map_err(std::io::Error::other)? } /// 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 let Some(package) = target.package.as_ref() else { return unknown_blob(); }; + let _gc = gc::lock().await; match state.store.oci_blob_size(&package.id, digest).await { Ok(Some(_)) => {} Ok(None) => return unknown_blob(), @@ -371,7 +367,6 @@ pub async fn delete_blob(state: &AppState, target: &Target, digest: &str) -> Res Ok(false) => {} Err(e) => return internal(e), } - let _gc = gc::lock().await; if let Err(e) = state.store.oci_unlink_blob(&package.id, digest).await { return internal(e); } diff --git a/crates/forge-web-app/src/oci/manifests.rs b/crates/forge-web-app/src/oci/manifests.rs index c018714..fe39213 100644 --- a/crates/forge-web-app/src/oci/manifests.rs +++ b/crates/forge-web-app/src/oci/manifests.rs @@ -12,22 +12,22 @@ use topcoat::router::{Body, StatusCode, to_bytes}; use super::auth::{self, Caller, internal}; use super::blobs::{insert, write_package}; -use super::{gc, oci_error}; +use super::{gc, name_unknown, oci_error}; use crate::package_ops::bump_linked_repo; use crate::state::AppState; /// Largest manifest accepted, in bytes. -pub const MAX_MANIFEST_BYTES: usize = 4 * 1024 * 1024; +const MAX_MANIFEST_BYTES: usize = 4 * 1024 * 1024; /// What a manifest reference names: a digest, or a tag. -pub enum Reference<'a> { +enum Reference<'a> { Digest(&'a str), Tag(&'a str), } /// Reads a reference from a path segment. A reference with a colon is a digest, anything else a /// tag. The error is the response to send. -pub fn parse_reference(reference: &str) -> Result<Reference<'_>, Box<Response>> { +fn parse_reference(reference: &str) -> Result<Reference<'_>, Box<Response>> { if reference.contains(':') { if rules::parse_digest(reference).is_some() { Ok(Reference::Digest(reference)) @@ -61,14 +61,6 @@ fn manifest_unknown() -> Response { ) } -fn name_unknown() -> Response { - oci_error( - StatusCode::NOT_FOUND, - "NAME_UNKNOWN", - "repository name not known to registry", - ) -} - /// `PUT /v2/{name}/manifests/{reference}`. The referenced blobs must already be in the package, so /// a manifest never names bytes the registry lacks. The digest of the bytes is the manifest's id. pub async fn put_manifest( diff --git a/crates/forge-web-app/src/oci/mod.rs b/crates/forge-web-app/src/oci/mod.rs index 36a6d93..9f8b8c5 100644 --- a/crates/forge-web-app/src/oci/mod.rs +++ b/crates/forge-web-app/src/oci/mod.rs @@ -25,7 +25,8 @@ use topcoat::router::response::Response; use topcoat::router::{Body, StatusCode, path_param, route}; use crate::state::AppState; -use auth::{Caller, unix_now}; +use auth::Caller; +use forge_core::time::now_unix; path_param!(*rest); @@ -38,6 +39,14 @@ pub fn oci_error(status: StatusCode, code: &str, message: &str) -> Response { json_response(status, &body) } +fn name_unknown() -> Response { + oci_error( + StatusCode::NOT_FOUND, + "NAME_UNKNOWN", + "repository name not known to registry", + ) +} + fn json_response(status: StatusCode, value: &Value) -> Response { let mut res = Response::new(Body::from(value.to_string())); *res.status_mut() = status; @@ -123,7 +132,7 @@ async fn token(cx: &Cx) -> topcoat::Result<Response> { Err(res) => return Ok(*res), }; let subject = caller.user.as_ref().map(|user| user.id.as_str()); - let now = unix_now(); + let now = now_unix(); let token = forge_core::oci::issue_token(&state.key, subject, now + auth::TOKEN_TTL_SECS); // Clients parse `issued_at` as an RFC 3339 time, so a number is refused. let issued_at = time::OffsetDateTime::now_utc() diff --git a/crates/forge-web-app/src/package_ops.rs b/crates/forge-web-app/src/package_ops.rs index 874916c..5dc3e88 100644 --- a/crates/forge-web-app/src/package_ops.rs +++ b/crates/forge-web-app/src/package_ops.rs @@ -20,8 +20,6 @@ use crate::state::AppState; pub const MAX_CRATE_BYTES: u64 = 10 * 1024 * 1024; /// Largest publish body accepted: the crate plus its JSON metadata. pub const MAX_PUBLISH_BYTES: usize = 16 * 1024 * 1024; -/// Bytes handed to the blob writer at a time. -const PUSH_CHUNK: usize = 1024 * 1024; /// Why a registry request failed. The API maps each to a status and a cargo error body. #[derive(Debug)] @@ -320,7 +318,7 @@ pub async fn download( } /// The blob key of a version's `.crate` file. -pub fn blob_key(version_id: &str) -> String { +fn blob_key(version_id: &str) -> String { format!("packages/{version_id}") } @@ -349,15 +347,13 @@ async fn link_repo( Ok(()) } -/// Streams `bytes` into the blob store under `key`, returning the sha256 the store computed. -async fn store_bytes(state: &AppState, key: &str, bytes: &[u8]) -> forge_core::Result<String> { +/// Streams `bytes` into the blob store under `key`. +async fn store_bytes(state: &AppState, key: &str, bytes: &[u8]) -> forge_core::Result<()> { let mut writer = state.blobs.begin(key, MAX_CRATE_BYTES).await?; - for chunk in bytes.chunks(PUSH_CHUNK) { - if let Err(e) = writer.push(chunk).await { - writer.abort().await; - return Err(e); - } + if let Err(e) = writer.push(bytes).await { + writer.abort().await; + return Err(e); } - let (_, sha) = writer.finish().await?; - Ok(sha) + writer.finish().await?; + Ok(()) } diff --git a/crates/forge-web-app/src/post_update.rs b/crates/forge-web-app/src/post_update.rs index 000d65c..4161852 100644 --- a/crates/forge-web-app/src/post_update.rs +++ b/crates/forge-web-app/src/post_update.rs @@ -12,11 +12,12 @@ //! `internal::trigger_maintenance`. Callers that update a ref outside receive-pack (the merge //! route) call it themselves. -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use forge_core::issue_refs::{find_closing_refs, find_issue_refs}; use forge_core::time::now_stamp; use forge_core::{IssueState, Repo, StateReason}; +use forge_git::browse::CommitInfo; use forge_git::{history, trailers}; use serde_json::json; @@ -46,23 +47,19 @@ pub async fn after_ref_update( ) -> forge_core::Result<()> { let sender = lookup_sender(state, actor_id).await; emit_ref_update(state, repo, &sender, refname, old, new).await; - // Code views that follow a branch or the ref list re-read it. state .live .bump(&crate::live::Topic::RepoRefs(repo.id.clone())); - // The pusher's contribution calendar on their profile counts the push. if !actor_id.is_empty() { state .live .bump(&crate::live::Topic::User(actor_id.to_owned())); } - // The owner's repo listing sorts by last update, so a push by someone else moves it too. if repo.owner_id != actor_id { state .live .bump(&crate::live::Topic::User(repo.owner_id.clone())); } - // The explore list shows each public repo's last activity, so a push moves it there. if repo.visibility == forge_core::Visibility::Public { state.live.bump(&crate::live::Topic::Explore); } @@ -72,31 +69,26 @@ pub async fn after_ref_update( { tracing::error!(error = %e, repo_id = %repo.id, "mirrors: could not queue push mirrors"); } - if refname == format!("refs/heads/{}", repo.default_branch) && !is_zero_oid(new) { + let branch = refname.starts_with("refs/heads/") && !is_zero_oid(new); + let default = branch && refname == format!("refs/heads/{}", repo.default_branch); + if default { crate::advisories::scan::spawn_repo_scan(state, repo); } crate::replication::enqueue_repo(state, &repo.id); - if refname == format!("refs/heads/{}", repo.default_branch) && !is_zero_oid(new) { - match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) { - Ok(repo_dir) => { - tokio::spawn(close_from_pushed_commits( - state.clone(), - repo.clone(), - sender, - repo_dir, - actor_id.to_owned(), - old.to_owned(), - new.to_owned(), - )); - } - Err(e) => { - tracing::error!(error = %e, repo_id = %repo.id, "issue refs: bad repo path"); - } - } - } - if refname.starts_with("refs/heads/") && !is_zero_oid(new) { + if branch { match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) { Ok(repo_dir) => { + if default { + tokio::spawn(close_from_pushed_commits( + state.clone(), + repo.clone(), + sender, + repo_dir.clone(), + actor_id.to_owned(), + old.to_owned(), + new.to_owned(), + )); + } tokio::spawn(credit_coauthors( state.clone(), repo.clone(), @@ -107,16 +99,40 @@ pub async fn after_ref_update( )); } Err(e) => { - tracing::error!(error = %e, repo_id = %repo.id, "co-authors: bad repo path"); + tracing::error!(error = %e, repo_id = %repo.id, "pushed commits: bad repo path"); } } } let synced = pulls_sync::sync_pulls_for_ref(state, repo, actor_id, refname, old, new).await; - // A push can move, merge or open any pull of the repo, so every pull page is woken. crate::live::bump_repo_pulls(state, &repo.id).await; synced } +/// Lists the commits a ref update added, newest first. A new branch (`old` is zero) reads at most +/// `MAX_NEW_BRANCH_COMMITS`; an update reads `max_update`. Errors are logged and yield `None`. +async fn pushed_commits( + state: &AppState, + repo: &Repo, + repo_dir: &Path, + old: &str, + new: &str, + max_update: usize, +) -> Option<Vec<CommitInfo>> { + let old = (!is_zero_oid(old)).then_some(old); + let max = if old.is_some() { + max_update + } else { + MAX_NEW_BRANCH_COMMITS + }; + match history::new_commits(&state.git, repo_dir, old, new, max).await { + Ok(commits) => Some(commits), + Err(e) => { + tracing::error!(error = %e, repo_id = %repo.id, "pushed commits: listing failed"); + None + } + } +} + /// Processes the commits added to the default branch by one ref update, oldest first. async fn close_from_pushed_commits( state: AppState, @@ -127,18 +143,10 @@ async fn close_from_pushed_commits( old: String, new: String, ) { - let old = (!is_zero_oid(&old)).then_some(old.as_str()); - let max = if old.is_some() { - MAX_PUSH_COMMITS - } else { - MAX_NEW_BRANCH_COMMITS - }; - let commits = match history::new_commits(&state.git, &repo_dir, old, &new, max).await { - Ok(commits) => commits, - Err(e) => { - tracing::error!(error = %e, repo_id = %repo.id, "issue refs: listing commits failed"); - return; - } + let Some(commits) = + pushed_commits(&state, &repo, &repo_dir, &old, &new, MAX_PUSH_COMMITS).await + else { + return; }; let actor = (!actor_id.is_empty()).then_some(actor_id.as_str()); for commit in &commits { @@ -160,18 +168,10 @@ async fn credit_coauthors( old: String, new: String, ) { - let old = (!is_zero_oid(&old)).then_some(old.as_str()); - let max = if old.is_some() { - MAX_COAUTHOR_COMMITS - } else { - MAX_NEW_BRANCH_COMMITS - }; - let commits = match history::new_commits(&state.git, &repo_dir, old, &new, max).await { - Ok(commits) => commits, - Err(e) => { - tracing::error!(error = %e, repo_id = %repo.id, "co-authors: listing commits failed"); - return; - } + let Some(commits) = + pushed_commits(&state, &repo, &repo_dir, &old, &new, MAX_COAUTHOR_COMMITS).await + else { + return; }; let actor = (!actor_id.is_empty()).then_some(actor_id.as_str()); let at = now_stamp(); @@ -233,7 +233,6 @@ async fn apply_commit_refs( .await?; if closed { state.live.bump_issue(&repo.id, &issue.id); - // A pull is an issue row too, so a keyword can close one. crate::live::bump_pull(state, &repo.id, &issue.id); emit_item_action(state, repo, sender, false, number, "closed").await; notify::dispatch( @@ -412,7 +411,6 @@ mod tests { assert_eq!(body["commits"][0]["id"], c1.as_str()); assert_eq!(body["commits"][0]["message"], "one"); - // Creating the branch also sends a create event for it. let creates = fx.deliveries(WebhookEvent::Create).await; assert_eq!(creates.len(), 1); assert_eq!(creates[0].1["ref"], "main"); @@ -428,8 +426,6 @@ mod tests { assert_eq!(body["total_commits"], 1); assert_eq!(body["commits"][0]["id"], c2.as_str()); - // A topic branch: create, then delete. Git will not delete the bare repo's - // current branch, so the delete uses a branch that is not HEAD. fx.update_ref("refs/heads/topic", ZERO, &c2).await; fx.update_ref("refs/heads/topic", &c2, ZERO).await; let deletes = fx.deliveries(WebhookEvent::Delete).await; diff --git a/crates/forge-web-app/src/raw/media.rs b/crates/forge-web-app/src/raw/media.rs index 68add2d..b60023e 100644 --- a/crates/forge-web-app/src/raw/media.rs +++ b/crates/forge-web-app/src/raw/media.rs @@ -1,14 +1,7 @@ -//! Raw-origin route `/{owner}/{repo}/-/media/{ref}/{path...}`. The literal `-` keeps it apart -//! from raw paths, since no ref name may start with `-`. It reads the Git LFS pointer at -//! `ref:path` and streams the object it names, when the repo links that object. Access follows -//! the raw route in `raw.rs`: public repos are open, and private repos need a signed `?token=`. - -use forge_core::raw_token::verify_raw; use forge_core::{Repo, Visibility}; use futures_util::TryStreamExt; use http_body::Frame; use http_body_util::StreamBody; -use serde::Deserialize; use tokio_util::io::ReaderStream; use topcoat::context::{Cx, context}; use topcoat::router::request::method; @@ -21,42 +14,31 @@ use topcoat::router::{ use crate::lfs::{has_object, object_path}; use crate::lfs_pointer; use crate::raw::{ - CACHE_NONE, CACHE_PRIVATE, CACHE_PUBLIC, LINK_TTL_SECS, Lookup, Meta, OCTET, encode_path, - finish, lookup, now_unix, plain, + CACHE_NONE, Lookup, Meta, OCTET, TokenQuery, encode_path, finish, lookup, plain, + resolve_repo, signed_url, }; use crate::state::AppState; -#[derive(Deserialize)] -struct TokenQuery { - token: Option<String>, -} - -/// Absolute URL of the media route for `path` at `rev` on the user-content origin. Private repos -/// get a signed `?token=`, the same as raw URLs. The route is `/{owner}/{repo}/-/media/...`. pub fn media_url(state: &AppState, repo: &Repo, rev: &str, path: &str) -> String { - let base = state.config.user_content_base_url.trim_end_matches('/'); - let mut url = format!( - "{base}/{}/{}/-/media/{}/{}", + let encoded = format!( + "{}/{}/-/media/{}/{}", encode_path(&repo.owner_name), encode_path(&repo.name), encode_path(rev), encode_path(path) ); - if matches!(repo.visibility, Visibility::Private) { - let expires = now_unix().saturating_add(LINK_TTL_SECS); - url.push_str("?token="); - url.push_str(&forge_core::raw_token::sign_raw( - &state.key, &repo.id, expires, - )); - } - url + signed_url( + state, + &encoded, + &repo.id, + matches!(repo.visibility, Visibility::Private), + ) } pub fn media_file(cx: &Cx, _body: Body) -> RouteFuture<'_> { Box::pin(async move { Ok(serve(cx).await) }) } -/// Serves one LFS object. Every failure is turned into a response here, so the route never errors. async fn serve(cx: &Cx) -> Response { let state = context::<AppState>(cx).clone(); let owner = path_param_segment(cx, "owner").to_owned(); @@ -69,38 +51,13 @@ async fn serve(cx: &Cx) -> Response { .ok() .and_then(|query| query.token); - let repo = match state.store.repo_by_owner_and_name(&owner, &name).await { - Ok(Some(repo)) => repo, - // A missing repo and a private repo without a valid token look the same. - Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None), - Err(e) => { - tracing::error!(error = %e, "media: repo lookup failed"); - return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); - } - }; - let cache = match repo.visibility { - Visibility::Public => CACHE_PUBLIC, - Visibility::Private => { - let valid = token - .as_deref() - .is_some_and(|t| verify_raw(&state.key, t, &repo.id, now_unix())); - if !valid { - return plain(StatusCode::NOT_FOUND, CACHE_NONE, None); - } - CACHE_PRIVATE - } - }; + let (repo, repo_dir, cache) = + match resolve_repo(&state, &owner, &name, token.as_deref()).await { + Ok(found) => found, + Err(response) => return response, + }; - let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) { - Ok(path) => path, - Err(e) => { - tracing::error!(error = %e, "media: repo path failed"); - return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); - } - }; let looked = tokio::task::spawn_blocking(move || lookup(&repo_dir, &rest, None)).await; - // Pointers are a few hundred bytes, so they always come back inline. Anything else is not - // a pointer, and a symlink is never one. let data = match looked { Ok(Ok(Lookup::Inline { symlink: false, @@ -121,7 +78,6 @@ async fn serve(cx: &Cx) -> Response { let Some(pointer) = lfs_pointer::parse(&data) else { return plain(StatusCode::NOT_FOUND, CACHE_NONE, None); }; - // The repo must link the object, even when the file is on disk: objects are shared by every repo. let size = match has_object(&state, &repo.id, &pointer.oid).await { Ok(Some(size)) => size, Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None), @@ -142,7 +98,6 @@ async fn serve(cx: &Cx) -> Response { return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); } }; - // The Content-Length comes from the link, so a file of another size would break the response. let on_disk = match file.metadata().await { Ok(meta) => meta.len(), Err(e) => { @@ -178,7 +133,8 @@ async fn serve(cx: &Cx) -> Response { mod tests { use super::*; - use forge_core::raw_token::sign_raw; + use crate::raw::now_unix; + use forge_core::raw_token::{sign_raw, verify_raw}; use sha2::{Digest, Sha256}; use topcoat::router::Router; use topcoat::router::request::Request; @@ -224,7 +180,6 @@ mod tests { ); } - /// Commits `files` on `main` in a work tree and pushes it to `bare`. fn populate(work: &std::path::Path, bare: &std::path::Path, files: &[(&str, Vec<u8>)]) { std::fs::create_dir_all(work).expect("mkdir work"); git(work, &["init", "-q", "-b", "main"]); @@ -292,7 +247,6 @@ mod tests { &[("big.bin", stored_pointer)], ); - // The object is linked to both repos and written once to the shared store. for repo in [&public, &private] { store .insert_lfs_object(&repo.id, &oid, object.len() as u64) @@ -339,13 +293,10 @@ mod tests { .to_vec() } - /// The public route, read-only, on one fixture: the linked object as a download, HEAD, and - /// the 404 cases (unlinked object, non-pointer, absent path, unknown repo). #[tokio::test] async fn public_media_serves_downloads_heads_and_404s() { let fx = fixture().await; - // Scenario: a linked object is served as a download with its headers. let res = get(&fx.router, "GET", "/tahinli/pub/-/media/main/big.bin").await; assert_eq!(res.status(), StatusCode::OK, "linked object"); assert_eq!( @@ -375,7 +326,6 @@ mod tests { ); assert_eq!(body_bytes(res).await, fx.object, "linked object body"); - // Scenario: HEAD has the headers and no body. let res = get(&fx.router, "HEAD", "/tahinli/pub/-/media/main/big.bin").await; assert_eq!(res.status(), StatusCode::OK, "head"); assert_eq!( @@ -385,11 +335,9 @@ mod tests { ); assert!(body_bytes(res).await.is_empty(), "head body"); - // Scenario: the pointer exists, but the repo does not link its object. let res = get(&fx.router, "GET", "/tahinli/pub/-/media/main/missing.bin").await; assert_eq!(res.status(), StatusCode::NOT_FOUND, "unlinked object"); - // Scenario: a non-pointer file, an absent path and an unknown repo all 404. let text = get(&fx.router, "GET", "/tahinli/pub/-/media/main/plain.txt").await; assert_eq!(text.status(), StatusCode::NOT_FOUND, "non-pointer"); let absent = get(&fx.router, "GET", "/tahinli/pub/-/media/main/nope.bin").await; @@ -398,30 +346,24 @@ mod tests { assert_eq!(unknown_repo.status(), StatusCode::NOT_FOUND, "unknown repo"); } - /// Private media and signed URLs, read-only, on one fixture: a private repo needs a valid - /// token, and `media_url` encodes paths and signs only private repos. #[tokio::test] async fn private_media_needs_a_valid_token_and_urls_sign_private_repos_only() { let fx = fixture().await; let path = "/tahinli/priv/-/media/main/big.bin"; - // Scenario: no token is a 404. let none = get(&fx.router, "GET", path).await; assert_eq!(none.status(), StatusCode::NOT_FOUND, "no token"); - // Scenario: a valid token serves the object. let now = now_unix(); let valid = sign_raw(&fx.state.key, &fx.private.id, now + 60); let ok = get(&fx.router, "GET", &format!("{path}?token={valid}")).await; assert_eq!(ok.status(), StatusCode::OK, "valid token"); assert_eq!(body_bytes(ok).await, fx.object, "valid token body"); - // Scenario: an expired token is a 404. let expired = sign_raw(&fx.state.key, &fx.private.id, now - 1); let res = get(&fx.router, "GET", &format!("{path}?token={expired}")).await; assert_eq!(res.status(), StatusCode::NOT_FOUND, "expired token"); - // Scenario: a token signed for the public repo does not open the private one. let other = sign_raw(&fx.state.key, &fx.public.id, now + 60); let res = get(&fx.router, "GET", &format!("{path}?token={other}")).await; assert_eq!( @@ -430,14 +372,12 @@ mod tests { "token for another repo" ); - // Scenario: a public URL is encoded and unsigned. let public = media_url(&fx.state, &fx.public, "main", "a b/big.bin"); assert_eq!( public, "http://127.0.0.1:7661/tahinli/pub/-/media/main/a%20b/big.bin", "public url" ); - // Scenario: a private URL carries a token that verifies for the private repo. let private = media_url(&fx.state, &fx.private, "main", "big.bin"); assert!( private.starts_with("http://127.0.0.1:7661/tahinli/priv/-/media/main/big.bin?token="), @@ -453,9 +393,6 @@ mod tests { ); } - /// A branch named `media` must not shadow the media route. The raw route serves its files, - /// and the URL from `media_url` still serves the linked LFS object. This test pushes a - /// branch, so it keeps its own fixture. #[tokio::test] async fn branch_named_media_does_not_shadow_the_media_route() { let fx = fixture().await; @@ -479,7 +416,6 @@ mod tests { "branch raw body" ); - // `-` is never a ref, so a raw path under it is not resolved. let dash = get(&fx.router, "GET", "/tahinli/pub/-/README.md").await; assert_eq!(dash.status(), StatusCode::NOT_FOUND, "dash is not a ref"); diff --git a/crates/forge-web-app/src/raw/mod.rs b/crates/forge-web-app/src/raw/mod.rs index be4fa3f..f2b5723 100644 --- a/crates/forge-web-app/src/raw/mod.rs +++ b/crates/forge-web-app/src/raw/mod.rs @@ -1,15 +1,12 @@ -//! Raw user-content origin (separate listener, explicit routes; never `.discover()`). -//! See docs/architecture.md, section 5.5. - pub mod media; pub mod snippet_raw; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::Stdio; -use std::time::{SystemTime, UNIX_EPOCH}; use bytes::Bytes; use forge_core::raw_token::{sign_raw, verify_raw}; +pub use forge_core::time::now_unix; use forge_core::{Repo, Visibility}; use forge_git::GitCommand; use forge_git::browse::{self, EntryKind}; @@ -28,49 +25,51 @@ use topcoat::router::{ header, parse_query_params, path_param_segment, path_param_segments, }; -use crate::internal::is_valid_oid; +use crate::internal::is_git_oid; use crate::state::AppState; -/// Blobs up to this size are read in full. Larger blobs are streamed from `git cat-file`. const MAX_INLINE_BYTES: u64 = 8 * 1024 * 1024; -/// Bytes inspected to decide text versus binary. const SNIFF_BYTES: usize = 8000; -/// Lifetime of a signed private raw URL. pub const LINK_TTL_SECS: i64 = 600; const CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox"; const CORP: &str = "cross-origin"; -/// Raw responses revalidate on every use (an unchanged blob answers 304 through If-None-Match), -/// so a repo made private, or a reader who lost access, stops being served at once. pub const CACHE_PRIVATE: &str = "private, no-cache"; pub const CACHE_PUBLIC: &str = "public, no-cache"; pub const CACHE_NONE: &str = "no-store"; const TEXT: &str = "text/plain; charset=utf-8"; pub const OCTET: &str = "application/octet-stream"; -/// Absolute URL of a file on the raw origin. For private repos it carries a signed `?token=` -/// valid for 10 minutes. `rev` is the ref name or commit oid as shown in the app URL. pub fn raw_url(state: &AppState, repo: &Repo, rev: &str, path: &str) -> String { - let base = state.config.user_content_base_url.trim_end_matches('/'); - let mut url = format!( - "{base}/{}/{}/{}", + let mut encoded = format!( + "{}/{}/{}", encode_path(&repo.owner_name), encode_path(&repo.name), encode_path(rev) ); if !path.is_empty() { - url.push('/'); - url.push_str(&encode_path(path)); + encoded.push('/'); + encoded.push_str(&encode_path(path)); } - if matches!(repo.visibility, Visibility::Private) { + signed_url( + state, + &encoded, + &repo.id, + matches!(repo.visibility, Visibility::Private), + ) +} + +pub fn signed_url(state: &AppState, path: &str, id: &str, private: bool) -> String { + let base = state.config.user_content_base_url.trim_end_matches('/'); + let mut url = format!("{base}/{path}"); + if private { let expires = now_unix().saturating_add(LINK_TTL_SECS); url.push_str("?token="); - url.push_str(&sign_raw(&state.key, &repo.id, expires)); + url.push_str(&sign_raw(&state.key, id, expires)); } url } -/// Percent-encodes each `/`-separated segment and keeps the separators. pub fn encode_path(value: &str) -> String { value .split('/') @@ -79,7 +78,6 @@ pub fn encode_path(value: &str) -> String { .join("/") } -/// Percent-encodes everything except RFC 3986 unreserved characters. fn encode_segment(segment: &str) -> String { let mut out = String::with_capacity(segment.len()); for byte in segment.bytes() { @@ -92,7 +90,6 @@ fn encode_segment(segment: &str) -> String { out } -/// Explicit routes only. No cookie layer: this origin never reads or sets cookies. pub fn router(state: AppState) -> Router { Router::builder() .route(RouteFn::new( @@ -100,22 +97,17 @@ pub fn router(state: AppState) -> Router { "/{owner}/{repo}/{*rest}", raw_file, )) - // Media is served from the LFS store, so it is routed before the catch-all raw route. - // It sits under the literal `-` segment, which no ref can use, so a branch named `media` - // still resolves through the raw route. .route(RouteFn::new( vec![Method::GET, Method::HEAD], "/{owner}/{repo}/-/media/{*rest}", crate::raw::media::media_file, )) - // Snippet files sit under the same reserved `-` segment: `/-/snippets/{id}/{file}`. .route(RouteFn::new( vec![Method::GET, Method::HEAD], "/-/snippets/{id}/{*rest}", crate::raw::snippet_raw::snippet_file, )) .route(RouteFn::new(Method::GET, "/healthz", healthz)) - // Responses must match the bytes behind the ETag and Content-Length. .with(Compression::disable()) .with(state) .build() @@ -138,7 +130,40 @@ fn raw_file(cx: &Cx, _body: topcoat::router::Body) -> RouteFuture<'_> { Box::pin(async move { Ok(serve(cx).await) }) } -/// Serves one file. Every failure is turned into a response here, so the route never errors. +async fn resolve_repo( + state: &AppState, + owner: &str, + name: &str, + token: Option<&str>, +) -> Result<(Repo, PathBuf, &'static str), Response> { + let repo = match state.store.repo_by_owner_and_name(owner, name).await { + Ok(Some(repo)) => repo, + Ok(None) => return Err(plain(StatusCode::NOT_FOUND, CACHE_NONE, None)), + Err(e) => { + tracing::error!(error = %e, "raw: repo lookup failed"); + return Err(plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None)); + } + }; + let cache = match repo.visibility { + Visibility::Public => CACHE_PUBLIC, + Visibility::Private => { + let valid = token.is_some_and(|t| verify_raw(&state.key, t, &repo.id, now_unix())); + if !valid { + return Err(plain(StatusCode::NOT_FOUND, CACHE_NONE, None)); + } + CACHE_PRIVATE + } + }; + let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) { + Ok(path) => path, + Err(e) => { + tracing::error!(error = %e, "raw: repo path failed"); + return Err(plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None)); + } + }; + Ok((repo, repo_dir, cache)) +} + async fn serve(cx: &Cx) -> Response { let state = context::<AppState>(cx).clone(); let owner = path_param_segment(cx, "owner").to_owned(); @@ -146,8 +171,6 @@ async fn serve(cx: &Cx) -> Response { let rest = path_param_segments(cx, "rest") .collect::<Vec<&str>>() .join("/"); - // `-` is never a ref name (git and the pre-receive hook reject it). It is reserved for the - // `/-/media/` route, so a raw path whose first segment is `-` is a plain 404. if rest.split('/').next() == Some("-") { return plain(StatusCode::NOT_FOUND, CACHE_NONE, None); } @@ -160,34 +183,9 @@ async fn serve(cx: &Cx) -> Response { .and_then(|v| v.to_str().ok()) .map(str::to_owned); - let repo = match state.store.repo_by_owner_and_name(&owner, &name).await { - Ok(Some(repo)) => repo, - // A missing repo and a private repo without a valid token look the same. - Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None), - Err(e) => { - tracing::error!(error = %e, "raw: repo lookup failed"); - return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); - } - }; - let cache = match repo.visibility { - Visibility::Public => CACHE_PUBLIC, - Visibility::Private => { - let valid = token - .as_deref() - .is_some_and(|t| verify_raw(&state.key, t, &repo.id, now_unix())); - if !valid { - return plain(StatusCode::NOT_FOUND, CACHE_NONE, None); - } - CACHE_PRIVATE - } - }; - - let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) { - Ok(path) => path, - Err(e) => { - tracing::error!(error = %e, "raw: repo path failed"); - return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); - } + let (_, repo_dir, cache) = match resolve_repo(&state, &owner, &name, token.as_deref()).await { + Ok(found) => found, + Err(response) => return response, }; let lookup_dir = repo_dir.clone(); @@ -260,11 +258,9 @@ async fn serve(cx: &Cx) -> Response { len: size, }; if is_head { - // Dropping the child kills it: only the headers were needed. drop(child); return finish(StatusCode::OK, Body::empty(), &oid, cache, Some(meta)); } - // The child lives inside the closure, so it stays alive until the body is consumed. let chunks = stream::iter([Ok::<Bytes, std::io::Error>(Bytes::from(sample))]) .chain(ReaderStream::new(stdout)) .map_ok(Frame::data) @@ -278,7 +274,6 @@ async fn serve(cx: &Cx) -> Response { } } -/// Result of the blocking lookup. pub enum Lookup { Missing, NotModified { @@ -295,7 +290,6 @@ pub enum Lookup { }, } -/// Resolves `rest` (`<ref>/<path>`) to an entry. Trees, submodules and missing paths are `Missing`. pub fn lookup( repo_dir: &Path, rest: &str, @@ -341,9 +335,8 @@ pub fn lookup( }) } -/// `git cat-file blob <oid>` with piped stdout. The OID must be full hex. fn spawn_cat_file(state: &AppState, repo_dir: &Path, oid: &str) -> std::io::Result<Child> { - if !is_valid_oid(oid) { + if !is_git_oid(oid) { return Err(std::io::Error::other("invalid object id")); } 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 cmd.spawn() } -/// Content type and whether the response must be an attachment. fn classify(file_name: &str, sample: &[u8], complete: bool) -> (&'static str, bool) { let ext = file_name .rsplit_once('.') @@ -385,8 +377,6 @@ fn image_type(ext: &str) -> Option<&'static str> { }) } -/// No NUL in the first 8000 bytes and valid UTF-8. For a partial sample (`complete` is false) an -/// incomplete sequence at the end is accepted. fn is_text(sample: &[u8], complete: bool) -> bool { let probe = &sample[..sample.len().min(SNIFF_BYTES)]; if probe.contains(&0) { @@ -398,7 +388,6 @@ fn is_text(sample: &[u8], complete: bool) -> bool { } } -/// True when an `If-None-Match` header lists `etag` (or `*`). Weak prefixes are ignored. fn etag_matches(header_value: &str, etag: &str) -> bool { header_value.split(',').map(str::trim).any(|candidate| { candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag @@ -411,7 +400,6 @@ pub struct Meta { pub len: u64, } -/// Builds a response with the security and caching headers that every raw response carries. pub fn finish( status: StatusCode, body: Body, @@ -458,7 +446,6 @@ pub fn finish( res } -/// Error or empty response with no ETag and a text body. pub fn plain(status: StatusCode, cache: &'static str, body: Option<&'static str>) -> Response { let text = body.unwrap_or(match status { StatusCode::NOT_FOUND => "not found", @@ -471,14 +458,6 @@ pub fn plain(status: StatusCode, cache: &'static str, body: Option<&'static str> res } -pub fn now_unix() -> i64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .ok() - .and_then(|d| i64::try_from(d.as_secs()).ok()) - .unwrap_or(0) -} - #[cfg(test)] mod tests { use super::*; @@ -515,7 +494,6 @@ mod tests { ); } - /// Creates a work tree with `files` and a symlink, then pushes it to `bare` as `main`. fn populate(work: &Path, bare: &Path, files: &[(&str, Vec<u8>)]) { std::fs::create_dir_all(work).expect("mkdir work"); git(work, &["init", "-q", "-b", "main"]); @@ -648,11 +626,9 @@ mod tests { assert_eq!(header_str(res, "referrer-policy"), "no-referrer"); } - /// One fixture (one 9 MB repo, private repo and signer) serves every read-only scenario below. #[tokio::test] async fn raw_serves_every_scenario_from_one_fixture() { let fx = fixture().await; - // Scenario: a public text file is plain and sandboxed. { let res = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await; assert_eq!(res.status(), 200); @@ -663,16 +639,13 @@ mod tests { assert_eq!(body_bytes(res).await, b"hello raw\n"); } - // Scenario: a nested path resolves. { let res = get(&fx.router, "GET", "/tahinli/pub/main/sub/a.txt", None).await; assert_eq!(res.status(), 200); assert_eq!(body_bytes(res).await, b"nested\n"); } - // Scenario: html is forced to an attachment and png is an image. { - // (path, want content-type, want content-disposition) let cases = [ ("/tahinli/pub/main/page.html", TEXT, "attachment"), ("/tahinli/pub/main/pic.png", "image/png", ""), @@ -689,7 +662,6 @@ mod tests { } } - // Scenario: a symlink is served as its target text. { let res = get(&fx.router, "GET", "/tahinli/pub/main/link", None).await; assert_eq!(res.status(), 200); @@ -697,7 +669,6 @@ mod tests { assert_eq!(body_bytes(res).await, b"hello.txt"); } - // Scenario: a private repo requires a valid, unexpired token for that repo. { let path = "/tahinli/priv/main/hello.txt"; let now = now_unix(); @@ -721,7 +692,6 @@ mod tests { assert_eq!(res.status(), 404); } - // Scenario: missing repos and directories are 404. { for uri in [ "/tahinli/nope/main/hello.txt", @@ -733,7 +703,6 @@ mod tests { } } - // Scenario: a matching etag gives 304. { let first = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await; let etag = header_str(&first, "etag"); @@ -749,7 +718,6 @@ mod tests { assert_eq!(header_str(&again, "etag"), etag); } - // Scenario: HEAD has headers and no body. { let res = get(&fx.router, "HEAD", "/tahinli/pub/main/hello.txt", None).await; assert_eq!(res.status(), 200); @@ -758,7 +726,6 @@ mod tests { assert!(body_bytes(res).await.is_empty()); } - // Scenario: a large file streams intact. { let res = get(&fx.router, "GET", "/tahinli/pub/main/big.txt", None).await; assert_eq!(res.status(), 200); @@ -773,7 +740,6 @@ mod tests { assert!(body == expected, "streamed body differs"); } - // Scenario: app routes are not on the raw origin, but healthz is. { for path in ["/login", "/settings/keys", "/tahinli/pub/tree/main"] { let res = get(&fx.router, "GET", path, None).await; @@ -783,7 +749,6 @@ mod tests { assert_eq!(health.status(), 200); } - // Scenario: raw URLs are encoded, and private ones are signed. { let url = raw_url(&fx.state, &fx.public, "main", "my file#1.txt"); assert_eq!( diff --git a/crates/forge-web-app/src/raw/snippet_raw.rs b/crates/forge-web-app/src/raw/snippet_raw.rs index b448130..ef3893b 100644 --- a/crates/forge-web-app/src/raw/snippet_raw.rs +++ b/crates/forge-web-app/src/raw/snippet_raw.rs @@ -1,11 +1,5 @@ -//! Raw-origin route `/-/snippets/{id}/{file}`. The literal `-` keeps it apart from repo raw paths, -//! as it does for media. Snippet files are served as text under the same sandbox headers as raw -//! files. Public and unlisted snippets are open. A private snippet needs a signed `?token=`, -//! signed over the snippet id by the same `sign_raw` that guards private repo files. - -use forge_core::raw_token::{sign_raw, verify_raw}; +use forge_core::raw_token::verify_raw; use forge_core::store::snippets::{Snippet, SnippetVisibility}; -use serde::Deserialize; use sha2::{Digest, Sha256}; use topcoat::context::{Cx, context}; use topcoat::router::request::{headers, method}; @@ -16,42 +10,32 @@ use topcoat::router::{ }; use crate::raw::{ - CACHE_NONE, CACHE_PRIVATE, CACHE_PUBLIC, LINK_TTL_SECS, Meta, encode_path, finish, now_unix, - plain, + CACHE_NONE, CACHE_PRIVATE, CACHE_PUBLIC, Meta, TEXT, TokenQuery, encode_path, finish, + now_unix, plain, signed_url, }; use crate::state::AppState; -const TEXT: &str = "text/plain; charset=utf-8"; const MARKDOWN: &str = "text/markdown; charset=utf-8"; const JSON: &str = "application/json; charset=utf-8"; -#[derive(Deserialize)] -struct TokenQuery { - token: Option<String>, -} - -/// Absolute URL of one file of a snippet on the user-content origin. A private snippet's URL -/// carries a signed `?token=` valid for the same 10 minutes as private raw URLs. pub fn snippet_raw_url(state: &AppState, snippet: &Snippet, file: &str) -> String { - let base = state.config.user_content_base_url.trim_end_matches('/'); - let mut url = format!( - "{base}/-/snippets/{}/{}", + let encoded = format!( + "-/snippets/{}/{}", encode_path(&snippet.id), encode_path(file) ); - if snippet.visibility == SnippetVisibility::Private { - let expires = now_unix().saturating_add(LINK_TTL_SECS); - url.push_str("?token="); - url.push_str(&sign_raw(&state.key, &snippet.id, expires)); - } - url + signed_url( + state, + &encoded, + &snippet.id, + snippet.visibility == SnippetVisibility::Private, + ) } pub fn snippet_file(cx: &Cx, _body: Body) -> RouteFuture<'_> { Box::pin(async move { Ok(serve(cx).await) }) } -/// Content type for a snippet file, chosen from its extension. Everything is text. fn content_type(file_name: &str) -> &'static str { match file_name .rsplit_once('.') @@ -64,7 +48,6 @@ fn content_type(file_name: &str) -> &'static str { } } -/// Serves one file. Every failure is turned into a response here, so the route never errors. async fn serve(cx: &Cx) -> Response { let state = context::<AppState>(cx).clone(); let id = path_param_segment(cx, "id").to_owned(); @@ -84,7 +67,6 @@ async fn serve(cx: &Cx) -> Response { let snippet = match state.store.get_snippet(&id).await { Ok(Some(snippet)) => snippet, - // A missing snippet and a private one without a valid token look the same. Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None), Err(e) => { tracing::error!(error = %e, "snippet raw: lookup failed"); @@ -110,12 +92,10 @@ async fn serve(cx: &Cx) -> Response { }; let etag = hex::encode(Sha256::digest(file.content.as_bytes())); let quoted = format!("\"{etag}\""); - if if_none_match.is_some_and(|value| { - value - .split(',') - .map(str::trim) - .any(|c| c == "*" || c.strip_prefix("W/").unwrap_or(c) == quoted) - }) { + if if_none_match + .as_deref() + .is_some_and(|value| super::etag_matches(value, "ed)) + { return finish(StatusCode::NOT_MODIFIED, Body::empty(), &etag, cache, None); } diff --git a/crates/forge-web-app/src/self_update.rs b/crates/forge-web-app/src/self_update.rs index 3155ec3..ec4c632 100644 --- a/crates/forge-web-app/src/self_update.rs +++ b/crates/forge-web-app/src/self_update.rs @@ -1,12 +1,3 @@ -//! Self-update: a green CI run of the forge's own repo replaces the running binary and restarts. -//! -//! Event-driven. `maybe_deploy` runs from the runner finish path when a job finishes. Nothing -//! polls. After the swap the process exits with `RESTART_EXIT_CODE`, and the systemd unit -//! (`Restart=on-failure`) starts the new binary. -//! -//! Runners update the same way. The claim route advertises the running binary's sha256 to a runner -//! of the same target, and `GET /api/v1/ci/runners/binary` serves the bytes. - use std::path::{Path, PathBuf}; use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, Ordering}; @@ -14,6 +5,7 @@ use std::time::Duration; use forge_core::ci::{CiRun, RunState}; use forge_core::config::SelfUpdateConfig; +use forge_core::token::sha256_reader; use futures_util::StreamExt; use futures_util::stream::BoxStream; use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; @@ -26,30 +18,21 @@ use topcoat::router::{Body, HeaderMap, StatusCode, response::Response}; use crate::state::AppState; pub use forge_ci::proto::RESTART_EXIT_CODE; -/// Response header carrying the sha256 of the running binary, lowercase hex. pub const SHA_HEADER: &str = "Forge-Binary-Sha256"; -/// Request header a runner sends with its `<arch>-<os>` target. pub const TARGET_HEADER: &str = "Forge-Runner-Target"; -/// How long the staged binary may take to answer `--version`. const SANITY_TIMEOUT: Duration = Duration::from_secs(10); -/// Serialises deploys. A deploy that finds another one running is skipped. static DEPLOY_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); -/// Wakes the server so it stops after a swap. static RESTART: tokio::sync::Notify = tokio::sync::Notify::const_new(); static RESTART_REQUESTED: AtomicBool = AtomicBool::new(false); -/// The running binary, hashed once at startup. pub struct Running { - /// The executable path, used to place the sibling `.prev`, `.bad` and staging files. pub path: PathBuf, pub sha256: String, } static RUNNING: OnceLock<Option<Running>> = OnceLock::new(); -/// The running binary, hashed on first use. `None` if it cannot be read, which disables -/// advertising and serving, and deploys. pub fn running() -> Option<&'static Running> { RUNNING .get_or_init(|| match load_running() { @@ -67,12 +50,10 @@ pub fn running() -> Option<&'static Running> { fn load_running() -> std::io::Result<Running> { let path = std::env::current_exe()?; - let sha256 = sha256_reader(std::fs::File::open(image_path())?)?; + let sha256 = sha256_reader(std::fs::File::open(image_path())?)?.1; Ok(Running { path, sha256 }) } -/// The file that holds the running image. On Linux that is `/proc/self/exe`, which still names the -/// old inode after a rename over the executable. Elsewhere it is the executable path. fn image_path() -> PathBuf { let proc_exe = PathBuf::from("/proc/self/exe"); if proc_exe.exists() { @@ -82,21 +63,15 @@ fn image_path() -> PathBuf { } } -/// Resolves once a swap has asked the server to stop. pub async fn restart_requested() { RESTART.notified().await; } -/// Asks the server to stop gracefully and exit with `RESTART_EXIT_CODE`, so the supervisor starts -/// the binary again. The same path a self-update swap takes, without a swap. Used by the admin -/// "Restart server" button. pub fn request_restart() { RESTART_REQUESTED.store(true, Ordering::SeqCst); RESTART.notify_one(); } -/// An id that is new for every process start. A page that sees it change knows the server -/// restarted. pub fn boot_id() -> &'static str { static ID: OnceLock<String> = OnceLock::new(); ID.get_or_init(|| { @@ -107,24 +82,18 @@ pub fn boot_id() -> &'static str { }) } -/// Whether a swap asked the process to exit with `RESTART_EXIT_CODE`. pub fn restart_pending() -> bool { RESTART_REQUESTED.load(Ordering::SeqCst) } -/// `<arch>-<os>` for this build, as a runner reports it in `Forge-Runner-Target`. pub fn target() -> String { format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS) } -/// Whether a runner's requested target is this build's target. fn target_matches(requested: Option<&str>) -> bool { requested == Some(target().as_str()) } -/// Whether a finished run should deploy. Pure, so the rules can be tested. A run deploys only when -/// it is a successful push to the configured branch of the configured repo, and it is still the -/// newest run on that branch. Pull request runs (including fork runs) never deploy. pub fn should_deploy( cfg: &SelfUpdateConfig, repo_full_name: &str, @@ -140,8 +109,6 @@ pub fn should_deploy( && newest_on_ref == Some(run.id.as_str()) } -/// Why a candidate binary must not be installed, or `None` to install it. `bad_list` is the text -/// of `<exe>.bad`: one hex sha256 per line, `#` starts a comment. pub fn skip_reason(candidate_sha: &str, running_sha: &str, bad_list: &str) -> Option<&'static str> { if candidate_sha.eq_ignore_ascii_case(running_sha) { 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 listed.then_some("listed in the bad list") } -/// `<name>.<suffix>` next to `exe`, for example `forge.prev`. fn sibling(exe: &Path, suffix: &str) -> PathBuf { let name = exe .file_name() @@ -163,7 +129,6 @@ fn sibling(exe: &Path, suffix: &str) -> PathBuf { exe.with_file_name(format!("{name}.{suffix}")) } -/// Called when a job finishes. Starts a deploy in the background when the run qualifies. pub async fn maybe_deploy(state: &AppState, run: &CiRun) { let cfg = &state.config.self_update; if !cfg.enabled || !matches!(run.state, RunState::Success) { @@ -198,8 +163,6 @@ pub async fn maybe_deploy(state: &AppState, run: &CiRun) { tokio::spawn(async move { deploy(state, run).await }); } -/// Installs the run's artifact over the running binary and asks the server to restart. Logs and -/// returns on any failure, leaving the running binary in place. pub async fn deploy(state: AppState, run: CiRun) { let Ok(_guard) = DEPLOY_LOCK.try_lock() else { 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> { tracing::info!(run_id = %run.id, job = %cfg.job, "self-update: no such job in the run, skipping"); return Ok(()); }; - // "dist_forge" was the old default; CI no longer uploads it, so it means the arch-named binary. let configured = match cfg.artifact.as_str() { "dist_forge" => "forge-{target}", other => other, @@ -246,7 +208,6 @@ async fn deploy_inner(state: &AppState, run: &CiRun) -> Result<(), String> { .map_err(|e| e.to_string())? .ok_or("the artifact bytes are missing")?; - // Stage next to the executable, so the final rename stays on one filesystem. let staged = sibling(&running.path, "new"); let sha = match write_staged(read.stream, &staged).await { Ok(sha) => sha, @@ -288,8 +249,6 @@ async fn deploy_inner(state: &AppState, run: &CiRun) -> Result<(), String> { Ok(()) } -/// Streams the artifact to `path`, hashing as it goes. The file is executable and synced before -/// this returns. Returns the sha256 in lowercase hex. async fn write_staged( mut stream: BoxStream<'static, std::io::Result<bytes::Bytes>>, path: &Path, @@ -313,7 +272,6 @@ async fn write_staged( Ok(hex::encode(hasher.finalize())) } -/// Runs `<staged> --version` with a timeout. Only exit 0 passes. async fn sanity_check(path: &Path) -> Result<(), String> { use std::process::Stdio; @@ -333,8 +291,6 @@ async fn sanity_check(path: &Path) -> Result<(), String> { } } -/// Keeps the current binary as `<exe>.prev` (a hard link when possible), then renames `staged` -/// over `exe`. fn swap(exe: &Path, staged: &Path) -> Result<(), String> { let prev = sibling(exe, "prev"); if prev.exists() { @@ -346,8 +302,6 @@ fn swap(exe: &Path, staged: &Path) -> Result<(), String> { std::fs::rename(staged, exe).map_err(|e| format!("cannot replace the binary: {e}")) } -/// Whether a claim response should advertise the binary: self-update is on and the runner asked -/// for this target. Adds `Forge-Binary-Sha256` to a 200 or 204 response. pub fn advertise(state: &AppState, request: &HeaderMap, res: &mut Response) { if !state.config.self_update.enabled { return; @@ -367,18 +321,16 @@ pub fn advertise(state: &AppState, request: &HeaderMap, res: &mut Response) { } } -/// The running binary as a streamed response, with its sha256. The caller checks auth and that -/// self-update is enabled. `Err` when the binary cannot be read. +const BODY_FRAME_BYTES: usize = 64 * 1024; + pub async fn binary_response() -> Result<Response, String> { let running = running().ok_or("the running binary was not hashed at startup")?; let file = tokio::fs::File::open(image_path()) .await .map_err(|e| e.to_string())?; let len = file.metadata().await.map_err(|e| e.to_string())?.len(); - // 64 KiB frames, not ReaderStream's 4 KiB default: the binary is ~1 GB, and 4 KiB frames mean - // ~250k body frames to push through hyper for every download. - let frames = - ReaderStream::with_capacity(file, 64 * 1024).map(|chunk| chunk.map(http_body::Frame::data)); + let frames = ReaderStream::with_capacity(file, BODY_FRAME_BYTES) + .map(|chunk| chunk.map(http_body::Frame::data)); let mut res = Response::new(Body::new(StreamBody::new(frames))); let headers = res.headers_mut(); headers.insert( @@ -392,19 +344,6 @@ pub async fn binary_response() -> Result<Response, String> { Ok(res) } -fn sha256_reader(mut reader: impl std::io::Read) -> std::io::Result<String> { - let mut hasher = Sha256::new(); - let mut buf = vec![0u8; 64 * 1024]; - loop { - let n = reader.read(&mut buf)?; - if n == 0 { - break; - } - hasher.update(&buf[..n]); - } - Ok(hex::encode(hasher.finalize())) -} - #[cfg(test)] mod tests { use super::*; @@ -437,7 +376,6 @@ mod tests { } } - /// A push run of the deploy branch that is still the newest run. fn good() -> CiRun { run("push", "refs/heads/main", RunState::Success, None) } @@ -448,7 +386,6 @@ mod tests { let mut off = cfg(); off.enabled = false; let failed = |state| run("push", "refs/heads/main", state, None); - // (case, config, repo, run, latest run id, want deploy) let cases = vec![ ( "good push", @@ -504,7 +441,6 @@ mod tests { Some("run-7"), false, ), - // Even if a PR run were stored on the branch ref, the trigger and pull number exclude it. ( "pull request on branch ref", &on, @@ -617,7 +553,6 @@ mod tests { skip_reason("1111", "ffff", bad), Some("listed in the bad list") ); - // A comment line is not a sha. assert_eq!(skip_reason("rolled", "ffff", bad), None); assert_eq!(skip_reason("3333", "ffff", bad), None); } @@ -631,7 +566,7 @@ mod tests { #[test] fn sha256_of_known_bytes() { - let digest = sha256_reader(&b"abc"[..]).unwrap(); + let digest = sha256_reader(&b"abc"[..]).unwrap().1; assert_eq!( digest, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" diff --git a/crates/forge-web-app/src/signatures.rs b/crates/forge-web-app/src/signatures.rs index 3967ba6..ebf4084 100644 --- a/crates/forge-web-app/src/signatures.rs +++ b/crates/forge-web-app/src/signatures.rs @@ -298,22 +298,16 @@ async fn gpg_with_input(state: &AppState, args: &[&str], armored: &str) -> Resul } } -/// Creates the forge keyring directory, mode 0700 on unix. +/// Creates the forge keyring directory, mode 0700. async fn ensure_gnupg_home(state: &AppState) -> std::io::Result<()> { let home = gnupg_home(state); tokio::fs::create_dir_all(&home).await?; - set_private_dir(&home).await + set_mode(&home, 0o700).await } -#[cfg(unix)] -async fn set_private_dir(path: &Path) -> std::io::Result<()> { +async fn set_mode(path: &Path, mode: u32) -> std::io::Result<()> { use std::os::unix::fs::PermissionsExt; - tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).await -} - -#[cfg(not(unix))] -async fn set_private_dir(_path: &Path) -> std::io::Result<()> { - Ok(()) + tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).await } /// 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: TMP_SEQ.fetch_add(1, Ordering::Relaxed) )); tokio::fs::write(&tmp, lines.as_bytes()).await?; - set_private(&tmp).await?; + set_mode(&tmp, 0o600).await?; tokio::fs::rename(&tmp, &target).await?; Ok(()) } -#[cfg(unix)] -async fn set_private(path: &Path) -> std::io::Result<()> { - use std::os::unix::fs::PermissionsExt; - tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).await -} - -#[cfg(not(unix))] -async fn set_private(_path: &Path) -> std::io::Result<()> { - Ok(()) -} - /// Called after a user's keys were added or removed. Rebuilds the SSH allowed-signers file and /// drops the cached verdicts those keys can change. pub async fn on_keys_changed(state: &AppState, user_id: &str) { diff --git a/crates/forge-web-app/src/ssh_backend.rs b/crates/forge-web-app/src/ssh_backend.rs index 4b68f05..8752057 100644 --- a/crates/forge-web-app/src/ssh_backend.rs +++ b/crates/forge-web-app/src/ssh_backend.rs @@ -1,9 +1,9 @@ //! `impl forge_ssh::GitBackend` for forge: key lookup, authz and git process construction. use std::path::PathBuf; -use std::time::{SystemTime, UNIX_EPOCH}; use forge_core::lfs_token::{self, LfsOp}; +use forge_core::time::now_unix; use forge_core::{Repo, User}; use forge_git::GitService; use forge_ssh::{GitBackend, LfsOperation, RepoPath}; @@ -64,14 +64,6 @@ impl SshBackend { } } -fn now_unix() -> i64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .ok() - .and_then(|d| i64::try_from(d.as_secs()).ok()) - .unwrap_or(0) -} - impl GitBackend for SshBackend { async fn authenticate_key(&self, _algorithm: &str, key_blob: &[u8]) -> Option<String> { let key = match self.state.store.ssh_key_by_blob(key_blob).await { diff --git a/crates/forge-web-app/src/test_support/fixture.rs b/crates/forge-web-app/src/test_support/fixture.rs index 77af87b..f690509 100644 --- a/crates/forge-web-app/src/test_support/fixture.rs +++ b/crates/forge-web-app/src/test_support/fixture.rs @@ -66,7 +66,7 @@ impl Fixture { .create_repo(&owner.id, REPO, "", visibility, "main") .await .unwrap(); - let bare = repo_dir(&dir, &repo.id); + let bare = forge_git::repo::repo_path(&dir, &repo.id).unwrap(); std::fs::create_dir_all(bare.parent().unwrap()).unwrap(); git( &dir, @@ -142,16 +142,6 @@ impl Fixture { } } -/// Same layout as `forge_git::repo::repo_path`, computed here so the test can create it. -fn repo_dir(data_dir: &Path, repo_id: &str) -> PathBuf { - let id = repo_id.to_ascii_lowercase(); - data_dir - .join("repos") - .join(&id[0..2]) - .join(&id[2..4]) - .join(format!("{id}.git")) -} - /// GET through the router: `(status, headers, body)`. pub async fn get(router: &Router, uri: &str) -> (u16, http::HeaderMap, Vec<u8>) { let req = Request::builder() diff --git a/crates/forge-web-app/src/test_support/http.rs b/crates/forge-web-app/src/test_support/http.rs new file mode 100644 index 0000000..6767cbf --- /dev/null +++ b/crates/forge-web-app/src/test_support/http.rs @@ -0,0 +1,16 @@ +use forge_core::Store; +use forge_core::token::{generate_token, hash_token}; + +pub async fn token_for(store: &Store, user_id: &str, scopes: &[&str]) -> String { + let raw = generate_token(); + let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect(); + store + .create_token(user_id, "test", &hash_token(&raw), &scopes, None) + .await + .expect("token"); + raw +} + +pub fn bearer(raw: &str) -> String { + format!("Bearer {raw}") +} diff --git a/crates/forge-web-app/src/test_support/mod.rs b/crates/forge-web-app/src/test_support/mod.rs index 689ab17..5444477 100644 --- a/crates/forge-web-app/src/test_support/mod.rs +++ b/crates/forge-web-app/src/test_support/mod.rs @@ -4,6 +4,7 @@ //! or state field is added in one place. pub mod fixture; +pub mod http; use std::path::Path; use std::sync::Arc; diff --git a/crates/forge-web-app/src/views/diff.rs b/crates/forge-web-app/src/views/diff.rs index d48d9ed..723ec45 100644 --- a/crates/forge-web-app/src/views/diff.rs +++ b/crates/forge-web-app/src/views/diff.rs @@ -24,8 +24,8 @@ use crate::i18n::browse as b; use crate::i18n::code::{self as g, K}; use crate::i18n::pulls_review::{self as pr_g, K as PrK}; use crate::state::AppState; -use crate::views::review_thread::{ThreadCtx, review_thread_in}; -use crate::views::url_path; +use crate::views::enc; +use crate::views::review_thread::{ThreadCtx, review_thread}; /// Key of the diff view: `split` or `unified`. pub const DIFF_VIEW: &str = "diff_view"; @@ -402,7 +402,7 @@ impl FileView { let blob_path = file.new_path.as_ref().or(file.old_path.as_ref()); let blob_href = match (blob_commit, blob_path) { (Some(commit), Some(path)) => { - format!("/{owner}/{repo}/blob/{commit}/{}", url_path(path)) + format!("/{owner}/{repo}/blob/{commit}/{}", enc(path)) } _ => String::new(), }; @@ -532,14 +532,8 @@ pub async fn diff_section( .files .iter() .enumerate() - .map(|(i, file)| { - ( - i, - FileView::new(i, file, oid, parent, owner, repo, lang, &mut comments), - ) - }) .filter(|(i, _)| opts.only.is_none_or(|only| only == *i)) - .map(|(_, file)| file) + .map(|(i, file)| FileView::new(i, file, oid, parent, owner, repo, lang, &mut comments)) .collect(); let alone = opts.only.is_some(); if split { @@ -750,7 +744,7 @@ async fn diff_split_line(cx: &Cx, row: SplitRow, lang: Lang, anchored: bool) -> <td colspan=(span)> <div class="review-threads"> for thread in threads.into_iter() { - review_thread_in(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files") + review_thread(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files") } if let Some(form) = form { inline_comment_form(form: form, lang: lang) @@ -801,7 +795,7 @@ async fn diff_line(cx: &Cx, row: DiffRow, lang: Lang) -> Result<impl View> { <td colspan=(span)> <div class="review-threads"> for thread in threads.into_iter() { - review_thread_in(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files") + review_thread(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files") } if let Some(form) = form { inline_comment_form(form: form, lang: lang) diff --git a/crates/forge-web-app/src/views/heatmap.rs b/crates/forge-web-app/src/views/heatmap.rs index 9aa85a0..a56ea13 100644 --- a/crates/forge-web-app/src/views/heatmap.rs +++ b/crates/forge-web-app/src/views/heatmap.rs @@ -15,7 +15,7 @@ use forge_core::time::stamp_to_unix; use topcoat::Result; use topcoat::view::{View, component, view}; -use super::{civil_from_days, now_unix, relative_time}; +use super::{civil_from_days, days_from_civil, now_unix, relative_time}; use crate::i18n::Lang; use crate::i18n::misc::{self as g, K}; @@ -61,8 +61,6 @@ pub struct Calendar { pub longest_streak: u64, /// The highest count on a single day. pub best_day: u64, - /// Today's count. - pub today_count: u64, } /// 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 { current_streak, longest_streak: longest, best_day, - today_count, } } @@ -161,18 +158,6 @@ fn parse_date(text: &str) -> Option<i64> { (civil_from_days(days) == (year, month, day)).then_some(days) } -/// Days since 1970-01-01 for `(year, month, day)`. Howard Hinnant's days-from-civil algorithm, the -/// inverse of `civil_from_days`. -fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { - let y = if month <= 2 { year - 1 } else { year }; - let era = y.div_euclid(400); - let yoe = y - era * 400; - let mp = (month + 9) % 12; - let doy = (153 * mp + 2) / 5 + day - 1; - let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; - era * 146_097 + doe - 719_468 -} - /// Monday = 0 through Sunday = 6. 1970-01-01 was a Thursday. fn weekday(days: i64) -> u8 { (days + 3).rem_euclid(7) as u8 @@ -275,6 +260,20 @@ fn day_row(lang: Lang, item: &ContributionItem, now: i64) -> DayRow { } } +#[component] +async fn day_line(cx: &Cx, row: DayRow) -> Result<impl View> { + Ok(view! { + <span>(row.before.as_str())</span> + if let Some(href) = row.href { + <a href=(href.as_str())>(row.link.as_str())</a> + } else { + <span>(row.link.as_str())</span> + } + <span>(row.after.as_str())</span> + <time data-rel="true" datetime=(row.updated.as_str())>(row.relative.as_str())</time> + }) +} + /// Items split into runs that share a key, in the order each key is first met. Items without a /// key (`None`) are each their own run. fn group_first_seen<'a>( @@ -510,39 +509,18 @@ pub async fn contribution_calendar( for entry in day.rows.into_iter() { if entry.pushes.is_empty() { <li> - <span>(entry.row.before.as_str())</span> - if let Some(href) = entry.row.href { - <a href=(href.as_str())>(entry.row.link.as_str())</a> - } else { - <span>(entry.row.link.as_str())</span> - } - <span>(entry.row.after.as_str())</span> - <time data-rel="true" datetime=(entry.row.updated.as_str())>(entry.row.relative.as_str())</time> + day_line(row: entry.row) </li> } else { <li class="day-group"> <details> <summary> - <span>(entry.row.before.as_str())</span> - if let Some(href) = entry.row.href { - <a href=(href.as_str())>(entry.row.link.as_str())</a> - } else { - <span>(entry.row.link.as_str())</span> - } - <span>(entry.row.after.as_str())</span> - <time data-rel="true" datetime=(entry.row.updated.as_str())>(entry.row.relative.as_str())</time> + day_line(row: entry.row) </summary> <ul> for push in entry.pushes.into_iter() { <li> - <span>(push.before.as_str())</span> - if let Some(href) = push.href { - <a href=(href.as_str())>(push.link.as_str())</a> - } else { - <span>(push.link.as_str())</span> - } - <span>(push.after.as_str())</span> - <time data-rel="true" datetime=(push.updated.as_str())>(push.relative.as_str())</time> + day_line(row: push) </li> } </ul> @@ -586,7 +564,6 @@ mod tests { assert_eq!(cal.current_streak, 0); assert_eq!(cal.longest_streak, 0); assert_eq!(cal.best_day, 0); - assert_eq!(cal.today_count, 0); assert!(cal.weeks.iter().flatten().flatten().all(|d| d.level == 0)); } @@ -598,7 +575,6 @@ mod tests { ); assert_eq!(cal.current_streak, 3); assert_eq!(cal.longest_streak, 3); - assert_eq!(cal.today_count, 5); assert_eq!(cal.total, 8); } @@ -608,7 +584,6 @@ mod tests { &counts(&[("2026-10-13", 1), ("2026-10-14", 1), ("2026-10-15", 1)]), TODAY, ); - assert_eq!(cal.today_count, 0); assert_eq!(cal.current_streak, 3); } diff --git a/crates/forge-web-app/src/views/mod.rs b/crates/forge-web-app/src/views/mod.rs index 3397524..f1a9471 100644 --- a/crates/forge-web-app/src/views/mod.rs +++ b/crates/forge-web-app/src/views/mod.rs @@ -135,6 +135,7 @@ fn percent_decode(s: &str) -> String { while i < bytes.len() { if bytes[i] == b'%' && let Some(hex) = s.get(i + 1..i + 3) + && hex.bytes().all(|b| b.is_ascii_hexdigit()) && let Ok(byte) = u8::from_str_radix(hex, 16) { out.push(byte); @@ -196,7 +197,6 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str let Some(owner) = parts.first() else { return Vec::new(); }; - // The page's own name: the part of its title after the last " · ", when there is one. let titled = title.rsplit_once(" · ").map(|(_, last)| last.to_owned()); match parts .iter() @@ -210,10 +210,7 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str Some("/snippets".to_owned()), )]; match rest { - // A snippet's own page is named by its title. [] => segments.push((title.to_owned(), None)), - // A page under a snippet goes back to the snippet, then names its step. The revisions - // page is titled by the snippet; the edit page by what it does. [.., last] => { let back = if *last == "revisions" { title.to_owned() @@ -249,12 +246,8 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str segments.push((crumb_label(part), Some(repo_href(owner, repo, "tree", &at)))); } } - // The repo's home: the repo name is the last segment already. [] => {} [kind, rest @ ..] => { - // Titles read "owner/repo · Page": the path bar has the repo already. A page titled by - // the repo alone is named by its route. A title ending in the repo plus a word - // ("Install · owner/repo wiki") reads by the part before it. let full = format!("{owner}/{repo}"); let mut tail = title.rsplit(" · "); let named = match tail.next() { @@ -269,7 +262,6 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str kind.as_str() }; match (repo_section_label(lang, section), rest) { - // Files at one commit, from the home page's timeline: under that commit. (None, [oid]) if kind == "scrub" => { let short: String = oid.chars().take(7).collect(); segments.push(( @@ -279,7 +271,6 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str segments.push((short, Some(repo_href(owner, repo, "commit", oid)))); segments.push((step_label(lang, "files"), None)); } - // Compare and search: their word, then what is compared. (None, rest) if matches!(kind.as_str(), "compare" | "search") => { let word = if kind == "compare" { s(lang, "Compare", "Karşılaştır") @@ -294,7 +285,6 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str segments.push((rest.join("/"), None)); } } - // A section's own page, or a word that is no section: one segment. (None, _) | (Some(_), []) => { let page = named.unwrap_or_else(|| { parts[2..] @@ -322,8 +312,6 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<Str format!("#{item}"), Some(repo_href(owner, repo, section, item)), )); - // The step, by its word: an edit history ends in an id, so its - // word is History; a comment's edit is Edit. let step = if rest.iter().any(|part| part == "history") { "history" } else { @@ -554,8 +542,6 @@ pub async fn shell( #[default] child: Child<'_>, ) -> Result<impl View> { let full_title = format!("{title} \u{b7} forge"); - // The unread count, the profile corner's inbox counts, their CI runs and the items waiting on - // them. Signed-in only. let (unread, inbox, runs) = match viewer { Some((user, _)) => match try_context::<AppState>(cx) { Some(state) => ( @@ -568,14 +554,9 @@ pub async fn shell( None => (0, InboxKinds::default(), no_runs()), }; let signed_in = viewer.is_some(); - // Both kinds of visitor post to `/-/theme`. Signed-in users send their CSRF token and get the - // stored preference saved. Anonymous visitors get the cookie. Either way the browser comes - // back to the page it was on. let theme_csrf = viewer.map(|(_, session)| session.csrf_token.clone()); let back = uri(cx).path_and_query().map(|p| p.as_str().to_owned()); let lang = i18n::lang(cx, viewer.map(|(user, _)| user)); - // A signed-in viewer's account preferences, read once for the banner, the tree width and the - // profile corner. Signed-out visitors keep theirs in the browser. let prefs = match (viewer, try_context::<AppState>(cx)) { (Some((user, _)), Some(state)) => Some(state.store.user_prefs(&user.id).await?), _ => None, @@ -584,7 +565,6 @@ pub async fn shell( let sound_attr = sound_attr(prefs.as_ref()); let banner_back = back.clone().unwrap_or_else(|| "/".to_owned()); let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss); - // The admin area and the user settings swap the global links for their own list. Signed-in only. let section = if signed_in { section_for(lang, uri(cx).path()) } else { @@ -592,12 +572,8 @@ pub async fn shell( }; let width = page_width(uri(cx).path()); let theme_attr = crate::theme::data_theme(cx, viewer.map(|(user, _)| user)); - // The relative-time wording and the server's clock, for nav.js to keep `<time data-rel>` labels current. let rel_words_attr = rel_words(lang); let rel_now_attr = now_unix().to_string(); - // Always set, defaults included, so a page never keeps the colours of the one before it. - // Each of the four choices is resolved on its own, so an id that is no longer offered falls - // back to its default. let (stored_accent_light, stored_accent_dark, stored_base_light, stored_base_dark) = match viewer { Some((user, _)) => ( @@ -613,25 +589,20 @@ pub async fn shell( crate::accent_palette::BASE_DEFAULT, ), }; - // A `hue-N` choice passes through as itself; an id forge does not offer shows the default. let accent_light_id = crate::accent::accent_id(stored_accent_light); let accent_dark_id = crate::accent::accent_id(stored_accent_dark); let base_light_id = crate::accent::base_id(stored_base_light); let base_dark_id = crate::accent::base_id(stored_base_dark); - // The stylesheet that styles the hue choices, when there is one. The presets need none. let custom_css = crate::accent::custom_css_href( accent_light_id, accent_dark_id, base_light_id, base_dark_id, ); - // The side of the shell sidebar: `right` only when stored so, `left` otherwise. let sidebar_side = match viewer { Some((user, _)) if user.sidebar_side == "right" => "right", _ => "left", }; - // The stored preference, "auto" included, drives the button: its icon, its label and the - // value it posts (the next preference in the cycle auto, light, dark). let theme_pref = crate::theme::preference(cx, viewer.map(|(user, _)| user)); let next_theme = theme_pref.next().as_str(); let theme_state = match theme_pref { @@ -653,10 +624,7 @@ pub async fn shell( let palette_label = br::t(lang, br::K::PaletteOpen).to_owned(); let explore_label = t(lang, Key::Explore); let home_label = o::t(lang, OK::Home); - // The path bar: one segment per part of the request path, the last one unlinked. let mut segments = path_segments(lang, uri(cx).path(), title); - // A page with no place of its own in the path, such as settings, names its section and itself. - // A page below one of the section's tabs (an account under Users) names that tab too. if segments.is_empty() { if let Some(section) = §ion { let first = section.items.first().map(|item| item.href.clone()); @@ -673,7 +641,6 @@ pub async fn shell( } segments.push((title.to_owned(), None)); } - // Places the path does not show, such as a job's run, go just before the page itself. if !parents.is_empty() { let at = segments.len().saturating_sub(1); for (offset, (label, href)) in parents.into_iter().enumerate() { @@ -699,15 +666,12 @@ pub async fn shell( }) .collect(); let strip = live_strip(lang, &runs); - // The strip's count phrases, as templates for nav.js: `{n}` stands for the count. let running_tpl = count_template(&mi::running_count(lang, 2), 2); let failed_tpl = count_template(&mi::failed_count(lang, 2), 2); let passed_tpl = count_template(&mi::passed_count(lang, 2), 2); let cancelled_tpl = count_template(&mi::cancelled_count(lang, 2), 2); let runs_label = mi::t(lang, MK::YourCiRuns); let search_for_label = mi::t(lang, MK::SearchPublicReposFor); - // The profile corner, the signed-in account panel. Its dot says something waits: an unread - // notification, a review request, a mention or a failed run. let corner = viewer.map(|(user, session)| ProfileCorner { username: user.username.clone(), name: user @@ -767,7 +731,6 @@ pub async fn shell( } </ol> if signed_in { - // The palette's strings ride on its button, so nav.js builds the dialog in the viewer's language. <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()) data-placeholder=(br::t(lang, br::K::PalettePlaceholder)) data-repos=(br::t(lang, br::K::PaletteRepos)) data-orgs=(o::t(lang, OK::Organizations)) data-pages=(br::t(lang, br::K::PalettePages)) @@ -852,7 +815,6 @@ pub async fn shell( </body> </html> } - // Boxed: the shell's view is part of every page's view, and inline it overflows the stack of a deep page. .boxed()) } @@ -1050,7 +1012,6 @@ pub fn section_for(lang: Lang, path: &str) -> Option<Section> { let second = match (first, second) { (_, "sessions") => "security", (_, "gpg" | "tokens") => "keys", - // Invites are a rail item of Users, replication one of Backups. ("admin", "invites") => "users", ("admin", "replication") => "backups", (_, other) => other, @@ -1059,7 +1020,6 @@ pub fn section_for(lang: Lang, path: &str) -> Option<Section> { .iter() .find(|item| item.key == second) .map_or("", |item| item.key); - // Every page of the user's settings follows their own change stream (see `pages::settings_live`). let live = if first == "settings" { "/settings/events" } else { @@ -1211,8 +1171,6 @@ pub async fn security_headers(cx: &Cx, body: Body, next: Next<'_>) -> Result<Res next.run(cx, body).await } -// Repo browsing helpers: URLs, times and sizes, and the shared tabs and ref selector. - /// Percent-encodes everything except unreserved characters and `/`. pub fn enc(s: &str) -> String { 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 { href } -/// Current time as Unix seconds. -pub fn now_unix() -> i64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) - .unwrap_or(0) -} +pub use forge_core::time::now_unix; /// ISO 8601 UTC timestamp, `YYYY-MM-DDTHH:MM:SSZ`. pub fn iso_time(unix: i64) -> String { @@ -1449,33 +1401,20 @@ pub async fn repo_tabs( let issues_count = open_issues.filter(|n| *n > 0).map(|n| n.to_string()); let pulls = repo_href(&owner, &repo, "pulls", ""); let pulls_count = open_pulls.filter(|n| *n > 0).map(|n| n.to_string()); - let pulls_on = active == "pulls"; let commits = repo_href(&owner, &repo, "commits", &default_branch); let branches = repo_href(&owner, &repo, "branches", ""); let tags = repo_href(&owner, &repo, "tags", ""); let releases = repo_href(&owner, &repo, "releases", ""); let ci = repo_href(&owner, &repo, "ci", ""); - let ci_on = active == "ci"; - // The four code pages sit in a menu after the Code tab, which stays active while one is open. let more_on = matches!( active.as_str(), "commits" | "branches" | "tags" | "releases" ); let code_on = active == "code" || more_on; - let issues_on = active == "issues"; - let commits_on = active == "commits"; - let branches_on = active == "branches"; - let tags_on = active == "tags"; - let releases_on = active == "releases"; - // Shown only to people who may manage the repo (owner, instance admin, or Admin collaborator). let settings = repo_href(&owner, &repo, "settings", ""); - let settings_on = active == "settings"; let discussions_tab = repo_href(&owner, &repo, "discussions", ""); - let discussions_on = active == "discussions"; let wiki_tab = repo_href(&owner, &repo, "wiki", ""); - let wiki_on = active == "wiki"; let security_tab = repo_href(&owner, &repo, "security", ""); - let security_on = active == "security"; Ok(view! { <nav class="repo-tabs" aria-label=(g::t(lang, K::RepositoryNav))> <a class=(tab_class(code_on)) href=(home)> @@ -1486,44 +1425,44 @@ pub async fn repo_tabs( <svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg> </summary> <div class="tab-more-list"> - <a class=(tab_more_class(commits_on)) href=(commits)>(g::t(lang, K::TabCommits))</a> - <a class=(tab_more_class(branches_on)) href=(branches)>(g::t(lang, K::BranchesTitle))</a> - <a class=(tab_more_class(tags_on)) href=(tags)>(g::t(lang, K::TagsTitle))</a> - <a class=(tab_more_class(releases_on)) href=(releases)>(g::t(lang, K::TabReleases))</a> + <a class=(tab_more_class(active == "commits")) href=(commits)>(g::t(lang, K::TabCommits))</a> + <a class=(tab_more_class(active == "branches")) href=(branches)>(g::t(lang, K::BranchesTitle))</a> + <a class=(tab_more_class(active == "tags")) href=(tags)>(g::t(lang, K::TagsTitle))</a> + <a class=(tab_more_class(active == "releases")) href=(releases)>(g::t(lang, K::TabReleases))</a> </div> </details> - <a class=(tab_class(issues_on)) href=(issues)> + <a class=(tab_class(active == "issues")) href=(issues)> (g::t(lang, K::TabIssues)) if let Some(count) = issues_count { " " <span class="tab-count" data-arrive=(count.as_str())>(count.as_str())</span> } </a> - <a class=(tab_class(pulls_on)) href=(pulls)> + <a class=(tab_class(active == "pulls")) href=(pulls)> (g::t(lang, K::TabPulls)) if let Some(count) = pulls_count { " " <span class="tab-count" data-arrive=(count.as_str())>(count.as_str())</span> } </a> - <a class=(tab_class(ci_on)) href=(ci)> + <a class=(tab_class(active == "ci")) href=(ci)> (g::t(lang, K::TabCi)) </a> if discussions { - <a class=(tab_class(discussions_on)) href=(discussions_tab)> + <a class=(tab_class(active == "discussions")) href=(discussions_tab)> (g::t(lang, K::TabDiscussions)) </a> } if wiki { - <a class=(tab_class(wiki_on)) href=(wiki_tab)> + <a class=(tab_class(active == "wiki")) href=(wiki_tab)> (g::t(lang, K::TabWiki)) </a> } if security { - <a class=(tab_class(security_on)) href=(security_tab)> + <a class=(tab_class(active == "security")) href=(security_tab)> (t(lang, Key::Security)) </a> } if can_admin { - <a class=(tab_class(settings_on)) href=(settings)> + <a class=(tab_class(active == "settings")) href=(settings)> (g::t(lang, K::TabSettings)) </a> } @@ -1612,7 +1551,6 @@ pub async fn ref_selector( branches_href: String, tags_href: String, ) -> Result<impl View> { - // A tag shows a tag icon only when it is the current ref and no branch of that name is. let is_tag = !branches.iter().any(|b| b.current) && tags.iter().any(|t| t.current); let none = branches.is_empty() && tags.is_empty(); let now = now_unix(); @@ -1696,20 +1634,6 @@ fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { era * 146_097 + doe - 719_468 } -/// Percent-encodes each byte outside the unreserved set, keeping `/` as the separator. -pub fn url_path(path: &str) -> String { - let mut out = String::with_capacity(path.len()); - for b in path.bytes() { - match b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => { - out.push(char::from(b)); - } - _ => out.push_str(&format!("%{b:02X}")), - } - } - out -} - /// The highlight classes, shared by the route and the page links (which hash them). pub fn highlight_css_text() -> &'static str { highlight_css() @@ -1988,7 +1912,6 @@ mod tests { let csp = csp_for(origin.as_deref()); assert!(csp.contains("img-src 'self' data: https://raw.forge.test:8443;")); assert!(csp.contains("form-action 'self'; frame-ancestors 'none'")); - // A base URL that is not an origin falls back to the plain policy. assert_eq!(origin_of("not a url"), None); assert_eq!(origin_of("ftp://files.test"), None); assert_eq!(origin_of("https://user:pw@files.test"), None); @@ -2019,7 +1942,6 @@ mod tests { assert_eq!(relative_time(Lang::Tr, 0, 3 * 86_400), "3 gün önce"); assert_eq!(relative_time(Lang::Tr, 0, 2 * 2_592_000), "2 ay önce"); assert_eq!(relative_time(Lang::Tr, 0, 365 * 86_400), "1 yıl önce"); - // The client re-words a label from these: the words for the same units, in the same order. assert_eq!( rel_words(Lang::En), "just now|{n} minute ago|{n} minutes ago|{n} hour ago|{n} hours ago|{n} day ago|\ diff --git a/crates/forge-web-app/src/views/review_thread.rs b/crates/forge-web-app/src/views/review_thread.rs index de8d85e..0ac4272 100644 --- a/crates/forge-web-app/src/views/review_thread.rs +++ b/crates/forge-web-app/src/views/review_thread.rs @@ -127,14 +127,7 @@ fn body_parts( struct ThreadParts { hunk: Option<String>, comments: Vec<CommentRow>, - resolve_action: Option<String>, - resolve_value: String, - resolve_label: String, - reply_action: Option<String>, - reply_id: String, - csrf: String, - return_to: String, - lang: Lang, + footer: ThreadFooter, } fn comment_row( @@ -162,26 +155,10 @@ fn comment_row( } } -/// One thread, in English. Pages that know the viewer's language use `review_thread_in`. -/// `show_hunk` adds the stored diff hunk as a code block; `return_to` is `files` or -/// `conversation` and tells the POST routes which tab to redirect to. +/// One thread with its strings in `lang`. `show_hunk` adds the stored diff hunk as a code block; +/// `return_to` is `files` or `conversation` and tells the POST routes which tab to redirect to. #[component] pub async fn review_thread( - cx: &Cx, - thread: Thread, - ctx: ThreadCtx, - show_hunk: bool, - return_to: &str, -) -> Result<impl View> { - Ok(view! { - review_thread_in(lang: Lang::En, thread: thread, ctx: ctx, show_hunk: show_hunk, - return_to: return_to) - }) -} - -/// One thread with its strings in `lang`. See `review_thread` for the arguments. -#[component] -pub async fn review_thread_in( cx: &Cx, lang: Lang, thread: Thread, @@ -218,9 +195,7 @@ pub async fn review_thread_in( }) .collect(); - let parts = ThreadParts { - hunk, - comments, + let footer = ThreadFooter { resolve_action, resolve_value: resolve_value.to_owned(), resolve_label: resolve_label.to_owned(), @@ -230,6 +205,11 @@ pub async fn review_thread_in( return_to, lang, }; + let parts = ThreadParts { + hunk, + comments, + footer, + }; // One `<details>` for every thread: open unless resolved, so a resolved thread starts // 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> { let ThreadParts { hunk, comments, - resolve_action, - resolve_value, - resolve_label, - reply_action, - reply_id, - csrf, - return_to, - lang, + footer, } = parts; - let footer = ThreadFooter { - resolve_action, - resolve_value, - resolve_label, - reply_action, - reply_id, - csrf: csrf.clone(), - return_to: return_to.clone(), - lang, - }; + let csrf = footer.csrf.clone(); + let return_to = footer.return_to.clone(); + let lang = footer.lang; Ok(view! { if let Some(text) = hunk { <pre class="review-hunk"><code>(text.as_str())</code></pre> diff --git a/crates/forge-web-app/src/web_push/crypto.rs b/crates/forge-web-app/src/web_push/crypto.rs index 262e674..3712428 100644 --- a/crates/forge-web-app/src/web_push/crypto.rs +++ b/crates/forge-web-app/src/web_push/crypto.rs @@ -1,7 +1,3 @@ -//! Web Push, on the RustCrypto crates: the RFC 8291 message encryption (aes128gcm content coding, -//! RFC 8188) and the RFC 8292 VAPID authorization (an ES256 JWT). This module converts the -//! base64url values that browsers and the database hold into key types, and builds the request. - use std::time::{SystemTime, UNIX_EPOCH}; use aes_gcm::Aes128Gcm; @@ -17,29 +13,21 @@ use sha2::Sha256; use forge_core::{Error, Result}; -/// The uncompressed P-256 point length: 0x04 followed by X and Y. const POINT_LEN: usize = 65; -/// The record size the body declares (RFC 8188 `rs`). One record holds the whole message. const RECORD_SIZE: u32 = 4096; -/// How long a VAPID token stays valid, in seconds: 12 hours, the most RFC 8292 allows. const VAPID_TTL: u64 = 12 * 60 * 60; -/// How long the push service may hold a message for an offline browser, in seconds. const PUSH_TTL: &str = "43200"; -/// Decodes base64url, with or without padding. pub fn decode_b64(text: &str) -> Result<Vec<u8>> { URL_SAFE_NO_PAD .decode(text.trim_end_matches('=')) .map_err(|_| Error::Invalid("not base64url".into())) } -/// Encodes base64url without padding, the form push services and browsers use. pub fn encode_b64(bytes: &[u8]) -> String { URL_SAFE_NO_PAD.encode(bytes) } -/// A random P-256 private key from the system RNG. A draw that is zero or not below the curve -/// order is rare enough that it is simply drawn again. fn random_secret() -> p256::SecretKey { loop { let mut bytes = [0u8; 32]; @@ -50,29 +38,23 @@ fn random_secret() -> p256::SecretKey { } } -/// A new VAPID private key (32 bytes) from the system RNG. pub fn new_vapid_private() -> [u8; 32] { - let mut out = [0u8; 32]; - out.copy_from_slice(&random_secret().to_bytes()); - out + random_secret().to_bytes().into() } -/// The key pair the VAPID signature is made with, from its 32-byte private scalar. pub fn vapid_key_pair(private: &[u8; 32]) -> Result<SigningKey> { SigningKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into())) } -/// The public key of a VAPID private key, as the uncompressed point in base64url. This is the -/// `applicationServerKey` the browser subscribes with. pub fn vapid_public_key(private: &[u8; 32]) -> Result<String> { - let secret = - p256::SecretKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into()))?; - let point = secret.public_key().to_sec1_point(false); - Ok(encode_b64(point.as_bytes())) + Ok(encode_b64( + vapid_key_pair(private)? + .verifying_key() + .to_sec1_point(false) + .as_bytes(), + )) } -/// The RFC 8291 body for one message. The ephemeral key and the salt are arguments so that a test -/// can fix them; `push_request` draws both at random. fn encrypt_body( ua_public: &p256::PublicKey, auth: &[u8], @@ -86,7 +68,6 @@ fn encrypt_body( let ua_point = ua_public.to_sec1_point(false); let shared = p256::ecdh::diffie_hellman(as_secret.to_nonzero_scalar(), ua_public.as_affine()); - // IKM: the ECDH secret, salted with the auth secret, expanded over both public keys. let mut key_info = b"WebPush: info\0".to_vec(); key_info.extend_from_slice(ua_point.as_bytes()); key_info.extend_from_slice(as_public.as_bytes()); @@ -95,7 +76,6 @@ fn encrypt_body( .expand(&key_info, &mut ikm) .map_err(|e| encryption_error(&e))?; - // The content encryption key and the nonce, from a PRK salted with the message salt. let mut cek = [0u8; 16]; let mut nonce = [0u8; 12]; let prk = Hkdf::<Sha256>::new(Some(salt), &ikm); @@ -104,8 +84,6 @@ fn encrypt_body( prk.expand(b"Content-Encoding: nonce\0", &mut nonce) .map_err(|e| encryption_error(&e))?; - // The plaintext ends with 0x02, the delimiter of the last record. With the 16-byte tag the one - // record must fit in `RECORD_SIZE`. if payload.len() + 1 + 16 > RECORD_SIZE as usize { return Err(Error::Invalid("the push message is too large".into())); } @@ -124,8 +102,6 @@ fn encrypt_body( Ok(body) } -/// The VAPID token (RFC 8292) for a push to `uri`: an ES256 JWT whose audience is the origin of -/// the endpoint. The signature is the raw 64-byte `r || s`, not DER. fn vapid_token(uri: &http::Uri, subject: &str, key_pair: &SigningKey) -> Result<String> { let bad_endpoint = || Error::Invalid("bad push endpoint".into()); 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< )) } -/// Builds the POST for one push: the body is encrypted for the browser's key and auth secret, -/// and the request carries the VAPID `Authorization` for `endpoint`'s origin. `subject` is the -/// contact URL (`mailto:` or `https:`). pub fn push_request( endpoint: &str, p256dh: &[u8], @@ -258,7 +231,6 @@ mod tests { assert_eq!(request.headers()["content-encoding"], "aes128gcm"); assert_eq!(request.headers()["ttl"], "43200"); - // The VAPID header names the push service's origin and carries the instance's public key. let auth_header = request.headers()["authorization"] .to_str() .expect("ascii") @@ -279,7 +251,6 @@ mod tests { assert_eq!(claims["aud"], "https://push.example.test"); assert_eq!(claims["sub"], "mailto:tahinli@example.test"); - // The body is encrypted: it is longer than the plaintext and does not contain it. let body = request.body(); assert!(body.len() > payload.len()); assert!(!body.windows(payload.len()).any(|w| w == payload.as_slice())); diff --git a/crates/forge-web-app/src/web_push/mod.rs b/crates/forge-web-app/src/web_push/mod.rs index e09a9a7..62d4917 100644 --- a/crates/forge-web-app/src/web_push/mod.rs +++ b/crates/forge-web-app/src/web_push/mod.rs @@ -1,13 +1,3 @@ -//! Web Push: a notification for the inbox also reaches the user's devices when no tab is open. A -//! browser (or an installed app) subscribes through the service worker, the server keeps the -//! subscription, and [`queue`] sends the message to every device of a user. -//! -//! Delivery never blocks the caller: [`queue`] spawns the work, which looks up the user's devices, -//! encrypts the message per device (RFC 8291), signs the request with the instance's VAPID key -//! (RFC 8292) and posts it to the push service. A device the service reports gone (404 or 410) is -//! removed. Every change to a user's devices is announced on [`PushLive`], so an open settings page -//! refreshes through its event stream. - pub mod crypto; use std::sync::OnceLock; @@ -23,13 +13,9 @@ use crate::i18n::{self, Lang, misc, push as text}; use crate::state::AppState; use crate::webhooks::client::{WebhookPolicy, policy_client, validate_url}; -/// How long one push request may take before it counts as failed. const SEND_TIMEOUT: Duration = Duration::from_secs(15); -/// Longest body text in a notification, in characters. const BODY_CHARS: usize = 140; -/// Announces changes to a user's devices to the settings pages that show them. Only the event -/// stream reads it; nothing here is stored, and a second server process would not see it. pub struct PushLive { tx: broadcast::Sender<String>, } @@ -43,59 +29,44 @@ impl Default for PushLive { } impl PushLive { - /// Says that the devices of `user_id` changed. Nobody listening is fine. pub fn publish(&self, user_id: &str) { let _ = self.tx.send(user_id.to_owned()); } - /// A receiver for every change, from every user. A stream filters for its own user. pub fn subscribe(&self) -> broadcast::Receiver<String> { self.tx.subscribe() } } -/// What a notification says. Built per recipient, in the recipient's language. #[derive(Clone)] pub enum Alert { - /// Activity on an issue or pull request the user hears about. Activity { - /// `owner/repo`. repo: String, number: i64, title: String, - /// The verb of the activity (`misc::K::VerbOpened` and so on). verb: misc::K, actor: Option<String>, - /// The relative link the notification opens. url: String, - /// The thread id. A newer notification for the same thread replaces the older one. thread: String, }, - /// New security advisory alerts on a repo. Advisories { repo: String, count: u64, url: String, }, - /// A site admin alert. Admin { subject: String, detail: String }, - /// The test button. Test, } -/// The JSON the service worker reads. Small, and nothing in it is a secret. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct Message { pub title: String, pub body: String, - /// A relative link on this origin. pub url: String, - /// Notifications with the same tag replace each other on the device. pub tag: String, } impl Alert { - /// The message for a recipient who reads `lang`. pub fn message(&self, lang: Lang) -> Message { match self { Alert::Activity { @@ -137,7 +108,6 @@ impl Alert { } } -/// Shortens text to the body limit, in characters, one line. fn clip(text: &str) -> String { let one_line: String = text.split_whitespace().collect::<Vec<_>>().join(" "); if one_line.chars().count() <= BODY_CHARS { @@ -148,9 +118,7 @@ fn clip(text: &str) -> String { short } -/// A relative link only. The service worker opens it on this origin, so anything that could leave -/// the origin (a scheme, a protocol-relative `//host`) falls back to the notifications page. -pub fn safe_url(url: &str) -> String { +fn safe_url(url: &str) -> String { if url.starts_with('/') && !url.starts_with("//") && !url.contains('\\') { url.to_owned() } else { @@ -158,12 +126,10 @@ pub fn safe_url(url: &str) -> String { } } -/// A short label for a device, from its User-Agent: "Chrome on Android", "Safari on iPhone". pub fn agent_label(user_agent: &str) -> String { agent_label_in(Lang::En, user_agent) } -/// [`agent_label`] in the viewer's language: "Chrome on Linux", "Linux üzerinde Chrome". pub fn agent_label_in(lang: Lang, user_agent: &str) -> String { let os = if user_agent.contains("iPhone") { "iPhone" @@ -190,7 +156,10 @@ pub fn agent_label_in(lang: Lang, user_agent: &str) -> String { "Opera" } else if user_agent.contains("Firefox/") { "Firefox" - } else if user_agent.contains("Chrome/") || user_agent.contains("Chromium/") { + } else if user_agent.contains("Chrome/") + || user_agent.contains("Chromium/") + || user_agent.contains("CriOS/") + { "Chrome" } else if user_agent.contains("Safari/") { "Safari" @@ -206,9 +175,6 @@ pub fn agent_label_in(lang: Lang, user_agent: &str) -> String { } } -/// The HTTP client for push requests: the webhook outbound policy (no internal addresses, no -/// redirects, no proxy). An endpoint is any URL a signed-in browser sent, so it gets the same -/// treatment as a hook URL. Built once; the policy comes from the config, which does not change. fn client(policy: &WebhookPolicy) -> Option<&'static reqwest::Client> { static CLIENT: OnceLock<Option<reqwest::Client>> = OnceLock::new(); CLIENT @@ -224,15 +190,11 @@ fn client(policy: &WebhookPolicy) -> Option<&'static reqwest::Client> { .as_ref() } -/// The instance's VAPID key pair. The private key is stored sealed with the instance key; the -/// first call creates the pair. pub struct VapidKeys { pub private: [u8; 32], - /// The public key, base64url. The browser subscribes with it. pub public: String, } -/// The VAPID keys of this instance, creating and storing them on first use. pub async fn vapid_keys(state: &AppState) -> Result<VapidKeys> { let (public, sealed) = match state.store.web_push_keys().await? { Some(pair) => pair, @@ -250,7 +212,6 @@ pub async fn vapid_keys(state: &AppState) -> Result<VapidKeys> { Ok(VapidKeys { private, public }) } -/// The contact the push service may use about this instance: the base URL when it is https. fn subject(base_url: &str) -> String { let base = base_url.trim_end_matches('/'); if base.starts_with("https://") { @@ -260,17 +221,14 @@ fn subject(base_url: &str) -> String { } } -/// What the push service answered for one device. #[derive(Debug, PartialEq, Eq)] -pub enum Outcome { +enum Outcome { Delivered, - /// 404 or 410: the subscription is gone and the device must be forgotten. Gone, Failed(String), } -/// Encrypts `payload` for one device and posts it to the device's push service. -pub async fn send_one( +async fn send_one( client: &reqwest::Client, policy: &WebhookPolicy, keys: &VapidKeys, @@ -278,7 +236,6 @@ pub async fn send_one( sub: &PushSubscription, payload: &[u8], ) -> Outcome { - // Checked again on each send: an address literal never reaches the resolver's filter. if let Err(e) = validate_url(&sub.endpoint, policy) { return Outcome::Failed(e.to_string()); } @@ -313,7 +270,6 @@ pub async fn send_one( } } -/// Queues `alert` for every device of `user_id`. Returns at once: the work runs on a spawned task. pub fn queue(state: &AppState, user_id: &str, alert: Alert) { let state = state.clone(); let user_id = user_id.to_owned(); @@ -324,12 +280,10 @@ pub fn queue(state: &AppState, user_id: &str, alert: Alert) { }); } -/// Sends `alert` to every device of `user_id` now and returns how many devices there are. Devices -/// the push service reports gone are removed. [`queue`] is the caller's entry point. -pub async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result<usize> { +async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result<()> { let devices = state.store.push_subscriptions(user_id).await?; if devices.is_empty() { - return Ok(0); + return Ok(()); } let lang = match state.store.user_by_id(user_id).await? { 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 for device in &devices { match send_one(client, &policy, &keys, &subject, device, &payload).await { Outcome::Delivered => { - state.store.mark_push_delivered(&device.id).await?; + if let Err(e) = state.store.mark_push_delivered(&device.id).await { + tracing::warn!( + error = %e, + device = %device.id, + "web push: the delivery stamp was not saved" + ); + } state.push_live.publish(user_id); } Outcome::Gone => { - state.store.delete_push_endpoint(&device.endpoint).await?; + if let Err(e) = state.store.delete_push_endpoint(&device.endpoint).await { + tracing::warn!( + error = %e, + device = %device.id, + "web push: the gone device was not removed" + ); + } state.push_live.publish(user_id); } Outcome::Failed(reason) => { @@ -358,7 +324,7 @@ pub async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result<u } } } - Ok(devices.len()) + Ok(()) } #[cfg(test)] @@ -449,8 +415,6 @@ mod tests { assert_eq!(rx.try_recv().expect("event"), "tahinli"); } - /// A local stand-in for a push service: `/gone` answers 410, `/ok` answers 201, and each - /// request is read in full (headers and body) before it is answered. async fn mock_push_service() -> std::net::SocketAddr { use tokio::io::{AsyncReadExt, AsyncWriteExt}; let listener = tokio::net::TcpListener::bind("127.0.0.1:0") @@ -523,7 +487,6 @@ mod tests { async fn a_device_the_service_reports_gone_is_removed_and_a_live_one_is_kept() { let dir = tempfile::tempdir().expect("tempdir"); let mut state = crate::test_support::test_state(dir.path()).await; - // The mock push service is on loopback over http, which the policy refuses by default. let mut config = crate::test_support::test_config(dir.path()); config.webhooks = forge_core::config::WebhookConfig { allow_http: true, @@ -538,13 +501,15 @@ mod tests { let addr = mock_push_service().await; let gone = format!("http://{addr}/gone"); let ok = format!("http://{addr}/ok"); + let gone_device = device(gone.clone()); + let ok_device = device(ok.clone()); state .store .save_push_subscription( &user.id, &gone, - &device(gone.clone()).p256dh, - &device(gone.clone()).auth, + &gone_device.p256dh, + &gone_device.auth, "Chrome on Linux", ) .await @@ -554,17 +519,16 @@ mod tests { .save_push_subscription( &user.id, &ok, - &device(ok.clone()).p256dh, - &device(ok.clone()).auth, + &ok_device.p256dh, + &ok_device.auth, "Chrome on Linux", ) .await .expect("save ok"); - let sent = deliver(&state, &user.id, &Alert::Test) + deliver(&state, &user.id, &Alert::Test) .await .expect("deliver"); - assert_eq!(sent, 2); let left = state .store .push_subscriptions(&user.id) @@ -615,7 +579,6 @@ mod tests { send(format!("http://{addr}/gone"), open).await, Outcome::Gone ); - // The default policy refuses an internal address before anything is sent. let strict = WebhookPolicy::from_config(&forge_core::config::WebhookConfig::default()) .expect("policy"); assert!(matches!( diff --git a/crates/forge-web-app/src/webhooks/client.rs b/crates/forge-web-app/src/webhooks/client.rs index 5f95b21..e59357b 100644 --- a/crates/forge-web-app/src/webhooks/client.rs +++ b/crates/forge-web-app/src/webhooks/client.rs @@ -80,7 +80,6 @@ impl WebhookPolicy { /// True when the address falls inside a CIDR network in the allow list. pub fn ip_allowed(&self, ip: IpAddr) -> bool { - // An IPv4-mapped address matches an IPv4 network, so check both forms. let mapped = ip.to_canonical(); self.allowed_hosts.iter().any(|entry| match entry { AllowEntry::Net(net) => net.contains(&ip) || net.contains(&mapped), @@ -131,7 +130,6 @@ pub fn validate_url(url: &str, policy: &WebhookPolicy) -> Result<Url, UrlError> if !parsed.username().is_empty() || parsed.password().is_some() { return Err(UrlError::Userinfo); } - // An explicit port is parsed by `Url` (so >65535 fails above); only 0 needs rejecting here. if parsed.port() == Some(0) { return Err(UrlError::BadPort); } @@ -139,7 +137,6 @@ pub fn validate_url(url: &str, policy: &WebhookPolicy) -> Result<Url, UrlError> if host.is_empty() { return Err(UrlError::MissingHost); } - // IPv6 literals come back bracketed, e.g. "[::1]". let bare = host.trim_start_matches('[').trim_end_matches(']'); if let Ok(ip) = bare.parse::<IpAddr>() { check_literal(ip, policy)?; @@ -156,7 +153,8 @@ fn check_literal(ip: IpAddr, policy: &WebhookPolicy) -> Result<(), UrlError> { } /// True for addresses a webhook must not reach by default: loopback, private, link-local, CGNAT, -/// unspecified, multicast, broadcast, documentation and reserved ranges. IPv4 addresses embedded +/// unspecified, multicast, broadcast, documentation and reserved ranges (including 0.0.0.0/8, +/// 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 /// in IPv6 (mapped, compatible, NAT64, 6to4, Teredo) are judged by the embedded IPv4 address. pub fn is_forbidden_ip(ip: IpAddr) -> bool { match ip { @@ -174,11 +172,11 @@ fn is_forbidden_v4(ip: Ipv4Addr) -> bool { || ip.is_multicast() || ip.is_broadcast() || ip.is_documentation() - || a == 0 // 0.0.0.0/8 - || (a == 100 && (b & 0xc0) == 64) // 100.64.0.0/10 CGNAT - || (a == 192 && b == 0 && c == 0) // 192.0.0.0/24 IETF protocol assignments - || (a == 198 && (b & 0xfe) == 18) // 198.18.0.0/15 benchmarking - || a >= 240 // 240.0.0.0/4 reserved + || a == 0 + || (a == 100 && (b & 0xc0) == 64) + || (a == 192 && b == 0 && c == 0) + || (a == 198 && (b & 0xfe) == 18) + || a >= 240 } fn is_forbidden_v6(ip: Ipv6Addr) -> bool { @@ -189,27 +187,22 @@ fn is_forbidden_v6(ip: Ipv6Addr) -> bool { if ip.is_loopback() || ip.is_unspecified() || ip.is_multicast() { return true; } - if (s[0] & 0xfe00) == 0xfc00 // fc00::/7 unique local - || (s[0] & 0xffc0) == 0xfe80 // fe80::/10 link-local - || (s[0] == 0x2001 && s[1] == 0x0db8) // 2001:db8::/32 documentation + if (s[0] & 0xfe00) == 0xfc00 + || (s[0] & 0xffc0) == 0xfe80 + || (s[0] == 0x2001 && s[1] == 0x0db8) || (s[0] == 0x0100 && s[1] == 0 && s[2] == 0 && s[3] == 0) - // 100::/64 discard { return true; } - // IPv4-compatible ::/96 (deprecated). if s[..6] == [0; 6] { return is_forbidden_v4(v4_from(s[6], s[7])); } - // NAT64 well-known prefix 64:ff9b::/96, and the local-use 64:ff9b:1::/48. if s[0] == 0x0064 && s[1] == 0xff9b { return s[2] == 0x0001 || (s[2..6] == [0; 4] && is_forbidden_v4(v4_from(s[6], s[7]))); } - // 6to4 2002::/16 embeds the IPv4 address in the second and third segments. if s[0] == 0x2002 { return is_forbidden_v4(v4_from(s[1], s[2])); } - // Teredo 2001::/32 embeds the server address and an obfuscated client address. if s[0] == 0x2001 && s[1] == 0 { let client = Ipv4Addr::from(!u32::from(v4_from(s[6], s[7]))); return is_forbidden_v4(v4_from(s[2], s[3])) || is_forbidden_v4(client); @@ -291,18 +284,15 @@ pub struct HookClient { impl HookClient { pub fn new(policy: WebhookPolicy) -> reqwest::Result<Arc<Self>> { - let policy = Arc::new(policy); - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .connect_timeout(Duration::from_secs(10)) - .timeout(Duration::from_secs(20)) - .dns_resolver(Arc::new(PolicyResolver { - policy: policy.clone(), - })) - .user_agent(concat!("forge-hookshot/", env!("CARGO_PKG_VERSION"))) - .no_proxy() - .build()?; - Ok(Arc::new(Self { client, policy })) + let client = policy_client( + policy.clone(), + Duration::from_secs(20), + concat!("forge-hookshot/", env!("CARGO_PKG_VERSION")), + )?; + Ok(Arc::new(Self { + client, + policy: Arc::new(policy), + })) } /// POSTs `body` to `url`. Never follows redirects, and reads at most [`MAX_BODY_BYTES`] of the response. @@ -377,11 +367,7 @@ impl HookClient { /// Signs a delivery body: `sha256=` followed by the hex HMAC-SHA256 of `body` under `secret`. pub fn sign(secret: &[u8], body: &[u8]) -> String { - // HMAC accepts keys of any length, so the error branch is unreachable. - let mut mac = match HmacSha256::new_from_slice(secret) { - Ok(mac) => mac, - Err(_) => return String::new(), - }; + let mut mac = HmacSha256::new_from_slice(secret).expect("HMAC takes keys of any length"); mac.update(body); format!("sha256={}", hex::encode(mac.finalize().into_bytes())) } @@ -537,7 +523,6 @@ mod tests { #[test] fn sign_matches_rfc4231_case_2() { - // RFC 4231 test case 2: key "Jefe", data "what do ya want for nothing?". assert_eq!( sign(b"Jefe", b"what do ya want for nothing?"), "sha256=5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" @@ -607,7 +592,6 @@ mod tests { #[tokio::test] async fn send_accepts_allowed_cidr_and_hostname() { - // (name, allowed entry, host used in the URL); both must deliver the same response. let cases = [ ("loopback cidr", "127.0.0.1/32", "127.0.0.1"), ("hostname", "localhost", "localhost"), diff --git a/crates/forge-web-app/src/webhooks/emit.rs b/crates/forge-web-app/src/webhooks/emit.rs index a21e688..8ee5397 100644 --- a/crates/forge-web-app/src/webhooks/emit.rs +++ b/crates/forge-web-app/src/webhooks/emit.rs @@ -486,13 +486,17 @@ async fn new_commits( } else { MAX_NEW_REF_COMMITS }; - match forge_git::history::new_commits(&state.git, &dir, old, new, max).await { - Ok(commits) => { - let total = commits.len(); - (commits, total) - } + let commits = match forge_git::history::new_commits(&state.git, &dir, old, new, max).await { + Ok(commits) => commits, Err(e) => { tracing::error!(error = %e, repo_id = %repo.id, "webhooks: listing push commits failed"); + return (Vec::new(), 0); + } + }; + match forge_git::history::count_new_commits(&state.git, &dir, old, new).await { + Ok(total) => (commits, total as usize), + Err(e) => { + tracing::error!(error = %e, repo_id = %repo.id, "webhooks: counting push commits failed"); (Vec::new(), 0) } } diff --git a/crates/forge-web-app/src/webhooks/payload.rs b/crates/forge-web-app/src/webhooks/payload.rs index 68b448c..732fa7e 100644 --- a/crates/forge-web-app/src/webhooks/payload.rs +++ b/crates/forge-web-app/src/webhooks/payload.rs @@ -53,7 +53,7 @@ pub fn sender(id: &str, username: &str) -> Value { /// `issues` payload: `issue`. The emit side adds `label` or `assignee` for those actions. pub fn issues(base_url: &str, repo: &Repo, issue: &Issue) -> Value { - json!({ "issue": issue_object(base_url, repo, issue, false) }) + json!({ "issue": issue_object(issue, &item_url(base_url, repo, "issues", issue.number)) }) } /// `pull_request` payload: `number` and `pull_request`. @@ -80,7 +80,7 @@ pub fn issue_comment( issue.number, ); json!({ - "issue": issue_object(base_url, repo, issue, pull), + "issue": issue_object(issue, &page), "comment": { "id": comment.id, "body": comment.body, @@ -154,18 +154,13 @@ pub fn ping(hook_id: &str) -> Value { }) } -fn issue_object(base_url: &str, repo: &Repo, issue: &Issue, pull: bool) -> Value { +fn issue_object(issue: &Issue, html_url: &str) -> Value { json!({ "number": issue.number, "title": issue.title, "body": issue.body, "state": issue.state.as_str(), - "html_url": item_url( - base_url, - repo, - if pull { "pulls" } else { "issues" }, - issue.number, - ), + "html_url": html_url, }) } diff --git a/crates/forge-web-pages/src/pages/issue_parts.rs b/crates/forge-web-pages/src/pages/issue_parts.rs index e36fa6c..57be255 100644 --- a/crates/forge-web-pages/src/pages/issue_parts.rs +++ b/crates/forge-web-pages/src/pages/issue_parts.rs @@ -29,7 +29,7 @@ use crate::pages::tree::link_context; use crate::render::markdown::{LinkContext, render_markdown}; use crate::state::AppState; use crate::views::parts::{confirm_act, post_act, reveal}; -use crate::views::review_thread::{ThreadCtx, review_thread_in}; +use crate::views::review_thread::{ThreadCtx, review_thread}; use crate::views::user_facing_message; use crate::views::{ 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 <div class="issue-item-body markdown-body">(Unescaped::new_unchecked(body))</div> } for thread in threads.into_iter() { - review_thread_in(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: true, return_to: "conversation") + review_thread(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: true, return_to: "conversation") } </article> }) diff --git a/crates/forge-web-repo/src/pages/branches.rs b/crates/forge-web-repo/src/pages/branches.rs index 0fb296e..642b7d7 100644 --- a/crates/forge-web-repo/src/pages/branches.rs +++ b/crates/forge-web-repo/src/pages/branches.rs @@ -31,8 +31,7 @@ use crate::post_update::after_ref_update; use crate::state::AppState; use crate::views::commit_line::commit_line; use crate::views::parts::{confirm_act, reveal}; -use crate::views::url_path; -use crate::views::{alert, iso_time, now_unix, relative_time, repo_href, shell}; +use crate::views::{alert, enc, iso_time, now_unix, relative_time, repo_href, shell}; path_param!(owner); path_param!(repo); @@ -222,7 +221,7 @@ async fn branches_page(cx: &Cx) -> Result<impl View> { &repo.owner_name, &repo.name, "compare", - &url_path(&format!("{}...{}", repo.default_branch, info.name)), + &enc(&format!("{}...{}", repo.default_branch, info.name)), )); } } diff --git a/crates/forge-web-repo/src/pages/commits.rs b/crates/forge-web-repo/src/pages/commits.rs index 19ee84a..8f2d518 100644 --- a/crates/forge-web-repo/src/pages/commits.rs +++ b/crates/forge-web-repo/src/pages/commits.rs @@ -28,7 +28,7 @@ use crate::signatures::{self, SigBadge}; use crate::state::AppState; use crate::views::commit_line::commit_line; use crate::views::commit_status::{StatusLang, StatusSummary, commit_status, status_list}; -use crate::views::{shell, url_path}; +use crate::views::{enc, shell}; path_param!(owner); path_param!(repo); @@ -267,7 +267,7 @@ async fn commits_page(cx: &Cx) -> Result<impl View> { Some(p) => format!("{ref_name}/{p}"), None => ref_name.clone(), }; - let base = format!("/{owner_name}/{repo_name}/commits/{}", url_path(&spec)); + let base = format!("/{owner_name}/{repo_name}/commits/{}", enc(&spec)); let href_for = |n: u32| { if n <= 1 { base.clone() @@ -286,11 +286,7 @@ async fn commits_page(cx: &Cx) -> Result<impl View> { .store .statuses_for_many_rows(&ctx.repo.id, &oids) .await?; - let shown_oids: Vec<String> = commits - .iter() - .take(PAGE_SIZE) - .map(|info| info.oid.clone()) - .collect(); + let shown_oids: Vec<String> = commits.iter().map(|info| info.oid.clone()).collect(); let sigs = signatures::badges(state, &ctx.repo, &shown_oids).await; let rows: Vec<CommitRow> = commits .iter() @@ -302,7 +298,7 @@ async fn commits_page(cx: &Cx) -> Result<impl View> { .collect(); let empty = rows.is_empty(); let title = format!("{owner_name}/{repo_name}"); - let clear_href = format!("/{owner_name}/{repo_name}/commits/{}", url_path(&ref_name)); + let clear_href = format!("/{owner_name}/{repo_name}/commits/{}", enc(&ref_name)); let has_filter = filter.is_some(); let filter_text = filter.unwrap_or_default(); let page_label = i18n::page_label(lang, page_no); @@ -411,7 +407,7 @@ mod tests { use crate::i18n::Lang; use crate::test_support::fixture::{Fixture, OWNER, REPO, get, git}; use crate::views::relative_time; - use crate::views::url_path; + use crate::views::enc; #[test] fn dates_and_relative_units_format() { @@ -426,7 +422,7 @@ mod tests { relative_time(Lang::En, 10_000 - 86_400, 10_000), "1 day ago" ); - assert_eq!(url_path("a b/c#d"), "a%20b/c%23d"); + assert_eq!(enc("a b/c#d"), "a%20b/c%23d"); } /// Pages through history (50, then 5), and refuses bad pages and unknown refs. diff --git a/crates/forge-web-repo/src/pages/compare.rs b/crates/forge-web-repo/src/pages/compare.rs index 94bfc3e..160ecde 100644 --- a/crates/forge-web-repo/src/pages/compare.rs +++ b/crates/forge-web-repo/src/pages/compare.rs @@ -39,8 +39,7 @@ use crate::templates; use crate::views::commit_line::commit_line; use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section}; use crate::views::parts::reveal; -use crate::views::url_path; -use crate::views::{alert, repo_href, shell, user_facing_message}; +use crate::views::{alert, enc, repo_href, shell, user_facing_message}; use crate::webhooks::emit::{Sender, emit_pull}; path_param!(owner); @@ -263,7 +262,7 @@ async fn compare_view( let compare_path = format!( "/{owner}/{name}/compare/{}", - url_path(&format!("{base}...{head}")) + enc(&format!("{base}...{head}")) ); let mut opts = DiffOpts::from_cx( cx, @@ -476,7 +475,7 @@ async fn compare_picker(cx: &Cx) -> Result<impl View> { "/{}/{}/compare/{}", ctx.repo.owner_name, ctx.repo.name, - url_path(&format!("{base}...{head}")) + enc(&format!("{base}...{head}")) ); return Err(see_other(target).into()); }