forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

internal.rs1211 lines, 42.1 KiBHistoryRawDownload
1//! Internal hook API, served over a unix socket at `data_dir/internal.sock`.
2//!
3//! Routes are registered explicitly with [`RouteFn`] instead of `#[route]`. The
4//! `#[route]` macro emits an `inventory::submit!` that `Router::builder().discover()`
5//! collects, and the public TCP router uses `.discover()`. A `RouteFn` passed to
6//! `.route(...)` never enters that inventory, so these endpoints are not reachable
7//! on the public listener.
8
9use std::collections::{BTreeMap, HashMap};
10use std::path::Path;
11use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
12
13use forge_core::protection::effective;
14use forge_core::{Repo, Role, Store};
15use forge_git::{GitCommand, GitEnv};
16use serde::{Deserialize, Serialize};
17use topcoat::context::{Cx, context};
18use topcoat::router::content::Json;
19use topcoat::router::error::{bad_request, forbidden};
20use topcoat::router::request::headers;
21use topcoat::router::response::IntoResponse;
22use topcoat::router::response::Response;
23use topcoat::router::{
24 Body, HeaderValue, Method, RouteFn, RouteFuture, Router, StatusCode, header, to_bytes,
25};
26
27use crate::admin_client::ADMIN_TOKEN_HEADER;
28use crate::audit::{self, Actor, Target};
29use crate::backup::scheduler::{run_backup_now, run_fsck_now};
30use crate::backup::{BackupOptions, Scope};
31use crate::live::{self, Topic};
32use crate::post_update::after_ref_update;
33use crate::state::AppState;
34use forge_core::AuditAction;
35use forge_core::store::backup_runs::{RunKind, RunTrigger};
36
37/// Largest accepted hook request body.
38const MAX_BODY_BYTES: usize = 1024 * 1024;
39/// Header carrying `AppState::internal_token`.
40const TOKEN_HEADER: &str = "x-forge-internal-token";
41/// Environment variables git sets for the quarantine directory of a push.
42pub const QUARANTINE_VARS: [&str; 3] = [
43 "GIT_QUARANTINE_PATH",
44 "GIT_OBJECT_DIRECTORY",
45 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
46];
47
48/// One ref update from receive-pack.
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50pub struct HookUpdate {
51 pub old: String,
52 pub new: String,
53 #[serde(rename = "ref")]
54 pub ref_name: String,
55}
56
57/// Body of `POST /hook/pre-receive` and `POST /hook/post-receive`.
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct HookRequest {
60 pub repo_id: String,
61 pub actor_id: String,
62 pub protocol: String,
63 /// True when the push targets the repo's wiki repo instead of the code repo (see forge-git
64 /// `wiki.rs`). Wiki pushes skip the branch rules and the post-push work, and may only touch main.
65 #[serde(default)]
66 pub wiki: bool,
67 pub updates: Vec<HookUpdate>,
68 #[serde(default)]
69 pub quarantine_env: BTreeMap<String, String>,
70}
71
72/// Response of both hook endpoints. `message` is shown to the pusher on stderr.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74pub struct HookResponse {
75 pub allow: bool,
76 pub message: String,
77}
78
79impl HookResponse {
80 fn allow() -> Self {
81 Self {
82 allow: true,
83 message: String::new(),
84 }
85 }
86
87 fn deny(message: impl Into<String>) -> Self {
88 Self {
89 allow: false,
90 message: message.into(),
91 }
92 }
93}
94
95/// Router for the internal API. Serve it on the unix socket only.
96pub fn router(state: AppState) -> Router {
97 Router::builder()
98 .route(RouteFn::new(Method::POST, "/hook/pre-receive", pre_receive))
99 .route(RouteFn::new(
100 Method::POST,
101 "/hook/post-receive",
102 post_receive,
103 ))
104 .route(RouteFn::new(
105 Method::POST,
106 "/internal/admin/backup",
107 admin_backup,
108 ))
109 .route(RouteFn::new(
110 Method::POST,
111 "/internal/admin/fsck",
112 admin_fsck,
113 ))
114 .route(RouteFn::new(
115 Method::POST,
116 "/internal/admin/lfs-gc",
117 admin_lfs_gc,
118 ))
119 .route(RouteFn::new(
120 Method::POST,
121 "/internal/admin/live",
122 admin_live,
123 ))
124 .with(state)
125 .build()
126}
127
128fn pre_receive(cx: &Cx, body: Body) -> RouteFuture<'_> {
129 Box::pin(async move { hook_endpoint(cx, body, Stage::PreReceive).await })
130}
131
132fn post_receive(cx: &Cx, body: Body) -> RouteFuture<'_> {
133 Box::pin(async move { hook_endpoint(cx, body, Stage::PostReceive).await })
134}
135
136#[derive(Clone, Copy)]
137enum Stage {
138 PreReceive,
139 PostReceive,
140}
141
142async fn hook_endpoint(
143 cx: &Cx,
144 body: Body,
145 stage: Stage,
146) -> topcoat::Result<topcoat::router::response::Response> {
147 let state = context::<AppState>(cx);
148 let presented = headers(cx)
149 .get(TOKEN_HEADER)
150 .and_then(|v| v.to_str().ok())
151 .unwrap_or("");
152 if !forge_core::token::constant_time_eq(presented.as_bytes(), state.internal_token.as_bytes()) {
153 return Err(forbidden().into());
154 }
155
156 let bytes = to_bytes(body, MAX_BODY_BYTES).await?;
157 let req: HookRequest = serde_json::from_slice(&bytes)
158 .map_err(|e| bad_request(format!("invalid hook request: {e}")))?;
159
160 let verdict = match stage {
161 Stage::PreReceive => match evaluate_pre_receive(&state.store, &state.git, &req).await {
162 Ok(verdict) => verdict,
163 Err(e) => {
164 // Fail closed: an internal error rejects the push.
165 tracing::error!(error = %e, repo_id = %req.repo_id, "pre-receive check failed");
166 HookResponse::deny("internal error while checking the push")
167 }
168 },
169 Stage::PostReceive if req.wiki => {
170 // A wiki push changes neither the code repo's refs nor its CI, pull requests or events.
171 // It still goes to the standby.
172 record_wiki_push(&state.store, &req).await;
173 crate::live::bump_wiki(state, &req.repo_id);
174 crate::replication::enqueue_repo(state, &req.repo_id);
175 HookResponse::allow()
176 }
177 Stage::PostReceive => {
178 let verdict = record_events(&state.store, &req).await;
179 trigger_maintenance(&state.git, &req.repo_id);
180 after_push_refs(state, &req).await;
181 verdict
182 }
183 };
184 Json(verdict).into_response(cx)
185}
186
187fn admin_backup(cx: &Cx, body: Body) -> RouteFuture<'_> {
188 Box::pin(async move { admin_backup_endpoint(cx, body).await })
189}
190
191fn admin_fsck(cx: &Cx, body: Body) -> RouteFuture<'_> {
192 Box::pin(async move { admin_fsck_endpoint(cx, body).await })
193}
194
195fn admin_lfs_gc(cx: &Cx, body: Body) -> RouteFuture<'_> {
196 Box::pin(async move { admin_lfs_gc_endpoint(cx, body).await })
197}
198
199fn admin_live(cx: &Cx, body: Body) -> RouteFuture<'_> {
200 Box::pin(async move { admin_live_endpoint(cx, body).await })
201}
202
203/// Body of `POST /internal/admin/live`. The CLI names what its write changed, and the server
204/// wakes the same topics its own writers would. Every list may be empty.
205#[derive(Deserialize, Default)]
206struct AdminLiveRequest {
207 /// Global admin topics by short name: `users`, `audit`, `backups`, `health`, `replication`,
208 /// `server`.
209 #[serde(default)]
210 admin: Vec<String>,
211 /// Users whose admin page and public profile changed.
212 #[serde(default)]
213 user_ids: Vec<String>,
214 /// Accounts whose own settings (sessions, username) changed.
215 #[serde(default)]
216 account_ids: Vec<String>,
217}
218
219/// `POST /internal/admin/live`. Wakes the open pages of the running server for a write made by
220/// another process (the admin CLI). The body is small and the answer carries no data.
221async fn admin_live_endpoint(cx: &Cx, body: Body) -> topcoat::Result<Response> {
222 let state = context::<AppState>(cx);
223 if !admin_authorized(cx, state) {
224 return Err(forbidden().into());
225 }
226 let bytes = to_bytes(body, MAX_BODY_BYTES).await?;
227 let req: AdminLiveRequest = serde_json::from_slice(&bytes)
228 .map_err(|e| bad_request(format!("invalid live request: {e}")))?;
229 let mut admin_topics = Vec::with_capacity(req.admin.len());
230 for name in &req.admin {
231 admin_topics.push(match name.as_str() {
232 "users" => Topic::AdminUsers,
233 "audit" => Topic::AdminAudit,
234 "backups" => Topic::AdminBackups,
235 "health" => Topic::AdminHealth,
236 "replication" => Topic::AdminReplication,
237 "server" => Topic::AdminServer,
238 other => {
239 return Ok(admin_error(&forge_core::Error::Invalid(format!(
240 "unknown admin topic: {other}"
241 ))));
242 }
243 });
244 }
245 let hub = live::admin();
246 for topic in &admin_topics {
247 hub.bump(topic);
248 }
249 for id in &req.user_ids {
250 hub.bump(&Topic::AdminUser(id.clone()));
251 state.live.bump(&Topic::User(id.clone()));
252 }
253 for id in &req.account_ids {
254 state.live.bump(&Topic::Account(id.clone()));
255 }
256 Ok(admin_response(
257 StatusCode::OK,
258 serde_json::json!({ "ok": true }),
259 ))
260}
261
262/// `POST /internal/admin/lfs-gc`. The body is ignored.
263async fn admin_lfs_gc_endpoint(cx: &Cx, _body: Body) -> topcoat::Result<Response> {
264 let state = context::<AppState>(cx);
265 if !admin_authorized(cx, state) {
266 return Err(forbidden().into());
267 }
268 Ok(
269 match crate::lfs::gc::gc(
270 &state.store,
271 &state.config.data_dir,
272 crate::lfs::gc::GC_MIN_AGE,
273 )
274 .await
275 {
276 Ok(summary) => admin_response(StatusCode::OK, serde_json::json!(summary)),
277 Err(e) => admin_error(&e),
278 },
279 )
280}
281
282/// Body of `POST /internal/admin/backup`. `out` is the directory that receives the set.
283#[derive(Deserialize)]
284struct AdminBackupRequest {
285 out: String,
286 #[serde(default)]
287 include_key: bool,
288 #[serde(default)]
289 scope: Option<Scope>,
290}
291
292/// Body of `POST /internal/admin/fsck`.
293#[derive(Deserialize)]
294struct AdminFsckRequest {
295 #[serde(default)]
296 full: bool,
297}
298
299/// Admin routes need the per-boot admin token. The socket itself is 0600 in the 0700 data dir.
300fn admin_authorized(cx: &Cx, state: &AppState) -> bool {
301 let presented = headers(cx)
302 .get(ADMIN_TOKEN_HEADER)
303 .and_then(|v| v.to_str().ok())
304 .unwrap_or("");
305 forge_core::token::constant_time_eq(presented.as_bytes(), state.admin_token.as_bytes())
306}
307
308async fn admin_backup_endpoint(cx: &Cx, body: Body) -> topcoat::Result<Response> {
309 let state = context::<AppState>(cx);
310 if !admin_authorized(cx, state) {
311 return Err(forbidden().into());
312 }
313 let bytes = to_bytes(body, MAX_BODY_BYTES).await?;
314 let req: AdminBackupRequest = serde_json::from_slice(&bytes)
315 .map_err(|e| bad_request(format!("invalid backup request: {e}")))?;
316 let out = match std::path::absolute(&req.out) {
317 Ok(out) => out,
318 Err(e) => return Ok(admin_error(&forge_core::Error::Io(e))),
319 };
320 let guard = match state.jobs.claim(RunKind::Backup) {
321 Ok(guard) => guard,
322 Err(e) => return Ok(admin_error(&e)),
323 };
324 let target_name = out.to_string_lossy().into_owned();
325 audit::record(
326 &state.store,
327 None,
328 Actor::Cli,
329 AuditAction::BackupStarted,
330 Target {
331 kind: "backup",
332 id: "",
333 name: &target_name,
334 },
335 serde_json::json!({ "trigger": "cli" }),
336 )
337 .await;
338 let opts = BackupOptions {
339 out,
340 include_key: req.include_key,
341 scope: req.scope.unwrap_or(Scope::All),
342 };
343 let result = run_backup_now(state, guard, RunTrigger::Cli, opts, false).await;
344 Ok(match result {
345 Ok(summary) => admin_response(StatusCode::OK, serde_json::json!(summary)),
346 Err(e) => admin_error(&e),
347 })
348}
349
350async fn admin_fsck_endpoint(cx: &Cx, body: Body) -> topcoat::Result<Response> {
351 let state = context::<AppState>(cx);
352 if !admin_authorized(cx, state) {
353 return Err(forbidden().into());
354 }
355 let bytes = to_bytes(body, MAX_BODY_BYTES).await?;
356 let req: AdminFsckRequest = if bytes.is_empty() {
357 AdminFsckRequest { full: false }
358 } else {
359 serde_json::from_slice(&bytes)
360 .map_err(|e| bad_request(format!("invalid fsck request: {e}")))?
361 };
362 let guard = match state.jobs.claim(RunKind::Fsck) {
363 Ok(guard) => guard,
364 Err(e) => return Ok(admin_error(&e)),
365 };
366 audit::record(
367 &state.store,
368 None,
369 Actor::Cli,
370 AuditAction::FsckStarted,
371 Target {
372 kind: "fsck",
373 id: "",
374 name: "",
375 },
376 serde_json::json!({ "trigger": "cli", "full": req.full }),
377 )
378 .await;
379 let result = run_fsck_now(state, guard, RunTrigger::Cli, req.full).await;
380 Ok(match result {
381 Ok(summary) => admin_response(StatusCode::OK, serde_json::json!(summary)),
382 Err(e) => admin_error(&e),
383 })
384}
385
386/// A JSON answer with the given status.
387fn admin_response(status: StatusCode, value: serde_json::Value) -> Response {
388 let mut res = Response::new(Body::from(value.to_string()));
389 *res.status_mut() = status;
390 res.headers_mut().insert(
391 header::CONTENT_TYPE,
392 HeaderValue::from_static("application/json"),
393 );
394 res
395}
396
397/// Maps a failed admin action to a status and a `{"error": ...}` body.
398fn admin_error(e: &forge_core::Error) -> Response {
399 let status = match e {
400 forge_core::Error::Conflict(_) => StatusCode::CONFLICT,
401 forge_core::Error::Invalid(_) | forge_core::Error::Config(_) => StatusCode::BAD_REQUEST,
402 forge_core::Error::Forbidden(_) => StatusCode::FORBIDDEN,
403 forge_core::Error::NotFound => StatusCode::NOT_FOUND,
404 _ => StatusCode::INTERNAL_SERVER_ERROR,
405 };
406 let message = match e {
407 forge_core::Error::Conflict(text) => text.clone(),
408 other => other.to_string(),
409 };
410 admin_response(status, serde_json::json!({ "error": message }))
411}
412
413async fn record_events(store: &Store, req: &HookRequest) -> HookResponse {
414 let mut failures = Vec::new();
415 for update in &req.updates {
416 let recorded = store
417 .record_push_event(
418 &req.repo_id,
419 &req.actor_id,
420 &update.ref_name,
421 &update.old,
422 &update.new,
423 &req.protocol,
424 )
425 .await;
426 if let Err(e) = recorded {
427 tracing::error!(error = %e, repo_id = %req.repo_id, ref_name = %update.ref_name, "failed to record push event");
428 failures.push(format!(
429 "warning: could not record push to {:?}",
430 update.ref_name
431 ));
432 }
433 }
434 // post-receive cannot reject a push, so the verdict is always allow.
435 HookResponse {
436 allow: true,
437 message: failures.join("\n"),
438 }
439}
440
441/// Repos with post-push maintenance in flight. The value is true when another push
442/// arrived while the run was active, so one rerun is due.
443static MAINTENANCE: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
444
445fn maintenance_state() -> MutexGuard<'static, HashMap<String, bool>> {
446 MAINTENANCE
447 .get_or_init(|| Mutex::new(HashMap::new()))
448 .lock()
449 .unwrap_or_else(PoisonError::into_inner)
450}
451
452/// Marks `repo_id` in flight. Returns true when the caller must start the worker; otherwise
453/// the running worker is flagged to run once more.
454fn claim_maintenance(map: &mut HashMap<String, bool>, repo_id: &str) -> bool {
455 match map.get_mut(repo_id) {
456 Some(dirty) => {
457 *dirty = true;
458 false
459 }
460 None => {
461 map.insert(repo_id.to_owned(), false);
462 true
463 }
464 }
465}
466
467/// Called after a run. Returns true when a rerun is due (the entry stays claimed);
468/// otherwise releases the repo.
469fn finish_maintenance(map: &mut HashMap<String, bool>, repo_id: &str) -> bool {
470 let rerun = map
471 .get_mut(repo_id)
472 .map(|dirty| std::mem::replace(dirty, false));
473 if rerun == Some(true) {
474 return true;
475 }
476 map.remove(repo_id);
477 false
478}
479
480/// Starts `maintenance::after_push` for the repo in the background, coalescing concurrent calls
481/// per repo. Failures are logged, never returned, so the push response is not failed. Called once
482/// per push by the post-receive hook, and by the web merge route after it updates a branch.
483pub fn trigger_maintenance(git: &Arc<GitEnv>, repo_id: &str) {
484 let repo_dir = match forge_git::repo::repo_path(&git.data_dir, repo_id) {
485 Ok(dir) => dir,
486 Err(e) => {
487 tracing::error!(error = %e, repo_id = %repo_id, "skipping post-push maintenance");
488 return;
489 }
490 };
491 if !claim_maintenance(&mut maintenance_state(), repo_id) {
492 return;
493 }
494 let git = Arc::clone(git);
495 let repo_id = repo_id.to_owned();
496 tokio::spawn(async move {
497 loop {
498 if let Err(e) = forge_git::maintenance::after_push(&git, &repo_dir).await {
499 tracing::error!(error = %e, repo_id = %repo_id, "post-push maintenance failed");
500 }
501 let rerun = finish_maintenance(&mut maintenance_state(), &repo_id);
502 if !rerun {
503 break;
504 }
505 }
506 });
507}
508
509/// Marks the repo for pruning when the push deleted a ref or moved one to a commit that does not
510/// contain its old one: that history is now unreachable.
511async fn mark_rewrites(state: &AppState, req: &HookRequest) {
512 let Ok(repo_dir) = forge_git::repo::repo_path(&state.git.data_dir, &req.repo_id) else {
513 return;
514 };
515 for update in &req.updates {
516 if is_zero_oid(&update.old) {
517 continue;
518 }
519 let kept = !is_zero_oid(&update.new)
520 && forge_git::pulls::is_ancestor(&state.git, &repo_dir, &update.old, &update.new)
521 .await
522 .unwrap_or(false);
523 if !kept {
524 forge_git::maintenance::mark_prune_due(&repo_dir);
525 return;
526 }
527 }
528}
529
530/// Runs `post_update::after_ref_update` for every ref the push updated. Errors are logged; the
531/// push itself is already accepted at this point.
532async fn after_push_refs(state: &AppState, req: &HookRequest) {
533 let repo: Repo = match state.store.repo_by_id(&req.repo_id).await {
534 Ok(Some(repo)) => repo,
535 Ok(None) => return,
536 Err(e) => {
537 tracing::error!(error = %e, repo_id = %req.repo_id, "post-update: repo lookup failed");
538 return;
539 }
540 };
541 mark_rewrites(state, req).await;
542 for update in &req.updates {
543 if let Err(e) = after_ref_update(
544 state,
545 &repo,
546 &req.actor_id,
547 &update.ref_name,
548 &update.old,
549 &update.new,
550 )
551 .await
552 {
553 tracing::error!(error = %e, repo_id = %req.repo_id, ref_name = %update.ref_name, "post-update failed");
554 }
555 }
556}
557
558/// Writes a `wiki_pushed` audit entry for an accepted wiki push. The pusher is looked up by id; a
559/// push with no known user (a CI job cannot push) is recorded as anonymous.
560async fn record_wiki_push(store: &Store, req: &HookRequest) {
561 let repo = match store.repo_by_id(&req.repo_id).await {
562 Ok(Some(repo)) => repo,
563 Ok(None) => return,
564 Err(e) => {
565 tracing::error!(error = %e, repo_id = %req.repo_id, "could not load repo for wiki audit");
566 return;
567 }
568 };
569 let user = match store.user_by_id(&req.actor_id).await {
570 Ok(user) => user,
571 Err(e) => {
572 tracing::error!(error = %e, actor_id = %req.actor_id, "could not load pusher for wiki audit");
573 None
574 }
575 };
576 let actor = match user.as_ref() {
577 Some(user) => Actor::User(user),
578 None => Actor::Anonymous,
579 };
580 let updates: Vec<serde_json::Value> = req
581 .updates
582 .iter()
583 .map(|u| serde_json::json!({ "ref": u.ref_name, "old": u.old, "new": u.new }))
584 .collect();
585 audit::record(
586 store,
587 None,
588 actor,
589 AuditAction::WikiPushed,
590 Target {
591 kind: "repo",
592 id: &repo.id,
593 name: &format!("{}/{}", repo.owner_name, repo.name),
594 },
595 serde_json::json!({ "updates": updates }),
596 )
597 .await;
598}
599
600/// Decides whether a push may proceed. `Ok(deny)` is a policy decision; `Err` is an
601/// internal failure (the caller turns it into a deny).
602pub async fn evaluate_pre_receive(
603 store: &Store,
604 git: &GitEnv,
605 req: &HookRequest,
606) -> forge_core::Result<HookResponse> {
607 let Some(repo) = store.repo_by_id(&req.repo_id).await? else {
608 return Ok(HookResponse::deny("repository not found"));
609 };
610 if repo.archived {
611 return Ok(HookResponse::deny("repository is archived"));
612 }
613 if req.wiki {
614 if !store.wiki_enabled(&repo.id).await? {
615 return Ok(HookResponse::deny("the wiki is disabled"));
616 }
617 } else if store.pull_mirror(&repo.id).await?.is_some() {
618 // A pull mirror's refs come from its remote; a push here would be overwritten by the next sync.
619 // Mirrors do not mirror wikis, so wiki pushes are not refused for this.
620 return Ok(HookResponse::deny("this repository is a pull mirror"));
621 }
622 let repo_dir = if req.wiki {
623 forge_git::repo::wiki_path(&git.data_dir, &repo.id)?
624 } else {
625 forge_git::repo::repo_path(&git.data_dir, &repo.id)?
626 };
627 // Loaded once per push; every branch update below is checked against the same rules. Wiki
628 // pushes skip the rules: the wiki has no protected branches, only its main branch.
629 let rules = if req.wiki {
630 Vec::new()
631 } else {
632 store.list_branch_rules(&repo.id).await?
633 };
634
635 for update in &req.updates {
636 if !is_valid_ref_name(&update.ref_name) {
637 return Ok(HookResponse::deny(format!(
638 "invalid ref name: {:?}",
639 update.ref_name
640 )));
641 }
642 if !is_valid_oid(&update.old) || !is_valid_oid(&update.new) {
643 return Ok(HookResponse::deny(format!(
644 "invalid object id in update to {:?}",
645 update.ref_name
646 )));
647 }
648 if req.wiki {
649 if update.ref_name != "refs/heads/main" {
650 return Ok(HookResponse::deny(
651 "the wiki only accepts changes to its main branch",
652 ));
653 }
654 if is_zero_oid(&update.new) {
655 return Ok(HookResponse::deny(
656 "the wiki's main branch cannot be deleted",
657 ));
658 }
659 continue;
660 }
661 let Some(branch) = update.ref_name.strip_prefix("refs/heads/") else {
662 continue;
663 };
664 let protection = effective(&rules, &repo.default_branch, branch);
665 if protection.restrict_push && !may_push_directly(store, &repo, &req.actor_id).await? {
666 return Ok(HookResponse::deny(format!(
667 "branch '{branch}' only accepts changes through pull requests"
668 )));
669 }
670 if is_zero_oid(&update.new) {
671 if !protection.allow_deletion {
672 return Ok(HookResponse::deny(format!(
673 "deleting protected branch '{branch}' is not allowed"
674 )));
675 }
676 continue;
677 }
678 if is_zero_oid(&update.old) || protection.allow_force_push {
679 continue;
680 }
681 match drops_commits(git, &repo_dir, req, update).await {
682 Ok(false) => {}
683 Ok(true) => {
684 return Ok(HookResponse::deny(format!(
685 "force-push to protected branch '{branch}' is not allowed"
686 )));
687 }
688 Err(e) => {
689 return Ok(HookResponse::deny(format!(
690 "could not verify the update to '{branch}': {e}"
691 )));
692 }
693 }
694 }
695 Ok(HookResponse::allow())
696}
697
698/// Whether `actor_id` may push straight to a `restrict_push` branch: an instance admin, the owner
699/// of a person-owned repo, or someone whose effective role is Admin (a collaborator Admin, or an
700/// org owner or admin team on an org-owned repo). Pull request merges do not go through here.
701pub async fn may_push_directly(
702 store: &Store,
703 repo: &Repo,
704 actor_id: &str,
705) -> forge_core::Result<bool> {
706 let Some(actor) = store.user_by_id(actor_id).await? else {
707 return Ok(false);
708 };
709 if actor.is_admin || actor.id == repo.owner_id {
710 return Ok(true);
711 }
712 let collaborator = store.collaborator_role(&repo.id, actor_id).await?;
713 let org = store
714 .org_repo_role(&repo.owner_id, actor_id, &repo.id)
715 .await?;
716 Ok(forge_core::authz::max_role(collaborator, org) == Some(Role::Admin))
717}
718
719/// True when `old` has commits that `new` does not contain, i.e. the update
720/// is not a fast-forward. Runs `git rev-list --max-count=1 <old> ^<new>` with the
721/// quarantine environment so that objects received in this push are visible.
722async fn drops_commits(
723 git: &GitEnv,
724 repo_dir: &Path,
725 req: &HookRequest,
726 update: &HookUpdate,
727) -> forge_git::Result<bool> {
728 let excluded = format!("^{}", update.new);
729 let mut cmd = GitCommand::new(git, "rev-list")
730 .git_dir(repo_dir)
731 .arg("--max-count=1")
732 .user_revs(&[update.old.as_str(), excluded.as_str()])?;
733 for key in QUARANTINE_VARS {
734 if let Some(value) = req.quarantine_env.get(key) {
735 cmd = cmd.env(key, value);
736 }
737 }
738 let stdout = cmd.output().await?;
739 Ok(!stdout.is_empty())
740}
741
742/// Accepts `refs/...` names without `..`, without a `-`-prefixed component, and
743/// without control characters.
744pub fn is_valid_ref_name(name: &str) -> bool {
745 let Some(rest) = name.strip_prefix("refs/") else {
746 return false;
747 };
748 !rest.is_empty()
749 && !name.contains("..")
750 && !name.chars().any(char::is_control)
751 && !name.split('/').any(|component| component.starts_with('-'))
752}
753
754/// True for the all-zero object id (40 or 64 hex digits), which git uses for
755/// creation (`old`) and deletion (`new`).
756pub fn is_zero_oid(oid: &str) -> bool {
757 matches!(oid.len(), 40 | 64) && oid.bytes().all(|b| b == b'0')
758}
759
760/// True for a SHA-1 or SHA-256 object id: 40 or 64 hex digits.
761pub fn is_valid_oid(oid: &str) -> bool {
762 matches!(oid.len(), 40 | 64) && oid.bytes().all(|b| b.is_ascii_hexdigit())
763}
764
765#[cfg(test)]
766mod tests {
767 use super::*;
768 use forge_core::protection::RuleFlags;
769 use std::path::PathBuf;
770 use topcoat::router::RouterBuilderDiscoverExt;
771
772 #[test]
773 fn ref_name_validity_cases() {
774 // (ref name, expected validity): must live under refs/, no dotdot or leading dash, no control chars.
775 let cases: [(&str, bool); 12] = [
776 ("refs/heads/main", true),
777 ("refs/tags/v1.0", true),
778 ("HEAD", false),
779 ("heads/main", false),
780 ("refs/", false),
781 ("refs/heads/a..b", false),
782 ("refs/heads/-evil", false),
783 ("refs/-evil/main", false),
784 ("refs/heads/a-b", true),
785 ("refs/heads/a\nb", false),
786 ("refs/heads/a\0b", false),
787 ("refs/heads/a\x7fb", false),
788 ];
789 for (name, want) in cases {
790 assert_eq!(is_valid_ref_name(name), want, "case {name:?}");
791 }
792 }
793
794 #[test]
795 fn zero_oid_detection() {
796 assert!(is_zero_oid(&"0".repeat(40)));
797 assert!(is_zero_oid(&"0".repeat(64)));
798 assert!(!is_zero_oid(&"0".repeat(39)));
799 assert!(!is_zero_oid(&format!("{}1", "0".repeat(39))));
800 assert!(!is_zero_oid(""));
801 }
802
803 #[test]
804 fn oid_validation() {
805 assert!(is_valid_oid(&"a".repeat(40)));
806 assert!(is_valid_oid(&"F".repeat(64)));
807 assert!(is_valid_oid(&"0".repeat(40)));
808 assert!(!is_valid_oid(&"g".repeat(40)));
809 assert!(!is_valid_oid(&"a".repeat(41)));
810 assert!(!is_valid_oid("--all"));
811 }
812
813 #[test]
814 fn maintenance_claims_coalesce_per_repo() {
815 let mut map = HashMap::new();
816 // First push starts a worker; pushes during the run only flag a rerun.
817 assert!(claim_maintenance(&mut map, "r1"));
818 assert!(!claim_maintenance(&mut map, "r1"));
819 assert!(!claim_maintenance(&mut map, "r1"));
820 // Other repos are independent.
821 assert!(claim_maintenance(&mut map, "r2"));
822 // One rerun is due after the first run, then the repo is released.
823 assert!(finish_maintenance(&mut map, "r1"));
824 assert!(!finish_maintenance(&mut map, "r1"));
825 assert!(!map.contains_key("r1"));
826 assert!(claim_maintenance(&mut map, "r1"));
827 assert!(!finish_maintenance(&mut map, "r2"));
828 }
829
830 fn git(dir: &Path, args: &[&str]) -> String {
831 let out = std::process::Command::new("git")
832 .arg("-C")
833 .arg(dir)
834 .args(args)
835 .env("GIT_AUTHOR_NAME", "test")
836 .env("GIT_AUTHOR_EMAIL", "test@example.com")
837 .env("GIT_COMMITTER_NAME", "test")
838 .env("GIT_COMMITTER_EMAIL", "test@example.com")
839 .output()
840 .expect("git runs");
841 assert!(
842 out.status.success(),
843 "git {args:?} failed: {}",
844 String::from_utf8_lossy(&out.stderr)
845 );
846 String::from_utf8_lossy(&out.stdout).trim().to_string()
847 }
848
849 fn commit(work: &Path, contents: &str) -> String {
850 std::fs::write(work.join("file.txt"), contents).expect("write file");
851 git(work, &["add", "file.txt"]);
852 git(work, &["commit", "-m", contents]);
853 git(work, &["rev-parse", "HEAD"])
854 }
855
856 #[tokio::test]
857 async fn admin_routes_reject_a_missing_or_wrong_token() {
858 let dir = tempfile::tempdir().expect("tempdir");
859 let state = crate::test_support::test_state(dir.path()).await;
860 let router = router(state);
861 for path in ["/internal/admin/backup", "/internal/admin/fsck"] {
862 for token in [None, Some("wrong")] {
863 let mut builder = topcoat::router::request::Request::builder()
864 .method("POST")
865 .uri(path)
866 .header("content-type", "application/json");
867 if let Some(token) = token {
868 builder = builder.header(ADMIN_TOKEN_HEADER, token);
869 }
870 let req = builder
871 .body(Body::from(r#"{"out":"/nonexistent/forge-test"}"#))
872 .expect("request");
873 let res = router.handle(req).await;
874 assert_eq!(res.status(), 403, "{path} with token {token:?}");
875 }
876 }
877 // The right token gets through: an fsck of an instance with no repos is clean.
878 let req = topcoat::router::request::Request::builder()
879 .method("POST")
880 .uri("/internal/admin/fsck")
881 .header("content-type", "application/json")
882 .header(ADMIN_TOKEN_HEADER, crate::test_support::ADMIN_TOKEN)
883 .body(Body::from("{}"))
884 .expect("request");
885 let res = router.handle(req).await;
886 assert_eq!(res.status(), 200);
887 }
888
889 /// The live route needs the admin token and wakes the topics it names on the right hub.
890 #[tokio::test]
891 async fn live_bump_wakes_the_named_topics() {
892 let dir = tempfile::tempdir().expect("tempdir");
893 let state = crate::test_support::test_state(dir.path()).await;
894 let users = live::admin().subscribe(&Topic::AdminUsers);
895 let profile = state.live.subscribe(&Topic::User("u1".to_owned()));
896 let router = router(state);
897 let body = r#"{"admin":["users"],"user_ids":["u1"]}"#;
898
899 let refused = topcoat::router::request::Request::builder()
900 .method("POST")
901 .uri("/internal/admin/live")
902 .header("content-type", "application/json")
903 .header(ADMIN_TOKEN_HEADER, "wrong")
904 .body(Body::from(body))
905 .expect("request");
906 assert_eq!(router.handle(refused).await.status(), 403);
907
908 let req = topcoat::router::request::Request::builder()
909 .method("POST")
910 .uri("/internal/admin/live")
911 .header("content-type", "application/json")
912 .header(ADMIN_TOKEN_HEADER, crate::test_support::ADMIN_TOKEN)
913 .body(Body::from(body))
914 .expect("request");
915 assert_eq!(router.handle(req).await.status(), 200);
916 assert!(users.has_changed().expect("open"));
917 assert!(profile.has_changed().expect("open"));
918 }
919
920 #[tokio::test]
921 async fn hook_routes_are_not_collected_by_discover() {
922 // The public router uses `.discover()`. Hook routes are plain RouteFns and must not be in it.
923 let public = Router::builder().discover().build();
924 for path in ["/hook/pre-receive", "/hook/post-receive"] {
925 let req = topcoat::router::request::Request::builder()
926 .method("POST")
927 .uri(path)
928 .body(Body::empty())
929 .expect("request");
930 let res = public.handle(req).await;
931 assert_eq!(
932 res.status(),
933 404,
934 "{path} is reachable on the discover router"
935 );
936 }
937 }
938
939 #[tokio::test]
940 async fn pre_receive_restrict_push_allows_only_repo_admins() {
941 let tmp = tempfile::tempdir().expect("tempdir");
942 let store = Store::open(&tmp.path().join("forge.db"))
943 .await
944 .expect("store");
945 let owner = store
946 .create_user("tahinli", None, "unused", false)
947 .await
948 .expect("owner");
949 let writer = store
950 .create_user("bob", None, "unused", false)
951 .await
952 .expect("writer");
953 let admin = store
954 .create_user("carol", None, "unused", false)
955 .await
956 .expect("admin");
957 let repo = store
958 .create_repo(
959 &owner.id,
960 "proj",
961 "",
962 forge_core::Visibility::Private,
963 "main",
964 )
965 .await
966 .expect("repo");
967 store
968 .set_collaborator(&repo.id, &writer.id, Role::Write)
969 .await
970 .expect("writer role");
971 store
972 .set_collaborator(&repo.id, &admin.id, Role::Admin)
973 .await
974 .expect("admin role");
975 let git_env = GitEnv {
976 git_bin: PathBuf::from("git"),
977 data_dir: tmp.path().to_path_buf(),
978 };
979 let bare = forge_git::repo::repo_path(&git_env.data_dir, &repo.id).expect("repo path");
980 forge_git::repo::init_bare(&git_env, &bare, "main")
981 .await
982 .expect("init bare");
983 let bare_str = bare.to_str().expect("utf8 path");
984 let work = tmp.path().join("work");
985 git(tmp.path(), &["init", "-b", "main", "work"]);
986 let first = commit(&work, "one");
987 git(&work, &["push", bare_str, "main"]);
988 let second = commit(&work, "two");
989 git(&work, &["push", bare_str, "main"]);
990
991 store
992 .upsert_branch_rule(
993 &repo.id,
994 "main",
995 RuleFlags {
996 restrict_push: true,
997 ..RuleFlags::default()
998 },
999 )
1000 .await
1001 .expect("upsert rule");
1002
1003 let request = |actor: &str, old: &str, new: &str| HookRequest {
1004 repo_id: repo.id.clone(),
1005 actor_id: actor.into(),
1006 protocol: "http".into(),
1007 wiki: false,
1008 updates: vec![HookUpdate {
1009 old: old.into(),
1010 new: new.into(),
1011 ref_name: "refs/heads/main".into(),
1012 }],
1013 quarantine_env: BTreeMap::new(),
1014 };
1015
1016 // A Write collaborator's direct fast-forward is refused.
1017 let refused = evaluate_pre_receive(&store, &git_env, &request(&writer.id, &first, &second))
1018 .await
1019 .expect("evaluate");
1020 assert!(!refused.allow);
1021 assert_eq!(
1022 refused.message,
1023 "branch 'main' only accepts changes through pull requests"
1024 );
1025 // So is creating the branch.
1026 let created = evaluate_pre_receive(
1027 &store,
1028 &git_env,
1029 &request(&writer.id, &"0".repeat(40), &second),
1030 )
1031 .await
1032 .expect("evaluate");
1033 assert!(!created.allow);
1034
1035 // Repo admins (Admin collaborators and the owner) may still push.
1036 for actor in [&admin.id, &owner.id] {
1037 let ok = evaluate_pre_receive(&store, &git_env, &request(actor, &first, &second))
1038 .await
1039 .expect("evaluate");
1040 assert_eq!(ok, HookResponse::allow());
1041 }
1042 }
1043
1044 #[tokio::test]
1045 async fn pre_receive_rejects_pushes_to_a_pull_mirror() {
1046 let tmp = tempfile::tempdir().expect("tempdir");
1047 let store = Store::open(&tmp.path().join("forge.db"))
1048 .await
1049 .expect("store");
1050 let owner = store
1051 .create_user("tahinli", None, "unused", false)
1052 .await
1053 .expect("user");
1054 let repo = store
1055 .create_repo(
1056 &owner.id,
1057 "mirror",
1058 "",
1059 forge_core::Visibility::Public,
1060 "main",
1061 )
1062 .await
1063 .expect("repo");
1064 let git_env = GitEnv {
1065 git_bin: "git".into(),
1066 data_dir: tmp.path().to_path_buf(),
1067 };
1068 let bare = forge_git::repo::repo_path(&git_env.data_dir, &repo.id).expect("repo path");
1069 forge_git::repo::init_bare(&git_env, &bare, "main")
1070 .await
1071 .expect("init bare");
1072 let request = HookRequest {
1073 repo_id: repo.id.clone(),
1074 actor_id: owner.id.clone(),
1075 protocol: "http".into(),
1076 wiki: false,
1077 updates: vec![HookUpdate {
1078 old: "0".repeat(40),
1079 new: "1".repeat(40),
1080 ref_name: "refs/heads/main".into(),
1081 }],
1082 quarantine_env: BTreeMap::new(),
1083 };
1084 // Before the pull mirror exists, the push is not refused for that reason.
1085 let before = evaluate_pre_receive(&store, &git_env, &request)
1086 .await
1087 .expect("evaluate");
1088 assert_ne!(before.message, "this repository is a pull mirror");
1089
1090 store
1091 .create_mirror(&forge_core::mirrors::NewMirror {
1092 repo_id: &repo.id,
1093 direction: forge_core::mirrors::MirrorDirection::Pull,
1094 url: "https://example.com/upstream.git",
1095 username: "",
1096 secret: None,
1097 interval_minutes: 480,
1098 })
1099 .await
1100 .expect("pull mirror");
1101 let refused = evaluate_pre_receive(&store, &git_env, &request)
1102 .await
1103 .expect("evaluate");
1104 assert!(!refused.allow);
1105 assert_eq!(refused.message, "this repository is a pull mirror");
1106 }
1107
1108 #[tokio::test]
1109 async fn pre_receive_detects_non_fast_forward_on_default_branch() {
1110 let tmp = tempfile::tempdir().expect("tempdir");
1111 let store = Store::open(&tmp.path().join("forge.db"))
1112 .await
1113 .expect("store");
1114 let owner = store
1115 .create_user("tahinli", None, "unused", false)
1116 .await
1117 .expect("user");
1118 let repo = store
1119 .create_repo(
1120 &owner.id,
1121 "proj",
1122 "",
1123 forge_core::Visibility::Private,
1124 "main",
1125 )
1126 .await
1127 .expect("repo");
1128 let git_env = GitEnv {
1129 git_bin: PathBuf::from("git"),
1130 data_dir: tmp.path().to_path_buf(),
1131 };
1132
1133 // Bare repo at the path forge would use for this repo id.
1134 let bare = forge_git::repo::repo_path(&git_env.data_dir, &repo.id).expect("repo path");
1135 forge_git::repo::init_bare(&git_env, &bare, "main")
1136 .await
1137 .expect("init bare");
1138 let bare_str = bare.to_str().expect("utf8 path");
1139
1140 // Two commits on main, then a divergent commit on a side branch.
1141 let work = tmp.path().join("work");
1142 git(tmp.path(), &["init", "-b", "main", "work"]);
1143 let first = commit(&work, "one");
1144 git(&work, &["push", bare_str, "main"]);
1145 let second = commit(&work, "two");
1146 git(&work, &["push", bare_str, "main"]);
1147 git(&work, &["reset", "--hard", &first]);
1148 let divergent = commit(&work, "three");
1149 git(
1150 &work,
1151 &["push", bare_str, &format!("{divergent}:refs/heads/side")],
1152 );
1153
1154 let request = |old: &str, new: &str| HookRequest {
1155 repo_id: repo.id.clone(),
1156 actor_id: owner.id.clone(),
1157 protocol: "http".into(),
1158 wiki: false,
1159 updates: vec![HookUpdate {
1160 old: old.into(),
1161 new: new.into(),
1162 ref_name: "refs/heads/main".into(),
1163 }],
1164 quarantine_env: BTreeMap::new(),
1165 };
1166
1167 // Fast-forward: allowed.
1168 let ff = evaluate_pre_receive(&store, &git_env, &request(&first, &second))
1169 .await
1170 .expect("evaluate");
1171 assert_eq!(ff, HookResponse::allow());
1172
1173 // Non-fast-forward: denied.
1174 let forced = evaluate_pre_receive(&store, &git_env, &request(&second, &divergent))
1175 .await
1176 .expect("evaluate");
1177 assert!(!forced.allow);
1178 assert_eq!(
1179 forced.message,
1180 "force-push to protected branch 'main' is not allowed"
1181 );
1182
1183 // Deleting the default branch: denied.
1184 let deleted = evaluate_pre_receive(&store, &git_env, &request(&second, &"0".repeat(40)))
1185 .await
1186 .expect("evaluate");
1187 assert!(!deleted.allow);
1188 assert_eq!(
1189 deleted.message,
1190 "deleting protected branch 'main' is not allowed"
1191 );
1192
1193 // A rule that allows force pushes lifts only that check; deletion stays denied.
1194 store
1195 .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(true, false))
1196 .await
1197 .expect("upsert rule");
1198 let forced_ok = evaluate_pre_receive(&store, &git_env, &request(&second, &divergent))
1199 .await
1200 .expect("evaluate");
1201 assert_eq!(forced_ok, HookResponse::allow());
1202 let deleted_again =
1203 evaluate_pre_receive(&store, &git_env, &request(&second, &"0".repeat(40)))
1204 .await
1205 .expect("evaluate");
1206 assert_eq!(
1207 deleted_again.message,
1208 "deleting protected branch 'main' is not allowed"
1209 );
1210 }
1211}