forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB0a2c24cTahinli1 month ago179 commits

api_tests.rs1506 lines, 47.5 KiBHistoryRawDownload
1//! Route tests for the runner and job API. Each test drives the public router, the same one the
2//! server builds, so routing, auth and status codes are covered end to end.
3
4use std::path::PathBuf;
5
6use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, NewJob};
7use forge_core::{Repo, Store, Visibility};
8use http::header::{AUTHORIZATION, CONTENT_TYPE};
9use serde_json::{Value, json};
10use topcoat::router::request::Request;
11use topcoat::router::{Body, Router, to_bytes};
12
13use super::{artifact_key, cache_scope, fit_to_cap, log_path, valid_artifact_name};
14use crate::pages::commits::test_support::{Fixture, OWNER, REPO};
15use crate::test_support::{app_router, test_state};
16
17/// A response: status, headers and raw body.
18struct Sent {
19 status: u16,
20 headers: http::HeaderMap,
21 body: Vec<u8>,
22}
23
24impl Sent {
25 fn json(&self) -> Value {
26 serde_json::from_slice(&self.body).unwrap_or(Value::Null)
27 }
28}
29
30/// Sends one request through the router.
31async fn send(
32 router: &Router,
33 method: &str,
34 uri: &str,
35 headers: &[(&str, String)],
36 body: Vec<u8>,
37) -> Sent {
38 let mut builder = Request::builder().method(method).uri(uri);
39 for (name, value) in headers {
40 builder = builder.header(*name, value.as_str());
41 }
42 let req = builder.body(Body::from(body)).unwrap();
43 let res = router.handle(req).await;
44 let status = res.status().as_u16();
45 let headers = res.headers().clone();
46 let body = to_bytes(res.into_body(), usize::MAX)
47 .await
48 .unwrap()
49 .to_vec();
50 Sent {
51 status,
52 headers,
53 body,
54 }
55}
56
57fn bearer(token: &str) -> (&'static str, String) {
58 (AUTHORIZATION.as_str(), format!("Bearer {token}"))
59}
60
61fn json_body(value: &Value) -> Vec<u8> {
62 value.to_string().into_bytes()
63}
64
65/// A repo with an owner, and a router over a fresh store. `tune` adjusts the CI limits.
66struct Bare {
67 router: Router,
68 store: Store,
69 data_dir: PathBuf,
70 owner_id: String,
71 repo: Repo,
72 _dir: tempfile::TempDir,
73}
74
75async fn bare(tune: impl FnOnce(&mut forge_core::config::CiConfig)) -> Bare {
76 let dir = tempfile::tempdir().expect("tempdir");
77 let data_dir = dir.path().to_path_buf();
78 let mut state = test_state(&data_dir).await;
79 let mut config = (*state.config).clone();
80 tune(&mut config.ci);
81 state.set_config(config);
82 let store = state.store.clone();
83 let router = app_router(state);
84 let owner = store
85 .create_user(OWNER, None, "not-a-real-hash", false)
86 .await
87 .unwrap();
88 let repo = store
89 .create_repo(&owner.id, REPO, "", Visibility::Public, "main")
90 .await
91 .unwrap();
92 Bare {
93 router,
94 store,
95 data_dir,
96 owner_id: owner.id,
97 repo,
98 _dir: dir,
99 }
100}
101
102/// A runner registered through the store, with its secret.
103async fn runner(env: &Bare, labels: &[&str]) -> (CiRunner, String) {
104 let token = env
105 .store
106 .create_registration_token(&env.owner_id, 24)
107 .await
108 .unwrap();
109 let labels: Vec<String> = labels.iter().map(|label| (*label).to_owned()).collect();
110 env.store
111 .register_runner(&token, "runner", &labels)
112 .await
113 .unwrap()
114}
115
116/// A JobSpec as JSON. `runs_on` and `secrets` are the only fields the tests vary.
117fn spec(runs_on: &[&str], secrets: &[&str]) -> String {
118 json!({
119 "image": "alpine:3",
120 "run": "echo hi",
121 "needs": [],
122 "secrets": secrets,
123 "env": {},
124 "artifacts": [],
125 "runs_on": runs_on,
126 "timeout_minutes": 60,
127 "network": true,
128 })
129 .to_string()
130}
131
132/// Creates a run. `jobs` are (name, spec, needs).
133async fn make_run(
134 env: &Bare,
135 trigger: &str,
136 pull: Option<i64>,
137 commit: &str,
138 jobs: &[(&str, String, Vec<String>)],
139) -> CiRun {
140 let new: Vec<NewJob> = jobs
141 .iter()
142 .map(|(name, spec_json, needs)| NewJob {
143 name,
144 spec_json,
145 needs,
146 })
147 .collect();
148 env.store
149 .create_run(
150 &env.repo.id,
151 trigger,
152 "refs/heads/main",
153 commit,
154 pull,
155 &env.owner_id,
156 false,
157 &new,
158 None,
159 )
160 .await
161 .unwrap()
162}
163
164fn job(name: &str, spec_json: String) -> (&str, String, Vec<String>) {
165 (name, spec_json, Vec::new())
166}
167
168const COMMIT: &str = "1111111111111111111111111111111111111111";
169
170async fn claim(router: &Router, secret: &str) -> Sent {
171 send(
172 router,
173 "POST",
174 "/api/v1/ci/runners/claim",
175 &[bearer(secret)],
176 b"{}".to_vec(),
177 )
178 .await
179}
180
181/// Claims a job for `secret` and returns the assignment JSON.
182async fn claim_job(router: &Router, secret: &str) -> Value {
183 let sent = claim(router, secret).await;
184 assert_eq!(sent.status, 200, "{}", sent.json());
185 sent.json()
186}
187
188fn log_post(
189 job_id: &str,
190 token: &str,
191 offset: u64,
192 body: &[u8],
193) -> (String, Vec<(&'static str, String)>, Vec<u8>) {
194 (
195 format!("/api/v1/ci/jobs/{job_id}/logs"),
196 vec![bearer(token), ("x-forge-log-offset", offset.to_string())],
197 body.to_vec(),
198 )
199}
200
201// ---------------------------------------------------------------------------------------------
202// Registration
203// ---------------------------------------------------------------------------------------------
204
205#[tokio::test]
206async fn register_good_and_reused_tokens() {
207 let env = bare(|_| {}).await;
208 let uri = "/api/v1/ci/runners/register";
209 let good = env
210 .store
211 .create_registration_token(&env.owner_id, 24)
212 .await
213 .unwrap();
214 let body = json!({ "token": good, "name": "linux-1", "labels": ["linux"] });
215
216 let sent = send(&env.router, "POST", uri, &[], json_body(&body)).await;
217 assert_eq!(sent.status, 201, "{}", sent.json());
218 assert!(
219 sent.json()["runner_secret"]
220 .as_str()
221 .is_some_and(|s| !s.is_empty())
222 );
223 assert!(sent.json()["runner_id"].as_str().is_some());
224
225 let reused = send(&env.router, "POST", uri, &[], json_body(&body)).await;
226 assert_eq!(reused.status, 401, "{}", reused.json());
227
228 // A blank runner name is refused before the token is looked at.
229 let bad = json!({ "token": "unused", "name": " ", "labels": [] });
230 let sent = send(&env.router, "POST", uri, &[], json_body(&bad)).await;
231 assert_eq!(sent.status, 422, "{}", sent.json());
232}
233
234// ---------------------------------------------------------------------------------------------
235// Claims
236// ---------------------------------------------------------------------------------------------
237
238#[tokio::test]
239async fn claim_answers_204_200_and_401_by_state() {
240 let env = bare(|_| {}).await;
241 let (_, secret) = runner(&env, &["linux"]).await;
242 let sent = claim(&env.router, &secret).await;
243 assert_eq!(sent.status, 204);
244 // A secret that matches no runner is refused.
245 let stranger = claim(&env.router, "not-a-secret").await;
246 assert_eq!(stranger.status, 401);
247
248 make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await;
249 let assignment = claim_job(&env.router, &secret).await;
250 assert_eq!(assignment["job_name"], "build");
251 assert_eq!(assignment["repo"], format!("{OWNER}/{REPO}"));
252 assert_eq!(assignment["commit"], COMMIT);
253 assert_eq!(assignment["image"], "alpine:3");
254 assert!(
255 assignment["job_token"]
256 .as_str()
257 .is_some_and(|t| !t.is_empty())
258 );
259 assert!(
260 assignment["clone_url"]
261 .as_str()
262 .is_some_and(|u| u.ends_with(&format!("/{OWNER}/{REPO}.git")))
263 );
264}
265
266#[tokio::test]
267async fn claim_skips_jobs_with_a_label_the_runner_lacks() {
268 let env = bare(|_| {}).await;
269 let (_, secret) = runner(&env, &["linux"]).await;
270 make_run(
271 &env,
272 "push",
273 None,
274 COMMIT,
275 &[job("gpu", spec(&["gpu"], &[]))],
276 )
277 .await;
278 let sent = claim(&env.router, &secret).await;
279 assert_eq!(sent.status, 204);
280}
281
282#[tokio::test]
283async fn disabled_runner_gets_403() {
284 let env = bare(|_| {}).await;
285 let (runner, secret) = runner(&env, &["linux"]).await;
286 env.store
287 .set_runner_disabled(&runner.id, true)
288 .await
289 .unwrap();
290 let sent = claim(&env.router, &secret).await;
291 assert_eq!(sent.status, 403, "{}", sent.json());
292}
293
294// ---------------------------------------------------------------------------------------------
295// Secrets on fork-PR runs
296// ---------------------------------------------------------------------------------------------
297
298#[tokio::test]
299async fn fork_pr_runs_get_no_secrets() {
300 let env = bare(|_| {}).await;
301 let (_, secret) = runner(&env, &[]).await;
302 env.store
303 .set_ci_secret(&env.repo.id, "DEPLOY", b"s3cret-value")
304 .await
305 .unwrap();
306
307 make_run(
308 &env,
309 "push",
310 None,
311 COMMIT,
312 &[job("deploy", spec(&[], &["DEPLOY"]))],
313 )
314 .await;
315 let trusted = claim_job(&env.router, &secret).await;
316 assert_eq!(trusted["secrets"]["DEPLOY"], "s3cret-value");
317
318 // A pull request with no pull row behaves as a fork: nothing is handed out.
319 make_run(
320 &env,
321 "pull_request",
322 None,
323 COMMIT,
324 &[job("deploy", spec(&[], &["DEPLOY"]))],
325 )
326 .await;
327 let fork = claim_job(&env.router, &secret).await;
328 assert_eq!(fork["secrets"], json!({}));
329}
330
331// ---------------------------------------------------------------------------------------------
332// Logs
333// ---------------------------------------------------------------------------------------------
334
335#[tokio::test]
336async fn logs_append_retry_mismatch_and_mask() {
337 let env = bare(|_| {}).await;
338 let (_, secret) = runner(&env, &[]).await;
339 env.store
340 .set_ci_secret(&env.repo.id, "TOKEN", b"hunter2-token")
341 .await
342 .unwrap();
343 make_run(
344 &env,
345 "push",
346 None,
347 COMMIT,
348 &[job("test", spec(&[], &["TOKEN"]))],
349 )
350 .await;
351 let assignment = claim_job(&env.router, &secret).await;
352 let job_id = assignment["job_id"].as_str().unwrap().to_owned();
353 let token = assignment["job_token"].as_str().unwrap().to_owned();
354 let path = log_path(&env.data_dir, &job_id);
355
356 let first = b"hello hunter2-token world".to_vec();
357 let (uri, headers, body) = log_post(&job_id, &token, 0, &first);
358 let sent = send(&env.router, "POST", &uri, &headers, body).await;
359 assert_eq!(sent.status, 200, "{}", sent.json());
360 let stored = std::fs::read_to_string(&path).unwrap();
361 assert_eq!(stored, "hello *** world");
362
363 // A retry of the same chunk at the same offset is accepted and writes nothing.
364 let (uri, headers, body) = log_post(&job_id, &token, 0, &first);
365 let sent = send(&env.router, "POST", &uri, &headers, body).await;
366 assert_eq!(sent.status, 200);
367 assert_eq!(std::fs::read_to_string(&path).unwrap(), stored);
368
369 // A different chunk at an old offset is a mismatch and says where the log really ends.
370 let (uri, headers, body) = log_post(&job_id, &token, 0, b"x");
371 let sent = send(&env.router, "POST", &uri, &headers, body).await;
372 assert_eq!(sent.status, 409);
373 assert_eq!(
374 sent.headers
375 .get("x-forge-log-size")
376 .and_then(|v| v.to_str().ok()),
377 Some(first.len().to_string().as_str())
378 );
379
380 // The next chunk, at the end, is stored.
381 let (uri, headers, body) = log_post(&job_id, &token, first.len() as u64, b"\nmore\n");
382 let sent = send(&env.router, "POST", &uri, &headers, body).await;
383 assert_eq!(sent.status, 200);
384 assert_eq!(
385 std::fs::read_to_string(&path).unwrap(),
386 "hello *** world\nmore\n"
387 );
388
389 // A chunk without the offset header is a bad request.
390 let sent = send(
391 &env.router,
392 "POST",
393 &format!("/api/v1/ci/jobs/{job_id}/logs"),
394 &[bearer(&token)],
395 b"text".to_vec(),
396 )
397 .await;
398 assert_eq!(sent.status, 400);
399}
400
401#[test]
402fn log_cap_keeps_what_fits_then_one_marker() {
403 // 100 byte cap. The marker is 17 bytes, so 83 bytes of data fit.
404 let out = fit_to_cap(0, 100, &[b'a'; 150]);
405 assert_eq!(out.len(), 100);
406 assert!(out.ends_with(b"[log truncated]\n"));
407 // Room is left: a short chunk is kept whole.
408 assert_eq!(fit_to_cap(10, 100, b"hello"), b"hello");
409 // The cap is reached: nothing more, not even a second marker.
410 assert!(fit_to_cap(100, 100, b"more").is_empty());
411 // Exactly full at the data limit: the next bytes bring the marker, and only that.
412 assert_eq!(fit_to_cap(83, 100, b"x"), b"\n[log truncated]\n");
413}
414
415// ---------------------------------------------------------------------------------------------
416// Heartbeat
417// ---------------------------------------------------------------------------------------------
418
419#[tokio::test]
420async fn heartbeat_reports_a_cancel_request() {
421 let env = bare(|_| {}).await;
422 let (_, secret) = runner(&env, &[]).await;
423 let run = make_run(&env, "push", None, COMMIT, &[job("a", spec(&[], &[]))]).await;
424 let assignment = claim_job(&env.router, &secret).await;
425 let job_id = assignment["job_id"].as_str().unwrap();
426 let token = assignment["job_token"].as_str().unwrap();
427 let uri = format!("/api/v1/ci/jobs/{job_id}/heartbeat");
428
429 let sent = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await;
430 assert_eq!(sent.status, 200);
431 assert_eq!(sent.json()["cancel"], false);
432
433 env.store.request_cancel(&run.id).await.unwrap();
434 let sent = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await;
435 assert_eq!(sent.status, 200);
436 assert_eq!(sent.json()["cancel"], true);
437
438 let sent = send(&env.router, "POST", &uri, &[bearer("wrong")], Vec::new()).await;
439 assert_eq!(sent.status, 401);
440}
441
442#[tokio::test]
443async fn claim_and_heartbeat_carry_the_concurrency_round_trip() {
444 let env = bare(|_| {}).await;
445 let (runner, secret) = runner(&env, &[]).await;
446 make_run(&env, "push", None, COMMIT, &[job("a", spec(&[], &[]))]).await;
447 make_run(&env, "push", None, COMMIT, &[job("b", spec(&[], &[]))]).await;
448
449 // No override: no header, and the runner's report is stored.
450 let body = serde_json::json!({
451 "labels": [], "concurrency": 2, "version": "9.9.9", "cpus": 8, "memory_bytes": 17179869184u64
452 });
453 let sent = send(
454 &env.router,
455 "POST",
456 "/api/v1/ci/runners/claim",
457 &[bearer(&secret)],
458 json_body(&body),
459 )
460 .await;
461 assert_eq!(sent.status, 200);
462 assert!(sent.headers.get("Forge-Runner-Concurrency").is_none());
463 let listed = env.store.list_runners().await.unwrap().remove(0);
464 assert_eq!(listed.reported.concurrency, Some(2));
465 assert_eq!(listed.reported.version.as_deref(), Some("9.9.9"));
466 assert_eq!(listed.reported.cpus, Some(8));
467 assert_eq!(listed.running_jobs, 1);
468 let assignment = sent.json();
469
470 // An override set in the UI shows up on the next claim answer and on the heartbeat.
471 env.store
472 .set_runner_concurrency(&runner.id, Some(4))
473 .await
474 .unwrap();
475 let sent = claim(&env.router, &secret).await;
476 assert_eq!(sent.status, 200);
477 assert_eq!(sent.headers.get("Forge-Runner-Concurrency").unwrap(), "4");
478 let uri = format!(
479 "/api/v1/ci/jobs/{}/heartbeat",
480 assignment["job_id"].as_str().unwrap()
481 );
482 let token = assignment["job_token"].as_str().unwrap();
483 let beat = send(
484 &env.router,
485 "POST",
486 &uri,
487 &[bearer(token), ("Forge-Runner-Concurrency", "3".to_owned())],
488 Vec::new(),
489 )
490 .await;
491 assert_eq!(beat.json()["concurrency"], 4);
492 assert_eq!(
493 env.store.list_runners().await.unwrap()[0]
494 .reported
495 .concurrency,
496 Some(3),
497 "the heartbeat reports the live value"
498 );
499
500 // Cleared: the heartbeat omits the field, so an old runner sees the same body as before.
501 env.store
502 .set_runner_concurrency(&runner.id, None)
503 .await
504 .unwrap();
505 let beat = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await;
506 assert!(beat.json().get("concurrency").is_none());
507}
508
509/// A spec with a declared `memory`, in bytes.
510fn spec_with_memory(bytes: u64) -> String {
511 let mut value: Value = serde_json::from_str(&spec(&[], &[])).unwrap();
512 value["memory"] = bytes.into();
513 value.to_string()
514}
515
516async fn claim_with_memory(router: &Router, secret: &str, free_gib: u64) -> Sent {
517 let body = json!({
518 "labels": [],
519 "free_memory_bytes": free_gib << 30,
520 "memory_budget_bytes": 6u64 << 30,
521 "reserve_memory_bytes": 1u64 << 30,
522 });
523 send(
524 router,
525 "POST",
526 "/api/v1/ci/runners/claim",
527 &[bearer(secret)],
528 json_body(&body),
529 )
530 .await
531}
532
533#[tokio::test]
534async fn claim_hands_out_only_a_job_that_fits_the_free_memory() {
535 let env = bare(|_| {}).await;
536 let (runner, secret) = runner(&env, &[]).await;
537 // Scenario 1: jobs are sized against the free memory the runner reports.
538 make_run(
539 &env,
540 "push",
541 None,
542 COMMIT,
543 &[
544 job("big", spec_with_memory(4 << 30)),
545 job("small", spec_with_memory(1 << 30)),
546 ],
547 )
548 .await;
549
550 // 2 GiB free: the small job passes the big one, and the assignment carries its memory.
551 let sent = claim_with_memory(&env.router, &secret, 2).await;
552 assert_eq!(sent.status, 200);
553 assert_eq!(sent.json()["job_name"], "small");
554 assert_eq!(sent.json()["memory_bytes"], 1u64 << 30);
555 // Nothing else fits in 1 GiB.
556 let sent = claim_with_memory(&env.router, &secret, 1).await;
557 assert_eq!(sent.status, 204);
558 // The runner's figures are stored for the admin page.
559 let listed = env.store.list_runners().await.unwrap().remove(0);
560 assert_eq!(listed.id, runner.id);
561 assert_eq!(listed.reported.memory_budget, Some(6 << 30));
562 assert_eq!(listed.reported.memory_free, Some(1 << 30));
563 assert_eq!(listed.reported.memory_reserve, Some(1 << 30));
564 assert_eq!(listed.reported.memory_reserved(), Some(5 << 30));
565 // With enough room the big job runs.
566 let sent = claim_with_memory(&env.router, &secret, 5).await;
567 assert_eq!(sent.json()["job_name"], "big");
568 assert_eq!(sent.json()["memory_bytes"], 4u64 << 30);
569
570 // Memory overrides from the admin travel on the claim answer. None before they are set.
571 let sent = claim_with_memory(&env.router, &secret, 6).await;
572 assert!(sent.headers.get("Forge-Runner-Memory-Budget").is_none());
573 assert!(sent.headers.get("Forge-Runner-Reserve-Memory").is_none());
574 env.store
575 .set_runner_field(&runner.id, "limits.memory_budget", Some("5g"))
576 .await
577 .unwrap();
578 env.store
579 .set_runner_field(&runner.id, "limits.reserve_memory", Some("2g"))
580 .await
581 .unwrap();
582 let sent = claim_with_memory(&env.router, &secret, 6).await;
583 assert_eq!(
584 sent.headers.get("Forge-Runner-Memory-Budget").unwrap(),
585 "5g"
586 );
587 assert_eq!(
588 sent.headers.get("Forge-Runner-Reserve-Memory").unwrap(),
589 "2g"
590 );
591}
592
593#[tokio::test]
594async fn an_old_runner_without_memory_fields_still_gets_jobs() {
595 let env = bare(|_| {}).await;
596 let (_runner, secret) = runner(&env, &[]).await;
597 make_run(
598 &env,
599 "push",
600 None,
601 COMMIT,
602 &[
603 job("big", spec_with_memory(64 << 30)),
604 job("plain", spec(&[], &[])),
605 ],
606 )
607 .await;
608 // An old runner sends a body with labels only, or nothing parseable at all. Both jobs are
609 // handed out whatever their size, in the queue's order (which ties here), and the one without
610 // memory carries no memory field, which an old runner ignores anyway.
611 let first = claim(&env.router, &secret).await;
612 let second = claim(&env.router, &secret).await;
613 assert_eq!((first.status, second.status), (200, 200));
614 let mut names = [first.json(), second.json()].map(|j| {
615 (
616 j["job_name"].as_str().unwrap().to_owned(),
617 j.get("memory_bytes").is_none(),
618 )
619 });
620 names.sort();
621 assert_eq!(
622 names,
623 [("big".to_owned(), false), ("plain".to_owned(), true)]
624 );
625 // And the stored figures stay empty.
626 let listed = env.store.list_runners().await.unwrap().remove(0);
627 assert_eq!(listed.reported.memory_budget, None);
628}
629
630async fn post_claim(router: &Router, secret: &str, boot: &str) -> Sent {
631 let body = serde_json::json!({ "labels": [], "boot_id": boot, "capabilities": ["restart"] });
632 send(
633 router,
634 "POST",
635 "/api/v1/ci/runners/claim",
636 &[bearer(secret)],
637 json_body(&body),
638 )
639 .await
640}
641
642#[tokio::test]
643async fn a_restart_request_is_delivered_until_the_runner_comes_back_with_a_new_boot_id() {
644 use forge_core::ci::RestartMode;
645
646 let env = bare(|_| {}).await;
647 let (runner, secret) = runner(&env, &[]).await;
648 make_run(&env, "push", None, COMMIT, &[job("a", spec(&[], &[]))]).await;
649 // A runner without the capability cannot be asked.
650 assert!(
651 env.store
652 .request_runner_restart(&runner.id, RestartMode::Drain)
653 .await
654 .is_err()
655 );
656
657 // The first claim reports the capability and takes the job. No restart header yet.
658 let sent = post_claim(&env.router, &secret, "boot-1").await;
659 assert_eq!(sent.status, 200);
660 assert!(sent.headers.get("Forge-Runner-Restart").is_none());
661 let assignment = sent.json();
662 let uri = format!(
663 "/api/v1/ci/jobs/{}/heartbeat",
664 assignment["job_id"].as_str().unwrap()
665 );
666 let token = assignment["job_token"].as_str().unwrap();
667
668 env.store
669 .request_runner_restart(&runner.id, RestartMode::Drain)
670 .await
671 .unwrap();
672 make_run(&env, "push", None, COMMIT, &[job("b", spec(&[], &[]))]).await;
673
674 // Delivered on the heartbeat, and the claim answers at once with no new job.
675 let beat = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await;
676 assert_eq!(beat.json()["restart"], "drain");
677 let sent = post_claim(&env.router, &secret, "boot-1").await;
678 assert_eq!(
679 sent.status, 204,
680 "a runner that is to restart gets no new job"
681 );
682 assert_eq!(sent.headers.get("Forge-Runner-Restart").unwrap(), "drain");
683 // Still delivered while the same process keeps asking.
684 let sent = post_claim(&env.router, &secret, "boot-1").await;
685 assert_eq!(sent.headers.get("Forge-Runner-Restart").unwrap(), "drain");
686
687 // "Now" replaces "drain".
688 env.store
689 .request_runner_restart(&runner.id, RestartMode::Now)
690 .await
691 .unwrap();
692 let beat = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await;
693 assert_eq!(beat.json()["restart"], "now");
694
695 // A new boot id clears it: no header, no field, and jobs flow again.
696 let sent = post_claim(&env.router, &secret, "boot-2").await;
697 assert_eq!(sent.status, 200);
698 assert!(sent.headers.get("Forge-Runner-Restart").is_none());
699 assert_eq!(env.store.runner_restart(&runner.id).await.unwrap(), None);
700 let beat = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await;
701 assert!(beat.json().get("restart").is_none());
702}
703
704#[tokio::test]
705async fn runner_config_report_and_overrides_round_trip() {
706 let env = bare(|_| {}).await;
707 let (runner, secret) = runner(&env, &["linux"]).await;
708 let uri = "/api/v1/ci/runners/config";
709 let sent = send(&env.router, "GET", uri, &[bearer(&secret)], Vec::new()).await;
710 assert_eq!(sent.status, 200);
711 assert_eq!(sent.json()["overrides"], serde_json::json!({}));
712
713 env.store
714 .set_runner_field(&runner.id, "limits.memory", Some("8g"))
715 .await
716 .unwrap();
717 let report = serde_json::json!({ "config": {
718 "limits.memory": "4g", "runner_secret": "leaked", "bogus.key": 1, "concurrency": 1
719 }});
720 let sent = send(
721 &env.router,
722 "PUT",
723 uri,
724 &[bearer(&secret)],
725 json_body(&report),
726 )
727 .await;
728 assert_eq!(sent.status, 200);
729 assert_eq!(sent.json()["overrides"]["limits.memory"], "8g");
730 let stored = env.store.list_runners().await.unwrap().remove(0);
731 assert_eq!(stored.reported_config["limits.memory"], "4g");
732 assert_eq!(stored.reported_config["runner_secret"], "<redacted>");
733 assert!(!stored.reported_config.contains_key("bogus.key"));
734
735 let sent = send(&env.router, "GET", uri, &[bearer("wrong")], Vec::new()).await;
736 assert_eq!(sent.status, 401);
737}
738
739// ---------------------------------------------------------------------------------------------
740// Artifacts
741// ---------------------------------------------------------------------------------------------
742
743#[test]
744fn artifact_names_are_validated() {
745 assert!(valid_artifact_name("out.tar.gz"));
746 assert!(valid_artifact_name("a+b_c-1"));
747 assert!(!valid_artifact_name(""));
748 assert!(!valid_artifact_name(".hidden"));
749 assert!(!valid_artifact_name("a b"));
750 assert!(!valid_artifact_name("a/b"));
751 assert!(!valid_artifact_name(&"a".repeat(129)));
752}
753
754async fn put_artifact(
755 router: &Router,
756 job_id: &str,
757 token: &str,
758 name: &str,
759 body: Vec<u8>,
760) -> Sent {
761 let uri = format!("/api/v1/ci/jobs/{job_id}/artifacts/{name}");
762 send(router, "PUT", &uri, &[bearer(token)], body).await
763}
764
765#[tokio::test]
766async fn artifact_upload_stores_and_checks_name_count_and_size() {
767 let env = bare(|ci| {
768 ci.max_artifacts_per_job = 3;
769 ci.max_artifact_mb = 1;
770 })
771 .await;
772 let (_, secret) = runner(&env, &[]).await;
773 make_run(&env, "push", None, COMMIT, &[job("a", spec(&[], &[]))]).await;
774 let assignment = claim_job(&env.router, &secret).await;
775 let job_id = assignment["job_id"].as_str().unwrap().to_owned();
776 let token = assignment["job_token"].as_str().unwrap().to_owned();
777
778 let bad = put_artifact(&env.router, &job_id, &token, ".hidden", b"x".to_vec()).await;
779 assert_eq!(bad.status, 422);
780
781 let ok = put_artifact(&env.router, &job_id, &token, "out.txt", b"abc".to_vec()).await;
782 assert_eq!(ok.status, 201, "{}", ok.json());
783 let stored = env
784 .store
785 .artifact(&job_id, "out.txt")
786 .await
787 .unwrap()
788 .expect("artifact row");
789 assert_eq!(stored.size, 3);
790 assert_eq!(
791 stored.sha256,
792 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
793 );
794 assert_eq!(artifact_key(&stored.id), format!("ci/{}", stored.id));
795
796 let again = put_artifact(&env.router, &job_id, &token, "out.txt", b"abc".to_vec()).await;
797 assert_eq!(again.status, 409);
798
799 let second = put_artifact(&env.router, &job_id, &token, "two.txt", b"two".to_vec()).await;
800 assert_eq!(second.status, 201);
801
802 let too_big = put_artifact(
803 &env.router,
804 &job_id,
805 &token,
806 "big.bin",
807 vec![0u8; 1024 * 1024 + 1],
808 )
809 .await;
810 assert_eq!(too_big.status, 413);
811
812 let third = put_artifact(&env.router, &job_id, &token, "three.txt", b"three".to_vec()).await;
813 assert_eq!(third.status, 201);
814 let fourth = put_artifact(&env.router, &job_id, &token, "four.txt", b"four".to_vec()).await;
815 assert_eq!(fourth.status, 409, "the count cap is 3");
816}
817
818// ---------------------------------------------------------------------------------------------
819// Finish
820// ---------------------------------------------------------------------------------------------
821
822fn finish_body(outcome: &str) -> Vec<u8> {
823 json_body(&json!({ "outcome": outcome, "exit_code": 0, "message": null }))
824}
825
826async fn finish_with(env: &Bare, secret: &str, body: Value) -> (String, Value) {
827 let assignment = claim_job(&env.router, secret).await;
828 let id = assignment["job_id"].as_str().unwrap().to_owned();
829 let token = assignment["job_token"].as_str().unwrap();
830 let sent = send(
831 &env.router,
832 "POST",
833 &format!("/api/v1/ci/jobs/{id}/finish"),
834 &[bearer(token)],
835 json_body(&body),
836 )
837 .await;
838 assert_eq!(sent.status, 200, "{}", sent.json());
839 (id, sent.json())
840}
841
842#[tokio::test]
843async fn requeue_hands_the_job_back_and_it_can_be_claimed_again() {
844 let env = bare(|_| {}).await;
845 let (_runner, secret) = runner(&env, &[]).await;
846 make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await;
847 let first = claim_job(&env.router, &secret).await;
848 let id = first["job_id"].as_str().unwrap().to_owned();
849 let token = first["job_token"].as_str().unwrap().to_owned();
850 let uri = format!("/api/v1/ci/jobs/{id}/requeue");
851 let body = json_body(&json!({ "reason": "the runner paused this job for memory" }));
852 let wrong = send(&env.router, "POST", &uri, &[bearer("nope")], body.clone()).await;
853 assert_eq!(wrong.status, 401);
854 let sent = send(&env.router, "POST", &uri, &[bearer(&token)], body.clone()).await;
855 assert_eq!(sent.status, 200, "{}", sent.json());
856 let stored = env.store.job_by_id(&id).await.unwrap().unwrap();
857 assert_eq!(stored.state, JobState::Queued);
858 let log = std::fs::read_to_string(log_path(&env.data_dir, &id)).unwrap();
859 assert!(log.starts_with("requeued: "), "{log}");
860 // The old token is dead, and the job is handed out again with a new one.
861 let again = send(&env.router, "POST", &uri, &[bearer(&token)], body).await;
862 assert_eq!(again.status, 401);
863 let second = claim_job(&env.router, &secret).await;
864 assert_eq!(second["job_id"], first["job_id"]);
865 assert_ne!(second["job_token"], first["job_token"]);
866}
867
868#[tokio::test]
869async fn finish_stores_oom_kills_and_old_bodies_leave_them_empty() {
870 let env = bare(|_| {}).await;
871 let (_runner, secret) = runner(&env, &[]).await;
872
873 // Scenario 1: cargo exited 101 because its rustc was killed: nothing in the exit code or
874 // message. The OOM kill count the runner saw is stored.
875 make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await;
876 let (id, _) = finish_with(
877 &env,
878 &secret,
879 json!({"outcome": "failure", "exit_code": 101, "message": null,
880 "oom_killed": true, "oom_kills": 2}),
881 )
882 .await;
883 let stored = env.store.job_by_id(&id).await.unwrap().unwrap();
884 assert_eq!(stored.oom_kills, Some(2));
885 assert_eq!(stored.exit_code, Some(101));
886
887 // Scenario 2: an old runner's finish body has no OOM fields, and the job still finishes.
888 make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await;
889 let (id, _) = finish_with(
890 &env,
891 &secret,
892 json!({"outcome": "failure", "exit_code": 1, "message": null}),
893 )
894 .await;
895 assert_eq!(
896 env.store.job_by_id(&id).await.unwrap().unwrap().oom_kills,
897 None,
898 "scenario old runner"
899 );
900}
901
902async fn two_step_run(env: &Bare) -> CiRun {
903 make_run(
904 env,
905 "push",
906 None,
907 COMMIT,
908 &[
909 job("a", spec(&[], &[])),
910 (
911 "b",
912 spec(&[], &[]).replace("\"needs\":[]", "\"needs\":[\"a\"]"),
913 vec!["a".to_owned()],
914 ),
915 ],
916 )
917 .await
918}
919
920#[tokio::test]
921async fn finish_queues_dependants_on_success_and_skips_them_on_failure() {
922 let env = bare(|_| {}).await;
923 let (_, secret) = runner(&env, &[]).await;
924
925 // Scenario 1: a green `a` queues `b`, which is then claimed and finished.
926 let run = two_step_run(&env).await;
927 let assignment = claim_job(&env.router, &secret).await;
928 assert_eq!(assignment["job_name"], "a");
929 let job_id = assignment["job_id"].as_str().unwrap();
930 let token = assignment["job_token"].as_str().unwrap();
931
932 let sent = send(
933 &env.router,
934 "POST",
935 &format!("/api/v1/ci/jobs/{job_id}/finish"),
936 &[bearer(token)],
937 finish_body("success"),
938 )
939 .await;
940 assert_eq!(sent.status, 200, "{}", sent.json());
941
942 let jobs = env.store.jobs_for_run(&run.id).await.unwrap();
943 let state_of =
944 |name: &str| -> JobState { jobs.iter().find(|j: &&CiJob| j.name == name).unwrap().state };
945 assert_eq!(state_of("a"), JobState::Success, "success scenario");
946 assert_eq!(state_of("b"), JobState::Queued, "success scenario");
947 let next = claim_job(&env.router, &secret).await;
948 assert_eq!(next["job_name"], "b");
949 let b_id = next["job_id"].as_str().unwrap();
950 let b_token = next["job_token"].as_str().unwrap();
951 let sent = send(
952 &env.router,
953 "POST",
954 &format!("/api/v1/ci/jobs/{b_id}/finish"),
955 &[bearer(b_token)],
956 finish_body("success"),
957 )
958 .await;
959 assert_eq!(sent.status, 200, "{}", sent.json());
960
961 // Scenario 2: a failed `a` skips `b`, and the run ends in failure.
962 let run = two_step_run(&env).await;
963 let assignment = claim_job(&env.router, &secret).await;
964 let job_id = assignment["job_id"].as_str().unwrap();
965 let token = assignment["job_token"].as_str().unwrap();
966
967 let sent = send(
968 &env.router,
969 "POST",
970 &format!("/api/v1/ci/jobs/{job_id}/finish"),
971 &[bearer(token)],
972 finish_body("failure"),
973 )
974 .await;
975 assert_eq!(sent.status, 200, "{}", sent.json());
976 assert_eq!(sent.json()["state"], "failure");
977
978 let jobs = env.store.jobs_for_run(&run.id).await.unwrap();
979 let b = jobs.iter().find(|j| j.name == "b").unwrap();
980 assert_eq!(b.state, JobState::Skipped);
981 let run_now = env.store.run_by_id(&run.id).await.unwrap().unwrap();
982 assert_eq!(run_now.state.as_str(), "failure");
983
984 // A finished job's token is refused.
985 let again = send(
986 &env.router,
987 "POST",
988 &format!("/api/v1/ci/jobs/{job_id}/finish"),
989 &[bearer(token)],
990 finish_body("success"),
991 )
992 .await;
993 assert_eq!(again.status, 401);
994}
995
996/// Parallel `test` and `build` on a deploy-branch push: `build` finishes green first, then `test`
997/// fails. Neither finish leaves the run in a state that self-update deploys.
998#[tokio::test]
999async fn build_green_before_test_fails_never_qualifies_for_self_update() {
1000 let env = bare_with_self_update().await;
1001 let (_, secret) = runner(&env, &[]).await;
1002 let run = make_run(
1003 &env,
1004 "push",
1005 None,
1006 COMMIT,
1007 &[job("build", spec(&[], &[])), job("test", spec(&[], &[]))],
1008 )
1009 .await;
1010 let cfg = forge_core::config::SelfUpdateConfig {
1011 enabled: true,
1012 repo: format!("{OWNER}/{REPO}"),
1013 ..Default::default()
1014 };
1015 let full_name = format!("{OWNER}/{REPO}");
1016 let qualifies = |run: &CiRun| {
1017 crate::self_update::should_deploy(&cfg, &full_name, run, Some(run.id.as_str()))
1018 };
1019
1020 // Both jobs are claimable at once: no `needs` between them.
1021 let first = claim_job(&env.router, &secret).await;
1022 let second = claim_job(&env.router, &secret).await;
1023 let (build, test) = if first["job_name"] == "build" {
1024 (first, second)
1025 } else {
1026 (second, first)
1027 };
1028 assert_eq!(build["job_name"], "build");
1029 assert_eq!(test["job_name"], "test");
1030 let finish = |assignment: &Value, outcome: &'static str| {
1031 let job_id = assignment["job_id"].as_str().unwrap().to_owned();
1032 let token = assignment["job_token"].as_str().unwrap().to_owned();
1033 let router = env.router.clone();
1034 async move {
1035 send(
1036 &router,
1037 "POST",
1038 &format!("/api/v1/ci/jobs/{job_id}/finish"),
1039 &[bearer(&token)],
1040 finish_body(outcome),
1041 )
1042 .await
1043 }
1044 };
1045
1046 let sent = finish(&build, "success").await;
1047 assert_eq!(sent.status, 200, "{}", sent.json());
1048 assert_eq!(sent.json()["state"], "running", "test is still running");
1049 let after_build = env.store.run_by_id(&run.id).await.unwrap().unwrap();
1050 assert!(
1051 !qualifies(&after_build),
1052 "a green build alone never deploys"
1053 );
1054
1055 let sent = finish(&test, "failure").await;
1056 assert_eq!(sent.status, 200, "{}", sent.json());
1057 assert_eq!(sent.json()["state"], "failure");
1058 let after_test = env.store.run_by_id(&run.id).await.unwrap().unwrap();
1059 assert!(
1060 !qualifies(&after_test),
1061 "a run with a failed job never deploys"
1062 );
1063
1064 // Control: the same run shape with both jobs green does qualify.
1065 let mut green = after_test.clone();
1066 green.state = forge_core::ci::RunState::Success;
1067 assert!(qualifies(&green));
1068}
1069
1070// ---------------------------------------------------------------------------------------------
1071// Git read with a job token
1072// ---------------------------------------------------------------------------------------------
1073
1074fn basic(user: &str, password: &str) -> (&'static str, String) {
1075 use base64::prelude::{BASE64_STANDARD, Engine};
1076 let encoded = BASE64_STANDARD.encode(format!("{user}:{password}"));
1077 (AUTHORIZATION.as_str(), format!("Basic {encoded}"))
1078}
1079
1080#[tokio::test]
1081async fn job_token_reads_over_smart_http_but_never_pushes() {
1082 let fx = Fixture::new(Visibility::Public).await;
1083 let repo = fx
1084 .store
1085 .repo_by_owner_and_name(OWNER, REPO)
1086 .await
1087 .unwrap()
1088 .expect("repo");
1089 let (_, secret) = {
1090 let token = fx
1091 .store
1092 .create_registration_token(
1093 &fx.store.user_by_username(OWNER).await.unwrap().unwrap().id,
1094 24,
1095 )
1096 .await
1097 .unwrap();
1098 fx.store
1099 .register_runner(&token, "runner", &[])
1100 .await
1101 .unwrap()
1102 };
1103 let owner_id = fx.store.user_by_username(OWNER).await.unwrap().unwrap().id;
1104 fx.store
1105 .create_run(
1106 &repo.id,
1107 "push",
1108 "refs/heads/main",
1109 &fx.root,
1110 None,
1111 &owner_id,
1112 false,
1113 &[NewJob {
1114 name: "a",
1115 spec_json: &spec(&[], &[]),
1116 needs: &[],
1117 }],
1118 None,
1119 )
1120 .await
1121 .unwrap();
1122 let runner = fx
1123 .store
1124 .runner_by_secret(&secret)
1125 .await
1126 .unwrap()
1127 .expect("runner");
1128 let (job, _run, job_token) = fx
1129 .store
1130 .claim_job(&runner)
1131 .await
1132 .unwrap()
1133 .expect("claimed job");
1134
1135 let password = format!("{}:{job_token}", job.id);
1136 let info = |service: &str| format!("/{OWNER}/{REPO}/info/refs?service={service}");
1137
1138 let read = send(
1139 &fx.router,
1140 "GET",
1141 &info("git-upload-pack"),
1142 &[basic("ci-job", &password)],
1143 Vec::new(),
1144 )
1145 .await;
1146 assert_eq!(read.status, 200, "job token should read");
1147
1148 let push = send(
1149 &fx.router,
1150 "GET",
1151 &info("git-receive-pack"),
1152 &[basic("ci-job", &password)],
1153 Vec::new(),
1154 )
1155 .await;
1156 assert_eq!(
1157 push.status, 403,
1158 "job token must not advertise receive-pack"
1159 );
1160
1161 let post_push = send(
1162 &fx.router,
1163 "POST",
1164 &format!("/{OWNER}/{REPO}/git-receive-pack"),
1165 &[
1166 basic("ci-job", &password),
1167 (
1168 CONTENT_TYPE.as_str(),
1169 "application/x-git-receive-pack-request".into(),
1170 ),
1171 ],
1172 Vec::new(),
1173 )
1174 .await;
1175 assert_eq!(post_push.status, 403, "job token must not push");
1176
1177 let wrong = send(
1178 &fx.router,
1179 "GET",
1180 &info("git-upload-pack"),
1181 &[basic("ci-job", &format!("{}:nope", job.id))],
1182 Vec::new(),
1183 )
1184 .await;
1185 assert_eq!(wrong.status, 401);
1186
1187 // Finishing the job ends the credential.
1188 fx.store
1189 .finish_job(&job.id, JobState::Success, Some(0), None)
1190 .await
1191 .unwrap();
1192 let after = send(
1193 &fx.router,
1194 "GET",
1195 &info("git-upload-pack"),
1196 &[basic("ci-job", &password)],
1197 Vec::new(),
1198 )
1199 .await;
1200 assert_eq!(
1201 after.status, 401,
1202 "a finished job's token must stop working"
1203 );
1204}
1205
1206/// Like `bare`, with self-update enabled for `OWNER/REPO`.
1207async fn bare_with_self_update() -> Bare {
1208 let dir = tempfile::tempdir().expect("tempdir");
1209 let data_dir = dir.path().to_path_buf();
1210 let mut state = test_state(&data_dir).await;
1211 let mut config = (*state.config).clone();
1212 config.self_update.enabled = true;
1213 config.self_update.repo = format!("{OWNER}/{REPO}");
1214 state.set_config(config);
1215 let store = state.store.clone();
1216 let router = app_router(state);
1217 let owner = store
1218 .create_user(OWNER, None, "not-a-real-hash", false)
1219 .await
1220 .unwrap();
1221 let repo = store
1222 .create_repo(&owner.id, REPO, "", Visibility::Public, "main")
1223 .await
1224 .unwrap();
1225 Bare {
1226 router,
1227 store,
1228 data_dir,
1229 owner_id: owner.id,
1230 repo,
1231 _dir: dir,
1232 }
1233}
1234
1235#[tokio::test]
1236async fn runner_binary_needs_runner_auth_and_self_update() {
1237 let env = bare(|_| {}).await;
1238 let (_, secret) = runner(&env, &[]).await;
1239 let uri = "/api/v1/ci/runners/binary";
1240
1241 let sent = send(&env.router, "GET", uri, &[], Vec::new()).await;
1242 assert_eq!(sent.status, 401);
1243 // Self-update is off in this fixture, so an authorized runner gets 404.
1244 let sent = send(&env.router, "GET", uri, &[bearer(&secret)], Vec::new()).await;
1245 assert_eq!(sent.status, 404);
1246}
1247
1248#[tokio::test]
1249async fn runner_binary_streams_the_running_binary_with_its_sha() {
1250 use sha2::{Digest, Sha256};
1251
1252 let env = bare_with_self_update().await;
1253 let (_, secret) = runner(&env, &[]).await;
1254 let uri = "/api/v1/ci/runners/binary";
1255
1256 let sent = send(
1257 &env.router,
1258 "GET",
1259 uri,
1260 &[bearer("not-a-secret")],
1261 Vec::new(),
1262 )
1263 .await;
1264 assert_eq!(sent.status, 401);
1265
1266 let sent = send(&env.router, "GET", uri, &[bearer(&secret)], Vec::new()).await;
1267 assert_eq!(sent.status, 200);
1268 assert_eq!(
1269 sent.headers.get(http::header::CONTENT_TYPE).unwrap(),
1270 "application/octet-stream"
1271 );
1272 let advertised = sent
1273 .headers
1274 .get("forge-binary-sha256")
1275 .unwrap()
1276 .to_str()
1277 .unwrap();
1278 let digest = hex::encode(Sha256::digest(&sent.body));
1279 assert_eq!(digest, advertised);
1280 assert_eq!(
1281 advertised,
1282 crate::self_update::running()
1283 .expect("hashed at startup")
1284 .sha256
1285 );
1286}
1287
1288#[tokio::test]
1289async fn claim_advertises_the_binary_only_to_a_matching_target() {
1290 let env = bare_with_self_update().await;
1291 let (_, secret) = runner(&env, &["linux"]).await;
1292 let target = crate::self_update::target();
1293 let claim_with = |target: Option<String>| {
1294 let mut headers = vec![bearer(&secret)];
1295 if let Some(target) = target {
1296 headers.push(("Forge-Runner-Target", target));
1297 }
1298 headers
1299 };
1300
1301 // A 204 (no work) carries the header for a matching target.
1302 let sent = send(
1303 &env.router,
1304 "POST",
1305 "/api/v1/ci/runners/claim",
1306 &claim_with(Some(target.clone())),
1307 Vec::new(),
1308 )
1309 .await;
1310 assert_eq!(sent.status, 204);
1311 let running = crate::self_update::running().expect("hashed at startup");
1312 assert_eq!(
1313 sent.headers
1314 .get("forge-binary-sha256")
1315 .unwrap()
1316 .to_str()
1317 .unwrap(),
1318 running.sha256
1319 );
1320
1321 // No target, or another target: no header.
1322 for requested in [None, Some("riscv64-plan9".to_owned())] {
1323 let sent = send(
1324 &env.router,
1325 "POST",
1326 "/api/v1/ci/runners/claim",
1327 &claim_with(requested),
1328 Vec::new(),
1329 )
1330 .await;
1331 assert_eq!(sent.status, 204);
1332 assert!(sent.headers.get("forge-binary-sha256").is_none());
1333 }
1334}
1335
1336#[test]
1337fn cache_scope_keys_and_restore_order() {
1338 // (name, trigger, ref, pull number, pull base, want key, want restore keys)
1339 type Case<'a> = (
1340 &'a str,
1341 &'a str,
1342 &'a str,
1343 Option<i64>,
1344 Option<&'a str>,
1345 &'a str,
1346 &'a [&'a str],
1347 );
1348 let cases: &[Case] = &[
1349 (
1350 "push default branch",
1351 "push",
1352 "refs/heads/main",
1353 None,
1354 None,
1355 "ref:refs/heads/main",
1356 &[],
1357 ),
1358 (
1359 "push branch",
1360 "push",
1361 "refs/heads/feature/x",
1362 None,
1363 None,
1364 "ref:refs/heads/feature/x",
1365 &["ref:refs/heads/main"],
1366 ),
1367 (
1368 "tag",
1369 "tag",
1370 "refs/tags/v1.0",
1371 None,
1372 None,
1373 "ref:refs/tags/v1.0",
1374 &["ref:refs/heads/main"],
1375 ),
1376 (
1377 "manual",
1378 "manual",
1379 "refs/heads/main",
1380 None,
1381 None,
1382 "ref:refs/heads/main",
1383 &[],
1384 ),
1385 (
1386 "pr into release",
1387 "pull_request",
1388 "refs/pull/12/head",
1389 Some(12),
1390 Some("release/1.0"),
1391 "pr:12",
1392 &["ref:refs/heads/release/1.0", "ref:refs/heads/main"],
1393 ),
1394 (
1395 "pr into default",
1396 "pull_request",
1397 "refs/pull/3/head",
1398 Some(3),
1399 Some("main"),
1400 "pr:3",
1401 &["ref:refs/heads/main"],
1402 ),
1403 // A fork or same-repo PR whose head branch is called `main` must never get a `ref:` write key.
1404 (
1405 "pr head named main",
1406 "pull_request",
1407 "refs/pull/7/head",
1408 Some(7),
1409 Some("main"),
1410 "pr:7",
1411 &["ref:refs/heads/main"],
1412 ),
1413 (
1414 "pr without base",
1415 "pull_request",
1416 "refs/pull/9/head",
1417 Some(9),
1418 None,
1419 "pr:9",
1420 &["ref:refs/heads/main"],
1421 ),
1422 ];
1423 for (name, trigger, git_ref, pull, base, key, restore) in cases {
1424 let scope = cache_scope(trigger, git_ref, *pull, *base, "main").unwrap();
1425 assert_eq!(scope.key, *key, "case {name}");
1426 let want: Vec<String> = restore.iter().map(|k| k.to_string()).collect();
1427 assert_eq!(scope.restore_keys, want, "case {name}");
1428 }
1429}
1430
1431#[test]
1432fn cache_scope_needs_a_pull_number_for_pull_requests_and_a_known_trigger() {
1433 assert!(
1434 cache_scope(
1435 "pull_request",
1436 "refs/pull/1/head",
1437 None,
1438 Some("main"),
1439 "main"
1440 )
1441 .is_none()
1442 );
1443 assert!(cache_scope("bogus", "refs/heads/main", None, None, "main").is_none());
1444}
1445
1446#[tokio::test]
1447async fn claim_and_heartbeat_store_the_runner_build() {
1448 let env = bare(|_| {}).await;
1449 let (_runner, secret) = runner(&env, &[]).await;
1450 make_run(&env, "push", None, COMMIT, &[job("a", spec(&[], &[]))]).await;
1451
1452 // An older runner sends no build: nothing is stored.
1453 let old = claim(&env.router, &secret).await;
1454 assert_eq!(old.status, 200);
1455 assert_eq!(
1456 env.store.list_runners().await.unwrap()[0].reported.build,
1457 None
1458 );
1459 let assignment = old.json();
1460
1461 // The claim body carries the build.
1462 let body = serde_json::json!({ "labels": [], "build": "0.1.0 (cf8e648, 2026-10-20)" });
1463 send(
1464 &env.router,
1465 "POST",
1466 "/api/v1/ci/runners/claim",
1467 &[bearer(&secret)],
1468 json_body(&body),
1469 )
1470 .await;
1471 assert_eq!(
1472 env.store.list_runners().await.unwrap()[0]
1473 .reported
1474 .build
1475 .as_deref(),
1476 Some("0.1.0 (cf8e648, 2026-10-20)")
1477 );
1478
1479 // The heartbeat header updates it, e.g. after the runner restarted on a new binary.
1480 let uri = format!(
1481 "/api/v1/ci/jobs/{}/heartbeat",
1482 assignment["job_id"].as_str().unwrap()
1483 );
1484 let token = assignment["job_token"].as_str().unwrap();
1485 send(
1486 &env.router,
1487 "POST",
1488 &uri,
1489 &[
1490 bearer(token),
1491 (
1492 "Forge-Runner-Build",
1493 "0.1.0 (4d21658, 2026-10-19)".to_owned(),
1494 ),
1495 ],
1496 Vec::new(),
1497 )
1498 .await;
1499 assert_eq!(
1500 env.store.list_runners().await.unwrap()[0]
1501 .reported
1502 .build
1503 .as_deref(),
1504 Some("0.1.0 (4d21658, 2026-10-19)")
1505 );
1506}