From 9a27aab6f6855aee2e532e037a5eed9965863689 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 15:57:23 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20harden:=20deleting=20or=20restor?= =?UTF-8?q?ing=20a=20PR's=20head=20branch=20from=20the=20PR=20page=20obeys?= =?UTF-8?q?=20"restrict=20push"=20like=20a=20git=20push=20does;=20the=20me?= =?UTF-8?q?rge=20form=20carries=20the=20head=20commit=20the=20page=20showe?= =?UTF-8?q?d=20and=20a=20PR=20that=20got=20new=20commits=20since=20is=20no?= =?UTF-8?q?t=20merged;=20at=20most=204=20source=20archives=20are=20built?= =?UTF-8?q?=20at=20once=20(503=20with=20Retry-After=20past=20that);=20acco?= =?UTF-8?q?unts=20can=20have=20at=20most=20100=20SSH=20keys=20and=20100=20?= =?UTF-8?q?tokens,=20repos=20at=20most=2020=20webhooks;=20a=20direct=20rep?= =?UTF-8?q?o=20move=20voids=20a=20pending=20transfer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- crates/forge-core/src/store/mod.rs | 46 ++++++++++++++ crates/forge-core/src/store/webhooks.rs | 11 ++++ crates/forge-web/src/i18n/pulls_review.rs | 8 +++ crates/forge-web/src/pages/archive.rs | 30 ++++++++- crates/forge-web/src/pages/pull_branch.rs | 41 ++++++++++-- crates/forge-web/src/pages/pull_view.rs | 10 ++- crates/forge-web/src/pages/pulls_merge.rs | 8 +++ crates/forge-web/src/pages/repo_webhooks.rs | 62 ++++++++++++------- crates/forge-web/src/pages/settings_tokens.rs | 39 +++++++----- 9 files changed, 207 insertions(+), 48 deletions(-) diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 949b38b..d4d2880 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -71,6 +71,10 @@ const BUSY_TIMEOUT: Duration = Duration::from_millis(5000); pub const MAX_ABOUT_CHARS: usize = 2000; /// Longest accepted display name, in characters. pub const MAX_DISPLAY_NAME_CHARS: usize = 80; +/// Most SSH keys one account can have. +pub const MAX_SSH_KEYS: i64 = 100; +/// Most access tokens one account can have, expired ones included until deleted. +pub const MAX_TOKENS: i64 = 100; /// Checks a display name. Surrounding whitespace is trimmed; an empty result means "no name" and /// gives `None`. Control characters are rejected; any other Unicode text is allowed. @@ -465,6 +469,14 @@ impl Store { last_used_at: None, }; let conn = self.inner.conn.lock().await; + refuse_at_limit( + &conn, + "SELECT COUNT(*) FROM ssh_keys WHERE user_id = ?1", + user_id, + MAX_SSH_KEYS, + "an account can have at most 100 SSH keys", + ) + .await?; conn.execute( "INSERT INTO ssh_keys (id, user_id, title, algorithm, key_blob, fingerprint, created_at) \ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", @@ -553,6 +565,14 @@ impl Store { last_used_at: None, }; let conn = self.inner.conn.lock().await; + refuse_at_limit( + &conn, + "SELECT COUNT(*) FROM access_tokens WHERE user_id = ?1", + user_id, + MAX_TOKENS, + "an account can have at most 100 access tokens", + ) + .await?; conn.execute( "INSERT INTO access_tokens (id, user_id, name, token_hash, scopes, expires_at, created_at) \ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", @@ -1000,6 +1020,24 @@ where Ok(out) } +/// Refuses with `Invalid(message)` once `count_sql` (one `?1` parameter) counts `max` rows or more. +/// Run under the write lock, before the insert it guards, so two inserts cannot both pass. +async fn refuse_at_limit( + conn: &Connection, + count_sql: &str, + key: &str, + max: i64, + message: &str, +) -> Result<()> { + let count = fetch_opt(conn, count_sql, (key.to_string(),), |row| col_int(row, 0)) + .await? + .unwrap_or(0); + if count >= max { + return Err(Error::Invalid(message.to_string())); + } + Ok(()) +} + async fn fetch_opt( conn: &Connection, sql: &str, @@ -1496,6 +1534,14 @@ impl Store { ) .await .map_err(db_err)?; + // A transfer the old owner offered is void once the repo has moved: its target + // must not be able to accept it later and take the repo from the new owner. + tx.execute( + "DELETE FROM repo_transfers WHERE repo_id = ?1", + (id.clone(),), + ) + .await + .map_err(db_err)?; } Ok(()) } diff --git a/crates/forge-core/src/store/webhooks.rs b/crates/forge-core/src/store/webhooks.rs index a3f8ff9..8e09b31 100644 --- a/crates/forge-core/src/store/webhooks.rs +++ b/crates/forge-core/src/store/webhooks.rs @@ -172,6 +172,9 @@ async fn insert_delivery(conn: &Connection, d: &Delivery) -> Result<()> { Ok(()) } +/// Most webhooks one repository can have. +pub const MAX_WEBHOOKS: i64 = 20; + impl Store { /// Creates a hook. `secret_sealed` is the `secret::seal` output as bytes. The hook starts /// with `created_at == updated_at`. @@ -206,6 +209,14 @@ impl Store { Value::Text(now), ]; let conn = self.inner.conn.lock().await; + super::refuse_at_limit( + &conn, + "SELECT COUNT(*) FROM webhooks WHERE repo_id = ?1", + repo_id, + MAX_WEBHOOKS, + "a repository can have at most 20 webhooks", + ) + .await?; conn.execute( "INSERT INTO webhooks (id, repo_id, url, secret_sealed, events, active, created_by, \ created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", diff --git a/crates/forge-web/src/i18n/pulls_review.rs b/crates/forge-web/src/i18n/pulls_review.rs index e4ea19d..62aa9f5 100644 --- a/crates/forge-web/src/i18n/pulls_review.rs +++ b/crates/forge-web/src/i18n/pulls_review.rs @@ -61,6 +61,7 @@ pub enum K { ErrUpToDate, ErrFfImpossible, ErrBaseMoved, + ErrHeadMoved, ErrAlreadyMerged, ErrNotOpen, ErrHeadMissing, @@ -242,6 +243,12 @@ pub fn t(lang: Lang, key: K) -> &'static str { (ErrBaseMoved, Tr) => { "Birleştirme sırasında taban dal değişti. Bu sayfayı yenileyip yeniden deneyin." } + (ErrHeadMoved, En) => { + "New commits were pushed to this pull request after the page loaded. Review them, then merge again." + } + (ErrHeadMoved, Tr) => { + "Sayfa yüklendikten sonra bu çekme isteğine yeni commitler gönderildi. Onları inceleyip yeniden birleştirin." + } (ErrAlreadyMerged, En) => "This pull request is already merged.", (ErrAlreadyMerged, Tr) => "Bu çekme isteği zaten birleştirilmiş.", (ErrNotOpen, En) => "This pull request is closed, so it cannot be merged.", @@ -489,6 +496,7 @@ pub const ALL: &[K] = &[ K::ErrUpToDate, K::ErrFfImpossible, K::ErrBaseMoved, + K::ErrHeadMoved, K::ErrAlreadyMerged, K::ErrNotOpen, K::ErrHeadMissing, diff --git a/crates/forge-web/src/pages/archive.rs b/crates/forge-web/src/pages/archive.rs index 39dadca..35a8f92 100644 --- a/crates/forge-web/src/pages/archive.rs +++ b/crates/forge-web/src/pages/archive.rs @@ -2,6 +2,7 @@ //! stdout is streamed as the response body. use std::process::Stdio; +use std::sync::{Arc, OnceLock}; use forge_git::browse; use forge_git::history::{self, ArchiveFormat}; @@ -13,6 +14,7 @@ use http_body::Frame; use http_body_util::StreamBody; use tokio::io::AsyncReadExt; use tokio::process::Child; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use tokio_util::io::ReaderStream; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -24,6 +26,16 @@ use crate::pages::commits::blocking; use crate::pages::repo_ctx::load_repo; use crate::state::AppState; +/// Archives built at once, server-wide. Each one is a `git archive` that compresses the whole +/// tree, so a burst of downloads of a big repo would otherwise take every core. +const MAX_CONCURRENT_ARCHIVES: usize = 4; + +/// Permits for running archives. A permit is held until its `git archive` exits. +fn archive_slots() -> &'static Arc { + static SLOTS: OnceLock> = OnceLock::new(); + SLOTS.get_or_init(|| Arc::new(Semaphore::new(MAX_CONCURRENT_ARCHIVES))) +} + path_param!(owner); path_param!(repo); path_param!(*rest); @@ -77,6 +89,17 @@ async fn archive(cx: &Cx) -> Result { return Err(not_found().into()); }; + // All slots busy: ask the client to come back rather than queueing work behind them. + let Ok(permit) = archive_slots().clone().try_acquire_owned() else { + let mut res = Response::new(Body::from( + "busy building other archives, try again shortly", + )); + *res.status_mut() = http::StatusCode::SERVICE_UNAVAILABLE; + res.headers_mut() + .insert(http::header::RETRY_AFTER, HeaderValue::from_static("10")); + return Ok(res); + }; + let prefix = archive_prefix(&ctx.repo.name, reference, &commit); let (content_type, extension) = match format { ArchiveFormat::TarGz => ("application/gzip", "tar.gz"), @@ -92,7 +115,7 @@ async fn archive(cx: &Cx) -> Result { let Some(stdout) = child.stdout.take() else { return Err(std::io::Error::other("git archive stdout missing").into()); }; - tokio::spawn(reap(child)); + tokio::spawn(reap(child, permit)); let chunks = ReaderStream::new(stdout).map_ok(Frame::data); let mut res = Response::new(Body::new(StreamBody::new(chunks))); @@ -107,8 +130,9 @@ async fn archive(cx: &Cx) -> Result { Ok(res) } -/// Drains stderr into the log and waits for `git archive`, so no zombie is left behind. -async fn reap(mut child: Child) { +/// Drains stderr into the log and waits for `git archive`, so no zombie is left behind. The slot +/// is given back when git exits (a client that goes away closes stdout, which ends git). +async fn reap(mut child: Child, _permit: OwnedSemaphorePermit) { let mut stderr = Vec::new(); if let Some(mut pipe) = child.stderr.take() { let _ = pipe.read_to_end(&mut stderr).await; diff --git a/crates/forge-web/src/pages/pull_branch.rs b/crates/forge-web/src/pages/pull_branch.rs index ea1bd28..1007bb7 100644 --- a/crates/forge-web/src/pages/pull_branch.rs +++ b/crates/forge-web/src/pages/pull_branch.rs @@ -28,6 +28,7 @@ use topcoat::view::{View, component, view}; use crate::auth::require_csrf; use crate::i18n::Lang; use crate::i18n::pulls::{self as g, K}; +use crate::internal::may_push_directly; use crate::pages::issue_parts::parse_number; use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::post_update::after_ref_update; @@ -165,7 +166,7 @@ async fn delete_branch( user: &User, pr: &PullRequest, ) -> forge_core::Result> { - if let Some(code) = deletion_refusal(state, head, &pr.head_branch).await? { + if let Some(code) = deletion_refusal(state, head, &user.id, &pr.head_branch).await? { return Ok(Some(code)); } let path = repo_path(&state.git.data_dir, &head.id)?; @@ -201,6 +202,9 @@ async fn restore_branch( user: &User, pr: &PullRequest, ) -> forge_core::Result> { + if let Some(code) = push_refusal(state, head, &user.id, &pr.head_branch).await? { + return Ok(Some(code)); + } let path = repo_path(&state.git.data_dir, &head.id)?; let refname = format!("refs/heads/{}", pr.head_branch); if default_branch_commit(&path, &pr.head_branch)?.is_some() { @@ -227,16 +231,21 @@ async fn restore_branch( Ok(None) } -/// The refusal that applies to deleting `branch` of `head`, if any: the default branch, or a -/// branch that branch protection does not allow to be deleted. +/// The refusal that applies to deleting `branch` of `head`, if any: the default branch, a branch +/// only pull requests may change (see [`push_refusal`]), or a branch that branch protection does +/// not allow to be deleted. async fn deletion_refusal( state: &AppState, head: &forge_core::Repo, + user_id: &str, branch: &str, ) -> forge_core::Result> { if branch == head.default_branch { return Ok(Some(ERR_DEFAULT_BRANCH)); } + if let Some(code) = push_refusal(state, head, user_id, branch).await? { + return Ok(Some(code)); + } let rules = state.store.list_branch_rules(&head.id).await?; if !protection::effective(&rules, &head.default_branch, branch).allow_deletion { return Ok(Some(ERR_PROTECTED)); @@ -244,6 +253,24 @@ async fn deletion_refusal( Ok(None) } +/// The refusal for changing `branch` of `head` directly, if any: a branch protected with +/// "restrict push" takes changes only through pull requests, unless the user may push directly. +/// The same rule a git push meets in the pre-receive hook and the branches page applies. +async fn push_refusal( + state: &AppState, + head: &forge_core::Repo, + user_id: &str, + branch: &str, +) -> forge_core::Result> { + let rules = state.store.list_branch_rules(&head.id).await?; + if protection::effective(&rules, &head.default_branch, branch).restrict_push + && !may_push_directly(&state.store, head, user_id).await? + { + return Ok(Some(ERR_PROTECTED)); + } + Ok(None) +} + /// Runs the post-update work for a head ref that moved from `old` to `new`. Failures are logged: /// the ref has already moved. async fn record_ref_change( @@ -293,7 +320,7 @@ pub(crate) async fn branch_action( ); let (restore, action) = match default_branch_commit(&path, &pr.head_branch)? { Some(tip) if tip == pr.head_oid => { - if deletion_refusal(state, &head, &pr.head_branch) + if deletion_refusal(state, &head, &user.id, &pr.head_branch) .await? .is_some() { @@ -303,7 +330,11 @@ pub(crate) async fn branch_action( } Some(_) => return Ok(None), None => { - if read_commit(&path, &pr.head_oid)?.is_none() { + if read_commit(&path, &pr.head_oid)?.is_none() + || push_refusal(state, &head, &user.id, &pr.head_branch) + .await? + .is_some() + { return Ok(None); } (true, "restore_branch") diff --git a/crates/forge-web/src/pages/pull_view.rs b/crates/forge-web/src/pages/pull_view.rs index 1760d14..dff0f22 100644 --- a/crates/forge-web/src/pages/pull_view.rs +++ b/crates/forge-web/src/pages/pull_view.rs @@ -35,8 +35,9 @@ use crate::pages::pull_reviews::error_text_in; use crate::pages::pulls_merge::{ ERR_ALREADY_MERGED, ERR_AUTO_MERGE_BLOCKED, ERR_BASE_MISSING, ERR_BASE_MOVED, ERR_CHANGES_REQUESTED, ERR_CONFLICT, ERR_DRAFT, ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING, - ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN, ERR_NOT_UP_TO_DATE, - ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, merge_gate, + ERR_HEAD_MOVED, ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN, + ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, + merge_gate, }; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, load_repo}; @@ -279,6 +280,8 @@ struct MergeForm { action: String, csrf: String, ff: bool, + /// The head commit the page showed; the merge is refused if the pull request moved since. + head: String, } /// One required check as the merge box lists it. @@ -386,6 +389,7 @@ async fn merge_box( if let Some(f) = form {
+
(style_legend) @@ -811,6 +815,7 @@ async fn pull_conversation( action: format!("{href}/merge"), csrf: csrf.clone(), ff, + head: pr.head_oid.clone(), }) } else { None @@ -922,6 +927,7 @@ fn merge_error_text(lang: Lang, code: &str) -> Option<&'static str> { ERR_UP_TO_DATE => g::t(lang, K::ErrUpToDate), ERR_FF_IMPOSSIBLE => g::t(lang, K::ErrFfImpossible), ERR_BASE_MOVED => g::t(lang, K::ErrBaseMoved), + ERR_HEAD_MOVED => g::t(lang, K::ErrHeadMoved), ERR_ALREADY_MERGED => g::t(lang, K::ErrAlreadyMerged), ERR_NOT_OPEN => g::t(lang, K::ErrNotOpen), ERR_HEAD_MISSING => g::t(lang, K::ErrHeadMissing), diff --git a/crates/forge-web/src/pages/pulls_merge.rs b/crates/forge-web/src/pages/pulls_merge.rs index 00c9766..cf2144d 100644 --- a/crates/forge-web/src/pages/pulls_merge.rs +++ b/crates/forge-web/src/pages/pulls_merge.rs @@ -56,6 +56,7 @@ pub const ERR_CONFLICT: &str = "conflict"; pub const ERR_UP_TO_DATE: &str = "up_to_date"; pub const ERR_FF_IMPOSSIBLE: &str = "ff_impossible"; pub const ERR_BASE_MOVED: &str = "base_moved"; +pub const ERR_HEAD_MOVED: &str = "head_moved"; pub const ERR_ALREADY_MERGED: &str = "already_merged"; pub const ERR_NOT_OPEN: &str = "not_open"; pub const ERR_HEAD_MISSING: &str = "head_missing"; @@ -93,6 +94,10 @@ struct MergeForm { /// Replaces the default commit message when not blank. #[serde(default)] message: String, + /// The head commit the page showed. When given, a pull request whose head moved since (a + /// push after the reviewers looked) is not merged. + #[serde(default)] + head: String, } /// What a merge attempt did: the base branch now points at `commit`, or the attempt was refused @@ -139,6 +144,9 @@ async fn merge_post(cx: &Cx, Form(form): Form) -> Result { if pr.head_repo_id.is_none() { return back_to_pull(&pull_href, ERR_HEAD_MISSING); } + if !form.head.is_empty() && form.head != pr.head_oid { + return back_to_pull(&pull_href, ERR_HEAD_MOVED); + } if let Some(code) = merge_gate(state, &ctx.repo, &pr).await?.blocked() { return back_to_pull(&pull_href, code); } diff --git a/crates/forge-web/src/pages/repo_webhooks.rs b/crates/forge-web/src/pages/repo_webhooks.rs index 92f780b..ff5bb27 100644 --- a/crates/forge-web/src/pages/repo_webhooks.rs +++ b/crates/forge-web/src/pages/repo_webhooks.rs @@ -838,29 +838,45 @@ async fn hook_create(cx: &Cx, Form(form): Form) -> Result { let events = form.events(); let lang = lang_of(cx, &ctx); let checked = check_form(lang, &url, &form.secret, &events, &policy(state)?); - if let Err(message) = checked { - let frame = Frame::new(&ctx, state, lang).await?; - let csrf = session.csrf_token.clone(); - let action = format!("{}/new", hooks_href(&frame.title)); - let draft = HookDraft::of_form(&form, message); - return Ok(view! { - shell(title: frame.page_title.as_str(), viewer: ctx.viewer.as_ref(), - hook_new_body(head: frame.head, title: frame.title, archived: frame.archived, - csrf: csrf, action: action, draft: draft, lang: lang)) - }); - } - let sealed = secret::seal(&state.key, form.secret.as_bytes())?; - let hook = state - .store - .create_webhook( - &ctx.repo.id, - &user.id, - &url, - sealed.as_bytes(), - &events, - form.active.is_some(), - ) - .await?; + // A form error, or the per-repo hook cap from the store: the form comes back with the message. + let created = match checked { + Err(message) => Err(message), + Ok(()) => { + let sealed = secret::seal(&state.key, form.secret.as_bytes())?; + let created = state + .store + .create_webhook( + &ctx.repo.id, + &user.id, + &url, + sealed.as_bytes(), + &events, + form.active.is_some(), + ) + .await; + match created { + Ok(hook) => Ok(hook), + Err(e) => match crate::views::user_facing_message(&e) { + Some(message) => Err(message), + None => return Err(e.into()), + }, + } + } + }; + let hook = match created { + Ok(hook) => hook, + Err(message) => { + let frame = Frame::new(&ctx, state, lang).await?; + let csrf = session.csrf_token.clone(); + let action = format!("{}/new", hooks_href(&frame.title)); + let draft = HookDraft::of_form(&form, message); + return Ok(view! { + shell(title: frame.page_title.as_str(), viewer: ctx.viewer.as_ref(), + hook_new_body(head: frame.head, title: frame.title, archived: frame.archived, + csrf: csrf, action: action, draft: draft, lang: lang)) + }); + } + }; audit::record( &state.store, Some(cx), diff --git a/crates/forge-web/src/pages/settings_tokens.rs b/crates/forge-web/src/pages/settings_tokens.rs index f676390..4ce6036 100644 --- a/crates/forge-web/src/pages/settings_tokens.rs +++ b/crates/forge-web/src/pages/settings_tokens.rs @@ -182,7 +182,7 @@ async fn tokens_create(cx: &Cx, Form(form): Form) -> Result) -> Result { + audit::record( + store, + Some(cx), + Actor::User(&viewer.0), + AuditAction::TokenCreated, + Target { + kind: "token", + id: &row.id, + name: &row.name, + }, + serde_json::Value::Null, + ) + .await; + (Some(token), None) + } + // The token cap: shown like the other form errors. + Err(e) => match crate::views::user_facing_message(&e) { + Some(message) => (None, Some(message)), + None => return Err(e.into()), }, - serde_json::Value::Null, - ) - .await; - (Some(token), None) + } }; // The response may carry the plaintext token, so keep it out of caches.