forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

ci_e2e.rs885 lines, 29.1 KiBHistoryRawDownload
1//! End-to-end: CI against the real `forge` binary, driven by the real `forge-runner` library.
2//!
3//! The runner side uses `HostExecutor` (behind the `test-host-executor` feature), so jobs run as
4//! plain `sh` on the test host. Everything else is the production path: runner registration over
5//! the HTTP API, claims, the job's git fetch over smart HTTP with its job token, log shipping with
6//! masking, artifact upload, and finish.
7//!
8//! Scenarios:
9//! - a push run: secrets are masked in the log, artifacts download, a failure skips dependants;
10//! - a fork pull request: it waits for approval, then runs without secrets;
11//! - a live log: `log.txt` streams while a job runs and ends when the job finishes.
12
13use crate::common::{
14 FAST_CLAIMS, Http, Server, bin, input_value, launch_with, login, pick_ports, write_config,
15};
16use forge_ci::proto::{JobAssignment, Outcome, RegisterRequest};
17use forge_runner::client::ForgeClient;
18use forge_runner::config::{Limits, RunnerConfig};
19use forge_runner::executor::HostExecutor;
20use forge_runner::runner::{RunOptions, Runner};
21use std::collections::BTreeMap;
22use std::fs;
23use std::path::{Path, PathBuf};
24use std::process::{Command, Output};
25use std::sync::Arc;
26use std::time::{Duration, Instant};
27use tokio_util::sync::CancellationToken;
28
29const TAHINLI_PW: &str = "tahinli-password-123";
30const BOB_PW: &str = "bob-password-4567";
31const BOB_EMAIL: &str = "bob@users.noreply.127.0.0.1";
32const REPO_PATH: &str = "/tahinli/r";
33const SECRET_VALUE: &str = "supersecretvalue";
34const LABELS: &[&str] = &["linux"];
35
36/// The push-triggered workflow. Image strings are ignored by `HostExecutor`.
37const CI_TOML: &str = r#"[on]
38push = ["main"]
39pull_request = true
40
41[jobs.build]
42image = "docker.io/library/alpine:3"
43run = "echo hello; echo $MY_SECRET; mkdir -p out; echo data > out/a.txt"
44secrets = ["MY_SECRET"]
45artifacts = ["out/*.txt"]
46
47[jobs.after]
48image = "docker.io/library/alpine:3"
49run = "echo after"
50needs = ["build"]
51
52# Runs after `after` so the failure cannot cancel the other jobs first (a failed job fails the run fast).
53[jobs.broken]
54image = "docker.io/library/alpine:3"
55run = "exit 3"
56needs = ["after"]
57
58[jobs.skipme]
59image = "docker.io/library/alpine:3"
60run = "echo never"
61needs = ["broken"]
62"#;
63
64/// The same workflow with the build line changed to print the secret in a form that stays
65/// readable when the variable is unset. Bob's pull request uses it, so `set -u` does not abort.
66const CI_TOML_FORK: &str = r#"[on]
67push = ["main"]
68pull_request = true
69
70[jobs.build]
71image = "docker.io/library/alpine:3"
72run = "echo hello; echo \"value=[${MY_SECRET-}]\"; mkdir -p out; echo data > out/a.txt"
73secrets = ["MY_SECRET"]
74artifacts = ["out/*.txt"]
75
76[jobs.after]
77image = "docker.io/library/alpine:3"
78run = "echo after"
79needs = ["build"]
80
81# Runs after `after` so the failure cannot cancel the other jobs first (a failed job fails the run fast).
82[jobs.broken]
83image = "docker.io/library/alpine:3"
84run = "exit 3"
85needs = ["after"]
86
87[jobs.skipme]
88image = "docker.io/library/alpine:3"
89run = "echo never"
90needs = ["broken"]
91"#;
92
93/// The text of the first element matching `selector`.
94fn first_text(body: &str, selector: &str) -> String {
95 let doc = scraper::Html::parse_document(body);
96 let selector = scraper::Selector::parse(selector).expect("selector");
97 doc.select(&selector)
98 .next()
99 .unwrap_or_else(|| panic!("no element matches {selector:?}"))
100 .text()
101 .collect::<String>()
102 .trim()
103 .to_owned()
104}
105
106fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
107 let out = Command::new(bin())
108 .arg("--config")
109 .arg(config)
110 .args(["admin", "create-user", username])
111 .args(extra)
112 .env("FORGE_PASSWORD", password)
113 .output()
114 .expect("run admin create-user");
115 ok(&out, &format!("create-user {username}"));
116}
117
118fn ok(out: &Output, what: &str) {
119 assert!(
120 out.status.success(),
121 "{what} failed:\n{}",
122 String::from_utf8_lossy(&out.stderr)
123 );
124}
125
126/// Runs git in `cwd` with `env` applied on top of the inherited environment. Returns stdout.
127fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String {
128 let mut cmd = Command::new("git");
129 cmd.current_dir(cwd)
130 .args(["-c", "credential.helper="])
131 .args(args)
132 .env("GIT_TERMINAL_PROMPT", "0");
133 for (key, value) in env {
134 cmd.env(key, value);
135 }
136 let out = cmd.output().expect("run git");
137 assert!(
138 out.status.success(),
139 "git {args:?} failed:\n{}",
140 String::from_utf8_lossy(&out.stderr)
141 );
142 String::from_utf8_lossy(&out.stdout).trim().to_owned()
143}
144
145fn git(cwd: &Path, args: &[&str]) -> String {
146 git_env(cwd, args, &[])
147}
148
149/// Writes `file` (creating its directory), commits it with `who` as author and committer, and
150/// returns the new HEAD.
151fn commit(
152 repo: &Path,
153 file: &str,
154 contents: &str,
155 message: &str,
156 who: &str,
157 email: &str,
158) -> String {
159 let path = repo.join(file);
160 if let Some(parent) = path.parent() {
161 fs::create_dir_all(parent).expect("create dir");
162 }
163 fs::write(&path, contents).expect("write file");
164 git(repo, &["add", file]);
165 git_env(
166 repo,
167 &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message],
168 &[
169 ("GIT_AUTHOR_NAME", who),
170 ("GIT_AUTHOR_EMAIL", email),
171 ("GIT_COMMITTER_NAME", who),
172 ("GIT_COMMITTER_EMAIL", email),
173 ],
174 );
175 git(repo, &["rev-parse", "HEAD"])
176}
177
178/// Clones `url` into `into` (a path that does not exist yet) and returns it.
179fn clone(url: &str, into: &Path) -> PathBuf {
180 let parent = into.parent().expect("clone target has a parent");
181 git(
182 parent,
183 &["clone", "-q", url, into.to_str().expect("utf-8 path")],
184 );
185 into.to_path_buf()
186}
187
188/// The HTTPS remote for `owner/repo`, authenticated with a token.
189fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String {
190 format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git")
191}
192
193/// The CSRF token shown on any settings page of the signed-in user.
194async fn csrf_from(http: &Http, path: &str, session: &str) -> String {
195 let page = http.get(path, Some(session)).await;
196 assert_eq!(page.status, 200, "GET {path}");
197 input_value(&page.body, "csrf")
198}
199
200/// Creates an access token through `/settings/tokens` and returns the token shown once.
201async fn create_token(http: &Http, session: &str, name: &str) -> String {
202 let csrf = csrf_from(http, "/settings/keys", session).await;
203 let res = http
204 .post_form(
205 "/settings/tokens",
206 &[("csrf", &csrf), ("name", name), ("expires", "30")],
207 Some(session),
208 )
209 .await;
210 assert_eq!(res.status, 200, "create token: {}", res.body);
211 let token = first_text(&res.body, "pre.code code");
212 assert!(token.starts_with("forge_"), "unexpected token shape");
213 token
214}
215
216/// Creates a public repo `name` owned by tahinli through `/new`.
217async fn create_repo(http: &Http, session: &str, name: &str) {
218 let page = http.get("/new", Some(session)).await;
219 assert_eq!(page.status, 200, "GET /new");
220 let csrf = input_value(&page.body, "csrf");
221 let res = http
222 .post_form(
223 "/new",
224 &[
225 ("csrf", &csrf),
226 ("name", name),
227 ("description", ""),
228 ("visibility", "public"),
229 ("default_branch", "main"),
230 ],
231 Some(session),
232 )
233 .await;
234 assert_eq!(res.status, 303, "create repo {name}: {}", res.body);
235 assert_eq!(
236 res.location().as_deref(),
237 Some(format!("/tahinli/{name}").as_str())
238 );
239}
240
241/// Adds or replaces a repo secret through the settings form.
242async fn set_secret(http: &Http, session: &str, name: &str, value: &str) {
243 let csrf = csrf_from(http, &format!("{REPO_PATH}/settings/secrets"), session).await;
244 let res = http
245 .post_form(
246 &format!("{REPO_PATH}/settings/secrets"),
247 &[("csrf", &csrf), ("name", name), ("value", value)],
248 Some(session),
249 )
250 .await;
251 assert_eq!(res.status, 303, "set secret {name}: {}", res.body);
252}
253
254/// A running server with its own temp data dir. Field order matters: the server is dropped (and
255/// killed) before the temp dir is removed.
256struct Booted {
257 _server: Server,
258 _root: tempfile::TempDir,
259 dir: PathBuf,
260 http: Http,
261 base_url: String,
262 port: u16,
263}
264
265/// The server's log, for assertion messages.
266fn server_log(b: &Booted) -> String {
267 fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default()
268}
269
270/// Creates tahinli (admin) and bob, then boots the server on fresh ports.
271async fn boot() -> Booted {
272 // Keep the path short: the internal unix socket path is limited to 108 bytes.
273 let root = tempfile::Builder::new()
274 .prefix("ci2e")
275 .tempdir_in("/tmp")
276 .expect("temp dir");
277 let dir = root.path().to_path_buf();
278 let ports = pick_ports();
279 let config = write_config(&dir, ports);
280
281 run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
282 run_admin(&config, "bob", &[], BOB_PW);
283 let (server, ports) = launch_with(&dir, ports, FAST_CLAIMS).await;
284 Booted {
285 _server: server,
286 _root: root,
287 dir,
288 http: Http::new(ports.http),
289 base_url: format!("http://127.0.0.1:{}", ports.http),
290 port: ports.http,
291 }
292}
293
294/// A registered runner and the secret it claims with.
295struct Worker {
296 runner: Runner,
297 secret: String,
298 labels: Vec<String>,
299}
300
301impl Worker {
302 /// One claim. `None` means the forge had nothing for this runner (after its long poll).
303 async fn claim(&self) -> Option<JobAssignment> {
304 self.runner
305 .client()
306 .claim(&self.secret, &self.labels)
307 .await
308 .expect("claim")
309 .job
310 }
311
312 /// Claims and runs jobs until the forge has nothing left. Returns how many ran.
313 async fn drain(&self) -> usize {
314 let mut ran = 0;
315 while let Some(job) = self.claim().await {
316 self.runner.process(job, CancellationToken::new()).await;
317 ran += 1;
318 }
319 ran
320 }
321}
322
323/// Registers a runner through the admin page and the runner API. The admin is `admin_session`.
324async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker {
325 let page = b.http.get("/admin/runners", Some(admin_session)).await;
326 assert_eq!(page.status, 200, "GET /admin/runners");
327 let csrf = input_value(&page.body, "csrf");
328 let res = b
329 .http
330 .post_form(
331 "/admin/runners/tokens",
332 &[("csrf", &csrf)],
333 Some(admin_session),
334 )
335 .await;
336 assert_eq!(res.status, 200, "create registration token: {}", res.body);
337 let token = first_text(&res.body, "#reg-token");
338
339 let client = ForgeClient::new(&b.base_url).expect("runner client");
340 let registered = client
341 .register(&RegisterRequest {
342 token,
343 name: name.to_owned(),
344 labels: LABELS.iter().map(|l| (*l).to_owned()).collect(),
345 })
346 .await
347 .expect("register runner");
348 let config = RunnerConfig {
349 url: b.base_url.clone(),
350 runner_id: registered.runner_id,
351 runner_secret: registered.runner_secret.clone(),
352 name: name.to_owned(),
353 labels: LABELS.iter().map(|l| (*l).to_owned()).collect(),
354 work_dir: b.dir.join("runner-work"),
355 concurrency: 1,
356 limits: Limits::default(),
357 executor: forge_runner::config::ExecutorKind::default(),
358 images: forge_runner::config::ImagesConfig::default(),
359 sandbox: forge_runner::config::SandboxConfig::default(),
360 registries: Vec::new(),
361 // The e2e runner must not replace the test binary under itself.
362 auto_update: false,
363 cache_max_gib: 0,
364 };
365 let runner =
366 Runner::new(config, Arc::new(HostExecutor), RunOptions::default()).expect("runner");
367 Worker {
368 runner,
369 secret: registered.runner_secret,
370 labels: LABELS.iter().map(|l| (*l).to_owned()).collect(),
371 }
372}
373
374/// One commit status as the status API reports it.
375#[derive(Debug, Clone)]
376struct Status {
377 state: String,
378 description: String,
379 target_url: String,
380}
381
382/// The statuses on `sha` of tahinli/r, keyed by context.
383async fn statuses(http: &Http, token: &str, sha: &str) -> BTreeMap<String, Status> {
384 let res = http
385 .get_bearer(
386 &format!("/api/v1/repos/tahinli/r/commits/{sha}/statuses"),
387 token,
388 )
389 .await;
390 assert_eq!(res.status, 200, "statuses for {sha}: {}", res.body);
391 let json: serde_json::Value = serde_json::from_str(&res.body).expect("statuses json");
392 json["statuses"]
393 .as_array()
394 .expect("statuses array")
395 .iter()
396 .map(|s| {
397 let field = |k: &str| s[k].as_str().unwrap_or_default().to_owned();
398 (
399 field("context"),
400 Status {
401 state: field("state"),
402 description: field("description"),
403 target_url: field("target_url"),
404 },
405 )
406 })
407 .collect()
408}
409
410/// Polls the statuses until every context in `contexts` is present, then returns them.
411async fn wait_statuses(
412 http: &Http,
413 token: &str,
414 sha: &str,
415 contexts: &[&str],
416) -> BTreeMap<String, Status> {
417 let deadline = Instant::now() + Duration::from_secs(20);
418 loop {
419 let found = statuses(http, token, sha).await;
420 if contexts.iter().all(|c| found.contains_key(*c)) {
421 return found;
422 }
423 assert!(
424 Instant::now() < deadline,
425 "statuses never showed {contexts:?}; got {found:?}"
426 );
427 tokio::time::sleep(Duration::from_millis(100)).await;
428 }
429}
430
431/// The job id at the end of a status `target_url` (`.../ci/jobs/<id>`).
432fn job_id_of(status: &Status) -> String {
433 status
434 .target_url
435 .rsplit('/')
436 .next()
437 .filter(|id| !id.is_empty())
438 .unwrap_or_else(|| panic!("no job id in {:?}", status.target_url))
439 .to_owned()
440}
441
442/// Pushes `.forge/ci.toml` (with `contents`) to `main` as tahinli. Returns the pushed commit.
443fn push_ci_config(work: &Path, contents: &str) -> String {
444 let sha = commit(
445 work,
446 ".forge/ci.toml",
447 contents,
448 "add ci",
449 "tahinli",
450 "tahinli@example.test",
451 );
452 git(work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
453 sha
454}
455
456#[tokio::test]
457async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() {
458 let b = boot().await;
459 let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
460 let token = create_token(&b.http, &tahinli, "ci-token").await;
461 create_repo(&b.http, &tahinli, "r").await;
462 set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await;
463 let worker = register_runner(&b, &tahinli, "runner-a").await;
464
465 let work = clone(
466 &remote(b.port, "tahinli", &token, "tahinli", "r"),
467 &b.dir.join("tahinli-work"),
468 );
469 let sha = push_ci_config(&work, CI_TOML);
470
471 let found = wait_statuses(
472 &b.http,
473 &token,
474 &sha,
475 &["ci/build", "ci/after", "ci/broken", "ci/skipme"],
476 )
477 .await;
478 assert_eq!(found["ci/build"].state, "pending", "build is queued");
479
480 let ran = worker.drain().await;
481 assert_eq!(ran, 3, "build, after and broken run; skipme never does");
482
483 let found = statuses(&b.http, &token, &sha).await;
484 assert_eq!(found["ci/build"].state, "success");
485 assert_eq!(found["ci/after"].state, "success");
486 assert_eq!(found["ci/broken"].state, "failure");
487 assert_eq!(found["ci/skipme"].state, "error");
488 assert_eq!(found["ci/skipme"].description, "skipped");
489
490 // The build log: the secret is masked, never printed.
491 let build_id = job_id_of(&found["ci/build"]);
492 let log = b
493 .http
494 .get(&format!("{REPO_PATH}/ci/jobs/{build_id}/log.txt"), None)
495 .await;
496 assert_eq!(log.status, 200, "GET log.txt");
497 assert!(log.body.contains("hello"), "log has the echo: {}", log.body);
498 assert!(log.body.contains("***"), "secret is masked: {}", log.body);
499 assert!(
500 !log.body.contains(SECRET_VALUE),
501 "secret leaked into the log: {}",
502 log.body
503 );
504
505 // The artifact comes back with the right bytes. `out/a.txt` is stored as `out_a.txt`.
506 let artifact = b
507 .http
508 .get(
509 &format!("{REPO_PATH}/ci/jobs/{build_id}/artifacts/out_a.txt"),
510 Some(&tahinli),
511 )
512 .await;
513 assert_eq!(artifact.status, 200, "GET artifact: {}", server_log(&b));
514 assert_eq!(artifact.body, "data\n", "artifact bytes");
515
516 // The run page lists every job.
517 let run = b
518 .http
519 .get(&format!("{REPO_PATH}/ci/runs/1"), Some(&tahinli))
520 .await;
521 assert_eq!(run.status, 200, "GET run page");
522 for job in ["build", "after", "broken", "skipme"] {
523 assert!(run.body.contains(job), "run page lists {job}");
524 }
525 // The timeline draws what a job needs as connectors, not as a line under its name: muted from
526 // build into after, in the accent from the failed broken onto the skipped skipme.
527 assert!(
528 run.body.contains(r#"class="ci-glink" data-rel="j"#),
529 "build links to after: {}",
530 run.body
531 );
532 assert!(
533 run.body.contains(r#"class="ci-glink ci-hot" data-rel="j"#),
534 "broken links to skipme in the accent"
535 );
536 assert!(
537 run.body.contains(r#"class="ci-ghead""#),
538 "connectors have arrowheads"
539 );
540 assert!(
541 run.body.contains("<title>after, needs build</title>"),
542 "the dependency is in after's box title"
543 );
544 assert!(
545 !run.body.contains(">needs build<"),
546 "no needs subtitle under a job's name"
547 );
548}
549
550#[tokio::test]
551async fn run_page_lists_a_jobs_steps_and_a_step_opens_its_part_of_the_log() {
552 let b = boot().await;
553 let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
554 let token = create_token(&b.http, &tahinli, "ci-token").await;
555 create_repo(&b.http, &tahinli, "r").await;
556 let worker = register_runner(&b, &tahinli, "runner-a").await;
557
558 // Each `::group::` line the job prints is one of its steps.
559 let work = clone(
560 &remote(b.port, "tahinli", &token, "tahinli", "r"),
561 &b.dir.join("tahinli-work"),
562 );
563 let sha = push_ci_config(
564 &work,
565 "[on]\npush = [\"main\"]\n\n[jobs.build]\nimage = \"docker.io/library/alpine:3\"\nrun = \"echo ::group::Compile; echo built; echo ::endgroup::; echo ::group::Test; echo tested\"\n",
566 );
567 let found = wait_statuses(&b.http, &token, &sha, &["ci/build"]).await;
568 let job_id = job_id_of(&found["ci/build"]);
569 assert_eq!(worker.drain().await, 1, "the build job runs");
570
571 let page = b
572 .http
573 .get(
574 &format!("{REPO_PATH}/ci/runs/1?job={job_id}"),
575 Some(&tahinli),
576 )
577 .await;
578 assert_eq!(page.status, 200, "GET run page");
579 assert!(
580 page.body.contains("class=\"lab\"") && page.body.contains("Compile"),
581 "the strip lists the step names: {}",
582 page.body
583 );
584 assert!(
585 page.body.contains("step=0"),
586 "a step links to its part of the log"
587 );
588
589 let step = b
590 .http
591 .get(
592 &format!("{REPO_PATH}/ci/runs/1?job={job_id}&step=1"),
593 Some(&tahinli),
594 )
595 .await;
596 assert_eq!(step.status, 200, "GET the step's run page");
597 assert!(
598 step.body.contains(r#"data-log-start="true""#),
599 "the log opens at the step: {}",
600 step.body
601 );
602}
603
604#[tokio::test]
605async fn fork_pull_waits_for_approval_and_runs_without_secrets() {
606 let b = boot().await;
607 let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
608 let token = create_token(&b.http, &tahinli, "ci-token").await;
609 create_repo(&b.http, &tahinli, "r").await;
610 set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await;
611 let worker = register_runner(&b, &tahinli, "runner-a").await;
612
613 // Base branch with the workflow, run to completion (run 1).
614 let work = clone(
615 &remote(b.port, "tahinli", &token, "tahinli", "r"),
616 &b.dir.join("tahinli-work"),
617 );
618 let base_sha = push_ci_config(&work, CI_TOML);
619 wait_statuses(&b.http, &token, &base_sha, &["ci/build"]).await;
620 worker.drain().await;
621
622 // Bob forks and changes the workflow on a branch.
623 let bob = login(&b.http, "bob", BOB_PW).await;
624 let bob_token = create_token(&b.http, &bob, "bob-token").await;
625 let csrf = csrf_from(&b.http, "/settings/keys", &bob).await;
626 let fork = b
627 .http
628 .post_form(&format!("{REPO_PATH}/fork"), &[("csrf", &csrf)], Some(&bob))
629 .await;
630 assert_eq!(fork.status, 303, "fork: {}\n{}", fork.body, server_log(&b));
631
632 let bob_work = clone(
633 &remote(b.port, "bob", &bob_token, "bob", "r"),
634 &b.dir.join("bob-work"),
635 );
636 git(&bob_work, &["checkout", "-q", "-b", "bob-feature"]);
637 let head = commit(
638 &bob_work,
639 ".forge/ci.toml",
640 CI_TOML_FORK,
641 "print the secret",
642 "bob",
643 BOB_EMAIL,
644 );
645 git(
646 &bob_work,
647 &["push", "-q", "origin", "HEAD:refs/heads/bob-feature"],
648 );
649
650 // Bob opens the pull request. The run waits for the owner.
651 let compare = b
652 .http
653 .get(
654 &format!("{REPO_PATH}/compare/main...bob:bob-feature"),
655 Some(&bob),
656 )
657 .await;
658 assert_eq!(compare.status, 200, "GET compare");
659 let csrf = csrf_from(&b.http, "/settings/keys", &bob).await;
660 let open = b
661 .http
662 .post_form(
663 &format!("{REPO_PATH}/pulls"),
664 &[
665 ("csrf", &csrf),
666 ("title", "Bob change"),
667 ("body", ""),
668 ("base", "main"),
669 ("head", "bob:bob-feature"),
670 ],
671 Some(&bob),
672 )
673 .await;
674 assert_eq!(open.status, 303, "open pull: {}", open.body);
675
676 let found = wait_statuses(&b.http, &token, &head, &["ci/build"]).await;
677 assert_eq!(found["ci/build"].state, "pending");
678 assert_eq!(found["ci/build"].description, "Waiting for approval");
679
680 let run_page = b
681 .http
682 .get(&format!("{REPO_PATH}/ci/runs/2"), Some(&tahinli))
683 .await;
684 assert_eq!(run_page.status, 200, "GET run 2");
685 assert!(
686 run_page.body.contains("Approve and run"),
687 "run 2 waits for approval: {}",
688 run_page.body
689 );
690
691 // The owner approves, and the job runs with no secrets.
692 let approve = b
693 .http
694 .post_form(
695 &format!("{REPO_PATH}/ci/runs/2/approve"),
696 &[("csrf", &input_value(&run_page.body, "csrf"))],
697 Some(&tahinli),
698 )
699 .await;
700 assert_eq!(approve.status, 303, "approve run 2: {}", approve.body);
701 worker.drain().await;
702
703 let found = statuses(&b.http, &token, &head).await;
704 assert_eq!(found["ci/build"].state, "success", "fork build runs");
705 assert_eq!(found["ci/skipme"].state, "error");
706
707 let build_id = job_id_of(&found["ci/build"]);
708 let log = b
709 .http
710 .get(&format!("{REPO_PATH}/ci/jobs/{build_id}/log.txt"), None)
711 .await;
712 assert_eq!(log.status, 200, "GET log.txt");
713 assert!(
714 log.body.contains("value=[]"),
715 "the secret is empty for a fork run: {}",
716 log.body
717 );
718 assert!(!log.body.contains("***"), "no value to mask: {}", log.body);
719 assert!(!log.body.contains(SECRET_VALUE), "secret leaked");
720}
721
722#[tokio::test]
723async fn live_log_streams_until_the_job_finishes() {
724 let b = boot().await;
725 let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
726 let token = create_token(&b.http, &tahinli, "ci-token").await;
727 create_repo(&b.http, &tahinli, "r").await;
728 let worker = register_runner(&b, &tahinli, "runner-a").await;
729
730 // The job holds until the test drops a release file, so the first line is seen while it runs.
731 // The loop is capped, so a test that dies early does not leave the job spinning.
732 let release = b.dir.join("release");
733 let slow = format!(
734 r#"[on]
735push = ["main"]
736
737[jobs.slow]
738image = "docker.io/library/alpine:3"
739run = "echo started; i=0; while [ ! -f {} ] && [ $i -lt 100 ]; do sleep 0.1; i=$((i+1)); done; echo done"
740"#,
741 release.display()
742 );
743 let work = clone(
744 &remote(b.port, "tahinli", &token, "tahinli", "r"),
745 &b.dir.join("tahinli-work"),
746 );
747 let sha = push_ci_config(&work, &slow);
748 let found = wait_statuses(&b.http, &token, &sha, &["ci/slow"]).await;
749 let job_id = job_id_of(&found["ci/slow"]);
750
751 let job = worker.claim().await.expect("the slow job is claimed");
752 assert_eq!(job.job_id, job_id, "claimed the job the status points at");
753 let runner = worker.runner.clone();
754 let handle = tokio::spawn(async move { runner.process(job, CancellationToken::new()).await });
755
756 // Read the stream chunk by chunk. The first line appears while the job is still sleeping.
757 let url = format!("{}{REPO_PATH}/ci/jobs/{job_id}/log.txt", b.http.base);
758 let mut res = b.http.client.get(url).send().await.expect("GET log.txt");
759 assert_eq!(res.status().as_u16(), 200, "GET log.txt");
760 let mut body = String::new();
761 let mut seen_started = false;
762 let read = async {
763 while let Some(chunk) = res.chunk().await.expect("log chunk") {
764 body.push_str(&String::from_utf8_lossy(&chunk));
765 if !seen_started && body.contains("started") {
766 seen_started = true;
767 assert!(
768 !handle.is_finished(),
769 "the first line arrived only after the job had finished"
770 );
771 fs::write(&release, "").expect("release the job");
772 }
773 }
774 };
775 tokio::time::timeout(Duration::from_secs(90), read)
776 .await
777 .expect("the log stream ends after the job finishes");
778
779 assert!(seen_started, "the live log showed the first line: {body}");
780 assert!(
781 body.contains("done"),
782 "the stream ends with the last line: {body}"
783 );
784 let outcome = handle.await.expect("job task");
785 assert_eq!(outcome, Outcome::Success);
786 let found = statuses(&b.http, &token, &sha).await;
787 assert_eq!(found["ci/slow"].state, "success");
788}
789
790#[tokio::test]
791async fn ci_job_token_clones_the_repos_wiki_read_only() {
792 let b = boot().await;
793 let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
794 let token = create_token(&b.http, &tahinli, "ci-token").await;
795 create_repo(&b.http, &tahinli, "r").await;
796 let worker = register_runner(&b, &tahinli, "runner-a").await;
797
798 // The wiki gets its first page through the web form.
799 let csrf = input_value(
800 &b.http
801 .get(&format!("{REPO_PATH}/wiki/-/new"), Some(&tahinli))
802 .await
803 .body,
804 "csrf",
805 );
806 let saved = b
807 .http
808 .post_form(
809 &format!("{REPO_PATH}/wiki/-/new"),
810 &[
811 ("csrf", &csrf),
812 ("name", "Home"),
813 ("base", ""),
814 ("content", "# Welcome from the wiki\n"),
815 ("message", "first page"),
816 ],
817 Some(&tahinli),
818 )
819 .await;
820 assert_eq!(saved.status, 303, "create Home: {}", saved.body);
821
822 // A slow job keeps running, so its token is valid while the test clones.
823 let slow = r#"[on]
824push = ["main"]
825
826[jobs.slow]
827image = "docker.io/library/alpine:3"
828run = "echo started; sleep 5; echo done"
829"#;
830 let work = clone(
831 &remote(b.port, "tahinli", &token, "tahinli", "r"),
832 &b.dir.join("tahinli-work"),
833 );
834 let sha = push_ci_config(&work, slow);
835 let found = wait_statuses(&b.http, &token, &sha, &["ci/slow"]).await;
836 let job = worker.claim().await.expect("the slow job is claimed");
837 assert_eq!(job.job_id, job_id_of(&found["ci/slow"]));
838
839 // The job reads the wiki with its own credential: `ci-job` and `<job id>:<job token>`.
840 let wiki_url = format!(
841 "http://ci-job:{}:{}@127.0.0.1:{}/tahinli/r.wiki.git",
842 job.job_id, job.job_token, b.port
843 );
844 let job_wiki = clone(&wiki_url, &b.dir.join("job-wiki"));
845 let home = fs::read_to_string(job_wiki.join("Home.md")).expect("Home.md in the job's clone");
846 assert!(home.contains("Welcome from the wiki"), "{home}");
847
848 // Pushing to the wiki is refused for a job token.
849 fs::write(job_wiki.join("Home.md"), "# changed by a job\n").expect("write");
850 git(&job_wiki, &["add", "Home.md"]);
851 git_env(
852 &job_wiki,
853 &[
854 "-c",
855 "commit.gpgsign=false",
856 "commit",
857 "-q",
858 "-m",
859 "job edit",
860 ],
861 &[
862 ("GIT_AUTHOR_NAME", "job"),
863 ("GIT_AUTHOR_EMAIL", "job@example.invalid"),
864 ("GIT_COMMITTER_NAME", "job"),
865 ("GIT_COMMITTER_EMAIL", "job@example.invalid"),
866 ],
867 );
868 let push = Command::new("git")
869 .current_dir(&job_wiki)
870 .args([
871 "-c",
872 "credential.helper=",
873 "push",
874 "-q",
875 "origin",
876 "HEAD:main",
877 ])
878 .env("GIT_TERMINAL_PROMPT", "0")
879 .output()
880 .expect("run git");
881 assert!(
882 !push.status.success(),
883 "a CI job token must not push to the wiki"
884 );
885}