forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli4 hours ago363 commits

ci_e2e.rs585 lines, 18.2 KiBHistoryRawDownload
1use crate::common::{
2 BOB_CMD, FAST_CLAIMS, Http, PW, Server, TAHINLI_CMD, boot_forge, clone, commit, create_repo,
3 create_token, csrf_for, first_text, git_text, login, temp_dir,
4};
5use forge_ci::proto::{JobAssignment, Outcome, RegisterRequest};
6use forge_runner::client::ForgeClient;
7use forge_runner::config::{Limits, RunnerConfig};
8use forge_runner::executor::HostExecutor;
9use forge_runner::runner::{RunOptions, Runner};
10use std::collections::BTreeMap;
11use std::fs;
12use std::path::{Path, PathBuf};
13use std::sync::Arc;
14use std::time::{Duration, Instant};
15use tokio_util::sync::CancellationToken;
16
17const BOB_EMAIL: &str = "bob@users.noreply.127.0.0.1";
18const TAHINLI: (&str, &str) = ("tahinli", "tahinli@example.test");
19const BOB: (&str, &str) = ("bob", BOB_EMAIL);
20const REPO_PATH: &str = "/tahinli/r";
21const SECRET_VALUE: &str = "supersecretvalue";
22const LABELS: &[&str] = &["linux"];
23
24const CI_TOML: &str = r#"[on]
25push = ["main"]
26pull_request = true
27
28[jobs.build]
29image = "docker.io/library/alpine:3"
30run = "echo hello; echo $MY_SECRET; mkdir -p out; echo data > out/a.txt"
31secrets = ["MY_SECRET"]
32artifacts = ["out/*.txt"]
33
34[jobs.after]
35image = "docker.io/library/alpine:3"
36run = "echo after"
37needs = ["build"]
38
39# Runs after `after` so the failure cannot cancel the other jobs first (a failed job fails the run fast).
40[jobs.broken]
41image = "docker.io/library/alpine:3"
42run = "exit 3"
43needs = ["after"]
44
45[jobs.skipme]
46image = "docker.io/library/alpine:3"
47run = "echo never"
48needs = ["broken"]
49"#;
50
51const CI_TOML_FORK: &str = r#"[on]
52push = ["main"]
53pull_request = true
54
55[jobs.build]
56image = "docker.io/library/alpine:3"
57run = "echo hello; echo \"value=[${MY_SECRET-}]\"; mkdir -p out; echo data > out/a.txt"
58secrets = ["MY_SECRET"]
59artifacts = ["out/*.txt"]
60
61[jobs.after]
62image = "docker.io/library/alpine:3"
63run = "echo after"
64needs = ["build"]
65
66# Runs after `after` so the failure cannot cancel the other jobs first (a failed job fails the run fast).
67[jobs.broken]
68image = "docker.io/library/alpine:3"
69run = "exit 3"
70needs = ["after"]
71
72[jobs.skipme]
73image = "docker.io/library/alpine:3"
74run = "echo never"
75needs = ["broken"]
76"#;
77
78fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String {
79 format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git")
80}
81
82async fn set_secret(http: &Http, session: &str, name: &str, value: &str) {
83 let csrf = csrf_for(http, &format!("{REPO_PATH}/settings/secrets"), session).await;
84 let res = http
85 .post_form(
86 &format!("{REPO_PATH}/settings/secrets"),
87 &[("csrf", &csrf), ("name", name), ("value", value)],
88 Some(session),
89 )
90 .await;
91 assert_eq!(res.status, 303, "set secret {name}: {}", res.body);
92}
93
94struct Booted {
95 _server: Server,
96 _root: tempfile::TempDir,
97 dir: PathBuf,
98 http: Http,
99 base_url: String,
100 port: u16,
101}
102
103fn server_log(b: &Booted) -> String {
104 fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default()
105}
106
107async fn boot() -> Booted {
108 let root = temp_dir("ci2e");
109 let dir = root.path().to_path_buf();
110 let (server, ports) = boot_forge(&dir, FAST_CLAIMS, &[TAHINLI_CMD, BOB_CMD]).await;
111 Booted {
112 _server: server,
113 _root: root,
114 dir,
115 http: Http::new(ports.http),
116 base_url: format!("http://127.0.0.1:{}", ports.http),
117 port: ports.http,
118 }
119}
120
121struct Worker {
122 runner: Runner,
123 secret: String,
124 labels: Vec<String>,
125}
126
127impl Worker {
128 async fn claim(&self) -> Option<JobAssignment> {
129 self.runner
130 .client()
131 .claim(&self.secret, &self.labels)
132 .await
133 .expect("claim")
134 .job
135 }
136
137 async fn drain(&self) -> usize {
138 let mut ran = 0;
139 while let Some(job) = self.claim().await {
140 self.runner.process(job, CancellationToken::new()).await;
141 ran += 1;
142 }
143 ran
144 }
145}
146
147async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker {
148 let csrf = csrf_for(&b.http, "/admin/runners", admin_session).await;
149 let res = b
150 .http
151 .post_form(
152 "/admin/runners/tokens",
153 &[("csrf", &csrf)],
154 Some(admin_session),
155 )
156 .await;
157 assert_eq!(res.status, 200, "create registration token: {}", res.body);
158 let token = first_text(&res.body, "#reg-token");
159
160 let client = ForgeClient::new(&b.base_url).expect("runner client");
161 let registered = client
162 .register(&RegisterRequest {
163 token,
164 name: name.to_owned(),
165 labels: LABELS.iter().map(|l| (*l).to_owned()).collect(),
166 })
167 .await
168 .expect("register runner");
169 let config = RunnerConfig {
170 url: b.base_url.clone(),
171 runner_id: registered.runner_id,
172 runner_secret: registered.runner_secret.clone(),
173 name: name.to_owned(),
174 labels: LABELS.iter().map(|l| (*l).to_owned()).collect(),
175 work_dir: b.dir.join("runner-work"),
176 concurrency: 1,
177 limits: Limits::default(),
178 executor: forge_runner::config::ExecutorKind::default(),
179 images: forge_runner::config::ImagesConfig::default(),
180 sandbox: forge_runner::config::SandboxConfig::default(),
181 registries: Vec::new(),
182 auto_update: false,
183 cache_max_gib: 0,
184 };
185 let runner =
186 Runner::new(config, Arc::new(HostExecutor), RunOptions::default()).expect("runner");
187 Worker {
188 runner,
189 secret: registered.runner_secret,
190 labels: LABELS.iter().map(|l| (*l).to_owned()).collect(),
191 }
192}
193
194#[derive(Debug, Clone)]
195struct Status {
196 state: String,
197 description: String,
198 target_url: String,
199}
200
201async fn statuses(http: &Http, token: &str, sha: &str) -> BTreeMap<String, Status> {
202 let res = http
203 .get_bearer(
204 &format!("/api/v1/repos/tahinli/r/commits/{sha}/statuses"),
205 token,
206 )
207 .await;
208 assert_eq!(res.status, 200, "statuses for {sha}: {}", res.body);
209 let json: serde_json::Value = serde_json::from_str(&res.body).expect("statuses json");
210 json["statuses"]
211 .as_array()
212 .expect("statuses array")
213 .iter()
214 .map(|s| {
215 let field = |k: &str| s[k].as_str().unwrap_or_default().to_owned();
216 (
217 field("context"),
218 Status {
219 state: field("state"),
220 description: field("description"),
221 target_url: field("target_url"),
222 },
223 )
224 })
225 .collect()
226}
227
228async fn wait_statuses(
229 http: &Http,
230 token: &str,
231 sha: &str,
232 contexts: &[&str],
233) -> BTreeMap<String, Status> {
234 let deadline = Instant::now() + Duration::from_secs(20);
235 loop {
236 let found = statuses(http, token, sha).await;
237 if contexts.iter().all(|c| found.contains_key(*c)) {
238 return found;
239 }
240 assert!(
241 Instant::now() < deadline,
242 "statuses never showed {contexts:?}; got {found:?}"
243 );
244 tokio::time::sleep(Duration::from_millis(100)).await;
245 }
246}
247
248fn job_id_of(status: &Status) -> String {
249 status
250 .target_url
251 .rsplit('/')
252 .next()
253 .filter(|id| !id.is_empty())
254 .unwrap_or_else(|| panic!("no job id in {:?}", status.target_url))
255 .to_owned()
256}
257
258fn push_ci_config(work: &Path, contents: &str) -> String {
259 let sha = commit(work, ".forge/ci.toml", contents, "add ci", TAHINLI);
260 git_text(work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
261 sha
262}
263
264#[tokio::test]
265async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() {
266 let b = boot().await;
267 let tahinli = login(&b.http, "tahinli", PW).await;
268 let token = create_token(&b.http, &tahinli, "ci-token").await;
269 create_repo(&b.http, &tahinli, "r", "public").await;
270 set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await;
271 let worker = register_runner(&b, &tahinli, "runner-a").await;
272
273 let work = clone(
274 &remote(b.port, "tahinli", &token, "tahinli", "r"),
275 &b.dir.join("tahinli-work"),
276 );
277 let sha = push_ci_config(&work, CI_TOML);
278
279 let found = wait_statuses(
280 &b.http,
281 &token,
282 &sha,
283 &["ci/build", "ci/after", "ci/broken", "ci/skipme"],
284 )
285 .await;
286 assert_eq!(found["ci/build"].state, "pending", "build is queued");
287
288 let ran = worker.drain().await;
289 assert_eq!(ran, 3, "build, after and broken run; skipme never does");
290
291 let found = statuses(&b.http, &token, &sha).await;
292 assert_eq!(found["ci/build"].state, "success");
293 assert_eq!(found["ci/after"].state, "success");
294 assert_eq!(found["ci/broken"].state, "failure");
295 assert_eq!(found["ci/skipme"].state, "error");
296 assert_eq!(found["ci/skipme"].description, "skipped");
297
298 let build_id = job_id_of(&found["ci/build"]);
299 let log = b
300 .http
301 .get(&format!("{REPO_PATH}/ci/jobs/{build_id}/log.txt"), None)
302 .await;
303 assert_eq!(log.status, 200, "GET log.txt");
304 assert!(log.body.contains("hello"), "log has the echo: {}", log.body);
305 assert!(log.body.contains("***"), "secret is masked: {}", log.body);
306 assert!(
307 !log.body.contains(SECRET_VALUE),
308 "secret leaked into the log: {}",
309 log.body
310 );
311
312 let artifact = b
313 .http
314 .get(
315 &format!("{REPO_PATH}/ci/jobs/{build_id}/artifacts/out_a.txt"),
316 Some(&tahinli),
317 )
318 .await;
319 assert_eq!(artifact.status, 200, "GET artifact: {}", server_log(&b));
320 assert_eq!(artifact.body, "data\n", "artifact bytes");
321
322 let run = b
323 .http
324 .get(&format!("{REPO_PATH}/ci/runs/1"), Some(&tahinli))
325 .await;
326 assert_eq!(run.status, 200, "GET run page");
327 for job in ["build", "after", "broken", "skipme"] {
328 assert!(run.body.contains(job), "run page lists {job}");
329 }
330 assert!(
331 run.body.contains(r#"class="ci-glink" data-rel="j"#),
332 "build links to after: {}",
333 run.body
334 );
335 assert!(
336 run.body.contains(r#"class="ci-glink ci-hot" data-rel="j"#),
337 "broken links to skipme in the accent"
338 );
339 assert!(
340 run.body.contains(r#"class="ci-ghead""#),
341 "connectors have arrowheads"
342 );
343 assert!(
344 run.body.contains("<title>after, needs build</title>"),
345 "the dependency is in after's box title"
346 );
347 assert!(
348 !run.body.contains(">needs build<"),
349 "no needs subtitle under a job's name"
350 );
351}
352
353#[tokio::test]
354async fn run_page_lists_a_jobs_steps_and_a_step_opens_its_part_of_the_log() {
355 let b = boot().await;
356 let tahinli = login(&b.http, "tahinli", PW).await;
357 let token = create_token(&b.http, &tahinli, "ci-token").await;
358 create_repo(&b.http, &tahinli, "r", "public").await;
359 let worker = register_runner(&b, &tahinli, "runner-a").await;
360
361 let work = clone(
362 &remote(b.port, "tahinli", &token, "tahinli", "r"),
363 &b.dir.join("tahinli-work"),
364 );
365 let sha = push_ci_config(
366 &work,
367 "[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",
368 );
369 let found = wait_statuses(&b.http, &token, &sha, &["ci/build"]).await;
370 let job_id = job_id_of(&found["ci/build"]);
371 assert_eq!(worker.drain().await, 1, "the build job runs");
372
373 let page = b
374 .http
375 .get(
376 &format!("{REPO_PATH}/ci/runs/1?job={job_id}"),
377 Some(&tahinli),
378 )
379 .await;
380 assert_eq!(page.status, 200, "GET run page");
381 assert!(
382 page.body.contains("class=\"lab\"") && page.body.contains("Compile"),
383 "the strip lists the step names: {}",
384 page.body
385 );
386 assert!(
387 page.body.contains("step=0"),
388 "a step links to its part of the log"
389 );
390
391 let step = b
392 .http
393 .get(
394 &format!("{REPO_PATH}/ci/runs/1?job={job_id}&step=1"),
395 Some(&tahinli),
396 )
397 .await;
398 assert_eq!(step.status, 200, "GET the step's run page");
399 assert!(
400 step.body.contains(r#"data-log-start="true""#),
401 "the log opens at the step: {}",
402 step.body
403 );
404}
405
406#[tokio::test]
407async fn fork_pull_waits_for_approval_and_runs_without_secrets() {
408 let b = boot().await;
409 let tahinli = login(&b.http, "tahinli", PW).await;
410 let token = create_token(&b.http, &tahinli, "ci-token").await;
411 create_repo(&b.http, &tahinli, "r", "public").await;
412 set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await;
413 let worker = register_runner(&b, &tahinli, "runner-a").await;
414
415 let work = clone(
416 &remote(b.port, "tahinli", &token, "tahinli", "r"),
417 &b.dir.join("tahinli-work"),
418 );
419 let base_sha = push_ci_config(&work, CI_TOML);
420 wait_statuses(&b.http, &token, &base_sha, &["ci/build"]).await;
421 worker.drain().await;
422
423 let bob = login(&b.http, "bob", PW).await;
424 let bob_token = create_token(&b.http, &bob, "bob-token").await;
425 let csrf = csrf_for(&b.http, "/settings/keys", &bob).await;
426 let fork = b
427 .http
428 .post_form(&format!("{REPO_PATH}/fork"), &[("csrf", &csrf)], Some(&bob))
429 .await;
430 assert_eq!(fork.status, 303, "fork: {}\n{}", fork.body, server_log(&b));
431
432 let bob_work = clone(
433 &remote(b.port, "bob", &bob_token, "bob", "r"),
434 &b.dir.join("bob-work"),
435 );
436 git_text(&bob_work, &["checkout", "-q", "-b", "bob-feature"]);
437 let head = commit(
438 &bob_work,
439 ".forge/ci.toml",
440 CI_TOML_FORK,
441 "print the secret",
442 BOB,
443 );
444 git_text(
445 &bob_work,
446 &["push", "-q", "origin", "HEAD:refs/heads/bob-feature"],
447 );
448
449 let compare = b
450 .http
451 .get(
452 &format!("{REPO_PATH}/compare/main...bob:bob-feature"),
453 Some(&bob),
454 )
455 .await;
456 assert_eq!(compare.status, 200, "GET compare");
457 let csrf = csrf_for(&b.http, "/settings/keys", &bob).await;
458 let open = b
459 .http
460 .post_form(
461 &format!("{REPO_PATH}/pulls"),
462 &[
463 ("csrf", &csrf),
464 ("title", "Bob change"),
465 ("body", ""),
466 ("base", "main"),
467 ("head", "bob:bob-feature"),
468 ],
469 Some(&bob),
470 )
471 .await;
472 assert_eq!(open.status, 303, "open pull: {}", open.body);
473
474 let found = wait_statuses(&b.http, &token, &head, &["ci/build"]).await;
475 assert_eq!(found["ci/build"].state, "pending");
476 assert_eq!(found["ci/build"].description, "Waiting for approval");
477
478 let run_page = b
479 .http
480 .get(&format!("{REPO_PATH}/ci/runs/2"), Some(&tahinli))
481 .await;
482 assert_eq!(run_page.status, 200, "GET run 2");
483 assert!(
484 run_page.body.contains("Approve and run"),
485 "run 2 waits for approval: {}",
486 run_page.body
487 );
488
489 let approve = b
490 .http
491 .post_form(
492 &format!("{REPO_PATH}/ci/runs/2/approve"),
493 &[(
494 "csrf",
495 &csrf_for(&b.http, &format!("{REPO_PATH}/ci/runs/2"), &tahinli).await,
496 )],
497 Some(&tahinli),
498 )
499 .await;
500 assert_eq!(approve.status, 303, "approve run 2: {}", approve.body);
501 worker.drain().await;
502
503 let found = statuses(&b.http, &token, &head).await;
504 assert_eq!(found["ci/build"].state, "success", "fork build runs");
505 assert_eq!(found["ci/skipme"].state, "error");
506
507 let build_id = job_id_of(&found["ci/build"]);
508 let log = b
509 .http
510 .get(&format!("{REPO_PATH}/ci/jobs/{build_id}/log.txt"), None)
511 .await;
512 assert_eq!(log.status, 200, "GET log.txt");
513 assert!(
514 log.body.contains("value=[]"),
515 "the secret is empty for a fork run: {}",
516 log.body
517 );
518 assert!(!log.body.contains("***"), "no value to mask: {}", log.body);
519 assert!(!log.body.contains(SECRET_VALUE), "secret leaked");
520}
521
522#[tokio::test]
523async fn live_log_streams_until_the_job_finishes() {
524 let b = boot().await;
525 let tahinli = login(&b.http, "tahinli", PW).await;
526 let token = create_token(&b.http, &tahinli, "ci-token").await;
527 create_repo(&b.http, &tahinli, "r", "public").await;
528 let worker = register_runner(&b, &tahinli, "runner-a").await;
529
530 let release = b.dir.join("release");
531 let slow = format!(
532 r#"[on]
533push = ["main"]
534
535[jobs.slow]
536image = "docker.io/library/alpine:3"
537run = "echo started; i=0; while [ ! -f {} ] && [ $i -lt 100 ]; do sleep 0.1; i=$((i+1)); done; echo done"
538"#,
539 release.display()
540 );
541 let work = clone(
542 &remote(b.port, "tahinli", &token, "tahinli", "r"),
543 &b.dir.join("tahinli-work"),
544 );
545 let sha = push_ci_config(&work, &slow);
546 let found = wait_statuses(&b.http, &token, &sha, &["ci/slow"]).await;
547 let job_id = job_id_of(&found["ci/slow"]);
548
549 let job = worker.claim().await.expect("the slow job is claimed");
550 assert_eq!(job.job_id, job_id, "claimed the job the status points at");
551 let runner = worker.runner.clone();
552 let handle = tokio::spawn(async move { runner.process(job, CancellationToken::new()).await });
553
554 let url = format!("{}{REPO_PATH}/ci/jobs/{job_id}/log.txt", b.http.base);
555 let mut res = b.http.client.get(url).send().await.expect("GET log.txt");
556 assert_eq!(res.status().as_u16(), 200, "GET log.txt");
557 let mut body = String::new();
558 let mut seen_started = false;
559 let read = async {
560 while let Some(chunk) = res.chunk().await.expect("log chunk") {
561 body.push_str(&String::from_utf8_lossy(&chunk));
562 if !seen_started && body.contains("started") {
563 seen_started = true;
564 assert!(
565 !handle.is_finished(),
566 "the first line arrived only after the job had finished"
567 );
568 fs::write(&release, "").expect("release the job");
569 }
570 }
571 };
572 tokio::time::timeout(Duration::from_secs(90), read)
573 .await
574 .expect("the log stream ends after the job finishes");
575
576 assert!(seen_started, "the live log showed the first line: {body}");
577 assert!(
578 body.contains("done"),
579 "the stream ends with the last line: {body}"
580 );
581 let outcome = handle.await.expect("job task");
582 assert_eq!(outcome, Outcome::Success);
583 let found = statuses(&b.http, &token, &sha).await;
584 assert_eq!(found["ci/slow"].state, "success");
585}