forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiBb00f3f4Tahinli1 month ago147 commits

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