Deleting or restoring a PR's head branch from the PR page obeys "restrict push" like a git push does
Browse files at this commit9a27aab6f6855aee2e532e037a5eed9965863689Parent: 8428320- harden
- deleting or restoring a PR's head branch from the PR page obeys "restrict push" like a git push does
- the merge form carries the head commit the page showed and a PR that got new commits since is not merged
- at most 4 source archives are built at once (503 with Retry-After past that)
- accounts can have at most 100 SSH keys and 100 tokens, repos at most 20 webhooks
- a direct repo move voids a pending transfer
9 changed files +207 -48
- crates/forge-core/src/store/mod.rs +46 -0
- crates/forge-core/src/store/webhooks.rs +11 -0
- crates/forge-web/src/i18n/pulls_review.rs +8 -0
- crates/forge-web/src/pages/archive.rs +27 -3
- crates/forge-web/src/pages/pull_branch.rs +36 -5
- crates/forge-web/src/pages/pull_view.rs +8 -2
- crates/forge-web/src/pages/pulls_merge.rs +8 -0
- crates/forge-web/src/pages/repo_webhooks.rs +39 -23
- crates/forge-web/src/pages/settings_tokens.rs +24 -15
crates/forge-core/src/store/mod.rsmodified+46 -0
| @@ -71,6 +71,10 @@ const BUSY_TIMEOUT: Duration = Duration::from_millis(5000); | |||
| 71 | pub const MAX_ABOUT_CHARS: usize = 2000; | 71 | pub const MAX_ABOUT_CHARS: usize = 2000; |
| 72 | /// Longest accepted display name, in characters. | 72 | /// Longest accepted display name, in characters. |
| 73 | pub const MAX_DISPLAY_NAME_CHARS: usize = 80; | 73 | pub const MAX_DISPLAY_NAME_CHARS: usize = 80; |
| 74 | +/// Most SSH keys one account can have. | ||
| 75 | +pub const MAX_SSH_KEYS: i64 = 100; | ||
| 76 | +/// Most access tokens one account can have, expired ones included until deleted. | ||
| 77 | +pub const MAX_TOKENS: i64 = 100; | ||
| 74 | 78 | ||
| 75 | /// Checks a display name. Surrounding whitespace is trimmed; an empty result means "no name" and | 79 | /// Checks a display name. Surrounding whitespace is trimmed; an empty result means "no name" and |
| 76 | /// gives `None`. Control characters are rejected; any other Unicode text is allowed. | 80 | /// gives `None`. Control characters are rejected; any other Unicode text is allowed. |
| @@ -465,6 +469,14 @@ impl Store { | |||
| 465 | last_used_at: None, | 469 | last_used_at: None, |
| 466 | }; | 470 | }; |
| 467 | let conn = self.inner.conn.lock().await; | 471 | let conn = self.inner.conn.lock().await; |
| 472 | + refuse_at_limit( | ||
| 473 | + &conn, | ||
| 474 | + "SELECT COUNT(*) FROM ssh_keys WHERE user_id = ?1", | ||
| 475 | + user_id, | ||
| 476 | + MAX_SSH_KEYS, | ||
| 477 | + "an account can have at most 100 SSH keys", | ||
| 478 | + ) | ||
| 479 | + .await?; | ||
| 468 | conn.execute( | 480 | conn.execute( |
| 469 | "INSERT INTO ssh_keys (id, user_id, title, algorithm, key_blob, fingerprint, created_at) \ | 481 | "INSERT INTO ssh_keys (id, user_id, title, algorithm, key_blob, fingerprint, created_at) \ |
| 470 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", | 482 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", |
| @@ -553,6 +565,14 @@ impl Store { | |||
| 553 | last_used_at: None, | 565 | last_used_at: None, |
| 554 | }; | 566 | }; |
| 555 | let conn = self.inner.conn.lock().await; | 567 | let conn = self.inner.conn.lock().await; |
| 568 | + refuse_at_limit( | ||
| 569 | + &conn, | ||
| 570 | + "SELECT COUNT(*) FROM access_tokens WHERE user_id = ?1", | ||
| 571 | + user_id, | ||
| 572 | + MAX_TOKENS, | ||
| 573 | + "an account can have at most 100 access tokens", | ||
| 574 | + ) | ||
| 575 | + .await?; | ||
| 556 | conn.execute( | 576 | conn.execute( |
| 557 | "INSERT INTO access_tokens (id, user_id, name, token_hash, scopes, expires_at, created_at) \ | 577 | "INSERT INTO access_tokens (id, user_id, name, token_hash, scopes, expires_at, created_at) \ |
| 558 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", | 578 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", |
| @@ -1000,6 +1020,24 @@ where | |||
| 1000 | Ok(out) | 1020 | Ok(out) |
| 1001 | } | 1021 | } |
| 1002 | 1022 | ||
| 1023 | +/// Refuses with `Invalid(message)` once `count_sql` (one `?1` parameter) counts `max` rows or more. | ||
| 1024 | +/// Run under the write lock, before the insert it guards, so two inserts cannot both pass. | ||
| 1025 | +async fn refuse_at_limit( | ||
| 1026 | + conn: &Connection, | ||
| 1027 | + count_sql: &str, | ||
| 1028 | + key: &str, | ||
| 1029 | + max: i64, | ||
| 1030 | + message: &str, | ||
| 1031 | +) -> Result<()> { | ||
| 1032 | + let count = fetch_opt(conn, count_sql, (key.to_string(),), |row| col_int(row, 0)) | ||
| 1033 | + .await? | ||
| 1034 | + .unwrap_or(0); | ||
| 1035 | + if count >= max { | ||
| 1036 | + return Err(Error::Invalid(message.to_string())); | ||
| 1037 | + } | ||
| 1038 | + Ok(()) | ||
| 1039 | +} | ||
| 1040 | + | ||
| 1003 | async fn fetch_opt<T, P>( | 1041 | async fn fetch_opt<T, P>( |
| 1004 | conn: &Connection, | 1042 | conn: &Connection, |
| 1005 | sql: &str, | 1043 | sql: &str, |
| @@ -1496,6 +1534,14 @@ impl Store { | |||
| 1496 | ) | 1534 | ) |
| 1497 | .await | 1535 | .await |
| 1498 | .map_err(db_err)?; | 1536 | .map_err(db_err)?; |
| 1537 | + // A transfer the old owner offered is void once the repo has moved: its target | ||
| 1538 | + // must not be able to accept it later and take the repo from the new owner. | ||
| 1539 | + tx.execute( | ||
| 1540 | + "DELETE FROM repo_transfers WHERE repo_id = ?1", | ||
| 1541 | + (id.clone(),), | ||
| 1542 | + ) | ||
| 1543 | + .await | ||
| 1544 | + .map_err(db_err)?; | ||
| 1499 | } | 1545 | } |
| 1500 | Ok(()) | 1546 | Ok(()) |
| 1501 | } | 1547 | } |
crates/forge-core/src/store/webhooks.rsmodified+11 -0
| @@ -172,6 +172,9 @@ async fn insert_delivery(conn: &Connection, d: &Delivery) -> Result<()> { | |||
| 172 | Ok(()) | 172 | Ok(()) |
| 173 | } | 173 | } |
| 174 | 174 | ||
| 175 | +/// Most webhooks one repository can have. | ||
| 176 | +pub const MAX_WEBHOOKS: i64 = 20; | ||
| 177 | + | ||
| 175 | impl Store { | 178 | impl Store { |
| 176 | /// Creates a hook. `secret_sealed` is the `secret::seal` output as bytes. The hook starts | 179 | /// Creates a hook. `secret_sealed` is the `secret::seal` output as bytes. The hook starts |
| 177 | /// with `created_at == updated_at`. | 180 | /// with `created_at == updated_at`. |
| @@ -206,6 +209,14 @@ impl Store { | |||
| 206 | Value::Text(now), | 209 | Value::Text(now), |
| 207 | ]; | 210 | ]; |
| 208 | let conn = self.inner.conn.lock().await; | 211 | let conn = self.inner.conn.lock().await; |
| 212 | + super::refuse_at_limit( | ||
| 213 | + &conn, | ||
| 214 | + "SELECT COUNT(*) FROM webhooks WHERE repo_id = ?1", | ||
| 215 | + repo_id, | ||
| 216 | + MAX_WEBHOOKS, | ||
| 217 | + "a repository can have at most 20 webhooks", | ||
| 218 | + ) | ||
| 219 | + .await?; | ||
| 209 | conn.execute( | 220 | conn.execute( |
| 210 | "INSERT INTO webhooks (id, repo_id, url, secret_sealed, events, active, created_by, \ | 221 | "INSERT INTO webhooks (id, repo_id, url, secret_sealed, events, active, created_by, \ |
| 211 | created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", | 222 | created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", |
crates/forge-web/src/i18n/pulls_review.rsmodified+8 -0
| @@ -61,6 +61,7 @@ pub enum K { | |||
| 61 | ErrUpToDate, | 61 | ErrUpToDate, |
| 62 | ErrFfImpossible, | 62 | ErrFfImpossible, |
| 63 | ErrBaseMoved, | 63 | ErrBaseMoved, |
| 64 | + ErrHeadMoved, | ||
| 64 | ErrAlreadyMerged, | 65 | ErrAlreadyMerged, |
| 65 | ErrNotOpen, | 66 | ErrNotOpen, |
| 66 | ErrHeadMissing, | 67 | ErrHeadMissing, |
| @@ -242,6 +243,12 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 242 | (ErrBaseMoved, Tr) => { | 243 | (ErrBaseMoved, Tr) => { |
| 243 | "Birleştirme sırasında taban dal değişti. Bu sayfayı yenileyip yeniden deneyin." | 244 | "Birleştirme sırasında taban dal değişti. Bu sayfayı yenileyip yeniden deneyin." |
| 244 | } | 245 | } |
| 246 | + (ErrHeadMoved, En) => { | ||
| 247 | + "New commits were pushed to this pull request after the page loaded. Review them, then merge again." | ||
| 248 | + } | ||
| 249 | + (ErrHeadMoved, Tr) => { | ||
| 250 | + "Sayfa yüklendikten sonra bu çekme isteğine yeni commitler gönderildi. Onları inceleyip yeniden birleştirin." | ||
| 251 | + } | ||
| 245 | (ErrAlreadyMerged, En) => "This pull request is already merged.", | 252 | (ErrAlreadyMerged, En) => "This pull request is already merged.", |
| 246 | (ErrAlreadyMerged, Tr) => "Bu çekme isteği zaten birleştirilmiş.", | 253 | (ErrAlreadyMerged, Tr) => "Bu çekme isteği zaten birleştirilmiş.", |
| 247 | (ErrNotOpen, En) => "This pull request is closed, so it cannot be merged.", | 254 | (ErrNotOpen, En) => "This pull request is closed, so it cannot be merged.", |
| @@ -489,6 +496,7 @@ pub const ALL: &[K] = &[ | |||
| 489 | K::ErrUpToDate, | 496 | K::ErrUpToDate, |
| 490 | K::ErrFfImpossible, | 497 | K::ErrFfImpossible, |
| 491 | K::ErrBaseMoved, | 498 | K::ErrBaseMoved, |
| 499 | + K::ErrHeadMoved, | ||
| 492 | K::ErrAlreadyMerged, | 500 | K::ErrAlreadyMerged, |
| 493 | K::ErrNotOpen, | 501 | K::ErrNotOpen, |
| 494 | K::ErrHeadMissing, | 502 | K::ErrHeadMissing, |
crates/forge-web/src/pages/archive.rsmodified+27 -3
| @@ -2,6 +2,7 @@ | |||
| 2 | //! stdout is streamed as the response body. | 2 | //! stdout is streamed as the response body. |
| 3 | 3 | ||
| 4 | use std::process::Stdio; | 4 | use std::process::Stdio; |
| 5 | +use std::sync::{Arc, OnceLock}; | ||
| 5 | 6 | ||
| 6 | use forge_git::browse; | 7 | use forge_git::browse; |
| 7 | use forge_git::history::{self, ArchiveFormat}; | 8 | use forge_git::history::{self, ArchiveFormat}; |
| @@ -13,6 +14,7 @@ use http_body::Frame; | |||
| 13 | use http_body_util::StreamBody; | 14 | use http_body_util::StreamBody; |
| 14 | use tokio::io::AsyncReadExt; | 15 | use tokio::io::AsyncReadExt; |
| 15 | use tokio::process::Child; | 16 | use tokio::process::Child; |
| 17 | +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; | ||
| 16 | use tokio_util::io::ReaderStream; | 18 | use tokio_util::io::ReaderStream; |
| 17 | use topcoat::Result; | 19 | use topcoat::Result; |
| 18 | use topcoat::context::{Cx, app_context}; | 20 | use topcoat::context::{Cx, app_context}; |
| @@ -24,6 +26,16 @@ use crate::pages::commits::blocking; | |||
| 24 | use crate::pages::repo_ctx::load_repo; | 26 | use crate::pages::repo_ctx::load_repo; |
| 25 | use crate::state::AppState; | 27 | use crate::state::AppState; |
| 26 | 28 | ||
| 29 | +/// Archives built at once, server-wide. Each one is a `git archive` that compresses the whole | ||
| 30 | +/// tree, so a burst of downloads of a big repo would otherwise take every core. | ||
| 31 | +const MAX_CONCURRENT_ARCHIVES: usize = 4; | ||
| 32 | + | ||
| 33 | +/// Permits for running archives. A permit is held until its `git archive` exits. | ||
| 34 | +fn archive_slots() -> &'static Arc<Semaphore> { | ||
| 35 | + static SLOTS: OnceLock<Arc<Semaphore>> = OnceLock::new(); | ||
| 36 | + SLOTS.get_or_init(|| Arc::new(Semaphore::new(MAX_CONCURRENT_ARCHIVES))) | ||
| 37 | +} | ||
| 38 | + | ||
| 27 | path_param!(owner); | 39 | path_param!(owner); |
| 28 | path_param!(repo); | 40 | path_param!(repo); |
| 29 | path_param!(*rest); | 41 | path_param!(*rest); |
| @@ -77,6 +89,17 @@ async fn archive(cx: &Cx) -> Result<Response> { | |||
| 77 | return Err(not_found().into()); | 89 | return Err(not_found().into()); |
| 78 | }; | 90 | }; |
| 79 | 91 | ||
| 92 | + // All slots busy: ask the client to come back rather than queueing work behind them. | ||
| 93 | + let Ok(permit) = archive_slots().clone().try_acquire_owned() else { | ||
| 94 | + let mut res = Response::new(Body::from( | ||
| 95 | + "busy building other archives, try again shortly", | ||
| 96 | + )); | ||
| 97 | + *res.status_mut() = http::StatusCode::SERVICE_UNAVAILABLE; | ||
| 98 | + res.headers_mut() | ||
| 99 | + .insert(http::header::RETRY_AFTER, HeaderValue::from_static("10")); | ||
| 100 | + return Ok(res); | ||
| 101 | + }; | ||
| 102 | + | ||
| 80 | let prefix = archive_prefix(&ctx.repo.name, reference, &commit); | 103 | let prefix = archive_prefix(&ctx.repo.name, reference, &commit); |
| 81 | let (content_type, extension) = match format { | 104 | let (content_type, extension) = match format { |
| 82 | ArchiveFormat::TarGz => ("application/gzip", "tar.gz"), | 105 | ArchiveFormat::TarGz => ("application/gzip", "tar.gz"), |
| @@ -92,7 +115,7 @@ async fn archive(cx: &Cx) -> Result<Response> { | |||
| 92 | let Some(stdout) = child.stdout.take() else { | 115 | let Some(stdout) = child.stdout.take() else { |
| 93 | return Err(std::io::Error::other("git archive stdout missing").into()); | 116 | return Err(std::io::Error::other("git archive stdout missing").into()); |
| 94 | }; | 117 | }; |
| 95 | - tokio::spawn(reap(child)); | 118 | + tokio::spawn(reap(child, permit)); |
| 96 | 119 | ||
| 97 | let chunks = ReaderStream::new(stdout).map_ok(Frame::data); | 120 | let chunks = ReaderStream::new(stdout).map_ok(Frame::data); |
| 98 | let mut res = Response::new(Body::new(StreamBody::new(chunks))); | 121 | let mut res = Response::new(Body::new(StreamBody::new(chunks))); |
| @@ -107,8 +130,9 @@ async fn archive(cx: &Cx) -> Result<Response> { | |||
| 107 | Ok(res) | 130 | Ok(res) |
| 108 | } | 131 | } |
| 109 | 132 | ||
| 110 | -/// Drains stderr into the log and waits for `git archive`, so no zombie is left behind. | 133 | +/// Drains stderr into the log and waits for `git archive`, so no zombie is left behind. The slot |
| 111 | -async fn reap(mut child: Child) { | 134 | +/// is given back when git exits (a client that goes away closes stdout, which ends git). |
| 135 | +async fn reap(mut child: Child, _permit: OwnedSemaphorePermit) { | ||
| 112 | let mut stderr = Vec::new(); | 136 | let mut stderr = Vec::new(); |
| 113 | if let Some(mut pipe) = child.stderr.take() { | 137 | if let Some(mut pipe) = child.stderr.take() { |
| 114 | let _ = pipe.read_to_end(&mut stderr).await; | 138 | let _ = pipe.read_to_end(&mut stderr).await; |
crates/forge-web/src/pages/pull_branch.rsmodified+36 -5
| @@ -28,6 +28,7 @@ use topcoat::view::{View, component, view}; | |||
| 28 | use crate::auth::require_csrf; | 28 | use crate::auth::require_csrf; |
| 29 | use crate::i18n::Lang; | 29 | use crate::i18n::Lang; |
| 30 | use crate::i18n::pulls::{self as g, K}; | 30 | use crate::i18n::pulls::{self as g, K}; |
| 31 | +use crate::internal::may_push_directly; | ||
| 31 | use crate::pages::issue_parts::parse_number; | 32 | use crate::pages::issue_parts::parse_number; |
| 32 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; | 33 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; |
| 33 | use crate::post_update::after_ref_update; | 34 | use crate::post_update::after_ref_update; |
| @@ -165,7 +166,7 @@ async fn delete_branch( | |||
| 165 | user: &User, | 166 | user: &User, |
| 166 | pr: &PullRequest, | 167 | pr: &PullRequest, |
| 167 | ) -> forge_core::Result<Option<&'static str>> { | 168 | ) -> forge_core::Result<Option<&'static str>> { |
| 168 | - if let Some(code) = deletion_refusal(state, head, &pr.head_branch).await? { | 169 | + if let Some(code) = deletion_refusal(state, head, &user.id, &pr.head_branch).await? { |
| 169 | return Ok(Some(code)); | 170 | return Ok(Some(code)); |
| 170 | } | 171 | } |
| 171 | let path = repo_path(&state.git.data_dir, &head.id)?; | 172 | let path = repo_path(&state.git.data_dir, &head.id)?; |
| @@ -201,6 +202,9 @@ async fn restore_branch( | |||
| 201 | user: &User, | 202 | user: &User, |
| 202 | pr: &PullRequest, | 203 | pr: &PullRequest, |
| 203 | ) -> forge_core::Result<Option<&'static str>> { | 204 | ) -> forge_core::Result<Option<&'static str>> { |
| 205 | + if let Some(code) = push_refusal(state, head, &user.id, &pr.head_branch).await? { | ||
| 206 | + return Ok(Some(code)); | ||
| 207 | + } | ||
| 204 | let path = repo_path(&state.git.data_dir, &head.id)?; | 208 | let path = repo_path(&state.git.data_dir, &head.id)?; |
| 205 | let refname = format!("refs/heads/{}", pr.head_branch); | 209 | let refname = format!("refs/heads/{}", pr.head_branch); |
| 206 | if default_branch_commit(&path, &pr.head_branch)?.is_some() { | 210 | if default_branch_commit(&path, &pr.head_branch)?.is_some() { |
| @@ -227,16 +231,21 @@ async fn restore_branch( | |||
| 227 | Ok(None) | 231 | Ok(None) |
| 228 | } | 232 | } |
| 229 | 233 | ||
| 230 | -/// The refusal that applies to deleting `branch` of `head`, if any: the default branch, or a | 234 | +/// The refusal that applies to deleting `branch` of `head`, if any: the default branch, a branch |
| 231 | -/// branch that branch protection does not allow to be deleted. | 235 | +/// only pull requests may change (see [`push_refusal`]), or a branch that branch protection does |
| 236 | +/// not allow to be deleted. | ||
| 232 | async fn deletion_refusal( | 237 | async fn deletion_refusal( |
| 233 | state: &AppState, | 238 | state: &AppState, |
| 234 | head: &forge_core::Repo, | 239 | head: &forge_core::Repo, |
| 240 | + user_id: &str, | ||
| 235 | branch: &str, | 241 | branch: &str, |
| 236 | ) -> forge_core::Result<Option<&'static str>> { | 242 | ) -> forge_core::Result<Option<&'static str>> { |
| 237 | if branch == head.default_branch { | 243 | if branch == head.default_branch { |
| 238 | return Ok(Some(ERR_DEFAULT_BRANCH)); | 244 | return Ok(Some(ERR_DEFAULT_BRANCH)); |
| 239 | } | 245 | } |
| 246 | + if let Some(code) = push_refusal(state, head, user_id, branch).await? { | ||
| 247 | + return Ok(Some(code)); | ||
| 248 | + } | ||
| 240 | let rules = state.store.list_branch_rules(&head.id).await?; | 249 | let rules = state.store.list_branch_rules(&head.id).await?; |
| 241 | if !protection::effective(&rules, &head.default_branch, branch).allow_deletion { | 250 | if !protection::effective(&rules, &head.default_branch, branch).allow_deletion { |
| 242 | return Ok(Some(ERR_PROTECTED)); | 251 | return Ok(Some(ERR_PROTECTED)); |
| @@ -244,6 +253,24 @@ async fn deletion_refusal( | |||
| 244 | Ok(None) | 253 | Ok(None) |
| 245 | } | 254 | } |
| 246 | 255 | ||
| 256 | +/// The refusal for changing `branch` of `head` directly, if any: a branch protected with | ||
| 257 | +/// "restrict push" takes changes only through pull requests, unless the user may push directly. | ||
| 258 | +/// The same rule a git push meets in the pre-receive hook and the branches page applies. | ||
| 259 | +async fn push_refusal( | ||
| 260 | + state: &AppState, | ||
| 261 | + head: &forge_core::Repo, | ||
| 262 | + user_id: &str, | ||
| 263 | + branch: &str, | ||
| 264 | +) -> forge_core::Result<Option<&'static str>> { | ||
| 265 | + let rules = state.store.list_branch_rules(&head.id).await?; | ||
| 266 | + if protection::effective(&rules, &head.default_branch, branch).restrict_push | ||
| 267 | + && !may_push_directly(&state.store, head, user_id).await? | ||
| 268 | + { | ||
| 269 | + return Ok(Some(ERR_PROTECTED)); | ||
| 270 | + } | ||
| 271 | + Ok(None) | ||
| 272 | +} | ||
| 273 | + | ||
| 247 | /// Runs the post-update work for a head ref that moved from `old` to `new`. Failures are logged: | 274 | /// Runs the post-update work for a head ref that moved from `old` to `new`. Failures are logged: |
| 248 | /// the ref has already moved. | 275 | /// the ref has already moved. |
| 249 | async fn record_ref_change( | 276 | async fn record_ref_change( |
| @@ -293,7 +320,7 @@ pub(crate) async fn branch_action( | |||
| 293 | ); | 320 | ); |
| 294 | let (restore, action) = match default_branch_commit(&path, &pr.head_branch)? { | 321 | let (restore, action) = match default_branch_commit(&path, &pr.head_branch)? { |
| 295 | Some(tip) if tip == pr.head_oid => { | 322 | Some(tip) if tip == pr.head_oid => { |
| 296 | - if deletion_refusal(state, &head, &pr.head_branch) | 323 | + if deletion_refusal(state, &head, &user.id, &pr.head_branch) |
| 297 | .await? | 324 | .await? |
| 298 | .is_some() | 325 | .is_some() |
| 299 | { | 326 | { |
| @@ -303,7 +330,11 @@ pub(crate) async fn branch_action( | |||
| 303 | } | 330 | } |
| 304 | Some(_) => return Ok(None), | 331 | Some(_) => return Ok(None), |
| 305 | None => { | 332 | None => { |
| 306 | - if read_commit(&path, &pr.head_oid)?.is_none() { | 333 | + if read_commit(&path, &pr.head_oid)?.is_none() |
| 334 | + || push_refusal(state, &head, &user.id, &pr.head_branch) | ||
| 335 | + .await? | ||
| 336 | + .is_some() | ||
| 337 | + { | ||
| 307 | return Ok(None); | 338 | return Ok(None); |
| 308 | } | 339 | } |
| 309 | (true, "restore_branch") | 340 | (true, "restore_branch") |
crates/forge-web/src/pages/pull_view.rsmodified+8 -2
| @@ -35,8 +35,9 @@ use crate::pages::pull_reviews::error_text_in; | |||
| 35 | use crate::pages::pulls_merge::{ | 35 | use crate::pages::pulls_merge::{ |
| 36 | ERR_ALREADY_MERGED, ERR_AUTO_MERGE_BLOCKED, ERR_BASE_MISSING, ERR_BASE_MOVED, | 36 | ERR_ALREADY_MERGED, ERR_AUTO_MERGE_BLOCKED, ERR_BASE_MISSING, ERR_BASE_MOVED, |
| 37 | ERR_CHANGES_REQUESTED, ERR_CONFLICT, ERR_DRAFT, ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING, | 37 | ERR_CHANGES_REQUESTED, ERR_CONFLICT, ERR_DRAFT, ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING, |
| 38 | - ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN, ERR_NOT_UP_TO_DATE, | 38 | + ERR_HEAD_MOVED, ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN, |
| 39 | - ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, merge_gate, | 39 | + ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, |
| 40 | + merge_gate, | ||
| 40 | }; | 41 | }; |
| 41 | use crate::pages::repo::repo_head; | 42 | use crate::pages::repo::repo_head; |
| 42 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; | 43 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; |
| @@ -279,6 +280,8 @@ struct MergeForm { | |||
| 279 | action: String, | 280 | action: String, |
| 280 | csrf: String, | 281 | csrf: String, |
| 281 | ff: bool, | 282 | ff: bool, |
| 283 | + /// The head commit the page showed; the merge is refused if the pull request moved since. | ||
| 284 | + head: String, | ||
| 282 | } | 285 | } |
| 283 | 286 | ||
| 284 | /// One required check as the merge box lists it. | 287 | /// One required check as the merge box lists it. |
| @@ -386,6 +389,7 @@ async fn merge_box( | |||
| 386 | if let Some(f) = form { | 389 | if let Some(f) = form { |
| 387 | <form method="post" action=(f.action.as_str()) class="stack merge-form"> | 390 | <form method="post" action=(f.action.as_str()) class="stack merge-form"> |
| 388 | <input type="hidden" name="csrf" value=(f.csrf.as_str())> | 391 | <input type="hidden" name="csrf" value=(f.csrf.as_str())> |
| 392 | + <input type="hidden" name="head" value=(f.head.as_str())> | ||
| 389 | <fieldset class="merge-styles"> | 393 | <fieldset class="merge-styles"> |
| 390 | <legend>(style_legend)</legend> | 394 | <legend>(style_legend)</legend> |
| 391 | <label><input type="radio" name="style" value="merge" checked=(true)>(style_merge)</label> | 395 | <label><input type="radio" name="style" value="merge" checked=(true)>(style_merge)</label> |
| @@ -811,6 +815,7 @@ async fn pull_conversation( | |||
| 811 | action: format!("{href}/merge"), | 815 | action: format!("{href}/merge"), |
| 812 | csrf: csrf.clone(), | 816 | csrf: csrf.clone(), |
| 813 | ff, | 817 | ff, |
| 818 | + head: pr.head_oid.clone(), | ||
| 814 | }) | 819 | }) |
| 815 | } else { | 820 | } else { |
| 816 | None | 821 | None |
| @@ -922,6 +927,7 @@ fn merge_error_text(lang: Lang, code: &str) -> Option<&'static str> { | |||
| 922 | ERR_UP_TO_DATE => g::t(lang, K::ErrUpToDate), | 927 | ERR_UP_TO_DATE => g::t(lang, K::ErrUpToDate), |
| 923 | ERR_FF_IMPOSSIBLE => g::t(lang, K::ErrFfImpossible), | 928 | ERR_FF_IMPOSSIBLE => g::t(lang, K::ErrFfImpossible), |
| 924 | ERR_BASE_MOVED => g::t(lang, K::ErrBaseMoved), | 929 | ERR_BASE_MOVED => g::t(lang, K::ErrBaseMoved), |
| 930 | + ERR_HEAD_MOVED => g::t(lang, K::ErrHeadMoved), | ||
| 925 | ERR_ALREADY_MERGED => g::t(lang, K::ErrAlreadyMerged), | 931 | ERR_ALREADY_MERGED => g::t(lang, K::ErrAlreadyMerged), |
| 926 | ERR_NOT_OPEN => g::t(lang, K::ErrNotOpen), | 932 | ERR_NOT_OPEN => g::t(lang, K::ErrNotOpen), |
| 927 | ERR_HEAD_MISSING => g::t(lang, K::ErrHeadMissing), | 933 | ERR_HEAD_MISSING => g::t(lang, K::ErrHeadMissing), |
crates/forge-web/src/pages/pulls_merge.rsmodified+8 -0
| @@ -56,6 +56,7 @@ pub const ERR_CONFLICT: &str = "conflict"; | |||
| 56 | pub const ERR_UP_TO_DATE: &str = "up_to_date"; | 56 | pub const ERR_UP_TO_DATE: &str = "up_to_date"; |
| 57 | pub const ERR_FF_IMPOSSIBLE: &str = "ff_impossible"; | 57 | pub const ERR_FF_IMPOSSIBLE: &str = "ff_impossible"; |
| 58 | pub const ERR_BASE_MOVED: &str = "base_moved"; | 58 | pub const ERR_BASE_MOVED: &str = "base_moved"; |
| 59 | +pub const ERR_HEAD_MOVED: &str = "head_moved"; | ||
| 59 | pub const ERR_ALREADY_MERGED: &str = "already_merged"; | 60 | pub const ERR_ALREADY_MERGED: &str = "already_merged"; |
| 60 | pub const ERR_NOT_OPEN: &str = "not_open"; | 61 | pub const ERR_NOT_OPEN: &str = "not_open"; |
| 61 | pub const ERR_HEAD_MISSING: &str = "head_missing"; | 62 | pub const ERR_HEAD_MISSING: &str = "head_missing"; |
| @@ -93,6 +94,10 @@ struct MergeForm { | |||
| 93 | /// Replaces the default commit message when not blank. | 94 | /// Replaces the default commit message when not blank. |
| 94 | #[serde(default)] | 95 | #[serde(default)] |
| 95 | message: String, | 96 | message: String, |
| 97 | + /// The head commit the page showed. When given, a pull request whose head moved since (a | ||
| 98 | + /// push after the reviewers looked) is not merged. | ||
| 99 | + #[serde(default)] | ||
| 100 | + head: String, | ||
| 96 | } | 101 | } |
| 97 | 102 | ||
| 98 | /// What a merge attempt did: the base branch now points at `commit`, or the attempt was refused | 103 | /// 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<MergeForm>) -> Result<Response> { | |||
| 139 | if pr.head_repo_id.is_none() { | 144 | if pr.head_repo_id.is_none() { |
| 140 | return back_to_pull(&pull_href, ERR_HEAD_MISSING); | 145 | return back_to_pull(&pull_href, ERR_HEAD_MISSING); |
| 141 | } | 146 | } |
| 147 | + if !form.head.is_empty() && form.head != pr.head_oid { | ||
| 148 | + return back_to_pull(&pull_href, ERR_HEAD_MOVED); | ||
| 149 | + } | ||
| 142 | if let Some(code) = merge_gate(state, &ctx.repo, &pr).await?.blocked() { | 150 | if let Some(code) = merge_gate(state, &ctx.repo, &pr).await?.blocked() { |
| 143 | return back_to_pull(&pull_href, code); | 151 | return back_to_pull(&pull_href, code); |
| 144 | } | 152 | } |
crates/forge-web/src/pages/repo_webhooks.rsmodified+39 -23
| @@ -838,29 +838,45 @@ async fn hook_create(cx: &Cx, Form(form): Form<HookForm>) -> Result<impl View> { | |||
| 838 | let events = form.events(); | 838 | let events = form.events(); |
| 839 | let lang = lang_of(cx, &ctx); | 839 | let lang = lang_of(cx, &ctx); |
| 840 | let checked = check_form(lang, &url, &form.secret, &events, &policy(state)?); | 840 | let checked = check_form(lang, &url, &form.secret, &events, &policy(state)?); |
| 841 | - if let Err(message) = checked { | 841 | + // A form error, or the per-repo hook cap from the store: the form comes back with the message. |
| 842 | - let frame = Frame::new(&ctx, state, lang).await?; | 842 | + let created = match checked { |
| 843 | - let csrf = session.csrf_token.clone(); | 843 | + Err(message) => Err(message), |
| 844 | - let action = format!("{}/new", hooks_href(&frame.title)); | 844 | + Ok(()) => { |
| 845 | - let draft = HookDraft::of_form(&form, message); | 845 | + let sealed = secret::seal(&state.key, form.secret.as_bytes())?; |
| 846 | - return Ok(view! { | 846 | + let created = state |
| 847 | - shell(title: frame.page_title.as_str(), viewer: ctx.viewer.as_ref(), | 847 | + .store |
| 848 | - hook_new_body(head: frame.head, title: frame.title, archived: frame.archived, | 848 | + .create_webhook( |
| 849 | - csrf: csrf, action: action, draft: draft, lang: lang)) | 849 | + &ctx.repo.id, |
| 850 | - }); | 850 | + &user.id, |
| 851 | - } | 851 | + &url, |
| 852 | - let sealed = secret::seal(&state.key, form.secret.as_bytes())?; | 852 | + sealed.as_bytes(), |
| 853 | - let hook = state | 853 | + &events, |
| 854 | - .store | 854 | + form.active.is_some(), |
| 855 | - .create_webhook( | 855 | + ) |
| 856 | - &ctx.repo.id, | 856 | + .await; |
| 857 | - &user.id, | 857 | + match created { |
| 858 | - &url, | 858 | + Ok(hook) => Ok(hook), |
| 859 | - sealed.as_bytes(), | 859 | + Err(e) => match crate::views::user_facing_message(&e) { |
| 860 | - &events, | 860 | + Some(message) => Err(message), |
| 861 | - form.active.is_some(), | 861 | + None => return Err(e.into()), |
| 862 | - ) | 862 | + }, |
| 863 | - .await?; | 863 | + } |
| 864 | + } | ||
| 865 | + }; | ||
| 866 | + let hook = match created { | ||
| 867 | + Ok(hook) => hook, | ||
| 868 | + Err(message) => { | ||
| 869 | + let frame = Frame::new(&ctx, state, lang).await?; | ||
| 870 | + let csrf = session.csrf_token.clone(); | ||
| 871 | + let action = format!("{}/new", hooks_href(&frame.title)); | ||
| 872 | + let draft = HookDraft::of_form(&form, message); | ||
| 873 | + return Ok(view! { | ||
| 874 | + shell(title: frame.page_title.as_str(), viewer: ctx.viewer.as_ref(), | ||
| 875 | + hook_new_body(head: frame.head, title: frame.title, archived: frame.archived, | ||
| 876 | + csrf: csrf, action: action, draft: draft, lang: lang)) | ||
| 877 | + }); | ||
| 878 | + } | ||
| 879 | + }; | ||
| 864 | audit::record( | 880 | audit::record( |
| 865 | &state.store, | 881 | &state.store, |
| 866 | Some(cx), | 882 | Some(cx), |
crates/forge-web/src/pages/settings_tokens.rsmodified+24 -15
| @@ -182,7 +182,7 @@ async fn tokens_create(cx: &Cx, Form(form): Form<CreateTokenForm>) -> Result<imp | |||
| 182 | if !form.packages.is_empty() { | 182 | if !form.packages.is_empty() { |
| 183 | scopes.push(PACKAGES_SCOPE.to_owned()); | 183 | scopes.push(PACKAGES_SCOPE.to_owned()); |
| 184 | } | 184 | } |
| 185 | - let row = store | 185 | + let created = store |
| 186 | .create_token( | 186 | .create_token( |
| 187 | &viewer.0.id, | 187 | &viewer.0.id, |
| 188 | name, | 188 | name, |
| @@ -190,21 +190,30 @@ async fn tokens_create(cx: &Cx, Form(form): Form<CreateTokenForm>) -> Result<imp | |||
| 190 | &scopes, | 190 | &scopes, |
| 191 | expires_at.as_deref(), | 191 | expires_at.as_deref(), |
| 192 | ) | 192 | ) |
| 193 | - .await?; | 193 | + .await; |
| 194 | - audit::record( | 194 | + match created { |
| 195 | - store, | 195 | + Ok(row) => { |
| 196 | - Some(cx), | 196 | + audit::record( |
| 197 | - Actor::User(&viewer.0), | 197 | + store, |
| 198 | - AuditAction::TokenCreated, | 198 | + Some(cx), |
| 199 | - Target { | 199 | + Actor::User(&viewer.0), |
| 200 | - kind: "token", | 200 | + AuditAction::TokenCreated, |
| 201 | - id: &row.id, | 201 | + Target { |
| 202 | - name: &row.name, | 202 | + kind: "token", |
| 203 | + id: &row.id, | ||
| 204 | + name: &row.name, | ||
| 205 | + }, | ||
| 206 | + serde_json::Value::Null, | ||
| 207 | + ) | ||
| 208 | + .await; | ||
| 209 | + (Some(token), None) | ||
| 210 | + } | ||
| 211 | + // The token cap: shown like the other form errors. | ||
| 212 | + Err(e) => match crate::views::user_facing_message(&e) { | ||
| 213 | + Some(message) => (None, Some(message)), | ||
| 214 | + None => return Err(e.into()), | ||
| 203 | }, | 215 | }, |
| 204 | - serde_json::Value::Null, | 216 | + } |
| 205 | - ) | ||
| 206 | - .await; | ||
| 207 | - (Some(token), None) | ||
| 208 | }; | 217 | }; |
| 209 | 218 | ||
| 210 | // The response may carry the plaintext token, so keep it out of caches. | 219 | // The response may carry the plaintext token, so keep it out of caches. |