forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.4 MiBbcaef90Tahinli1 month ago164 commits

internal.rs1089 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_name_validity_cases() {
683 // (ref name, expected validity): must live under refs/, no dotdot or leading dash, no control chars.
684 let cases: [(&str, bool); 12] = [
685 ("refs/heads/main", true),
686 ("refs/tags/v1.0", true),
687 ("HEAD", false),
688 ("heads/main", false),
689 ("refs/", false),
690 ("refs/heads/a..b", false),
691 ("refs/heads/-evil", false),
692 ("refs/-evil/main", false),
693 ("refs/heads/a-b", true),
694 ("refs/heads/a\nb", false),
695 ("refs/heads/a\0b", false),
696 ("refs/heads/a\x7fb", false),
697 ];
698 for (name, want) in cases {
699 assert_eq!(is_valid_ref_name(name), want, "case {name:?}");
700 }
701 }
702
703 #[test]
704 fn zero_oid_detection() {
705 assert!(is_zero_oid(&"0".repeat(40)));
706 assert!(is_zero_oid(&"0".repeat(64)));
707 assert!(!is_zero_oid(&"0".repeat(39)));
708 assert!(!is_zero_oid(&format!("{}1", "0".repeat(39))));
709 assert!(!is_zero_oid(""));
710 }
711
712 #[test]
713 fn oid_validation() {
714 assert!(is_valid_oid(&"a".repeat(40)));
715 assert!(is_valid_oid(&"F".repeat(64)));
716 assert!(is_valid_oid(&"0".repeat(40)));
717 assert!(!is_valid_oid(&"g".repeat(40)));
718 assert!(!is_valid_oid(&"a".repeat(41)));
719 assert!(!is_valid_oid("--all"));
720 }
721
722 #[test]
723 fn maintenance_claims_coalesce_per_repo() {
724 let mut map = HashMap::new();
725 // First push starts a worker; pushes during the run only flag a rerun.
726 assert!(claim_maintenance(&mut map, "r1"));
727 assert!(!claim_maintenance(&mut map, "r1"));
728 assert!(!claim_maintenance(&mut map, "r1"));
729 // Other repos are independent.
730 assert!(claim_maintenance(&mut map, "r2"));
731 // One rerun is due after the first run, then the repo is released.
732 assert!(finish_maintenance(&mut map, "r1"));
733 assert!(!finish_maintenance(&mut map, "r1"));
734 assert!(!map.contains_key("r1"));
735 assert!(claim_maintenance(&mut map, "r1"));
736 assert!(!finish_maintenance(&mut map, "r2"));
737 }
738
739 fn git(dir: &Path, args: &[&str]) -> String {
740 let out = std::process::Command::new("git")
741 .arg("-C")
742 .arg(dir)
743 .args(args)
744 .env("GIT_AUTHOR_NAME", "test")
745 .env("GIT_AUTHOR_EMAIL", "test@example.com")
746 .env("GIT_COMMITTER_NAME", "test")
747 .env("GIT_COMMITTER_EMAIL", "test@example.com")
748 .output()
749 .expect("git runs");
750 assert!(
751 out.status.success(),
752 "git {args:?} failed: {}",
753 String::from_utf8_lossy(&out.stderr)
754 );
755 String::from_utf8_lossy(&out.stdout).trim().to_string()
756 }
757
758 fn commit(work: &Path, contents: &str) -> String {
759 std::fs::write(work.join("file.txt"), contents).expect("write file");
760 git(work, &["add", "file.txt"]);
761 git(work, &["commit", "-m", contents]);
762 git(work, &["rev-parse", "HEAD"])
763 }
764
765 #[tokio::test]
766 async fn admin_routes_reject_a_missing_or_wrong_token() {
767 let dir = tempfile::tempdir().expect("tempdir");
768 let state = crate::test_support::test_state(dir.path()).await;
769 let router = router(state);
770 for path in ["/internal/admin/backup", "/internal/admin/fsck"] {
771 for token in [None, Some("wrong")] {
772 let mut builder = topcoat::router::request::Request::builder()
773 .method("POST")
774 .uri(path)
775 .header("content-type", "application/json");
776 if let Some(token) = token {
777 builder = builder.header(ADMIN_TOKEN_HEADER, token);
778 }
779 let req = builder
780 .body(Body::from(r#"{"out":"/nonexistent/forge-test"}"#))
781 .expect("request");
782 let res = router.handle(req).await;
783 assert_eq!(res.status(), 403, "{path} with token {token:?}");
784 }
785 }
786 // The right token gets through: an fsck of an instance with no repos is clean.
787 let req = topcoat::router::request::Request::builder()
788 .method("POST")
789 .uri("/internal/admin/fsck")
790 .header("content-type", "application/json")
791 .header(ADMIN_TOKEN_HEADER, crate::test_support::ADMIN_TOKEN)
792 .body(Body::from("{}"))
793 .expect("request");
794 let res = router.handle(req).await;
795 assert_eq!(res.status(), 200);
796 }
797
798 #[tokio::test]
799 async fn hook_routes_are_not_collected_by_discover() {
800 // The public router uses `.discover()`. Hook routes are plain RouteFns and must not be in it.
801 let public = Router::builder().discover().build();
802 for path in ["/hook/pre-receive", "/hook/post-receive"] {
803 let req = topcoat::router::request::Request::builder()
804 .method("POST")
805 .uri(path)
806 .body(Body::empty())
807 .expect("request");
808 let res = public.handle(req).await;
809 assert_eq!(
810 res.status(),
811 404,
812 "{path} is reachable on the discover router"
813 );
814 }
815 }
816
817 #[tokio::test]
818 async fn pre_receive_restrict_push_allows_only_repo_admins() {
819 let tmp = tempfile::tempdir().expect("tempdir");
820 let store = Store::open(&tmp.path().join("forge.db"))
821 .await
822 .expect("store");
823 let owner = store
824 .create_user("tahinli", None, "unused", false)
825 .await
826 .expect("owner");
827 let writer = store
828 .create_user("bob", None, "unused", false)
829 .await
830 .expect("writer");
831 let admin = store
832 .create_user("carol", None, "unused", false)
833 .await
834 .expect("admin");
835 let repo = store
836 .create_repo(
837 &owner.id,
838 "proj",
839 "",
840 forge_core::Visibility::Private,
841 "main",
842 )
843 .await
844 .expect("repo");
845 store
846 .set_collaborator(&repo.id, &writer.id, Role::Write)
847 .await
848 .expect("writer role");
849 store
850 .set_collaborator(&repo.id, &admin.id, Role::Admin)
851 .await
852 .expect("admin role");
853 let git_env = GitEnv {
854 git_bin: PathBuf::from("git"),
855 data_dir: tmp.path().to_path_buf(),
856 };
857 let bare = forge_git::repo::repo_path(&git_env.data_dir, &repo.id).expect("repo path");
858 forge_git::repo::init_bare(&git_env, &bare, "main")
859 .await
860 .expect("init bare");
861 let bare_str = bare.to_str().expect("utf8 path");
862 let work = tmp.path().join("work");
863 git(tmp.path(), &["init", "-b", "main", "work"]);
864 let first = commit(&work, "one");
865 git(&work, &["push", bare_str, "main"]);
866 let second = commit(&work, "two");
867 git(&work, &["push", bare_str, "main"]);
868
869 store
870 .upsert_branch_rule(
871 &repo.id,
872 "main",
873 RuleFlags {
874 restrict_push: true,
875 ..RuleFlags::default()
876 },
877 )
878 .await
879 .expect("upsert rule");
880
881 let request = |actor: &str, old: &str, new: &str| HookRequest {
882 repo_id: repo.id.clone(),
883 actor_id: actor.into(),
884 protocol: "http".into(),
885 wiki: false,
886 updates: vec![HookUpdate {
887 old: old.into(),
888 new: new.into(),
889 ref_name: "refs/heads/main".into(),
890 }],
891 quarantine_env: BTreeMap::new(),
892 };
893
894 // A Write collaborator's direct fast-forward is refused.
895 let refused = evaluate_pre_receive(&store, &git_env, &request(&writer.id, &first, &second))
896 .await
897 .expect("evaluate");
898 assert!(!refused.allow);
899 assert_eq!(
900 refused.message,
901 "branch 'main' only accepts changes through pull requests"
902 );
903 // So is creating the branch.
904 let created = evaluate_pre_receive(
905 &store,
906 &git_env,
907 &request(&writer.id, &"0".repeat(40), &second),
908 )
909 .await
910 .expect("evaluate");
911 assert!(!created.allow);
912
913 // Repo admins (Admin collaborators and the owner) may still push.
914 for actor in [&admin.id, &owner.id] {
915 let ok = evaluate_pre_receive(&store, &git_env, &request(actor, &first, &second))
916 .await
917 .expect("evaluate");
918 assert_eq!(ok, HookResponse::allow());
919 }
920 }
921
922 #[tokio::test]
923 async fn pre_receive_rejects_pushes_to_a_pull_mirror() {
924 let tmp = tempfile::tempdir().expect("tempdir");
925 let store = Store::open(&tmp.path().join("forge.db"))
926 .await
927 .expect("store");
928 let owner = store
929 .create_user("tahinli", None, "unused", false)
930 .await
931 .expect("user");
932 let repo = store
933 .create_repo(
934 &owner.id,
935 "mirror",
936 "",
937 forge_core::Visibility::Public,
938 "main",
939 )
940 .await
941 .expect("repo");
942 let git_env = GitEnv {
943 git_bin: "git".into(),
944 data_dir: tmp.path().to_path_buf(),
945 };
946 let bare = forge_git::repo::repo_path(&git_env.data_dir, &repo.id).expect("repo path");
947 forge_git::repo::init_bare(&git_env, &bare, "main")
948 .await
949 .expect("init bare");
950 let request = HookRequest {
951 repo_id: repo.id.clone(),
952 actor_id: owner.id.clone(),
953 protocol: "http".into(),
954 wiki: false,
955 updates: vec![HookUpdate {
956 old: "0".repeat(40),
957 new: "1".repeat(40),
958 ref_name: "refs/heads/main".into(),
959 }],
960 quarantine_env: BTreeMap::new(),
961 };
962 // Before the pull mirror exists, the push is not refused for that reason.
963 let before = evaluate_pre_receive(&store, &git_env, &request)
964 .await
965 .expect("evaluate");
966 assert_ne!(before.message, "this repository is a pull mirror");
967
968 store
969 .create_mirror(&forge_core::mirrors::NewMirror {
970 repo_id: &repo.id,
971 direction: forge_core::mirrors::MirrorDirection::Pull,
972 url: "https://example.com/upstream.git",
973 username: "",
974 secret: None,
975 interval_minutes: 480,
976 })
977 .await
978 .expect("pull mirror");
979 let refused = evaluate_pre_receive(&store, &git_env, &request)
980 .await
981 .expect("evaluate");
982 assert!(!refused.allow);
983 assert_eq!(refused.message, "this repository is a pull mirror");
984 }
985
986 #[tokio::test]
987 async fn pre_receive_detects_non_fast_forward_on_default_branch() {
988 let tmp = tempfile::tempdir().expect("tempdir");
989 let store = Store::open(&tmp.path().join("forge.db"))
990 .await
991 .expect("store");
992 let owner = store
993 .create_user("tahinli", None, "unused", false)
994 .await
995 .expect("user");
996 let repo = store
997 .create_repo(
998 &owner.id,
999 "proj",
1000 "",
1001 forge_core::Visibility::Private,
1002 "main",
1003 )
1004 .await
1005 .expect("repo");
1006 let git_env = GitEnv {
1007 git_bin: PathBuf::from("git"),
1008 data_dir: tmp.path().to_path_buf(),
1009 };
1010
1011 // Bare repo at the path forge would use for this repo id.
1012 let bare = forge_git::repo::repo_path(&git_env.data_dir, &repo.id).expect("repo path");
1013 forge_git::repo::init_bare(&git_env, &bare, "main")
1014 .await
1015 .expect("init bare");
1016 let bare_str = bare.to_str().expect("utf8 path");
1017
1018 // Two commits on main, then a divergent commit on a side branch.
1019 let work = tmp.path().join("work");
1020 git(tmp.path(), &["init", "-b", "main", "work"]);
1021 let first = commit(&work, "one");
1022 git(&work, &["push", bare_str, "main"]);
1023 let second = commit(&work, "two");
1024 git(&work, &["push", bare_str, "main"]);
1025 git(&work, &["reset", "--hard", &first]);
1026 let divergent = commit(&work, "three");
1027 git(
1028 &work,
1029 &["push", bare_str, &format!("{divergent}:refs/heads/side")],
1030 );
1031
1032 let request = |old: &str, new: &str| HookRequest {
1033 repo_id: repo.id.clone(),
1034 actor_id: owner.id.clone(),
1035 protocol: "http".into(),
1036 wiki: false,
1037 updates: vec![HookUpdate {
1038 old: old.into(),
1039 new: new.into(),
1040 ref_name: "refs/heads/main".into(),
1041 }],
1042 quarantine_env: BTreeMap::new(),
1043 };
1044
1045 // Fast-forward: allowed.
1046 let ff = evaluate_pre_receive(&store, &git_env, &request(&first, &second))
1047 .await
1048 .expect("evaluate");
1049 assert_eq!(ff, HookResponse::allow());
1050
1051 // Non-fast-forward: denied.
1052 let forced = evaluate_pre_receive(&store, &git_env, &request(&second, &divergent))
1053 .await
1054 .expect("evaluate");
1055 assert!(!forced.allow);
1056 assert_eq!(
1057 forced.message,
1058 "force-push to protected branch 'main' is not allowed"
1059 );
1060
1061 // Deleting the default branch: denied.
1062 let deleted = evaluate_pre_receive(&store, &git_env, &request(&second, &"0".repeat(40)))
1063 .await
1064 .expect("evaluate");
1065 assert!(!deleted.allow);
1066 assert_eq!(
1067 deleted.message,
1068 "deleting protected branch 'main' is not allowed"
1069 );
1070
1071 // A rule that allows force pushes lifts only that check; deletion stays denied.
1072 store
1073 .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(true, false))
1074 .await
1075 .expect("upsert rule");
1076 let forced_ok = evaluate_pre_receive(&store, &git_env, &request(&second, &divergent))
1077 .await
1078 .expect("evaluate");
1079 assert_eq!(forced_ok, HookResponse::allow());
1080 let deleted_again =
1081 evaluate_pre_receive(&store, &git_env, &request(&second, &"0".repeat(40)))
1082 .await
1083 .expect("evaluate");
1084 assert_eq!(
1085 deleted_again.message,
1086 "deleting protected branch 'main' is not allowed"
1087 );
1088 }
1089}