use crate::common::{ BOB_CMD, FAST_CLAIMS, Http, PW, Server, TAHINLI_CMD, boot_forge, clone, commit, create_repo, create_token, csrf_for, first_text, git_text, login, temp_dir, }; use forge_ci::proto::{JobAssignment, Outcome, RegisterRequest}; use forge_runner::client::ForgeClient; use forge_runner::config::{Limits, RunnerConfig}; use forge_runner::executor::HostExecutor; use forge_runner::runner::{RunOptions, Runner}; use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio_util::sync::CancellationToken; const BOB_EMAIL: &str = "bob@users.noreply.127.0.0.1"; const TAHINLI: (&str, &str) = ("tahinli", "tahinli@example.test"); const BOB: (&str, &str) = ("bob", BOB_EMAIL); const REPO_PATH: &str = "/tahinli/r"; const SECRET_VALUE: &str = "supersecretvalue"; const LABELS: &[&str] = &["linux"]; const CI_TOML: &str = r#"[on] push = ["main"] pull_request = true [jobs.build] image = "docker.io/library/alpine:3" run = "echo hello; echo $MY_SECRET; mkdir -p out; echo data > out/a.txt" secrets = ["MY_SECRET"] artifacts = ["out/*.txt"] [jobs.after] image = "docker.io/library/alpine:3" run = "echo after" needs = ["build"] # Runs after `after` so the failure cannot cancel the other jobs first (a failed job fails the run fast). [jobs.broken] image = "docker.io/library/alpine:3" run = "exit 3" needs = ["after"] [jobs.skipme] image = "docker.io/library/alpine:3" run = "echo never" needs = ["broken"] "#; const CI_TOML_FORK: &str = r#"[on] push = ["main"] pull_request = true [jobs.build] image = "docker.io/library/alpine:3" run = "echo hello; echo \"value=[${MY_SECRET-}]\"; mkdir -p out; echo data > out/a.txt" secrets = ["MY_SECRET"] artifacts = ["out/*.txt"] [jobs.after] image = "docker.io/library/alpine:3" run = "echo after" needs = ["build"] # Runs after `after` so the failure cannot cancel the other jobs first (a failed job fails the run fast). [jobs.broken] image = "docker.io/library/alpine:3" run = "exit 3" needs = ["after"] [jobs.skipme] image = "docker.io/library/alpine:3" run = "echo never" needs = ["broken"] "#; fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String { format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git") } async fn set_secret(http: &Http, session: &str, name: &str, value: &str) { let csrf = csrf_for(http, &format!("{REPO_PATH}/settings/secrets"), session).await; let res = http .post_form( &format!("{REPO_PATH}/settings/secrets"), &[("csrf", &csrf), ("name", name), ("value", value)], Some(session), ) .await; assert_eq!(res.status, 303, "set secret {name}: {}", res.body); } struct Booted { _server: Server, _root: tempfile::TempDir, dir: PathBuf, http: Http, base_url: String, port: u16, } fn server_log(b: &Booted) -> String { fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default() } async fn boot() -> Booted { let root = temp_dir("ci2e"); let dir = root.path().to_path_buf(); let (server, ports) = boot_forge(&dir, FAST_CLAIMS, &[TAHINLI_CMD, BOB_CMD]).await; Booted { _server: server, _root: root, dir, http: Http::new(ports.http), base_url: format!("http://127.0.0.1:{}", ports.http), port: ports.http, } } struct Worker { runner: Runner, secret: String, labels: Vec, } impl Worker { async fn claim(&self) -> Option { self.runner .client() .claim(&self.secret, &self.labels) .await .expect("claim") .job } async fn drain(&self) -> usize { let mut ran = 0; while let Some(job) = self.claim().await { self.runner.process(job, CancellationToken::new()).await; ran += 1; } ran } } async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker { let csrf = csrf_for(&b.http, "/admin/runners", admin_session).await; let res = b .http .post_form( "/admin/runners/tokens", &[("csrf", &csrf)], Some(admin_session), ) .await; assert_eq!(res.status, 200, "create registration token: {}", res.body); let token = first_text(&res.body, "#reg-token"); let client = ForgeClient::new(&b.base_url).expect("runner client"); let registered = client .register(&RegisterRequest { token, name: name.to_owned(), labels: LABELS.iter().map(|l| (*l).to_owned()).collect(), }) .await .expect("register runner"); let config = RunnerConfig { url: b.base_url.clone(), runner_id: registered.runner_id, runner_secret: registered.runner_secret.clone(), name: name.to_owned(), labels: LABELS.iter().map(|l| (*l).to_owned()).collect(), work_dir: b.dir.join("runner-work"), concurrency: 1, limits: Limits::default(), executor: forge_runner::config::ExecutorKind::default(), images: forge_runner::config::ImagesConfig::default(), sandbox: forge_runner::config::SandboxConfig::default(), registries: Vec::new(), auto_update: false, cache_max_gib: 0, }; let runner = Runner::new(config, Arc::new(HostExecutor), RunOptions::default()).expect("runner"); Worker { runner, secret: registered.runner_secret, labels: LABELS.iter().map(|l| (*l).to_owned()).collect(), } } #[derive(Debug, Clone)] struct Status { state: String, description: String, target_url: String, } async fn statuses(http: &Http, token: &str, sha: &str) -> BTreeMap { let res = http .get_bearer( &format!("/api/v1/repos/tahinli/r/commits/{sha}/statuses"), token, ) .await; assert_eq!(res.status, 200, "statuses for {sha}: {}", res.body); let json: serde_json::Value = serde_json::from_str(&res.body).expect("statuses json"); json["statuses"] .as_array() .expect("statuses array") .iter() .map(|s| { let field = |k: &str| s[k].as_str().unwrap_or_default().to_owned(); ( field("context"), Status { state: field("state"), description: field("description"), target_url: field("target_url"), }, ) }) .collect() } async fn wait_statuses( http: &Http, token: &str, sha: &str, contexts: &[&str], ) -> BTreeMap { let deadline = Instant::now() + Duration::from_secs(20); loop { let found = statuses(http, token, sha).await; if contexts.iter().all(|c| found.contains_key(*c)) { return found; } assert!( Instant::now() < deadline, "statuses never showed {contexts:?}; got {found:?}" ); tokio::time::sleep(Duration::from_millis(100)).await; } } fn job_id_of(status: &Status) -> String { status .target_url .rsplit('/') .next() .filter(|id| !id.is_empty()) .unwrap_or_else(|| panic!("no job id in {:?}", status.target_url)) .to_owned() } fn push_ci_config(work: &Path, contents: &str) -> String { let sha = commit(work, ".forge/ci.toml", contents, "add ci", TAHINLI); git_text(work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); sha } #[tokio::test] async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() { let b = boot().await; let tahinli = login(&b.http, "tahinli", PW).await; let token = create_token(&b.http, &tahinli, "ci-token").await; create_repo(&b.http, &tahinli, "r", "public").await; set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await; let worker = register_runner(&b, &tahinli, "runner-a").await; let work = clone( &remote(b.port, "tahinli", &token, "tahinli", "r"), &b.dir.join("tahinli-work"), ); let sha = push_ci_config(&work, CI_TOML); let found = wait_statuses( &b.http, &token, &sha, &["ci/build", "ci/after", "ci/broken", "ci/skipme"], ) .await; assert_eq!(found["ci/build"].state, "pending", "build is queued"); let ran = worker.drain().await; assert_eq!(ran, 3, "build, after and broken run; skipme never does"); let found = statuses(&b.http, &token, &sha).await; assert_eq!(found["ci/build"].state, "success"); assert_eq!(found["ci/after"].state, "success"); assert_eq!(found["ci/broken"].state, "failure"); assert_eq!(found["ci/skipme"].state, "error"); assert_eq!(found["ci/skipme"].description, "skipped"); let build_id = job_id_of(&found["ci/build"]); let log = b .http .get(&format!("{REPO_PATH}/ci/jobs/{build_id}/log.txt"), None) .await; assert_eq!(log.status, 200, "GET log.txt"); assert!(log.body.contains("hello"), "log has the echo: {}", log.body); assert!(log.body.contains("***"), "secret is masked: {}", log.body); assert!( !log.body.contains(SECRET_VALUE), "secret leaked into the log: {}", log.body ); let artifact = b .http .get( &format!("{REPO_PATH}/ci/jobs/{build_id}/artifacts/out_a.txt"), Some(&tahinli), ) .await; assert_eq!(artifact.status, 200, "GET artifact: {}", server_log(&b)); assert_eq!(artifact.body, "data\n", "artifact bytes"); let run = b .http .get(&format!("{REPO_PATH}/ci/runs/1"), Some(&tahinli)) .await; assert_eq!(run.status, 200, "GET run page"); for job in ["build", "after", "broken", "skipme"] { assert!(run.body.contains(job), "run page lists {job}"); } assert!( run.body.contains(r#"class="ci-glink" data-rel="j"#), "build links to after: {}", run.body ); assert!( run.body.contains(r#"class="ci-glink ci-hot" data-rel="j"#), "broken links to skipme in the accent" ); assert!( run.body.contains(r#"class="ci-ghead""#), "connectors have arrowheads" ); assert!( run.body.contains("after, needs build"), "the dependency is in after's box title" ); assert!( !run.body.contains(">needs build<"), "no needs subtitle under a job's name" ); } #[tokio::test] async fn run_page_lists_a_jobs_steps_and_a_step_opens_its_part_of_the_log() { let b = boot().await; let tahinli = login(&b.http, "tahinli", PW).await; let token = create_token(&b.http, &tahinli, "ci-token").await; create_repo(&b.http, &tahinli, "r", "public").await; let worker = register_runner(&b, &tahinli, "runner-a").await; let work = clone( &remote(b.port, "tahinli", &token, "tahinli", "r"), &b.dir.join("tahinli-work"), ); let sha = push_ci_config( &work, "[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", ); let found = wait_statuses(&b.http, &token, &sha, &["ci/build"]).await; let job_id = job_id_of(&found["ci/build"]); assert_eq!(worker.drain().await, 1, "the build job runs"); let page = b .http .get( &format!("{REPO_PATH}/ci/runs/1?job={job_id}"), Some(&tahinli), ) .await; assert_eq!(page.status, 200, "GET run page"); assert!( page.body.contains("class=\"lab\"") && page.body.contains("Compile"), "the strip lists the step names: {}", page.body ); assert!( page.body.contains("step=0"), "a step links to its part of the log" ); let step = b .http .get( &format!("{REPO_PATH}/ci/runs/1?job={job_id}&step=1"), Some(&tahinli), ) .await; assert_eq!(step.status, 200, "GET the step's run page"); assert!( step.body.contains(r#"data-log-start="true""#), "the log opens at the step: {}", step.body ); } #[tokio::test] async fn fork_pull_waits_for_approval_and_runs_without_secrets() { let b = boot().await; let tahinli = login(&b.http, "tahinli", PW).await; let token = create_token(&b.http, &tahinli, "ci-token").await; create_repo(&b.http, &tahinli, "r", "public").await; set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await; let worker = register_runner(&b, &tahinli, "runner-a").await; let work = clone( &remote(b.port, "tahinli", &token, "tahinli", "r"), &b.dir.join("tahinli-work"), ); let base_sha = push_ci_config(&work, CI_TOML); wait_statuses(&b.http, &token, &base_sha, &["ci/build"]).await; worker.drain().await; let bob = login(&b.http, "bob", PW).await; let bob_token = create_token(&b.http, &bob, "bob-token").await; let csrf = csrf_for(&b.http, "/settings/keys", &bob).await; let fork = b .http .post_form(&format!("{REPO_PATH}/fork"), &[("csrf", &csrf)], Some(&bob)) .await; assert_eq!(fork.status, 303, "fork: {}\n{}", fork.body, server_log(&b)); let bob_work = clone( &remote(b.port, "bob", &bob_token, "bob", "r"), &b.dir.join("bob-work"), ); git_text(&bob_work, &["checkout", "-q", "-b", "bob-feature"]); let head = commit( &bob_work, ".forge/ci.toml", CI_TOML_FORK, "print the secret", BOB, ); git_text( &bob_work, &["push", "-q", "origin", "HEAD:refs/heads/bob-feature"], ); let compare = b .http .get( &format!("{REPO_PATH}/compare/main...bob:bob-feature"), Some(&bob), ) .await; assert_eq!(compare.status, 200, "GET compare"); let csrf = csrf_for(&b.http, "/settings/keys", &bob).await; let open = b .http .post_form( &format!("{REPO_PATH}/pulls"), &[ ("csrf", &csrf), ("title", "Bob change"), ("body", ""), ("base", "main"), ("head", "bob:bob-feature"), ], Some(&bob), ) .await; assert_eq!(open.status, 303, "open pull: {}", open.body); let found = wait_statuses(&b.http, &token, &head, &["ci/build"]).await; assert_eq!(found["ci/build"].state, "pending"); assert_eq!(found["ci/build"].description, "Waiting for approval"); let run_page = b .http .get(&format!("{REPO_PATH}/ci/runs/2"), Some(&tahinli)) .await; assert_eq!(run_page.status, 200, "GET run 2"); assert!( run_page.body.contains("Approve and run"), "run 2 waits for approval: {}", run_page.body ); let approve = b .http .post_form( &format!("{REPO_PATH}/ci/runs/2/approve"), &[( "csrf", &csrf_for(&b.http, &format!("{REPO_PATH}/ci/runs/2"), &tahinli).await, )], Some(&tahinli), ) .await; assert_eq!(approve.status, 303, "approve run 2: {}", approve.body); worker.drain().await; let found = statuses(&b.http, &token, &head).await; assert_eq!(found["ci/build"].state, "success", "fork build runs"); assert_eq!(found["ci/skipme"].state, "error"); let build_id = job_id_of(&found["ci/build"]); let log = b .http .get(&format!("{REPO_PATH}/ci/jobs/{build_id}/log.txt"), None) .await; assert_eq!(log.status, 200, "GET log.txt"); assert!( log.body.contains("value=[]"), "the secret is empty for a fork run: {}", log.body ); assert!(!log.body.contains("***"), "no value to mask: {}", log.body); assert!(!log.body.contains(SECRET_VALUE), "secret leaked"); } #[tokio::test] async fn live_log_streams_until_the_job_finishes() { let b = boot().await; let tahinli = login(&b.http, "tahinli", PW).await; let token = create_token(&b.http, &tahinli, "ci-token").await; create_repo(&b.http, &tahinli, "r", "public").await; let worker = register_runner(&b, &tahinli, "runner-a").await; let release = b.dir.join("release"); let slow = format!( r#"[on] push = ["main"] [jobs.slow] image = "docker.io/library/alpine:3" run = "echo started; i=0; while [ ! -f {} ] && [ $i -lt 100 ]; do sleep 0.1; i=$((i+1)); done; echo done" "#, release.display() ); let work = clone( &remote(b.port, "tahinli", &token, "tahinli", "r"), &b.dir.join("tahinli-work"), ); let sha = push_ci_config(&work, &slow); let found = wait_statuses(&b.http, &token, &sha, &["ci/slow"]).await; let job_id = job_id_of(&found["ci/slow"]); let job = worker.claim().await.expect("the slow job is claimed"); assert_eq!(job.job_id, job_id, "claimed the job the status points at"); let runner = worker.runner.clone(); let handle = tokio::spawn(async move { runner.process(job, CancellationToken::new()).await }); let url = format!("{}{REPO_PATH}/ci/jobs/{job_id}/log.txt", b.http.base); let mut res = b.http.client.get(url).send().await.expect("GET log.txt"); assert_eq!(res.status().as_u16(), 200, "GET log.txt"); let mut body = String::new(); let mut seen_started = false; let read = async { while let Some(chunk) = res.chunk().await.expect("log chunk") { body.push_str(&String::from_utf8_lossy(&chunk)); if !seen_started && body.contains("started") { seen_started = true; assert!( !handle.is_finished(), "the first line arrived only after the job had finished" ); fs::write(&release, "").expect("release the job"); } } }; tokio::time::timeout(Duration::from_secs(90), read) .await .expect("the log stream ends after the job finishes"); assert!(seen_started, "the live log showed the first line: {body}"); assert!( body.contains("done"), "the stream ends with the last line: {body}" ); let outcome = handle.await.expect("job task"); assert_eq!(outcome, Outcome::Success); let found = statuses(&b.http, &token, &sha).await; assert_eq!(found["ci/slow"].state, "success"); }