OXYGENHUB
# 3eb491e9489b oxygenhub / crates / hub / tests / flow.rs
275.6 KiB · Rust · last changed The hub countersigns updates by keys it certified (keyless step 4c) 19 days ago source blame history raw
1
//! OxygenFlow on the hub (hub spec §13.2), end to end: a real `oxy` push
2
//! starts a run, a runner claims jobs through the API in dependency order,
3
//! job tokens read only their repository, results become checks and pages.
4
5
use axum::body::Body;
6
use axum::http::{header, Request, StatusCode};
7
use http_body_util::BodyExt;
8
use oxy_core::protocol::{open_remote, RemoteOptions};
9
use oxy_core::repo::Repo;
10
use oxygenhub::config::Config;
11
use oxygenhub::repos::RepoName;
12
use oxygenhub::{db, Shared};
13
use std::path::Path;
14
use tower::ServiceExt;
15
16
const ROOTFS: &str = "36fc4e3238044e424219a2b9002bf61bbe1805fec14d52cf37e17fae77c9ff16";
17
18
fn hermetic() {
19
    static ONCE: std::sync::Once = std::sync::Once::new();
20
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
21
    ONCE.call_once(|| {
22
        let d = tempfile::tempdir().unwrap();
23
        std::env::set_var("OXY_HOME", d.path());
24
        DIR.set(d).ok();
25
    });
26
}
27
28
fn write(root: &Path, rel: &str, content: &str) {
29
    let p = root.join(rel);
30
    std::fs::create_dir_all(p.parent().unwrap()).unwrap();
31
    std::fs::write(p, content).unwrap();
32
}
33
34
struct Hub {
35
    app: Shared,
36
    base: String,
37
    _dir: tempfile::TempDir,
38
}
39
40
async fn hub() -> Hub {
41
    hermetic();
42
    let dir = tempfile::tempdir().unwrap();
43
    let mut config = Config::load(dir.path()).unwrap();
44
    // The first account's setup code (oxygenhub#245).
45
    config.registration.setup_code = "test-setup".into();
46
    config.auth.push_tokens = vec!["site".into()];
47
    config.flow.runner_tokens = vec!["runner-secret".into(), "runner-two".into(), "runner-three".into()];
48
    config.flow.repos = vec!["andy/*".into()];
49
    config.registration.mode = "open".into();
50
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
51
    let port = listener.local_addr().unwrap().port();
52
    config.server.base_url = format!("http://127.0.0.1:{port}");
53
    let app = oxygenhub::build(config).await.unwrap();
54
    let router = oxygenhub::router(app.clone());
55
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
56
    Hub { app, base: format!("http://127.0.0.1:{port}"), _dir: dir }
57
}
58
59
async fn call(app: &Shared, method: &str, path: &str, bearer: Option<&str>, json: Option<String>) -> (StatusCode, String) {
60
    let mut req = Request::builder().method(method).uri(path);
61
    if let Some(b) = bearer {
62
        req = req.header(header::AUTHORIZATION, format!("Bearer {b}"));
63
    }
64
    let body = match json {
65
        Some(j) => {
66
            req = req.header(header::CONTENT_TYPE, "application/json");
67
            Body::from(j)
68
        }
69
        None => Body::empty(),
70
    };
71
    let res = oxygenhub::router(app.clone()).oneshot(req.body(body).unwrap()).await.unwrap();
72
    let status = res.status();
73
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
74
    (status, String::from_utf8_lossy(&bytes).into_owned())
75
}
76
77
/// A GET's status, `Location` and `Content-Type`.
78
async fn head(app: &Shared, path: &str) -> (StatusCode, String, String) {
79
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(path).body(Body::empty()).unwrap()).await.unwrap();
80
    let h = |k: header::HeaderName| res.headers().get(k).and_then(|v| v.to_str().ok()).unwrap_or("").to_string();
81
    (res.status(), h(header::LOCATION), h(header::CONTENT_TYPE))
82
}
83
84
async fn claim(app: &Shared) -> Option<serde_json::Value> {
85
    let (st, body) =
86
        call(app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(r#"{"runner":"test-1","runtimes":["microvm"]}"#.into())).await;
87
    match st {
88
        StatusCode::NO_CONTENT => None,
89
        StatusCode::OK => Some(serde_json::from_str(&body).unwrap()),
90
        other => panic!("claim: {other} {body}"),
91
    }
92
}
93
94
fn receipt(job: &str, pipeline_hash: &str, exit: u32) -> serde_json::Value {
95
    serde_json::json!({
96
        "job_name": job, "pipeline_hash": pipeline_hash, "scope_tree_hash": "11".repeat(32),
97
        "inputs": [], "environment": "22".repeat(32), "outputs": [], "exit_code": exit, "duration_ms": 640
98
    })
99
}
100
101
async fn finish(app: &Shared, id: i64, body: serde_json::Value) -> StatusCode {
102
    call(app, "POST", &format!("/api/v1/flow/jobs/{id}/finish"), Some("runner-secret"), Some(body.to_string())).await.0
103
}
104
105
async fn create(app: &Shared, owner: &str, name: &str) {
106
    app.repos.create(&RepoName::parse(&format!("{owner}/{name}")).unwrap(), None).unwrap();
107
    db::repos::create(&app.db, owner, name, "", hub_api::Visibility::Public).await.unwrap();
108
}
109
110
fn client(url: &str, work: &Path) -> Repo {
111
    let mut c = Repo::init(work).unwrap();
112
    c.config.set("remote.origin.url", url).unwrap();
113
    c.config.set("remote.origin.token", "site").unwrap();
114
    c.save_config().unwrap();
115
    c
116
}
117
118
fn pipeline(extra: &str) -> String {
119
    format!(
120
        "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\njob \"test\" {{\n    sandbox \"alpine\"\n    depends-on \"build\"\n    exec \"sh\" \"-eu\" \"test.sh\"\n}}\njob \"lint\" {{\n    sandbox \"alpine\"\n    exec \"true\"\n}}\n{extra}"
121
    )
122
}
123
124
async fn runs_of(app: &Shared, owner: &str, name: &str) -> Vec<db::flow::Run> {
125
    let row = db::repos::get(&app.db, owner, name).await.unwrap().unwrap();
126
    for _ in 0..100 {
127
        let r = db::flow::runs(&app.db, row.id, 10, None).await.unwrap();
128
        if !r.is_empty() {
129
            return r;
130
        }
131
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
132
    }
133
    vec![]
134
}
135
136
/// The checks on a state once there are `n` of them (they follow the run).
137
async fn checks_when(app: &Shared, repo_id: i64, state: &str, n: usize) -> Vec<db::hooks::Check> {
138
    for _ in 0..100 {
139
        let c = db::hooks::checks_for_state(&app.db, repo_id, state).await.unwrap();
140
        if c.len() >= n {
141
            return c;
142
        }
143
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
144
    }
145
    db::hooks::checks_for_state(&app.db, repo_id, state).await.unwrap()
146
}
147
148
#[tokio::test(flavor = "multi_thread")]
149
async fn a_push_runs_the_pipeline_through_a_runner() {
150
    let h = hub().await;
151
    create(&h.app, "andy", "demo").await;
152
    create(&h.app, "andy", "secret").await;
153
    create(&h.app, "other", "plain").await;
154
    let url = format!("{}/andy/demo", h.base);
155
    let work = tempfile::tempdir().unwrap();
156
    let mut c = client(&url, work.path());
157
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
158
    write(work.path(), "test.sh", "echo ok\n");
159
    c.snapshot("test").unwrap();
160
    c.commit("Add a pipeline", &[]).unwrap();
161
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
162
163
    // The push started a run with three queued jobs, and checks for them.
164
    let runs = runs_of(&h.app, "andy", "demo").await;
165
    assert_eq!(runs.len(), 1);
166
    let run = &runs[0];
167
    assert_eq!((run.bookmark.as_str(), run.status.as_str(), run.actor.as_str()), ("main", "queued", "site token"));
168
    assert_eq!(run.pipeline_hash.len(), 64);
169
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
170
    assert_eq!(jobs.iter().map(|j| (j.name.as_str(), j.depth)).collect::<Vec<_>>(), [("build", 0), ("lint", 0), ("test", 1)]);
171
    // The checks are reported just after the run is recorded.
172
    let checks = checks_when(&h.app, run.repo_id, &run.state, 3).await;
173
    assert_eq!(
174
        checks.iter().map(|c| (c.name.as_str(), c.status.as_str())).collect::<Vec<_>>(),
175
        [("flow/build", "queued"), ("flow/lint", "queued"), ("flow/test", "queued")]
176
    );
177
178
    // Runners need a runner token.
179
    assert_eq!(
180
        call(&h.app, "POST", "/api/v1/flow/claim", Some("site"), Some(r#"{"runner":"x","runtimes":["microvm"]}"#.into())).await.0,
181
        StatusCode::UNAUTHORIZED
182
    );
183
    assert_eq!(
184
        call(&h.app, "POST", "/api/v1/flow/claim", None, Some(r#"{"runner":"x","runtimes":["microvm"]}"#.into())).await.0,
185
        StatusCode::UNAUTHORIZED
186
    );
187
    // A runner without the tier gets nothing.
188
    let (st, _) =
189
        call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(r#"{"runner":"x","runtimes":["wasm"]}"#.into())).await;
190
    assert_eq!(st, StatusCode::NO_CONTENT);
191
192
    // Claims come in dependency order; `test` waits for `build`.
193
    let a = claim(&h.app).await.unwrap();
194
    let b = claim(&h.app).await.unwrap();
195
    assert_eq!((a["job"]["name"].as_str(), b["job"]["name"].as_str()), (Some("build"), Some("lint")));
196
    assert!(claim(&h.app).await.is_none(), "test waits for build");
197
    assert_eq!(a["repo"], "andy/demo");
198
    assert_eq!(a["clone_url"], url.as_str());
199
    assert_eq!(a["sandbox"]["rootfs"], ROOTFS);
200
    assert_eq!(a["job"]["exec"], serde_json::json!(["make"]));
201
    assert_eq!(a["timeout_s"], 3600);
202
    // The job is told what it builds (FLOW_STATE, FLOW_BOOKMARK, FLOW_RUN).
203
    assert_eq!(
204
        (a["state"].as_str(), a["bookmark"].as_str(), a["run_number"].as_i64()),
205
        (Some(run.state.as_str()), Some("main"), Some(run.number))
206
    );
207
    let heads: Vec<String> = a["heads"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
208
    assert_eq!(heads.join("+"), run.heads);
209
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
210
    assert_eq!(checks.iter().find(|c| c.name == "flow/build").unwrap().status, "running");
211
212
    // The job token reads this repository over the wire, and nothing else.
213
    let token = a["token"].as_str().unwrap().to_string();
214
    assert!(token.starts_with("flowjob_"));
215
    let opts = RemoteOptions { token: Some(token.clone()), ..Default::default() };
216
    open_remote(&url, &opts).unwrap().refs().unwrap();
217
    assert!(open_remote(&format!("{}/andy/secret", h.base), &opts).unwrap().refs().is_err(), "another repository");
218
    let bad = RemoteOptions { token: Some("flowjob_00".into()), ..Default::default() };
219
    assert!(open_remote(&url, &bad).unwrap().refs().is_err(), "an unknown job token");
220
    // … and cannot push.
221
    c.config.set("remote.origin.token", &token).unwrap();
222
    c.save_config().unwrap();
223
    write(work.path(), "more.txt", "x\n");
224
    c.snapshot("test").unwrap();
225
    c.commit("More", &[]).unwrap();
226
    let pushed = c.push("origin", false);
227
    assert!(pushed.is_err() || pushed.unwrap().iter().all(|r| !r.ok), "a job token cannot push");
228
    c.config.set("remote.origin.token", "site").unwrap();
229
    c.save_config().unwrap();
230
231
    // Logs, then results with receipts.
232
    let a_id = a["job_id"].as_i64().unwrap();
233
    let b_id = b["job_id"].as_i64().unwrap();
234
    let log = serde_json::json!({ "records": [
235
        { "t": 5, "stream": "flow", "text": "booting" },
236
        { "t": 120, "stream": "out", "text": "cc -o demo demo.c" },
237
        { "t": 130, "stream": "weird", "text": "x".repeat(20_000) },
238
    ]});
239
    assert_eq!(
240
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{a_id}/log"), Some("runner-secret"), Some(log.to_string())).await.0,
241
        StatusCode::NO_CONTENT
242
    );
243
    let lines = db::flow::log(&h.app.db, a_id, 0, 100).await.unwrap();
244
    assert_eq!(lines.len(), 3);
245
    assert_eq!((lines[2].stream.as_str(), lines[2].text.len()), ("console", 16 * 1024), "streams are known ones, text is capped");
246
    let ph = a["pipeline_hash"].as_str().unwrap();
247
    assert_eq!(
248
        finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("lint", ph, 0) })).await,
249
        StatusCode::BAD_REQUEST,
250
        "a receipt for another job"
251
    );
252
    assert_eq!(
253
        finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("build", ph, 0) })).await,
254
        StatusCode::NO_CONTENT
255
    );
256
    assert_eq!(finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700 })).await, StatusCode::CONFLICT, "only once");
257
    assert!(open_remote(&url, &opts).unwrap().refs().is_err(), "the token ends with its job");
258
    assert_eq!(
259
        finish(&h.app, b_id, serde_json::json!({ "exit_code": 0, "duration_ms": 300, "receipt": receipt("lint", ph, 0) })).await,
260
        StatusCode::NO_CONTENT
261
    );
262
    let t = claim(&h.app).await.unwrap();
263
    assert_eq!(t["job"]["name"], "test");
264
    let t_id = t["job_id"].as_i64().unwrap();
265
    assert_eq!(
266
        finish(&h.app, t_id, serde_json::json!({ "exit_code": 3, "duration_ms": 500, "receipt": receipt("test", ph, 3) })).await,
267
        StatusCode::NO_CONTENT
268
    );
269
270
    let run = db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap();
271
    assert_eq!(run.status, "failed");
272
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
273
    let build = jobs.iter().find(|j| j.name == "build").unwrap();
274
    assert_eq!((build.status.as_str(), build.exit_code, build.receipt_hash.len()), ("passed", Some(0), 64));
275
    assert_eq!(jobs.iter().find(|j| j.name == "test").unwrap().status, "failed");
276
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
277
    assert_eq!(
278
        checks.iter().map(|c| (c.name.as_str(), c.status.as_str())).collect::<Vec<_>>(),
279
        [("flow/build", "passed"), ("flow/lint", "passed"), ("flow/test", "failed")]
280
    );
281
    assert!(checks[2].summary.contains("exit 3") && checks[2].url.ends_with(&format!("/andy/demo/flow/{}", run.number)));
282
283
    // Pages: the list, the run with its graph and logs, and the live view.
284
    let (st, list) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
285
    assert_eq!(st, StatusCode::OK);
286
    assert!(list.contains(&format!("/andy/demo/flow/{}", run.number)) && list.contains("st-failed"), "{list}");
287
    let (st, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
288
    assert_eq!(st, StatusCode::OK);
289
    assert!(page.contains("<svg class=\"flow-graph\""), "graph");
290
    assert_eq!(page.matches("data-job-node=").count(), 3);
291
    assert_eq!(page.matches("<path class=\"edge").count(), 1, "one dependency edge");
292
    assert!(page.contains("cc -o demo demo.c"), "log shown");
293
    assert!(!page.contains("data-flow-live"), "a finished run does not poll");
294
    let (st, live) = call(&h.app, "GET", &format!("/andy/demo/flow/{}/live?after={a_id}:1", run.number), None, None).await;
295
    assert_eq!(st, StatusCode::OK);
296
    let live: serde_json::Value = serde_json::from_str(&live).unwrap();
297
    assert_eq!(live["status"], "failed");
298
    let build_live = live["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "build").unwrap().clone();
299
    assert_eq!(build_live["lines"].as_array().unwrap().len(), 2, "lines after seq 1");
300
    assert_eq!(call(&h.app, "GET", "/andy/demo/flow/999", None, None).await.0, StatusCode::NOT_FOUND);
301
302
    // A failed dependency skips what follows; an unrun job is an error.
303
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
304
    write(work.path(), "test.sh", "echo changed\n");
305
    c.snapshot("test").unwrap();
306
    c.commit("Change the test", &[]).unwrap();
307
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
308
    let mut second = None;
309
    for _ in 0..100 {
310
        let r = runs_of(&h.app, "andy", "demo").await;
311
        if r.len() == 2 {
312
            second = Some(r[0].clone());
313
            break;
314
        }
315
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
316
    }
317
    let second = second.expect("a second run");
318
    let x = claim(&h.app).await.unwrap();
319
    let y = claim(&h.app).await.unwrap();
320
    let (build_id, lint_id) = if x["job"]["name"] == "build" {
321
        (x["job_id"].as_i64().unwrap(), y["job_id"].as_i64().unwrap())
322
    } else {
323
        (y["job_id"].as_i64().unwrap(), x["job_id"].as_i64().unwrap())
324
    };
325
    assert_eq!(
326
        finish(&h.app, build_id, serde_json::json!({ "exit_code": null, "duration_ms": 10, "error": "rootfs is not on this runner" }))
327
            .await,
328
        StatusCode::NO_CONTENT
329
    );
330
    assert_eq!(finish(&h.app, lint_id, serde_json::json!({ "exit_code": 0, "duration_ms": 10 })).await, StatusCode::NO_CONTENT);
331
    assert!(claim(&h.app).await.is_none(), "test was skipped");
332
    let jobs = db::flow::jobs(&h.app.db, second.id).await.unwrap();
333
    assert_eq!(
334
        jobs.iter().map(|j| (j.name.as_str(), j.status.as_str())).collect::<Vec<_>>(),
335
        [("build", "error"), ("lint", "passed"), ("test", "skipped")]
336
    );
337
    assert_eq!(db::flow::run_by_id(&h.app.db, second.id).await.unwrap().unwrap().status, "failed");
338
339
    // An invalid pipeline is a run in error with the line.
340
    write(work.path(), ".flow/pipeline.kdl", &pipeline("job \"broken\" {\n    sandbox \"missing\"\n    exec \"x\"\n}\n"));
341
    c.snapshot("test").unwrap();
342
    c.commit("Break the pipeline", &[]).unwrap();
343
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
344
    let mut third = None;
345
    for _ in 0..100 {
346
        let r = runs_of(&h.app, "andy", "demo").await;
347
        if r.len() == 3 {
348
            third = Some(r[0].clone());
349
            break;
350
        }
351
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
352
    }
353
    let third = third.expect("a third run");
354
    assert_eq!(third.status, "error");
355
    assert!(third.error.contains("line 18") && third.error.contains("\"missing\""), "{}", third.error);
356
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", third.number), None, None).await;
357
    assert!(page.contains("The pipeline is not valid"));
358
359
    // State stamps (hub spec §13.2) and images in READMEs.
360
    write(work.path(), "README.md", "# Demo\n\n[![flow](.flow/stamp)](.flow/run)\n\n![logo](img/logo.png)\n");
361
    std::fs::create_dir_all(work.path().join("img")).unwrap();
362
    std::fs::write(work.path().join("img/logo.png"), b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\0\x01\0\0\0\x01\x08\x06\0\0\0\x1f\x15\xc4\x89")
363
        .unwrap();
364
    c.snapshot("test").unwrap();
365
    c.commit("A README with a stamp", &[]).unwrap();
366
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
367
    let mut fourth = None;
368
    for _ in 0..100 {
369
        let r = runs_of(&h.app, "andy", "demo").await;
370
        if r.len() == 4 {
371
            fourth = Some(r[0].clone());
372
            break;
373
        }
374
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
375
    }
376
    let fourth = fourth.expect("a fourth run");
377
    let (_, overview) = call(&h.app, "GET", "/andy/demo", None, None).await;
378
    assert!(overview.contains("src=\"/andy/demo/raw/main/.flow/stamp\""), "{overview}");
379
    assert!(overview.contains("href=\"/andy/demo/file/main/.flow/run\""));
380
    assert!(overview.contains("src=\"/andy/demo/raw/main/img/logo.png\""), "images use the raw route");
381
    let (st, _, ct) = head(&h.app, "/andy/demo/raw/main/img/logo.png").await;
382
    assert_eq!((st, ct.as_str()), (StatusCode::OK, "image/png"));
383
    let (st, loc, _) = head(&h.app, "/andy/demo/raw/main/.flow/stamp").await;
384
    assert!(st.is_redirection() && loc == "/andy/demo/flow/stamp/main", "{st} {loc}");
385
    let (st, loc, _) = head(&h.app, "/andy/demo/flow/stamp/main").await;
386
    assert!(st.is_redirection() && loc == format!("/andy/demo/flow/stamp/{}", fourth.heads), "a bookmark's stamp names its state: {loc}");
387
    let (st, _, ct) = head(&h.app, &loc).await;
388
    assert_eq!((st, ct.as_str()), (StatusCode::OK, "image/svg+xml; charset=utf-8"));
389
    let (_, svg) = call(&h.app, "GET", &loc, None, None).await;
390
    assert!(svg.starts_with("<svg") && svg.contains("error ·") && svg.contains(&fourth.heads[..12]), "{svg}");
391
    let (_, svg1) = call(&h.app, "GET", &format!("/andy/demo/flow/stamp/{}", run.heads), None, None).await;
392
    assert!(svg1.contains("failed ·") && svg1.contains(&format!("run #{} failed", run.id)), "an older state keeps its own result: {svg1}");
393
    assert!(svg1.contains(&build.receipt_hash), "receipt hashes in the metadata");
394
    assert_eq!(svg1.matches("text-anchor=\"middle\"").count(), 3, "one glyph per job");
395
    let (st, loc, _) = head(&h.app, "/andy/demo/file/main/.flow/run").await;
396
    assert!(st.is_redirection() && loc == "/andy/demo/flow/at/main", "{loc}");
397
    let (st, loc, _) = head(&h.app, "/andy/demo/flow/at/main").await;
398
    assert!(st.is_redirection() && loc == format!("/andy/demo/flow/{}", fourth.id), "{loc}");
399
400
    // A repository outside [flow] repos starts nothing.
401
    let work2 = tempfile::tempdir().unwrap();
402
    let c2 = client(&format!("{}/other/plain", h.base), work2.path());
403
    write(work2.path(), ".flow/pipeline.kdl", &pipeline(""));
404
    c2.snapshot("test").unwrap();
405
    c2.commit("Pipeline", &[]).unwrap();
406
    assert!(c2.push("origin", false).unwrap().iter().all(|r| r.ok));
407
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
408
    let row = db::repos::get(&h.app.db, "other", "plain").await.unwrap().unwrap();
409
    assert!(db::flow::runs(&h.app.db, row.id, 10, None).await.unwrap().is_empty());
410
    let (_, page) = call(&h.app, "GET", "/other/plain/flow", None, None).await;
411
    assert!(page.contains("not enabled for this repository"));
412
    let (_, loc, _) = head(&h.app, "/other/plain/flow/stamp/main").await;
413
    let (_, svg) = call(&h.app, "GET", &loc, None, None).await;
414
    assert!(svg.contains("no run ·"), "{svg}");
415
    let (_, loc, _) = head(&h.app, "/other/plain/flow/at/main").await;
416
    assert_eq!(loc, "/other/plain/flow");
417
}
418
419
#[tokio::test(flavor = "multi_thread")]
420
async fn claims_carry_pinned_subrepos_and_the_job_token_reads_only_those() {
421
    let h = hub().await;
422
    for n in ["base", "lib", "vault", "other", "app"] {
423
        create(&h.app, "andy", n).await;
424
    }
425
    let push = |name: &str, file: &str| {
426
        let work = tempfile::tempdir().unwrap();
427
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
428
        write(work.path(), file, "x\n");
429
        c.snapshot("t").unwrap();
430
        c.commit("first", &[]).unwrap();
431
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
432
        let heads = c.bookmark_heads().unwrap();
433
        (work, heads)
434
    };
435
    let (_b, base_heads) = push("base", "base.rs");
436
    // lib pins base in turn: a subrepo of a subrepo.
437
    let lib_work = tempfile::tempdir().unwrap();
438
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
439
    lib.submodule_add(&format!("{}/andy/base", h.base), "deps/base", Some("main")).unwrap();
440
    write(lib_work.path(), "lib.rs", "x\n");
441
    lib.snapshot("t").unwrap();
442
    lib.commit("lib on base", &[]).unwrap();
443
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
444
    let lib_heads = lib.bookmark_heads().unwrap();
445
    let (_v, _) = push("vault", "secret.rs");
446
    let (_o, _) = push("other", "o.rs");
447
448
    // The app pins lib and vault as subrepos and pushes as the site token.
449
    let work = tempfile::tempdir().unwrap();
450
    let app = client(&format!("{}/andy/app", h.base), work.path());
451
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
452
    // Vault is private: a checkout with no token for this hub cannot add
453
    // it, but the app's remote on the same hub lends its token (oxygen#32).
454
    // The subrepo keeps no copy: its own fetches find the parent's (oxygen#47).
455
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'vault'").execute(&h.app.db).await.unwrap();
456
    let bare_work = tempfile::tempdir().unwrap();
457
    let mut bare = Repo::init(bare_work.path()).unwrap();
458
    bare.config.set("remote.origin.url", &format!("{}/andy/bare", h.base)).unwrap();
459
    bare.save_config().unwrap();
460
    assert!(bare.submodule_add(&format!("{}/andy/vault", h.base), "deps/vault", Some("main")).is_err(), "not without a token");
461
    app.submodule_add(&format!("{}/andy/vault", h.base), "deps/vault", Some("main")).unwrap();
462
    let nested = Repo::open(&work.path().join("deps/vault")).unwrap();
463
    assert!(nested.config.remote_tokens.is_empty(), "no token is copied into a subrepo");
464
    nested.fetch("origin").unwrap();
465
    // The pusher below is the site token, which has no account: it cannot read vault.
466
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
467
    write(work.path(), "Makefile", "all:\n");
468
    app.snapshot("t").unwrap();
469
    app.commit("app with deps", &[]).unwrap();
470
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
471
    assert!(!runs_of(&h.app, "andy", "app").await.is_empty());
472
473
    let job = claim(&h.app).await.unwrap();
474
    let subs = job["subrepos"].as_array().cloned().unwrap_or_default();
475
    assert_eq!(subs.len(), 2, "lib and what lib pins; vault is private and the pusher has no account: {subs:?}");
476
    assert_eq!(subs[1]["path"], "deps/lib/deps/base", "nested under its parent, after it");
477
    assert_eq!(subs[1]["heads"], serde_json::json!(base_heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>()));
478
    let _ = std::fs::remove_dir_all(work.path().join("deps/vault2"));
479
    assert_eq!(subs[0]["path"], "deps/lib");
480
    assert_eq!(subs[0]["repo"], "andy/lib");
481
    assert_eq!(subs[0]["heads"], serde_json::json!(lib_heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>()));
482
    assert!(subs[0]["clone_url"].as_str().unwrap().ends_with("/andy/lib"));
483
    // The job's log says vault was left out, and why (oxygenhub#56).
484
    let job_id = job["job_id"].as_i64().unwrap();
485
    let lines = db::flow::log(&h.app.db, job_id, 0, 100).await.unwrap();
486
    assert!(
487
        lines.iter().any(|l| l.stream == "flow" && l.text.contains("subrepo deps/vault (andy/vault) is left out")),
488
        "{:?}",
489
        lines.iter().map(|l| &l.text).collect::<Vec<_>>()
490
    );
491
492
    // The job token reads its repository and the pinned lib, nothing else.
493
    let token = job["token"].as_str().unwrap().to_string();
494
    let read = |name: &str| {
495
        let opts = RemoteOptions { token: Some(token.clone()), ..Default::default() };
496
        open_remote(&format!("{}/andy/{name}", h.base), &opts).and_then(|r| r.refs()).is_ok()
497
    };
498
    assert!(read("app") && read("lib") && read("base"));
499
    assert!(!read("vault"), "not pinned for this pusher");
500
    assert!(!read("other"), "public, but not the job's to read");
501
}
502
503
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
504
async fn concurrent_log_appends_never_fail_on_a_locked_database() {
505
    let h = hub().await;
506
    create(&h.app, "andy", "demo").await;
507
    let work = tempfile::tempdir().unwrap();
508
    let c = client(&format!("{}/andy/demo", h.base), work.path());
509
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
510
    write(work.path(), "Makefile", "all:\n");
511
    c.snapshot("t").unwrap();
512
    c.commit("pipeline", &[]).unwrap();
513
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
514
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
515
    let job = db::flow::jobs(&h.app.db, run.id).await.unwrap().remove(0);
516
    // Many writers at once, each reading the count and then inserting: a
517
    // deferred transaction would fail with "database is locked".
518
    let mut tasks = Vec::new();
519
    for w in 0..16 {
520
        let pool = h.app.db.clone();
521
        tasks.push(tokio::spawn(async move {
522
            let records: Vec<flow_core::api::Record> =
523
                (0..20).map(|i| flow_core::api::Record { t: i, stream: "out".into(), text: format!("writer {w} line {i}") }).collect();
524
            db::flow::append_log(&pool, job.id, &records, 100_000).await
525
        }));
526
    }
527
    for t in tasks {
528
        assert_eq!(t.await.unwrap().unwrap(), 20, "every append succeeds");
529
    }
530
    let lines = db::flow::log(&h.app.db, job.id, 0, 1_000).await.unwrap();
531
    assert_eq!(lines.len(), 320);
532
    let seqs: std::collections::BTreeSet<i64> = lines.iter().map(|l| l.seq).collect();
533
    assert_eq!(seqs.len(), 320, "sequence numbers are unique");
534
}
535
536
/// A repository's own Flow setting overrides hub.toml either way.
537
#[tokio::test(flavor = "multi_thread")]
538
async fn a_repository_setting_turns_flow_on_or_off() {
539
    let h = hub().await;
540
    create(&h.app, "other", "plain").await;
541
    create(&h.app, "andy", "quiet").await;
542
    // A run elsewhere first, so hub-wide ids and per-repository numbers differ.
543
    create(&h.app, "andy", "first").await;
544
    {
545
        let work = tempfile::tempdir().unwrap();
546
        let c = client(&format!("{}/andy/first", h.base), work.path());
547
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
548
        write(work.path(), "test.sh", "echo ok\n");
549
        c.commit("Add a pipeline", &[]).unwrap();
550
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
551
        assert_eq!(runs_of(&h.app, "andy", "first").await.len(), 1);
552
    }
553
    let row = db::repos::get(&h.app.db, "other", "plain").await.unwrap().unwrap();
554
    db::repos::set_flow(&h.app.db, row.id, "on").await.unwrap();
555
    let quiet = db::repos::get(&h.app.db, "andy", "quiet").await.unwrap().unwrap();
556
    db::repos::set_flow(&h.app.db, quiet.id, "off").await.unwrap();
557
    for (owner, name) in [("other", "plain"), ("andy", "quiet")] {
558
        let work = tempfile::tempdir().unwrap();
559
        let c = client(&format!("{}/{owner}/{name}", h.base), work.path());
560
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
561
        write(work.path(), "test.sh", "echo ok\n");
562
        c.commit("Add a pipeline", &[]).unwrap();
563
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
564
    }
565
    let plain = runs_of(&h.app, "other", "plain").await;
566
    assert_eq!(plain.len(), 1, "turned on");
567
    // andy/first has a job running, so plain's goes next (repositories take
568
    // turns, #244), and its run says where it stands.
569
    let a = claim(&h.app).await.unwrap();
570
    assert_eq!(a["repo"], "andy/first");
571
    let (_, page) = call(&h.app, "GET", "/other/plain/flow/1", None, None).await;
572
    assert!(page.contains("Waiting for a runner: 1st in line") && page.contains("Running now: andy/first #1"), "{page}");
573
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/other/plain/flow/runs/1", None, None).await;
574
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["queue_position"], 1);
575
    let (_, list) = call(&h.app, "GET", "/other/plain/flow", None, None).await;
576
    assert!(list.contains("queued, 1st in line"), "{list}");
577
    // Runs are numbered per repository: this is plain's first, whatever
578
    // other repositories ran before.
579
    assert_eq!(plain[0].number, 1);
580
    let checks = checks_when(&h.app, row.id, &plain[0].state, 3).await;
581
    assert!(checks.iter().all(|c| c.url.ends_with("/other/plain/flow/1")), "{checks:?}");
582
    let (st, page) = call(&h.app, "GET", "/other/plain/flow/1", None, None).await;
583
    assert!(st == StatusCode::OK && page.contains("Run #1"), "{st}");
584
    assert!(runs_of(&h.app, "andy", "quiet").await.is_empty(), "turned off despite andy/*");
585
}
586
587
/// "Run pipeline" and "Re-run" (hub spec §13.2): runs that move no
588
/// bookmark, through the API and the pages.
589
#[tokio::test(flavor = "multi_thread")]
590
async fn runs_start_without_a_push_and_finished_runs_re_run() {
591
    let h = hub().await;
592
    // The site token acts as the first site administrator.
593
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
594
    create(&h.app, "andy", "demo").await;
595
    let url = format!("{}/andy/demo", h.base);
596
    let work = tempfile::tempdir().unwrap();
597
    let c = client(&url, work.path());
598
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
599
    write(work.path(), "test.sh", "echo ok\n");
600
    c.commit("Add a pipeline", &[]).unwrap();
601
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
602
    let first = runs_of(&h.app, "andy", "demo").await;
603
    assert_eq!((first.len(), first[0].trigger.as_str()), (1, "push"));
604
605
    // Run pipeline on the default bookmark: a new run of the same state.
606
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
607
    assert_eq!(st, StatusCode::CREATED, "{body}");
608
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
609
    assert_eq!(v["number"], 2);
610
    assert!(v["url"].as_str().unwrap().ends_with("/andy/demo/flow/2"));
611
    let second = db::flow::run(&h.app.db, first[0].repo_id, 2).await.unwrap().unwrap();
612
    assert_eq!((second.trigger.as_str(), second.actor.as_str(), second.state.as_str()), ("manual", "andy", first[0].state.as_str()));
613
    assert_eq!(db::flow::jobs(&h.app.db, second.id).await.unwrap().len(), 3);
614
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/2", None, None).await;
615
    assert!(page.contains("started by andy"), "the run page says what started it");
616
617
    // Run pipeline on one change: its state, with no bookmark.
618
    let head = first[0].head_list()[0].to_string();
619
    let (st, body) =
620
        call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(format!(r#"{{"change":"{head}"}}"#))).await;
621
    assert_eq!(st, StatusCode::CREATED, "{body}");
622
    let on_change = db::flow::run(&h.app.db, first[0].repo_id, 3).await.unwrap().unwrap();
623
    assert_eq!(
624
        (on_change.bookmark.as_str(), on_change.heads.as_str(), on_change.state.as_str()),
625
        ("", head.as_str(), first[0].state.as_str())
626
    );
627
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/3", None, None).await;
628
    assert!(page.contains("title=\"Run on one change, not a bookmark\">change</span>"), "run page");
629
    let (st, body) =
630
        call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(format!(r#"{{"change":"{}"}}"#, "ab".repeat(32))))
631
            .await;
632
    assert!(st == StatusCode::CONFLICT && body.contains("no change"), "{st} {body}");
633
    // Viewers who cannot start runs are told why, and get no button.
634
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
635
    assert!(page.contains("Sign in with write access to run the pipeline.") && !page.contains("primary-btn"));
636
    let (_, page) = call(&h.app, "GET", "/andy/demo/bookmarks", None, None).await;
637
    assert!(!page.contains("/flow/start"), "no run buttons for anonymous viewers");
638
639
    // A live run is not re-run; unknown bookmarks and runs are refused.
640
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/1/rerun", Some("site"), None).await;
641
    assert!(st == StatusCode::CONFLICT && body.contains("still queued"), "{st} {body}");
642
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"bookmark":"nope"}"#.into())).await;
643
    assert_eq!(st, StatusCode::CONFLICT);
644
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/99/rerun", Some("site"), None).await;
645
    assert_eq!(st, StatusCode::NOT_FOUND);
646
    // Anonymous callers cannot start runs.
647
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", None, Some("{}".into())).await;
648
    assert_ne!(st, StatusCode::CREATED);
649
650
    // A finished run re-runs as a new run of the same state.
651
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
652
    for r in [&first[0], &second] {
653
        for j in db::flow::jobs(&h.app.db, r.id).await.unwrap() {
654
            sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE id = $1").bind(j.id).execute(&h.app.db).await.unwrap();
655
        }
656
        sqlx::query("UPDATE flow_runs SET status = 'passed', finished_ms = 1 WHERE id = $1").bind(r.id).execute(&h.app.db).await.unwrap();
657
    }
658
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/1/rerun", Some("site"), None).await;
659
    assert_eq!(st, StatusCode::CREATED, "{body}");
660
    let third = db::flow::run(&h.app.db, row.id, 4).await.unwrap().unwrap();
661
    assert_eq!(
662
        (third.trigger_label().as_str(), third.status.as_str(), third.state.as_str()),
663
        ("rerun:1", "queued", first[0].state.as_str())
664
    );
665
    assert_eq!(third.trigger, "rerun:1:push", "a rerun keeps the event it repeats");
666
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, &third.state).await.unwrap();
667
    assert!(
668
        checks.iter().all(|c| c.status == "queued" && c.url.ends_with("/flow/4")),
669
        "the re-run's checks replace the old ones: {checks:?}"
670
    );
671
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/4", None, None).await;
672
    assert!(page.contains("re-run of #1 by andy"));
673
    assert!(!page.contains("RE-RUN"), "anonymous viewers get no button");
674
675
    // oxygenhub#130: one job, with what it depends on; an unknown one is
676
    // refused, naming the jobs a manual run can start.
677
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"jobs":["test"]}"#.into())).await;
678
    assert_eq!(st, StatusCode::CREATED, "{body}");
679
    let n = serde_json::from_str::<serde_json::Value>(&body).unwrap()["number"].as_i64().unwrap();
680
    let only = db::flow::run(&h.app.db, first[0].repo_id, n).await.unwrap().unwrap();
681
    let mut names: Vec<String> = db::flow::jobs(&h.app.db, only.id).await.unwrap().into_iter().map(|j| j.name).collect();
682
    names.sort();
683
    assert_eq!(names, ["build", "test"], "test and the job it depends on, not lint");
684
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"jobs":["deploy"]}"#.into())).await;
685
    assert!(st == StatusCode::CONFLICT && body.contains("not in the pipeline") && body.contains("build, lint, test"), "{st} {body}");
686
687
    // With Flow off, nothing starts.
688
    db::repos::set_flow(&h.app.db, row.id, "off").await.unwrap();
689
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
690
    assert!(st == StatusCode::CONFLICT && body.contains("not enabled"), "{body}");
691
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
692
    assert!(page.contains("Flow is off for this repository"), "and the Flow tab says so");
693
}
694
695
/// The Flow API (hub spec §13.2): runs, a run with its jobs, a job's log,
696
/// checks by the heads a client has, and JSON for unknown API routes.
697
#[tokio::test(flavor = "multi_thread")]
698
async fn runs_jobs_and_logs_are_in_the_api() {
699
    let h = hub().await;
700
    create(&h.app, "andy", "demo").await;
701
    let url = format!("{}/andy/demo", h.base);
702
    let work = tempfile::tempdir().unwrap();
703
    let c = client(&url, work.path());
704
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
705
    write(work.path(), "test.sh", "echo ok\n");
706
    let head = c.commit("Add a pipeline", &[]).unwrap();
707
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
708
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
709
710
    // A job runs and logs.
711
    let a = claim(&h.app).await.unwrap();
712
    let id = a["job_id"].as_i64().unwrap();
713
    let recs =
714
        serde_json::json!({ "records": [{ "t": 1, "stream": "stdout", "text": "one" }, { "t": 3, "stream": "stderr", "text": "three" }] });
715
    let (st, _) = call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(recs.to_string())).await;
716
    assert!(st.is_success(), "{st}");
717
718
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs", None, None).await;
719
    assert_eq!(st, StatusCode::OK, "{body}");
720
    let runs: Vec<hub_api::FlowRun> = serde_json::from_str(&body).unwrap();
721
    assert_eq!(runs.len(), 1);
722
    assert_eq!((runs[0].number, runs[0].state.as_str(), runs[0].trigger.as_str()), (1, run.state.as_str(), "push"));
723
    assert!(runs[0].url.ends_with("/andy/demo/flow/1") && runs[0].jobs.is_empty());
724
725
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", None, None).await;
726
    let one: hub_api::FlowRun = serde_json::from_str(&body).unwrap();
727
    let names: Vec<(&str, &str)> = one.jobs.iter().map(|j| (j.name.as_str(), j.status.as_str())).collect();
728
    assert_eq!(names.len(), 3);
729
    let running = one.jobs.iter().find(|j| j.status == "running").unwrap();
730
    assert_eq!(running.name, a["job"]["name"].as_str().unwrap());
731
    assert!(one.jobs.iter().any(|j| j.name == "test" && j.depends_on == ["build"]));
732
733
    let job = running.name.clone();
734
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/1/jobs/{job}/log"), None, None).await;
735
    assert_eq!(st, StatusCode::OK, "{body}");
736
    let lines: Vec<hub_api::FlowLogLine> = serde_json::from_str(&body).unwrap();
737
    assert!(lines.iter().any(|l| l.text == "three"), "{body}");
738
    let last = lines.last().unwrap().seq;
739
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/1/jobs/{job}/log?after={last}"), None, None).await;
740
    assert_eq!(body, "[]", "nothing after the last line");
741
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/9", None, None).await.0, StatusCode::NOT_FOUND);
742
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1/jobs/nope/log", None, None).await.0, StatusCode::NOT_FOUND);
743
744
    // Checks by the state hash, by the head `oxy log` shows, and by bookmark.
745
    let by = |key: String| {
746
        let app = h.app.clone();
747
        async move {
748
            let (st, body) = call(&app, "GET", &format!("/api/v1/repos/andy/demo/checks/{key}"), None, None).await;
749
            assert_eq!(st, StatusCode::OK, "{key}: {body}");
750
            serde_json::from_str::<Vec<hub_api::Check>>(&body).unwrap().len()
751
        }
752
    };
753
    checks_when(&h.app, run.repo_id, &run.state, 3).await;
754
    assert_eq!(by(run.state.clone()).await, 3);
755
    assert_eq!(by(head.to_hex()).await, 3, "a single head names its state");
756
    assert_eq!(by("main".into()).await, 3);
757
    let (st, _) = call(&h.app, "GET", "/api/v1/repos/andy/demo/checks/no-such-bookmark", None, None).await;
758
    assert_eq!(st, StatusCode::NOT_FOUND);
759
760
    // An unknown API route answers with a problem document.
761
    let (st, body) = call(&h.app, "GET", "/api/v1/users/andy/repos", None, None).await;
762
    assert_eq!(st, StatusCode::NOT_FOUND);
763
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
764
    assert_eq!(v["status"], 404, "{body}");
765
}
766
767
async fn get_bytes(app: &Shared, path: &str) -> (StatusCode, Vec<u8>) {
768
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(path).body(Body::empty()).unwrap()).await.unwrap();
769
    let status = res.status();
770
    (status, res.into_body().collect().await.unwrap().to_bytes().to_vec())
771
}
772
773
#[tokio::test(flavor = "multi_thread")]
774
async fn signed_receipts_are_checked_kept_and_shown() {
775
    use oxy_core::hash::{hash_object, ChangeHash, ObjectRef, ObjectType};
776
    use oxy_core::identity::SecretKey;
777
    use oxy_core::objects::StateObject;
778
    use oxy_core::receipt::SignedReceipt;
779
    let h = hub().await;
780
    create(&h.app, "andy", "demo").await;
781
    let url = format!("{}/andy/demo", h.base);
782
    let work = tempfile::tempdir().unwrap();
783
    let c = client(&url, work.path());
784
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
785
    c.snapshot("test").unwrap();
786
    c.commit("Add a pipeline", &[]).unwrap();
787
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
788
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
789
    let heads: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
790
    let state = hash_object(ObjectType::State, &StateObject::new(heads.clone()).encode());
791
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
792
    let sk = SecretKey::generate();
793
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
794
    let sign = |r: &serde_json::Value, state: ObjectRef, sk: &SecretKey, id: &oxy_core::identity::Identity| {
795
        let r: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
796
        let run_url = format!("{url}/flow/{}", run.number);
797
        hex::encode(SignedReceipt::sign(r.to_oxy(), repo_id, state, &run_url, id, sk).encode())
798
    };
799
800
    let a = claim(&h.app).await.unwrap();
801
    let b = claim(&h.app).await.unwrap();
802
    let ph = a["pipeline_hash"].as_str().unwrap().to_string();
803
    let (a_id, b_id) = (a["job_id"].as_i64().unwrap(), b["job_id"].as_i64().unwrap());
804
    // The first signed receipt binds the runner token to its key, and is kept.
805
    let rb = receipt("build", &ph, 0);
806
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": rb, "signed_receipt": sign(&rb, state, &sk, &runner) });
807
    assert_eq!(finish(&h.app, a_id, body).await, StatusCode::NO_CONTENT);
808
    // Another key under the same token: the result counts, the receipt is not kept.
809
    let other = SecretKey::generate();
810
    let rl = receipt("lint", &ph, 0);
811
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 300, "receipt": rl,
812
        "signed_receipt": sign(&rl, state, &other, &other.identity("mallory", "", 1)) });
813
    assert_eq!(finish(&h.app, b_id, body).await, StatusCode::NO_CONTENT);
814
    // The right key, but for another state.
815
    let t = claim(&h.app).await.unwrap();
816
    let rt = receipt("test", &ph, 0);
817
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 500, "receipt": rt,
818
        "signed_receipt": sign(&rt, ObjectRef([9; 32]), &sk, &runner) });
819
    assert_eq!(finish(&h.app, t["job_id"].as_i64().unwrap(), body).await, StatusCode::NO_CONTENT);
820
821
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
822
    let job = |n: &str| jobs.iter().find(|j| j.name == n).unwrap().clone();
823
    assert_eq!(job("build").status, "passed");
824
    assert_eq!((job("build").receipt_attest.len(), job("build").receipt_signer.as_str()), (64, "test-1 (OxygenFlow runner)"));
825
    assert_eq!(job("lint").status, "passed", "the job's result stands");
826
    assert!(job("lint").receipt_attest.is_empty());
827
    assert!(job("lint").receipt_note.contains("not the key this runner signs with"), "{}", job("lint").receipt_note);
828
    assert!(job("test").receipt_note.contains("another state"), "{}", job("test").receipt_note);
829
830
    // The repository keeps it, and anyone who can read the repository can
831
    // download it and check it on their own.
832
    let kept = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().receipts(&heads).unwrap();
833
    assert_eq!(kept.len(), 1);
834
    let attest = job("build").receipt_attest;
835
    let (st, bytes) = get_bytes(&h.app, &format!("/andy/demo/receipts/{attest}")).await;
836
    assert_eq!(st, StatusCode::OK);
837
    let sr = SignedReceipt::decode(&bytes).unwrap();
838
    sr.verify().unwrap();
839
    assert_eq!((sr.state(), sr.receipt.job_name.as_str()), (state, "build"));
840
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/receipts/{}", "0".repeat(64))).await.0, StatusCode::NOT_FOUND);
841
842
    // Pages: the run names the signer or why a receipt was not kept; the
843
    // change whose state it is lists it.
844
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
845
    assert!(page.contains("signed receipt</a> by test-1"), "run page");
846
    assert!(page.contains("receipt not kept"), "run page");
847
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/change/{}", heads[0].to_hex()), None, None).await;
848
    assert!(page.contains("<dt>Receipts</dt>") && page.contains(&format!("/andy/demo/receipts/{attest}")), "change page");
849
}
850
851
async fn upload(app: &Shared, job: i64, name: &str, bytes: &[u8]) -> (StatusCode, String) {
852
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/artifacts/{name}"))
853
        .header(header::AUTHORIZATION, "Bearer runner-secret")
854
        .header(header::CONTENT_TYPE, "application/octet-stream")
855
        .body(Body::from(bytes.to_vec()))
856
        .unwrap();
857
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
858
    let status = res.status();
859
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
860
}
861
862
#[tokio::test(flavor = "multi_thread")]
863
async fn artifacts_are_kept_named_by_the_receipt_and_served() {
864
    let h = hub().await;
865
    create(&h.app, "andy", "demo").await;
866
    let url = format!("{}/andy/demo", h.base);
867
    let work = tempfile::tempdir().unwrap();
868
    let c = client(&url, work.path());
869
    write(
870
        work.path(),
871
        ".flow/pipeline.kdl",
872
        &format!(
873
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n    output {{\n        artifact \"tool\" {{\n            path \"/src/out/tool\"\n        }}\n    }}\n}}\n"
874
        ),
875
    );
876
    c.snapshot("test").unwrap();
877
    c.commit("Build a tool", &[]).unwrap();
878
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
879
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
880
    let a = claim(&h.app).await.unwrap();
881
    assert_eq!(a["job"]["outputs"], serde_json::json!([{ "name": "tool", "path": "/src/out/tool" }]), "the runner is told");
882
    let id = a["job_id"].as_i64().unwrap();
883
884
    let body: Vec<u8> = (0..300_000u32).map(|i| (i % 253) as u8).collect();
885
    let (st, text) = upload(&h.app, id, "other", &body).await;
886
    assert_eq!(st, StatusCode::BAD_REQUEST, "an undeclared artifact: {text}");
887
    let (st, text) = upload(&h.app, id, "tool", &body).await;
888
    assert_eq!(st, StatusCode::OK, "{text}");
889
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
890
    assert_eq!(blob, oxy_core::repo::Repo::blob_ref(&body).to_hex(), "the same blob the runner computes");
891
892
    // The receipt must name exactly the uploaded artifacts.
893
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
894
    assert_eq!(
895
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r.clone() })).await,
896
        StatusCode::BAD_REQUEST
897
    );
898
    r["outputs"] = serde_json::json!([blob]);
899
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r })).await, StatusCode::NO_CONTENT);
900
901
    // The run page lists it; anyone who can read the repository downloads it.
902
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
903
    let link = format!("/andy/demo/flow/{}/artifacts/build/tool", run.number);
904
    assert!(page.contains(&link), "run page lists the artifact");
905
    let (st, got) = get_bytes(&h.app, &link).await;
906
    assert_eq!((st, got == body), (StatusCode::OK, true));
907
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/flow/{}/artifacts/build/none", run.number)).await.0, StatusCode::NOT_FOUND);
908
909
    // The nightly gc keeps it (#126): only the database names it, so with
910
    // no grace period a gc that did not root it would prune it at once.
911
    {
912
        let name = RepoName::parse("andy/demo").unwrap();
913
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
914
        hosted.config.set("core.gc-grace", "0").unwrap();
915
        hosted.save_config().unwrap();
916
    }
917
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
918
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
919
    let (st, got) = get_bytes(&h.app, &link).await;
920
    assert_eq!((st, got == body), (StatusCode::OK, true), "the artifact survives gc");
921
922
    // A writer attaches the artifact to a release from the run page; the
923
    // release then names the run and job that built it, as does the API.
924
    let form = |f: String| {
925
        Request::post("/register").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(Body::from(f)).unwrap()
926
    };
927
    let res = oxygenhub::router(h.app.clone())
928
        .oneshot(form("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup".into()))
929
        .await
930
        .unwrap();
931
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
932
    let with_cookie = |method: &str, path: &str, body: Option<String>| {
933
        let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie.clone());
934
        if body.is_some() {
935
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
936
        }
937
        req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()
938
    };
939
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
940
    db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
941
    let res = oxygenhub::router(h.app.clone()).oneshot(with_cookie("GET", &format!("/andy/demo/flow/{}", run.number), None)).await.unwrap();
942
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
943
    let attach = format!("/andy/demo/flow/{}/artifacts/build/tool/attach", run.number);
944
    assert!(page.contains(&attach), "a writer is offered the release");
945
    let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
946
    let csrf = page[i..].split('"').next().unwrap().to_string();
947
    let release_id = db::releases::list(&h.app.db, row.id).await.unwrap()[0].id;
948
    let res = oxygenhub::router(h.app.clone())
949
        .oneshot(with_cookie("POST", &attach, Some(format!("_csrf={csrf}&release={release_id}"))))
950
        .await
951
        .unwrap();
952
    assert_eq!(res.status(), StatusCode::SEE_OTHER);
953
    let (_, page) = call(&h.app, "GET", "/andy/demo/releases/tag/v1", None, None).await;
954
    assert!(
955
        page.contains(">tool</a>") && page.contains(&format!("built by <a href=\"/andy/demo/flow/{0}\">run #{0}</a> build", run.number)),
956
        "{page}"
957
    );
958
    let (_, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases", None, None).await;
959
    let api: serde_json::Value = serde_json::from_str(&api).unwrap();
960
    let asset = &api[0]["assets"][0];
961
    assert_eq!(
962
        (asset["name"].as_str(), asset["built_by"]["run"].as_i64(), asset["built_by"]["job"].as_str()),
963
        (Some("tool"), Some(run.number), Some("build"))
964
    );
965
    assert!(asset["built_by"]["receipt"].is_null(), "that receipt was not signed");
966
}
967
968
/// oxygenflow#37: a failing job keeps a `when "always"` artifact; its
969
/// receipt names none, and the run page says the file is outside it.
970
async fn upload_report_file(app: &Shared, job: i64, name: &str, path: &str, bytes: &[u8]) -> (StatusCode, String) {
971
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/reports/{name}/files"))
972
        .header(header::AUTHORIZATION, "Bearer runner-secret")
973
        .header(header::CONTENT_TYPE, "application/octet-stream")
974
        .header("X-Flow-Report-Path", path)
975
        .body(Body::from(bytes.to_vec()))
976
        .unwrap();
977
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
978
    let status = res.status();
979
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
980
}
981
982
/// #127: a report's files arrive one by one, then its manifest as the
983
/// report's artifact; the hub indexes the declaration, metrics and files,
984
/// and gc keeps every file.
985
#[tokio::test(flavor = "multi_thread")]
986
async fn reports_are_kept_file_by_file_and_indexed() {
987
    let h = hub().await;
988
    create(&h.app, "andy", "demo").await;
989
    let url = format!("{}/andy/demo", h.base);
990
    let work = tempfile::tempdir().unwrap();
991
    let c = client(&url, work.path());
992
    write(
993
        work.path(),
994
        ".flow/pipeline.kdl",
995
        &format!(
996
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"perf\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n    output {{\n        artifact \"tool\" {{\n            path \"/src/out/tool\"\n        }}\n        report \"frame-timing\" {{\n            path \"/src/out/report\"\n            when \"always\"\n        }}\n    }}\n}}\n"
997
        ),
998
    );
999
    c.snapshot("test").unwrap();
1000
    c.commit("Measure frames", &[]).unwrap();
1001
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1002
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1003
    let a = claim(&h.app).await.unwrap();
1004
    let id = a["job_id"].as_i64().unwrap();
1005
1006
    let toml = b"kind = \"performance\"\ntitle = \"Frame timing\"\nsummary = \"Median 16.4 ms\"\n\n[metrics]\nmedian_ms = { value = 16.4, unit = \"ms\", better = \"lower\", fail_above = 20 }\n\n[context]\ntarget_fps = 30\n";
1007
    let page = b"<p>frames</p>".to_vec();
1008
    let data: Vec<u8> = (0..100_000u32).map(|i| (i % 241) as u8).collect();
1009
    let (page_bytes, data_bytes) = (page.clone(), data.clone());
1010
    let files: [(&str, &[u8]); 3] = [("data/frames.csv", &data), ("index.html", &page), ("report.toml", toml)];
1011
1012
    assert_eq!(upload_report_file(&h.app, id, "tool", "report.toml", toml).await.0, StatusCode::BAD_REQUEST, "not a report");
1013
    assert_eq!(upload_report_file(&h.app, id, "frame-timing", "../x", toml).await.0, StatusCode::BAD_REQUEST, "not a clean path");
1014
    let mut listed = vec![];
1015
    for (path, bytes) in files {
1016
        let (st, text) = upload_report_file(&h.app, id, "frame-timing", path, bytes).await;
1017
        assert_eq!(st, StatusCode::OK, "{text}");
1018
        let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1019
        assert_eq!(blob, oxy_core::repo::Repo::blob_ref(bytes).to_hex());
1020
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1021
    }
1022
    let mut missing = listed.clone();
1023
    missing.push(serde_json::json!({ "path": "assets/x.js", "blob": "ab".repeat(32), "size": 1 }));
1024
    let (st, text) =
1025
        upload(&h.app, id, "frame-timing", &serde_json::to_vec(&serde_json::json!({ "version": 1, "files": missing })).unwrap()).await;
1026
    assert_eq!(st, StatusCode::BAD_REQUEST, "a file never uploaded: {text}");
1027
    assert!(text.contains("assets/x.js"), "{text}");
1028
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed })).unwrap();
1029
    let (st, text) = upload(&h.app, id, "frame-timing", &manifest).await;
1030
    assert_eq!(st, StatusCode::OK, "{text}");
1031
1032
    let (kind, title, summary, files_n, bytes): (String, String, String, i64, i64) =
1033
        sqlx::query_as("SELECT kind, title, summary, files, bytes FROM reports WHERE job_id = $1 AND name = 'frame-timing'")
1034
            .bind(id)
1035
            .fetch_one(&h.app.db)
1036
            .await
1037
            .unwrap();
1038
    assert_eq!((kind.as_str(), title.as_str(), summary.as_str()), ("performance", "Frame timing", "Median 16.4 ms"));
1039
    assert_eq!((files_n, bytes), (3, (data.len() + page.len() + toml.len()) as i64));
1040
    let rid: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE job_id = $1").bind(id).fetch_one(&h.app.db).await.unwrap();
1041
    let m = oxygenhub::reports::metrics(&h.app.db, rid).await.unwrap();
1042
    assert_eq!((m[0].key.as_str(), m[0].value, m[0].fail_above), ("median_ms", 16.4, Some(20.0)));
1043
    let log = db::flow::log(&h.app.db, id, 0, 1000).await.unwrap();
1044
    assert!(log.iter().any(|r| r.text.contains("report frame-timing: performance \"Frame timing\", 1 metric")), "{log:?}");
1045
1046
    // The threshold is a check on the run's state, passing at 16.4.
1047
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
1048
    let c = checks.iter().find(|c| c.name == "report/frame-timing/median_ms").expect("a check per threshold");
1049
    assert_eq!(c.status, "passed", "{c:?}");
1050
    assert!(c.summary.contains("16.4 ms") && c.url.contains("/reports/frame-timing?id="), "{c:?}");
1051
1052
    // The Reports tab, the report's page, and its own page in a sandbox.
1053
    let (_, page) = call(&h.app, "GET", "/andy/demo", None, None).await;
1054
    assert!(page.contains(">Reports</a>"), "the tab");
1055
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports", None, None).await;
1056
    assert!(st == StatusCode::OK && page.contains("Frame timing") && page.contains("median_ms"), "{st}");
1057
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1058
    assert!(st == StatusCode::OK && page.contains("fails above 20") && page.contains("sandbox=\"allow-scripts\""), "{st}");
1059
    let src = page.split("class=\"rep-frame\" src=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
1060
    assert!(src.ends_with("/index.html"), "{src}");
1061
    let res = oxygenhub::router(h.app.clone()).oneshot(Request::get(&src).body(Body::empty()).unwrap()).await.unwrap();
1062
    assert_eq!(res.status(), StatusCode::OK);
1063
    let csp = res.headers()[header::CONTENT_SECURITY_POLICY].to_str().unwrap().to_string();
1064
    assert!(csp.starts_with("sandbox allow-scripts;") && csp.contains("default-src 'none'"), "{csp}");
1065
    // The site's own policy and frame refusal stay off it: report frames are framed (#222).
1066
    assert!(
1067
        res.headers().get(header::X_FRAME_OPTIONS).is_none() && res.headers().get(header::CONTENT_SECURITY_POLICY_REPORT_ONLY).is_none()
1068
    );
1069
    assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
1070
    assert_eq!(res.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*");
1071
    // The page as kept, with the frame script that sizes the frame added.
1072
    let served = res.into_body().collect().await.unwrap().to_bytes().to_vec();
1073
    assert!(served.starts_with(&page_bytes), "the report's page");
1074
    assert!(String::from_utf8_lossy(&served).contains("/static/report-frame.js"), "with the frame script");
1075
    let (st, _) = get_bytes(&h.app, "/static/report.css").await;
1076
    assert_eq!(st, StatusCode::OK, "the stylesheet a report may link");
1077
    let data = src.replace("/index.html", "/data/frames.csv");
1078
    assert_eq!(get_bytes(&h.app, &data).await, (StatusCode::OK, data_bytes.clone()));
1079
    // A link with another report's MAC, or a file it lacks, finds nothing.
1080
    // A second run of the report: the timeline has two stops, and the
1081
    // first can be compared with it (RP4).
1082
    let first: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE name = 'frame-timing'").fetch_one(&h.app.db).await.unwrap();
1083
    let second: i64 = sqlx::query_scalar(
1084
        "INSERT INTO reports (repo_id, name, kind, title, summary, context, run_id, job_id, run_number, job, bookmark, state, manifest, files, bytes, created_ms) \
1085
         SELECT repo_id, name, kind, title, 'Median 18.0 ms', context, run_id, NULL, 2, job, bookmark, state, manifest, files, bytes, created_ms + 1000 FROM reports WHERE id = $1 RETURNING id",
1086
    )
1087
    .bind(first)
1088
    .fetch_one(&h.app.db)
1089
    .await
1090
    .unwrap();
1091
    sqlx::query(
1092
        "INSERT INTO report_metrics (report_id, key, value, unit, better, fail_above) VALUES ($1, 'median_ms', 18.0, 'ms', 'lower', 20)",
1093
    )
1094
    .bind(second)
1095
    .execute(&h.app.db)
1096
    .await
1097
    .unwrap();
1098
    let (_, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1099
    assert_eq!(page.matches("data-tl-stop").count(), 2, "a stop per run");
1100
    assert!(page.contains("Median 18.0 ms"), "the newest run is shown");
1101
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/frame-timing?id={first}&compare={second}&play=3"), None, None).await;
1102
    assert!(page.contains("This run against run #2") && page.contains("-1.6"), "every metric against the other run");
1103
    let stop = page.split("data-tl-stop").next().unwrap_or("").rsplit("href=").next().unwrap_or("").to_string();
1104
    assert!(page.contains("data-play=\"3\""), "playing");
1105
    assert!(stop.contains("play") && stop.contains('3'), "playing carries on from stop to stop: {stop}");
1106
    assert!(page.contains("data-report-runs="), "the frame interface knows the runs");
1107
    let forged = src.replacen("/files/", "/files/9", 1);
1108
    assert_eq!(get_bytes(&h.app, &forged).await.0, StatusCode::NOT_FOUND);
1109
    assert_eq!(get_bytes(&h.app, &src.replace("/index.html", "/secret.txt")).await.0, StatusCode::NOT_FOUND);
1110
    let _ = run;
1111
1112
    // gc keeps every file: only the database names them.
1113
    {
1114
        let name = RepoName::parse("andy/demo").unwrap();
1115
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
1116
        hosted.config.set("core.gc-grace", "0").unwrap();
1117
        hosted.save_config().unwrap();
1118
    }
1119
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
1120
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
1121
    let hosted = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
1122
    for (path, bytes) in files {
1123
        assert_eq!(hosted.read_blob(&oxy_core::repo::Repo::blob_ref(bytes)).unwrap(), bytes, "{path} survives gc");
1124
    }
1125
}
1126
1127
#[tokio::test(flavor = "multi_thread")]
1128
async fn a_failing_job_keeps_an_artifact_outside_its_receipt() {
1129
    let h = hub().await;
1130
    create(&h.app, "andy", "demo").await;
1131
    let url = format!("{}/andy/demo", h.base);
1132
    let work = tempfile::tempdir().unwrap();
1133
    let c = client(&url, work.path());
1134
    write(
1135
        work.path(),
1136
        ".flow/pipeline.kdl",
1137
        &format!(
1138
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"test\" {{\n    sandbox \"alpine\"\n    exec \"make\" \"test\"\n    output {{\n        artifact \"junit\" {{\n            path \"/src/out/junit.xml\"\n            when \"always\"\n        }}\n    }}\n}}\n"
1139
        ),
1140
    );
1141
    c.snapshot("test").unwrap();
1142
    c.commit("Test", &[]).unwrap();
1143
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1144
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1145
    let a = claim(&h.app).await.unwrap();
1146
    assert_eq!(a["job"]["outputs"][0]["always"], true, "the runner is told to keep it from a failing job");
1147
    let id = a["job_id"].as_i64().unwrap();
1148
    // A JUnit report (#114): parsed on upload, counted, failures listed.
1149
    let xml = br#"<testsuites><testsuite name="pytest"><testcase classname="tests.test_io" name="test_read" time="0.5"/><testcase classname="tests.test_io" name="test_write" time="1.5"><failure message="disk full">E   OSError: disk full</failure></testcase></testsuite></testsuites>"#;
1150
    let (st, text) = upload(&h.app, id, "junit", xml).await;
1151
    assert_eq!(st, StatusCode::OK, "{text}");
1152
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1153
    let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), 1);
1154
    r["outputs"] = serde_json::json!([blob]);
1155
    assert_eq!(
1156
        finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r.clone() })).await,
1157
        StatusCode::BAD_REQUEST,
1158
        "a failing receipt names no outputs"
1159
    );
1160
    r["outputs"] = serde_json::json!([]);
1161
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r })).await, StatusCode::NO_CONTENT);
1162
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
1163
    assert!(page.contains(&format!("/andy/demo/flow/{}/artifacts/test/junit", run.number)), "listed");
1164
    assert!(page.contains("not in its receipt"), "marked");
1165
    assert!(page.contains("2 tests: 1 failed"), "counts beside the job");
1166
    assert!(page.contains("tests.test_io::test_write") && page.contains("disk full") && page.contains("OSError"), "the failure");
1167
    assert!(page.contains("tests: 2 tests: 1 failed in 2.0 s"), "said in the job's log");
1168
}
1169
1170
/// A release's trust report (hub spec §9.1): a signed tag, an asset built
1171
/// by a job with a signed receipt from the tagged state, and one uploaded
1172
/// by hand; the page, its JSON export and the API.
1173
#[tokio::test(flavor = "multi_thread")]
1174
async fn a_release_is_audited_from_authors_to_receipts() {
1175
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
1176
    use oxy_core::identity::SecretKey;
1177
    use oxy_core::objects::StateObject;
1178
    use oxy_core::receipt::SignedReceipt;
1179
    let h = hub().await;
1180
    create(&h.app, "andy", "demo").await;
1181
    let url = format!("{}/andy/demo", h.base);
1182
    let work = tempfile::tempdir().unwrap();
1183
    let mut c = client(&url, work.path());
1184
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
1185
    write(
1186
        work.path(),
1187
        ".flow/pipeline.kdl",
1188
        &format!(
1189
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n    output {{\n        artifact \"tool\" {{\n            path \"/src/out/tool\"\n        }}\n    }}\n}}\n"
1190
        ),
1191
    );
1192
    c.snapshot("test").unwrap();
1193
    c.commit("Build a tool", &[]).unwrap();
1194
    let heads = c.bookmark_heads().unwrap();
1195
    c.tag_create("v1", &heads, "first").unwrap();
1196
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1197
1198
    // The runner builds, uploads the artifact and signs its receipt.
1199
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1200
    let a = claim(&h.app).await.unwrap();
1201
    let id = a["job_id"].as_i64().unwrap();
1202
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
1203
    let (_, text) = upload(&h.app, id, "tool", &body).await;
1204
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1205
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
1206
    r["outputs"] = serde_json::json!([blob]);
1207
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
1208
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
1209
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
1210
    let sk = SecretKey::generate();
1211
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
1212
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
1213
    let signed = hex::encode(SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/1"), &runner, &sk).encode());
1214
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
1215
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
1216
1217
    // A release with the built asset and a file uploaded by hand.
1218
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1219
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
1220
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
1221
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "notes.txt", "", b"by hand\n").await.unwrap();
1222
1223
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
1224
    assert_eq!(st, StatusCode::OK);
1225
    for want in [
1226
        "Tag v1 is signed",
1227
        "The one change in the release is authenticated",
1228
        "tool: signed receipt from run #1 build",
1229
        "a runner key of this hub",
1230
        "tool: built from the tagged state",
1231
        "tool: pinned environment",
1232
        "notes.txt: no build found",
1233
        "<svg class=\"trust-graph\"",
1234
        // oxygenhub#79: a summary of badges, badges in the graph, and the
1235
        // graph drawn at its own size rather than stretched to the page.
1236
        "Tag signed by",
1237
        "1 of 1 changes signed or sealed",
1238
        "1 of 2 assets built and attested by OxygenFlow",
1239
        "attested build",
1240
        "uploaded by hand",
1241
        "receipt verified",
1242
        "class=\"shackle\"",
1243
        "<title>notes.txt:",
1244
    ] {
1245
        assert!(page.contains(want), "missing {want:?}");
1246
    }
1247
    let svg = &page[page.find("<svg class=\"trust-graph\"").unwrap()..];
1248
    assert!(svg[..200].contains(" width=\"") && svg[..200].contains(" height=\""), "the graph has its own size: {}", &svg[..200]);
1249
    let (_, releases) = call(&h.app, "GET", "/andy/demo/releases", None, None).await;
1250
    assert!(releases.contains("/andy/demo/releases/trust/v1"), "the release links its audit");
1251
1252
    // The export carries the signed receipt, which checks on its own.
1253
    let (st, json) = call(&h.app, "GET", "/andy/demo/releases/trust/v1?format=json", None, None).await;
1254
    assert_eq!(st, StatusCode::OK);
1255
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
1256
    assert_eq!((t["tag"].as_str(), t["tag_signature"].as_str(), t["changes"].as_i64()), (Some("v1"), Some("valid"), Some(1)));
1257
    assert_eq!(t["authors"][0]["who"]["name"], "Andy");
1258
    let tool = t["assets"].as_array().unwrap().iter().find(|a| a["name"] == "tool").unwrap();
1259
    let hex_receipt = tool["build"]["signed_receipt"].as_str().unwrap();
1260
    let sr = SignedReceipt::decode(&hex::decode(hex_receipt).unwrap()).unwrap();
1261
    sr.verify().unwrap();
1262
    assert_eq!(sr.receipt.outputs[0].to_hex(), blob);
1263
    let audit = t["audit"].as_array().unwrap();
1264
    assert!(audit.iter().any(|c| c["verdict"] == "warn" && c["title"].as_str().unwrap().starts_with("notes.txt")));
1265
    assert!(!audit.iter().any(|c| c["verdict"] == "fail"), "{audit:?}");
1266
    // The API gives the same report; an unknown release is a 404.
1267
    let (st, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v1", None, None).await;
1268
    assert_eq!(st, StatusCode::OK);
1269
    assert_eq!(serde_json::from_str::<serde_json::Value>(&api).unwrap()["assets"].as_array().unwrap().len(), 2);
1270
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1271
    assert_eq!(call(&h.app, "GET", "/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1272
}
1273
1274
/// Runners (hub spec §13.2): an administrator makes a registration token,
1275
/// a runner registers with it (binding its key), claims, shows on Admin →
1276
/// Runners with its history, and is drained, disabled and removed.
1277
#[tokio::test(flavor = "multi_thread")]
1278
async fn runners_register_show_their_history_and_are_drained_and_removed() {
1279
    use oxy_core::identity::SecretKey;
1280
    let h = hub().await;
1281
    create(&h.app, "andy", "demo").await;
1282
    // A signed-in site administrator.
1283
    let res = oxygenhub::router(h.app.clone())
1284
        .oneshot(
1285
            Request::post("/register")
1286
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1287
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
1288
                .unwrap(),
1289
        )
1290
        .await
1291
        .unwrap();
1292
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1293
    let admin = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
1294
    db::accounts::set_admin(&h.app.db, admin.id, true).await.unwrap();
1295
    let web = |method: &'static str, path: String, body: Option<String>| {
1296
        let (app, cookie) = (h.app.clone(), cookie.clone());
1297
        async move {
1298
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1299
            if body.is_some() {
1300
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1301
            }
1302
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1303
            let st = res.status();
1304
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1305
        }
1306
    };
1307
    let csrf_of = |page: &str| {
1308
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1309
        page[i..].split('"').next().unwrap().to_string()
1310
    };
1311
    let (st, page) = web("GET", "/admin/runners".into(), None).await;
1312
    assert_eq!(st, StatusCode::OK);
1313
    assert!(page.contains("No runners yet"));
1314
    assert_eq!(call(&h.app, "GET", "/admin/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1315
1316
    // A one-time registration token, shown once with the command.
1317
    let (_, page) = web("POST", "/admin/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1318
    let i = page.find("--token ").unwrap() + "--token ".len();
1319
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1320
    assert!(token.starts_with("flowreg_"), "{token}");
1321
1322
    // The runner registers, binding its key; the token then is spent.
1323
    let sk = SecretKey::generate();
1324
    let identity = sk.identity("plex (OxygenFlow runner)", "", 1);
1325
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": ["big-disk"], "max_jobs": 2, "memory_mib": 16384, "cpus": 4 });
1326
    let reg = serde_json::json!({ "token": token, "name": "plex", "identity": hex::encode(identity.encode()), "info": info });
1327
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1328
    assert_eq!(st, StatusCode::OK, "{body}");
1329
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1330
    assert!(credential.starts_with("flowrunner_"));
1331
    assert_eq!(
1332
        call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0,
1333
        StatusCode::FORBIDDEN,
1334
        "used once"
1335
    );
1336
1337
    // It claims with its credential; the hub.toml runner shows too.
1338
    let claim_as = |who: String| {
1339
        let app = h.app.clone();
1340
        let info = info.clone();
1341
        async move {
1342
            let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
1343
            call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await
1344
        }
1345
    };
1346
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "nothing queued");
1347
    assert_eq!(claim(&h.app).await, None);
1348
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1349
    assert!(
1350
        page.contains(">plex</strong>") && page.contains("st-online") && page.contains("x86_64 · linux") && page.contains("big-disk"),
1351
        "{page}"
1352
    );
1353
    assert!(page.contains(">test-1</strong>") && page.contains("hub.toml"), "the configured runner, by its claimed name");
1354
    let plex = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1355
    assert_eq!(plex.key, identity.hash().to_hex(), "bound at registration");
1356
1357
    // A run: plex takes a job, and its history shows it.
1358
    let url = format!("{}/andy/demo", h.base);
1359
    let work = tempfile::tempdir().unwrap();
1360
    let c = client(&url, work.path());
1361
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1362
    c.snapshot("test").unwrap();
1363
    c.commit("Add a pipeline", &[]).unwrap();
1364
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1365
    runs_of(&h.app, "andy", "demo").await;
1366
    let (st, body) = claim_as(credential.clone()).await;
1367
    assert_eq!(st, StatusCode::OK, "{body}");
1368
    let job: serde_json::Value = serde_json::from_str(&body).unwrap();
1369
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1370
    assert!(
1371
        page.contains("andy/demo") && page.contains(job["job"]["name"].as_str().unwrap()) && page.contains("Running now</dt><dd>1 job"),
1372
        "{page}"
1373
    );
1374
    // The queue on Admin → Runners and through the API (#41, part 4).
1375
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1376
    assert!(page.contains("id=\"queue\"") && page.contains(">plex</a></td>"), "{page}");
1377
    // Connectivity and what it is doing, kept apart (#243); its status
1378
    // opens the queue filtered to it, and the filters keep and drop jobs.
1379
    assert!(page.contains("running 1 of ") && page.contains("/admin/runners?runner=plex#queue"), "{page}");
1380
    let (_, only) = web("GET", "/admin/runners?runner=plex".into(), None).await;
1381
    assert!(only.contains(">plex</a></td>") && only.contains(" of ") && only.contains(">all</a>"), "{only}");
1382
    let (_, none) = web("GET", "/admin/runners?runner=nobody&status=running".into(), None).await;
1383
    assert!(none.contains("Nothing matches."), "{none}");
1384
    // A busy runner claims nothing; its heartbeat keeps it online.
1385
    sqlx::query("UPDATE flow_runners SET last_seen_ms = 0 WHERE id = $1").bind(plex.id).execute(&h.app.db).await.unwrap();
1386
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1387
    assert!(page.contains("st-offline"), "quiet for long: offline");
1388
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/heartbeat", Some(&credential), None).await.0, StatusCode::NO_CONTENT);
1389
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/heartbeat", Some("flowrunner_nope"), None).await.0, StatusCode::UNAUTHORIZED);
1390
    let plex_now = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1391
    assert_eq!(plex_now.connectivity(), "online");
1392
    let (_, tokens) = web("GET", "/settings/tokens".into(), None).await;
1393
    let (_, made) = web("POST", "/settings/tokens".into(), Some(format!("_csrf={}&name=admin&scopes=user%3Aread", csrf_of(&tokens)))).await;
1394
    let i = made.find("oxyhub_").unwrap();
1395
    let admin_token: String = made[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
1396
    let (st, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1397
    assert_eq!(st, StatusCode::OK, "{body}");
1398
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1399
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1400
    assert_eq!((plex_row["running"].as_i64(), plex_row["arch"].as_str()), (Some(1), Some("x86_64")));
1401
    // A runner's own labels and time limit from its page (#98).
1402
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1403
    let (st, _) = web(
1404
        "POST",
1405
        format!("/admin/runners/{}/limits", plex.id),
1406
        Some(format!("_csrf={}&labels=gpu%2C+plex&timeout_minutes=5", csrf_of(&page))),
1407
    )
1408
    .await;
1409
    assert_eq!(st, StatusCode::SEE_OTHER);
1410
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1411
    assert!(page.contains(">gpu<") && page.contains("5 min for its jobs"), "{page}");
1412
    let (_, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1413
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1414
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1415
    assert!(plex_row["labels"].as_array().unwrap().iter().any(|l| l == "gpu"), "{plex_row}");
1416
    let (st, _) = web(
1417
        "POST",
1418
        format!("/admin/runners/{}/limits", plex.id),
1419
        Some(format!("_csrf={}&labels=bad%20label%21&timeout_minutes=", csrf_of(&page))),
1420
    )
1421
    .await;
1422
    assert_eq!(st, StatusCode::BAD_REQUEST, "a label with a space or punctuation is refused");
1423
    let (_, body) = call(&h.app, "GET", "/api/v1/runners/queue", Some(&admin_token), None).await;
1424
    let queue: serde_json::Value = serde_json::from_str(&body).unwrap();
1425
    assert!(queue.as_array().unwrap().iter().any(|q| q["status"] == "running" && q["runner"] == "plex"), "{queue}");
1426
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/runners/{}/jobs", plex.id), Some(&admin_token), None).await;
1427
    let jobs: serde_json::Value = serde_json::from_str(&body).unwrap();
1428
    assert_eq!(jobs[0]["repo"], "andy/demo", "{jobs}");
1429
    assert_eq!(call(&h.app, "GET", "/api/v1/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1430
1431
    // Draining: no new work; removing while busy is refused.
1432
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1433
    let csrf = csrf_of(&page);
1434
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=draining"))).await;
1435
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "a draining runner takes nothing");
1436
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1437
    assert!(page.contains("is running jobs: drain it first"), "{page}");
1438
    // Its job finishes; disabled, it is refused; removed, its credential is dead.
1439
    let id = job["job_id"].as_i64().unwrap();
1440
    let done = call(
1441
        &h.app,
1442
        "POST",
1443
        &format!("/api/v1/flow/jobs/{id}/finish"),
1444
        Some(&credential),
1445
        Some(r#"{"exit_code":0,"duration_ms":5}"#.into()),
1446
    )
1447
    .await;
1448
    assert_eq!(done.0, StatusCode::NO_CONTENT);
1449
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=disabled"))).await;
1450
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::FORBIDDEN);
1451
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1452
    assert!(page.contains("Removed plex."), "{page}");
1453
    assert_eq!(claim_as(credential).await.0, StatusCode::UNAUTHORIZED);
1454
}
1455
1456
/// Runner scopes (oxygenhub#41): a runner registered for one repository, or
1457
/// one owner, takes only those jobs; a site runner takes any.
1458
#[tokio::test(flavor = "multi_thread")]
1459
async fn scoped_runners_take_only_their_scope() {
1460
    use oxy_core::identity::SecretKey;
1461
    let h = hub().await;
1462
    create(&h.app, "andy", "demo").await;
1463
    create(&h.app, "andy", "other").await;
1464
    let register = |scope: db::runners::Scope, name: &'static str| {
1465
        let app = h.app.clone();
1466
        async move {
1467
            let token = format!("flowreg_{name}");
1468
            db::runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &scope).await.unwrap();
1469
            let identity = SecretKey::generate().identity(name, "", 1);
1470
            let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1471
            let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
1472
            let (st, body) = call(&app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1473
            assert_eq!(st, StatusCode::OK, "{body}");
1474
            serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string()
1475
        }
1476
    };
1477
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1478
    let only_demo = register(db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) }, "demo-runner").await;
1479
    let carols = register(db::runners::Scope { owner: "carol".into(), repo_id: None }, "carol-runner").await;
1480
    let andys = register(db::runners::Scope { owner: "andy".into(), repo_id: None }, "andy-runner").await;
1481
    let claim_as = |who: String| {
1482
        let app = h.app.clone();
1483
        async move {
1484
            let body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"] }).to_string();
1485
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await;
1486
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["repo"].as_str().unwrap().to_string())
1487
        }
1488
    };
1489
    // Jobs queued in andy/other only.
1490
    let work = tempfile::tempdir().unwrap();
1491
    let c = client(&format!("{}/andy/other", h.base), work.path());
1492
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1493
    c.snapshot("t").unwrap();
1494
    c.commit("pipeline", &[]).unwrap();
1495
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1496
    assert!(!runs_of(&h.app, "andy", "other").await.is_empty());
1497
    assert_eq!(claim_as(only_demo.clone()).await, None, "nothing of andy/demo is queued");
1498
    assert_eq!(claim_as(carols).await, None, "nothing of carol's");
1499
    assert_eq!(claim_as(andys).await.as_deref(), Some("andy/other"), "the owner's runner takes its repositories' jobs");
1500
    // The site runner (hub.toml) takes any.
1501
    assert_eq!(claim(&h.app).await.unwrap()["repo"], "andy/other");
1502
    assert_eq!(claim_as(only_demo).await, None, "still nothing of its own");
1503
}
1504
1505
/// Settings → Runners (oxygenhub#41, part 2b): a repository's admin adds a
1506
/// runner for that repository alone, sees which runners serve it, and
1507
/// removes only its own.
1508
#[tokio::test(flavor = "multi_thread")]
1509
async fn repository_admins_add_and_remove_their_own_runners() {
1510
    use oxy_core::identity::SecretKey;
1511
    let h = hub().await;
1512
    let res = oxygenhub::router(h.app.clone())
1513
        .oneshot(
1514
            Request::post("/register")
1515
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1516
                .body(Body::from("username=andy&email=andy%40example.com&password=correct-horse-battery&setup=test-setup"))
1517
                .unwrap(),
1518
        )
1519
        .await
1520
        .unwrap();
1521
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1522
    create(&h.app, "andy", "demo").await;
1523
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1524
    let web = |method: &'static str, path: String, body: Option<String>| {
1525
        let (app, cookie) = (h.app.clone(), cookie.clone());
1526
        async move {
1527
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1528
            if body.is_some() {
1529
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1530
            }
1531
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1532
            let st = res.status();
1533
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1534
        }
1535
    };
1536
    let csrf_of = |page: &str| {
1537
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1538
        page[i..].split('"').next().unwrap().to_string()
1539
    };
1540
    let (st, page) = web("GET", "/andy/demo/settings".into(), None).await;
1541
    assert_eq!(st, StatusCode::OK);
1542
    assert!(page.contains("<h2>Runners</h2>"), "the owner sees the section");
1543
    let (_, page) = web("POST", "/andy/demo/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1544
    let i = page.find("--token ").unwrap() + "--token ".len();
1545
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1546
    let identity = SecretKey::generate().identity("mine", "", 1);
1547
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1548
    let reg = serde_json::json!({ "token": token, "name": "mine", "identity": hex::encode(identity.encode()), "info": info });
1549
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1550
    assert_eq!(st, StatusCode::OK, "{body}");
1551
    let mine = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "mine").unwrap();
1552
    assert_eq!(mine.scope(), db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) });
1553
    // The site's runner (hub.toml, from its first claim) serves it too, but is not the owner's to remove.
1554
    claim(&h.app).await;
1555
    let site = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "test-1").unwrap();
1556
    let (_, page) = web("GET", "/andy/demo/settings".into(), None).await;
1557
    assert!(page.contains("<strong>mine</strong>") && page.contains("this repository"), "{page}");
1558
    assert!(page.contains("<strong>test-1</strong>") && page.contains("the whole site"), "{page}");
1559
    let csrf = csrf_of(&page);
1560
    let (st, _) = web("POST", format!("/andy/demo/settings/runners/{}/remove", site.id), Some(format!("_csrf={csrf}"))).await;
1561
    assert_eq!(st, StatusCode::NOT_FOUND, "not the repository's own");
1562
    let (_, page) = web("POST", format!("/andy/demo/settings/runners/{}/remove", mine.id), Some(format!("_csrf={csrf}"))).await;
1563
    assert!(page.contains("mine removed"), "{page}");
1564
    assert!(db::runners::get(&h.app.db, mine.id).await.unwrap().is_none());
1565
1566
    // The same for an organisation's owner.
1567
    let (_, page) = web("GET", "/orgs/new".into(), None).await;
1568
    web("POST", "/orgs/new".into(), Some(format!("_csrf={}&name=acme&display_name=Acme", csrf_of(&page)))).await;
1569
    let (st, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1570
    assert_eq!(st, StatusCode::OK);
1571
    let (_, page) = web("POST", "/orgs/acme/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1572
    let i = page.find("--token ").unwrap() + "--token ".len();
1573
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1574
    let identity = SecretKey::generate().identity("acme-runner", "", 1);
1575
    let reg = serde_json::json!({ "token": token, "name": "acme-runner", "identity": hex::encode(identity.encode()), "info": info });
1576
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0, StatusCode::OK);
1577
    let acme = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "acme-runner").unwrap();
1578
    assert_eq!(acme.scope(), db::runners::Scope { owner: "acme".into(), repo_id: None });
1579
    let (_, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1580
    assert!(page.contains("<strong>acme-runner</strong>") && page.contains("the organisation's repositories"), "{page}");
1581
    let (_, page) = web("POST", format!("/orgs/acme/settings/runners/{}/remove", acme.id), Some(format!("_csrf={}", csrf_of(&page)))).await;
1582
    assert!(page.contains("acme-runner removed"), "{page}");
1583
}
1584
1585
/// runs-on (oxygenhub#41, part 3): a job that asks for a label goes only to
1586
/// a runner that has it, and waits for one otherwise.
1587
#[tokio::test(flavor = "multi_thread")]
1588
async fn jobs_that_ask_for_labels_wait_for_a_runner_with_them() {
1589
    use oxy_core::identity::SecretKey;
1590
    let h = hub().await;
1591
    create(&h.app, "andy", "demo").await;
1592
    let work = tempfile::tempdir().unwrap();
1593
    let c = client(&format!("{}/andy/demo", h.base), work.path());
1594
    let cross = "job \"cross\" {\n    sandbox \"alpine\"\n    runs-on \"riscv64\"\n    exec \"true\"\n}\n";
1595
    write(work.path(), ".flow/pipeline.kdl", &pipeline(cross));
1596
    c.snapshot("t").unwrap();
1597
    c.commit("pipeline", &[]).unwrap();
1598
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1599
    assert!(!runs_of(&h.app, "andy", "demo").await.is_empty());
1600
    // The site runner has no labels: it takes the others, never cross.
1601
    let mut taken = Vec::new();
1602
    while let Some(j) = claim(&h.app).await {
1603
        taken.push(j["job"]["name"].as_str().unwrap().to_string());
1604
    }
1605
    assert!(!taken.contains(&"cross".to_string()) && taken.contains(&"lint".to_string()), "{taken:?}");
1606
    let queue = db::flow::queue(&h.app.db).await.unwrap();
1607
    let waiting = queue.iter().find(|q| q.job == "cross").unwrap();
1608
    assert_eq!((waiting.status.as_str(), waiting.needs()), ("queued", vec!["riscv64".to_string()]));
1609
    // A runner registered with the label takes it.
1610
    let token = "flowreg_riscv";
1611
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
1612
    let identity = SecretKey::generate().identity("visionfive", "", 1);
1613
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": ["riscv64"], "max_jobs": 1 });
1614
    let reg = serde_json::json!({ "token": token, "name": "visionfive", "identity": hex::encode(identity.encode()), "info": info });
1615
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1616
    assert_eq!(st, StatusCode::OK, "{body}");
1617
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1618
    let claim_body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"], "info": info }).to_string();
1619
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(claim_body)).await;
1620
    assert_eq!(st, StatusCode::OK, "{body}");
1621
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"], "cross");
1622
}
1623
1624
/// oxygenhub#71: a job its runner stopped reporting (restarted, or lost
1625
/// the hub as the job ended) is ended once it has run past the time limit
1626
/// and a grace: an error with the reason, its dependents skipped and its
1627
/// run settled, as if the runner had reported the error.
1628
#[tokio::test(flavor = "multi_thread")]
1629
async fn a_job_no_runner_reports_is_ended_after_the_time_limit() {
1630
    let h = hub().await;
1631
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1632
    create(&h.app, "andy", "lost").await;
1633
    let url = format!("{}/andy/lost", h.base);
1634
    let work = tempfile::tempdir().unwrap();
1635
    let c = client(&url, work.path());
1636
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1637
    write(work.path(), "test.sh", "echo ok\n");
1638
    c.commit("Add a pipeline", &[]).unwrap();
1639
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1640
    assert_eq!(runs_of(&h.app, "andy", "lost").await.len(), 1);
1641
    let job = claim(&h.app).await.expect("a job to claim");
1642
    let id = job["job_id"].as_i64().unwrap();
1643
1644
    // Running, but well within the limit: left alone.
1645
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 0);
1646
    // Started long ago and never reported: ended.
1647
    let old = db::now_ms() - 24 * 3600 * 1000;
1648
    sqlx::query("UPDATE flow_jobs SET started_ms = $1 WHERE id = $2").bind(old).bind(id).execute(&h.app.db).await.unwrap();
1649
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 1);
1650
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1651
    assert_eq!(j.status, "error");
1652
    assert!(j.error.starts_with("lost:"), "{}", j.error);
1653
    let run = &runs_of(&h.app, "andy", "lost").await[0];
1654
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
1655
    assert!(jobs.iter().all(|j| j.status != "running"), "nothing left running");
1656
    // A late report, should one come, does not overwrite the ending.
1657
    assert_ne!(finish(&h.app, id, serde_json::json!({ "exit_code": 0 })).await, StatusCode::NO_CONTENT);
1658
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "error");
1659
}
1660
1661
/// oxygenhub#73: a runner that lists the images it holds is offered only
1662
/// the jobs whose rootfs is among them; one that does not say gets any.
1663
#[tokio::test(flavor = "multi_thread")]
1664
async fn a_runner_is_offered_only_jobs_whose_image_it_holds() {
1665
    let h = hub().await;
1666
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1667
    create(&h.app, "andy", "images").await;
1668
    let url = format!("{}/andy/images", h.base);
1669
    let work = tempfile::tempdir().unwrap();
1670
    let c = client(&url, work.path());
1671
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1672
    write(work.path(), "test.sh", "echo ok\n");
1673
    c.commit("Add a pipeline", &[]).unwrap();
1674
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1675
    assert_eq!(runs_of(&h.app, "andy", "images").await.len(), 1);
1676
    let claim_with = |images: Vec<String>| {
1677
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "images": images }).to_string();
1678
        let app = h.app.clone();
1679
        async move {
1680
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await;
1681
            (st, body)
1682
        }
1683
    };
1684
    let (st, _) = claim_with(vec!["ab".repeat(32)]).await;
1685
    assert_eq!(st, StatusCode::NO_CONTENT, "no job for a runner without the image");
1686
    let jobs = db::flow::jobs(&h.app.db, runs_of(&h.app, "andy", "images").await[0].id).await.unwrap();
1687
    let rootfs: serde_json::Value = serde_json::from_str(&jobs[0].sandbox).unwrap();
1688
    let rootfs = rootfs["rootfs"].as_str().unwrap().to_string();
1689
    let (st, body) = claim_with(vec!["ab".repeat(32), rootfs]).await;
1690
    assert_eq!(st, StatusCode::OK, "{body}");
1691
}
1692
1693
/// oxygenhub#71: a runner that lists the jobs it holds has the others it
1694
/// was given ended at once (it restarted, or never received them), not at
1695
/// the time limit; a held job is left alone.
1696
#[tokio::test(flavor = "multi_thread")]
1697
async fn a_job_its_runner_no_longer_holds_is_ended_at_its_next_claim() {
1698
    let h = hub().await;
1699
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1700
    create(&h.app, "andy", "held").await;
1701
    let url = format!("{}/andy/held", h.base);
1702
    let work = tempfile::tempdir().unwrap();
1703
    let c = client(&url, work.path());
1704
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1705
    write(work.path(), "test.sh", "echo ok\n");
1706
    c.commit("Add a pipeline", &[]).unwrap();
1707
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1708
    assert_eq!(runs_of(&h.app, "andy", "held").await.len(), 1);
1709
    let id = claim(&h.app).await.expect("a job to claim")["job_id"].as_i64().unwrap();
1710
    let claim_holding = |holding: Vec<i64>| {
1711
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "holding": holding }).to_string();
1712
        let app = h.app.clone();
1713
        async move { call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await.0 }
1714
    };
1715
    claim_holding(vec![id]).await;
1716
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "running", "a held job stays");
1717
    claim_holding(vec![]).await;
1718
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1719
    assert_eq!(j.status, "error");
1720
    assert!(j.error.starts_with("lost:") && j.error.contains("no longer holds"), "{}", j.error);
1721
    let run = &runs_of(&h.app, "andy", "held").await[0];
1722
    assert!(db::flow::jobs(&h.app.db, run.id).await.unwrap().iter().all(|j| j.status != "running"), "the run settles");
1723
}
1724
1725
/// oxygen#59: a job with a `scope` runs on a push only when the push's
1726
/// changes touch a path it names (a release job, when Cargo.toml's version
1727
/// moves); a bookmark's first run and manual runs have every job.
1728
#[tokio::test(flavor = "multi_thread")]
1729
async fn a_scoped_job_runs_only_when_a_push_touches_its_paths() {
1730
    let h = hub().await;
1731
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1732
    create(&h.app, "andy", "scoped").await;
1733
    let url = format!("{}/andy/scoped", h.base);
1734
    let work = tempfile::tempdir().unwrap();
1735
    let c = client(&url, work.path());
1736
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\" \"packaging/**\"\n    exec \"true\"\n}\n";
1737
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1738
    write(work.path(), "test.sh", "echo ok\n");
1739
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1740
    c.commit("Start", &[]).unwrap();
1741
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1742
    let names = |app: Shared, n: usize| async move {
1743
        let mut runs = Vec::new();
1744
        for _ in 0..100 {
1745
            runs = runs_of(&app, "andy", "scoped").await;
1746
            if runs.len() >= n {
1747
                break;
1748
            }
1749
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1750
        }
1751
        assert_eq!(runs.len(), n, "runs");
1752
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1753
        j.sort();
1754
        // Passed, so the next push is scoped against it, not superseding it.
1755
        sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(runs[0].id).execute(&app.db).await.unwrap();
1756
        j
1757
    };
1758
    assert_eq!(names(h.app.clone(), 1).await, ["build", "dist", "lint", "test"], "the first run has every job");
1759
    write(work.path(), "test.sh", "echo still ok\n");
1760
    c.commit("Edit the test", &[]).unwrap();
1761
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1762
    assert_eq!(names(h.app.clone(), 2).await, ["build", "lint", "test"], "dist is out of scope");
1763
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1764
    c.commit("Release 0.1.1", &[]).unwrap();
1765
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1766
    assert_eq!(names(h.app.clone(), 3).await, ["build", "dist", "lint", "test"], "a version bump runs dist");
1767
}
1768
1769
/// oxygenflow#32: a run still going is cancelled from the API, the web or
1770
/// by a newer push to its bookmark; its runner is refused from then on,
1771
/// and the next push is scoped past the cancelled run.
1772
#[tokio::test(flavor = "multi_thread")]
1773
async fn runs_are_cancelled_by_hand_or_by_a_newer_push() {
1774
    let h = hub().await;
1775
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1776
    create(&h.app, "andy", "stop").await;
1777
    let url = format!("{}/andy/stop", h.base);
1778
    let work = tempfile::tempdir().unwrap();
1779
    let c = client(&url, work.path());
1780
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\"\n    exec \"true\"\n}\n";
1781
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1782
    write(work.path(), "test.sh", "echo ok\n");
1783
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1784
    c.commit("Start", &[]).unwrap();
1785
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1786
    let wait_runs = |app: Shared, n: usize| async move {
1787
        for _ in 0..100 {
1788
            let runs = runs_of(&app, "andy", "stop").await;
1789
            if runs.len() >= n {
1790
                return runs;
1791
            }
1792
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1793
        }
1794
        panic!("no run {n}");
1795
    };
1796
    let first = wait_runs(h.app.clone(), 1).await;
1797
    sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(first[0].id).execute(&h.app.db).await.unwrap();
1798
    sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE run_id = $1").bind(first[0].id).execute(&h.app.db).await.unwrap();
1799
1800
    // Run 2 (a version bump) has a job running when run 3 is pushed.
1801
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1802
    c.commit("Release 0.1.1", &[]).unwrap();
1803
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1804
    wait_runs(h.app.clone(), 2).await;
1805
    let job = claim(&h.app).await.expect("a job of run 2");
1806
    let id = job["job_id"].as_i64().unwrap();
1807
    write(work.path(), "test.sh", "echo still ok\n");
1808
    c.commit("Edit the test", &[]).unwrap();
1809
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1810
    let runs = wait_runs(h.app.clone(), 3).await;
1811
    let third = &runs[0];
1812
    let mut second = runs[1].clone();
1813
    for _ in 0..100 {
1814
        second = db::flow::run_by_id(&h.app.db, runs[1].id).await.unwrap().unwrap();
1815
        if !second.live() {
1816
            break;
1817
        }
1818
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1819
    }
1820
    assert_eq!(second.status, "cancelled", "a newer push supersedes a run still going");
1821
    let jobs = db::flow::jobs(&h.app.db, second.id).await.unwrap();
1822
    assert!(jobs.iter().all(|j| j.status == "cancelled" && j.error == "superseded by run #3"), "{jobs:?}");
1823
    let mut names: Vec<String> = db::flow::jobs(&h.app.db, third.id).await.unwrap().into_iter().map(|j| j.name).collect();
1824
    names.sort();
1825
    assert_eq!(names, ["build", "dist", "lint", "test"], "run 3 also checks what run 2 would have: the version bump");
1826
    let mut checks = vec![];
1827
    for _ in 0..100 {
1828
        checks = db::hooks::checks_for_state(&h.app.db, second.repo_id, &second.state).await.unwrap();
1829
        if checks.iter().all(|c| c.status == "cancelled") {
1830
            break;
1831
        }
1832
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1833
    }
1834
    assert!(checks.iter().all(|c| c.status == "cancelled"), "{checks:?}");
1835
    // The runner of the cancelled job is refused, so it stops the job.
1836
    let (st, _) =
1837
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(r#"{"records":[]}"#.into())).await;
1838
    assert_eq!(st, StatusCode::CONFLICT);
1839
1840
    // By hand: the API, then a run already ended is refused.
1841
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
1842
    assert_eq!(st, StatusCode::OK, "{body}");
1843
    let third = db::flow::run_by_id(&h.app.db, third.id).await.unwrap().unwrap();
1844
    assert_eq!(third.status, "cancelled");
1845
    assert!(db::flow::jobs(&h.app.db, third.id).await.unwrap().iter().all(|j| j.error == "cancelled by andy"));
1846
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
1847
    assert!(st == StatusCode::CONFLICT && body.contains("already cancelled"), "{st} {body}");
1848
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", None, None).await;
1849
    assert_ne!(st, StatusCode::OK, "anonymous callers cannot cancel");
1850
    let (_, page) = call(&h.app, "GET", "/andy/stop/flow/3", None, None).await;
1851
    assert!(page.contains("⊘") && !page.contains("CANCEL</button>"), "a cancelled run shows so, with no button");
1852
}
1853
1854
/// oxygenflow#23 and oxygenhub#89: a job runs under its pipeline's
1855
/// timeout, capped at the site's maximum, else the site's default; and the
1856
/// hub gives a job up only past its own limit.
1857
#[tokio::test(flavor = "multi_thread")]
1858
async fn a_job_runs_under_its_own_time_limit_within_the_sites() {
1859
    let h = hub().await;
1860
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1861
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_DEFAULT, "30").await.unwrap();
1862
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_MAX, "120").await.unwrap();
1863
    create(&h.app, "andy", "limits").await;
1864
    let url = format!("{}/andy/limits", h.base);
1865
    let work = tempfile::tempdir().unwrap();
1866
    let c = client(&url, work.path());
1867
    let extra = "job \"slow\" {\n    sandbox \"alpine\"\n    timeout \"90m\"\n    exec \"true\"\n}\njob \"huge\" {\n    sandbox \"alpine\"\n    timeout \"5h\"\n    exec \"true\"\n}\n";
1868
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1869
    write(work.path(), "test.sh", "echo ok\n");
1870
    c.commit("Add a pipeline", &[]).unwrap();
1871
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1872
    assert_eq!(runs_of(&h.app, "andy", "limits").await.len(), 1);
1873
    let mut limits = std::collections::HashMap::new();
1874
    let mut ids = std::collections::HashMap::new();
1875
    while let Some(j) = claim(&h.app).await {
1876
        let name = j["job"]["name"].as_str().unwrap().to_string();
1877
        limits.insert(name.clone(), j["timeout_s"].as_u64().unwrap());
1878
        ids.insert(name, j["job_id"].as_i64().unwrap());
1879
    }
1880
    assert_eq!(limits["slow"], 5400, "its own");
1881
    assert_eq!(limits["huge"], 7200, "cut to the site's maximum");
1882
    assert_eq!(limits["build"], 1800, "the site's default");
1883
    // 40 minutes in: past the default and its grace, within slow's limit.
1884
    let started = db::now_ms() - 40 * 60 * 1000;
1885
    sqlx::query("UPDATE flow_jobs SET started_ms = $1").bind(started).execute(&h.app.db).await.unwrap();
1886
    oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap();
1887
    let status = |id: i64| {
1888
        let app = h.app.clone();
1889
        async move { db::flow::job(&app.db, id).await.unwrap().unwrap().status }
1890
    };
1891
    assert_eq!(status(ids["build"]).await, "error", "past its 30 minutes");
1892
    assert_eq!(status(ids["slow"]).await, "running", "within its 90");
1893
    assert_eq!(status(ids["huge"]).await, "running", "within its 120");
1894
}
1895
1896
/// oxygenflow#24: a job's `on` decides which events start it: a pushed
1897
/// tag runs only the jobs that name it; a push to a bookmark the pipeline
1898
/// does not name starts no run; a rerun repeats its run's event.
1899
#[tokio::test(flavor = "multi_thread")]
1900
async fn on_decides_which_events_start_a_job() {
1901
    let h = hub().await;
1902
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1903
    create(&h.app, "andy", "events").await;
1904
    let url = format!("{}/andy/events", h.base);
1905
    let work = tempfile::tempdir().unwrap();
1906
    let c = client(&url, work.path());
1907
    let text = format!(
1908
        "on {{\n    push \"main\"\n    manual\n}}\n{}job \"dist\" {{\n    sandbox \"alpine\"\n    on {{\n        tag \"v*\"\n    }}\n    exec \"true\"\n}}\n",
1909
        pipeline("")
1910
    );
1911
    // `on` must come after schema-version; pipeline() starts with it.
1912
    let text = text.replacen(
1913
        "on {\n    push \"main\"\n    manual\n}\nschema-version 1\n",
1914
        "schema-version 1\non {\n    push \"main\"\n    manual\n}\n",
1915
        1,
1916
    );
1917
    write(work.path(), ".flow/pipeline.kdl", &text);
1918
    write(work.path(), "test.sh", "echo ok\n");
1919
    c.commit("Start", &[]).unwrap();
1920
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1921
    let jobs_of_latest = |app: Shared, n: usize| async move {
1922
        let mut runs = Vec::new();
1923
        for _ in 0..100 {
1924
            runs = runs_of(&app, "andy", "events").await;
1925
            if runs.len() >= n {
1926
                break;
1927
            }
1928
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1929
        }
1930
        assert_eq!(runs.len(), n, "runs");
1931
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1932
        j.sort();
1933
        (runs[0].clone(), j)
1934
    };
1935
    let (_, j) = jobs_of_latest(h.app.clone(), 1).await;
1936
    assert_eq!(j, ["build", "lint", "test"], "a push to main: no dist");
1937
    // A tag: only dist.
1938
    let heads = c.bookmark_heads().unwrap();
1939
    c.tag_create("v1.0.0", &heads, "first").unwrap();
1940
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1941
    let (run, j) = jobs_of_latest(h.app.clone(), 2).await;
1942
    assert_eq!(j, ["dist"], "a tag runs only what names it");
1943
    assert_eq!(run.trigger, "tag:v1.0.0");
1944
    // A rerun repeats the tag's event.
1945
    let row = db::repos::get(&h.app.db, "andy", "events").await.unwrap().unwrap();
1946
    db::flow::finish(
1947
        &h.app.db,
1948
        db::flow::jobs(&h.app.db, run.id).await.unwrap()[0].id,
1949
        db::flow::Outcome { status: "passed", exit_code: Some(0), error: "", receipt: "", receipt_hash: "" },
1950
    )
1951
    .await
1952
    .unwrap();
1953
    let run = db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap();
1954
    oxygenhub::flow::rerun(&h.app, &row, &run, "andy").await.unwrap();
1955
    let (_, j) = jobs_of_latest(h.app.clone(), 3).await;
1956
    assert_eq!(j, ["dist"], "the rerun is the tag's run again");
1957
    // A bookmark the pipeline does not name starts nothing.
1958
    c.bookmark_create("develop", None).unwrap();
1959
    assert!(c.push_bookmark("origin", "develop", false).unwrap().iter().all(|r| r.ok));
1960
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1961
    assert_eq!(runs_of(&h.app, "andy", "events").await.len(), 3, "no run for develop");
1962
}
1963
1964
/// oxygenflow#24: a job with a `schedule` line runs on the default
1965
/// bookmark when the line comes due, and only then; other jobs stay out.
1966
#[tokio::test(flavor = "multi_thread")]
1967
async fn scheduled_jobs_run_when_due() {
1968
    let h = hub().await;
1969
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1970
    create(&h.app, "andy", "nightly").await;
1971
    let url = format!("{}/andy/nightly", h.base);
1972
    let work = tempfile::tempdir().unwrap();
1973
    let c = client(&url, work.path());
1974
    // An odd minute, so the hub's own ticker cannot fire it during the test.
1975
    let extra = "job \"nightly\" {\n    sandbox \"alpine\"\n    on {\n        schedule \"17 4 29 2 *\"\n    }\n    exec \"true\"\n}\n";
1976
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1977
    write(work.path(), "test.sh", "echo ok\n");
1978
    c.commit("Start", &[]).unwrap();
1979
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1980
    assert_eq!(runs_of(&h.app, "andy", "nightly").await.len(), 1);
1981
    let first = runs_of(&h.app, "andy", "nightly").await;
1982
    let names: Vec<String> = db::flow::jobs(&h.app.db, first[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1983
    assert!(!names.contains(&"nightly".to_string()), "a push does not run a scheduled job");
1984
    use flow_core::pipeline::When;
1985
    let not_yet = When { minute: 16, hour: 4, day: 29, month: 2, weekday: 4 };
1986
    assert_eq!(oxygenhub::flow::run_due(&h.app, not_yet).await, 0);
1987
    let due = When { minute: 17, ..not_yet };
1988
    assert_eq!(oxygenhub::flow::run_due(&h.app, due).await, 1);
1989
    let runs = runs_of(&h.app, "andy", "nightly").await;
1990
    assert_eq!(runs.len(), 2);
1991
    assert_eq!(runs[0].trigger, "schedule");
1992
    let names: Vec<String> = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1993
    assert_eq!(names, ["nightly"]);
1994
    assert_eq!(runs[0].bookmark, "main", "on the default bookmark");
1995
}
1996
1997
#[tokio::test(flavor = "multi_thread")]
1998
async fn variables_from_three_levels_reach_a_job_inner_overriding_outer() {
1999
    use oxygenhub::levels::Scope;
2000
    use oxygenhub::variables;
2001
    let h = hub().await;
2002
    let app = &h.app;
2003
    // Andy, the site's administrator, owns the acme organisation.
2004
    let res = oxygenhub::router(app.clone())
2005
        .oneshot(
2006
            Request::post("/register")
2007
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
2008
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
2009
                .unwrap(),
2010
        )
2011
        .await
2012
        .unwrap();
2013
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
2014
    let andy = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
2015
    db::accounts::create_org(&app.db, "acme", "Acme", andy.id).await.unwrap();
2016
    create(app, "acme", "app").await;
2017
    let page = |path: &str, form: Option<String>| {
2018
        let mut req =
2019
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2020
        if form.is_some() {
2021
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2022
        }
2023
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
2024
        let app = app.clone();
2025
        async move {
2026
            let res = oxygenhub::router(app).oneshot(req).await.unwrap();
2027
            let status = res.status();
2028
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2029
            (status, body)
2030
        }
2031
    };
2032
    let csrf_of = |page: &str| {
2033
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2034
        page[i..].split('"').next().unwrap().to_string()
2035
    };
2036
2037
    // The site sets CC and LANG, the organisation its own CC, the
2038
    // repository RUST_LOG from its settings page.
2039
    variables::set(&app.db, Scope::Site, "CC", "gcc").await.unwrap();
2040
    variables::set(&app.db, Scope::Site, "LANG", "C").await.unwrap();
2041
    let org = db::accounts::org_by_name(&app.db, "acme").await.unwrap().unwrap();
2042
    variables::set(&app.db, Scope::Org(org.id), "CC", "clang").await.unwrap();
2043
    let (st, settings) = page("/acme/app/settings", None).await;
2044
    assert_eq!(st, StatusCode::OK, "{settings}");
2045
    assert!(settings.contains("Inherited") && settings.contains("the acme organisation") && settings.contains("overridden"), "{settings}");
2046
    let csrf = csrf_of(&settings);
2047
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=RUST_LOG&value=debug"))).await;
2048
    assert!(body.contains("RUST_LOG set.") && body.contains("<code>debug</code>"), "{body}");
2049
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=FLOW_REPO&value=x"))).await;
2050
    assert!(body.contains("not FLOW_"), "{body}");
2051
    let repo = db::repos::get(&app.db, "acme", "app").await.unwrap().unwrap();
2052
    db::repos::set_flow(&app.db, repo.id, "on").await.unwrap();
2053
    let env = variables::env_for_repo(&app.db, &repo).await.unwrap();
2054
    assert_eq!(
2055
        env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect::<Vec<_>>(),
2056
        [("CC", "clang"), ("LANG", "C"), ("RUST_LOG", "debug")],
2057
        "the organisation's CC wins over the site's"
2058
    );
2059
2060
    // A claim carries them.
2061
    let url = format!("{}/acme/app", h.base);
2062
    let work = tempfile::tempdir().unwrap();
2063
    let c = client(&url, work.path());
2064
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2065
    write(work.path(), "test.sh", "echo ok\n");
2066
    c.snapshot("test").unwrap();
2067
    c.commit("Add a pipeline", &[]).unwrap();
2068
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2069
    let runs = runs_of(app, "acme", "app").await;
2070
    assert_eq!(runs.len(), 1, "{runs:?}");
2071
    let got = claim(app).await.unwrap_or_else(|| panic!("a job: {:?}", runs[0]));
2072
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "LANG": "C", "RUST_LOG": "debug" }), "{got}");
2073
2074
    // Removing a site variable from the admin page takes effect at the next claim.
2075
    let (_, admin) = page("/admin", None).await;
2076
    assert!(admin.contains("Variables") && admin.contains("<code>gcc</code>"), "{admin}");
2077
    let (_, body) = page("/admin/variables", Some(format!("_csrf={}&action=delete&name=LANG", csrf_of(&admin)))).await;
2078
    assert!(body.contains("LANG removed."), "{body}");
2079
    let got = claim(app).await.expect("another job");
2080
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "RUST_LOG": "debug" }), "{got}");
2081
}
2082
2083
#[tokio::test(flavor = "multi_thread")]
2084
async fn secrets_a_job_declares_come_with_the_claim_and_never_reach_the_log() {
2085
    let h = hub().await;
2086
    let app = &h.app;
2087
    let res = oxygenhub::router(app.clone())
2088
        .oneshot(
2089
            Request::post("/register")
2090
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
2091
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
2092
                .unwrap(),
2093
        )
2094
        .await
2095
        .unwrap();
2096
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
2097
    let page = |path: &str, form: Option<String>| {
2098
        let mut req =
2099
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2100
        if form.is_some() {
2101
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2102
        }
2103
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
2104
        let app = app.clone();
2105
        async move {
2106
            let res = oxygenhub::router(app).oneshot(req).await.unwrap();
2107
            let status = res.status();
2108
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2109
            (status, body)
2110
        }
2111
    };
2112
    let csrf_of = |page: &str| {
2113
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2114
        page[i..].split('"').next().unwrap().to_string()
2115
    };
2116
    create(app, "andy", "demo").await;
2117
    // The site sets deploy-token; the repository overrides it. Neither
2118
    // page shows a value, only that it is set.
2119
    let (_, admin) = page("/admin", None).await;
2120
    let csrf = csrf_of(&admin);
2121
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=deploy-token&value=site-level-value"))).await;
2122
    assert!(body.contains("deploy-token set.") && !body.contains("site-level-value"), "{body}");
2123
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=bad+name&value=x"))).await;
2124
    assert!(body.contains("name is 1 to 64 of"), "{body}");
2125
    let (_, settings) = page("/andy/demo/settings", None).await;
2126
    assert!(
2127
        settings.contains("Secrets") && settings.contains("<code>deploy-token</code>") && settings.contains("the site</td>"),
2128
        "{settings}"
2129
    );
2130
    let csrf_r = csrf_of(&settings);
2131
    let (_, body) =
2132
        page("/andy/demo/settings/secrets", Some(format!("_csrf={csrf_r}&action=set&name=deploy-token&value=hunter22-repo-value"))).await;
2133
    assert!(body.contains("deploy-token set.") && body.contains("overridden") && !body.contains("hunter22"), "{body}");
2134
    let repo = db::repos::get(&app.db, "andy", "demo").await.unwrap().unwrap();
2135
    assert!(
2136
        !String::from_utf8_lossy(&oxygenhub::secrets::list(&app.db, oxygenhub::levels::Scope::Repo(repo.id)).await.unwrap()[0].value)
2137
            .contains("hunter22"),
2138
        "sealed at rest"
2139
    );
2140
2141
    // A job that declares the secret, and one the levels do not hold.
2142
    let url = format!("{}/andy/demo", h.base);
2143
    let work = tempfile::tempdir().unwrap();
2144
    let c = client(&url, work.path());
2145
    write(
2146
        work.path(),
2147
        ".flow/pipeline.kdl",
2148
        &pipeline("job \"deploy\" {\n    sandbox \"alpine\"\n    secret \"deploy-token\" {\n        mount-path \"/run/secrets/token\"\n    }\n    secret \"missing\" {\n        mount-path \"/run/secrets/missing\"\n    }\n    exec \"deploy\"\n}\n"),
2149
    );
2150
    write(work.path(), "test.sh", "echo ok\n");
2151
    c.snapshot("test").unwrap();
2152
    c.commit("Add a pipeline", &[]).unwrap();
2153
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2154
    let runs = runs_of(app, "andy", "demo").await;
2155
    let jobs = match runs.first() {
2156
        Some(r) => db::flow::jobs(&app.db, r.id).await.unwrap().iter().map(|j| format!("{}:{}", j.name, j.status)).collect::<Vec<_>>(),
2157
        None => vec![],
2158
    };
2159
    let mut deploy = None;
2160
    for _ in 0..50 {
2161
        let Some(got) = claim(app).await else {
2162
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2163
            continue;
2164
        };
2165
        if got["job"]["name"] == "deploy" {
2166
            deploy = Some(got);
2167
            break;
2168
        }
2169
        assert_eq!(got["secrets"], serde_json::Value::Null, "{got}");
2170
    }
2171
    let got = deploy.unwrap_or_else(|| panic!("the deploy job: runs {runs:?} jobs {jobs:?}"));
2172
    assert_eq!(
2173
        got["secrets"],
2174
        serde_json::json!([{ "name": "deploy-token", "path": "/run/secrets/token", "value": "hunter22-repo-value" }]),
2175
        "the repository's value, the missing one left out: {got}"
2176
    );
2177
    let id = got["job_id"].as_i64().unwrap();
2178
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2179
    assert!(log.iter().any(|l| l.stream == "flow" && l.text.contains("secret \"missing\" is not set")), "{log:?}");
2180
2181
    // The value never reaches the stored log, plain or base64.
2182
    let records = serde_json::json!({ "records": [
2183
        { "t": 1, "stream": "out", "text": "token=hunter22-repo-value" },
2184
        { "t": 2, "stream": "err", "text": "b64 aHVudGVyMjItcmVwby12YWx1ZQ== end" },
2185
    ] });
2186
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2187
    assert_eq!(st, StatusCode::NO_CONTENT);
2188
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2189
    let texts: Vec<&str> = log.iter().map(|l| l.text.as_str()).collect();
2190
    assert!(texts.contains(&"token=***") && texts.contains(&"b64 *** end"), "{texts:?}");
2191
    assert!(!texts.iter().any(|t| t.contains("hunter22")), "{texts:?}");
2192
}
2193
2194
#[tokio::test(flavor = "multi_thread")]
2195
async fn a_job_s_identity_is_a_signed_token_the_discovery_document_lets_anyone_verify() {
2196
    let h = hub().await;
2197
    let app = &h.app;
2198
    let (st, disc) = call(app, "GET", "/.well-known/openid-configuration", None, None).await;
2199
    assert_eq!(st, StatusCode::OK, "{disc}");
2200
    let disc: serde_json::Value = serde_json::from_str(&disc).unwrap();
2201
    assert_eq!(disc["issuer"], h.base.as_str());
2202
    assert_eq!(disc["jwks_uri"], format!("{}/.well-known/jwks.json", h.base));
2203
    let (st, jwks) = call(app, "GET", "/.well-known/jwks.json", None, None).await;
2204
    assert_eq!(st, StatusCode::OK, "{jwks}");
2205
    let jwks: serde_json::Value = serde_json::from_str(&jwks).unwrap();
2206
    assert_eq!(jwks["keys"][0]["alg"], "RS256");
2207
    let kid = jwks["keys"][0]["kid"].as_str().unwrap().to_string();
2208
2209
    create(app, "andy", "demo").await;
2210
    let url = format!("{}/andy/demo", h.base);
2211
    let work = tempfile::tempdir().unwrap();
2212
    let c = client(&url, work.path());
2213
    write(
2214
        work.path(),
2215
        ".flow/pipeline.kdl",
2216
        &pipeline("job \"deploy\" {\n    sandbox \"alpine\"\n    identity \"sts.amazonaws.com\" {\n        mount-path \"/run/secrets/aws-token\"\n    }\n    exec \"deploy\"\n}\n"),
2217
    );
2218
    write(work.path(), "test.sh", "echo ok\n");
2219
    c.snapshot("test").unwrap();
2220
    c.commit("Add a pipeline", &[]).unwrap();
2221
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2222
    let mut deploy = None;
2223
    for _ in 0..50 {
2224
        let Some(got) = claim(app).await else {
2225
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2226
            continue;
2227
        };
2228
        if got["job"]["name"] == "deploy" {
2229
            deploy = Some(got);
2230
            break;
2231
        }
2232
    }
2233
    let got = deploy.expect("the deploy job");
2234
    let secrets = got["secrets"].as_array().expect("secrets");
2235
    assert_eq!(secrets.len(), 1);
2236
    assert_eq!(
2237
        (secrets[0]["name"].as_str(), secrets[0]["path"].as_str()),
2238
        (Some("identity:sts.amazonaws.com"), Some("/run/secrets/aws-token"))
2239
    );
2240
    let token = secrets[0]["value"].as_str().unwrap().to_string();
2241
    let issuer = app.oidc().await.unwrap();
2242
    assert_eq!(issuer.kid, kid, "the key the JWKS publishes signed it");
2243
    let claims = issuer.verify(&token, "sts.amazonaws.com", db::now_ms()).expect("verifies");
2244
    assert_eq!(claims["sub"], "repo:andy/demo:bookmark:main");
2245
    assert_eq!(claims["repository"], "andy/demo");
2246
    assert_eq!(claims["job"], "deploy");
2247
    assert_eq!(claims["run_number"], 1);
2248
    assert_eq!(claims["runner"], "test-1");
2249
    assert_eq!(claims["iss"], h.base.as_str());
2250
    assert!(claims["state"].as_str().unwrap().len() == 64);
2251
    // A job that prints its token leaves *** in the log.
2252
    let id = got["job_id"].as_i64().unwrap();
2253
    let records = serde_json::json!({ "records": [{ "t": 1, "stream": "out", "text": format!("TOKEN={token} end") }] });
2254
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2255
    assert_eq!(st, StatusCode::NO_CONTENT);
2256
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2257
    assert!(log.iter().any(|l| l.text == "TOKEN=*** end"), "{log:?}");
2258
}
2259
2260
#[tokio::test(flavor = "multi_thread")]
2261
async fn jobs_are_offered_only_to_runners_of_their_architecture() {
2262
    let h = hub().await;
2263
    let app = &h.app;
2264
    create(app, "andy", "demo").await;
2265
    let url = format!("{}/andy/demo", h.base);
2266
    let work = tempfile::tempdir().unwrap();
2267
    let c = client(&url, work.path());
2268
    write(work.path(), ".flow/pipeline.kdl", &pipeline("sandbox \"board\" {\n    rootfs \"cas://blob/{ROOTFS}\"\n    arch \"riscv64\"\n}\njob \"flash\" {\n    sandbox \"board\"\n    exec \"flash\"\n}\n").replace("{ROOTFS}", &"ab".repeat(32)));
2269
    write(work.path(), "test.sh", "echo ok\n");
2270
    c.snapshot("test").unwrap();
2271
    c.commit("Add a pipeline", &[]).unwrap();
2272
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2273
    let claim_as = |arch: &'static str, archs: serde_json::Value| {
2274
        let app = app.clone();
2275
        async move {
2276
            let body = serde_json::json!({
2277
                "runner": format!("{arch}-1"), "runtimes": ["microvm"],
2278
                "info": { "arch": arch, "os": "linux", "version": "t", "labels": [], "max_jobs": 1 },
2279
                "image_archs": archs,
2280
            });
2281
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
2282
            match st {
2283
                StatusCode::NO_CONTENT => None,
2284
                StatusCode::OK => {
2285
                    Some(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"].as_str().unwrap().to_string())
2286
                }
2287
                other => panic!("claim: {other} {body}"),
2288
            }
2289
        }
2290
    };
2291
    // An x86_64 runner that says the alpine image is x86_64: it takes the
2292
    // alpine jobs, never the one that asks for riscv64.
2293
    let rootfs = pipeline("").split("cas://blob/").nth(1).unwrap()[..64].to_string();
2294
    for _ in 0..50 {
2295
        if !runs_of(app, "andy", "demo").await.is_empty() {
2296
            break;
2297
        }
2298
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2299
    }
2300
    let runs = runs_of(app, "andy", "demo").await;
2301
    assert_eq!(runs.len(), 1, "{runs:?}");
2302
    let mut taken = vec![];
2303
    while let Some(j) = claim_as("x86_64", serde_json::json!({ rootfs.clone(): "x86_64" })).await {
2304
        taken.push(j);
2305
    }
2306
    assert_eq!(taken, ["build", "lint"], "test waits for build; flash is for riscv64");
2307
    // A riscv64 runner: the alpine image is known to be x86_64, so only flash.
2308
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await.as_deref(), Some("flash"));
2309
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await, None);
2310
    let (_, queue) = call(app, "GET", "/admin/runners", None, None).await;
2311
    let _ = queue;
2312
}
2313
2314
/// OxygenFlow spec §11.5: a runner hands back a job it cannot run. The
2315
/// job is queued again and not offered to that runner again, the decline
2316
/// shows on the run's page and is kept for the runner's, and once three
2317
/// runners have declined it the job ends as unplaceable with their reasons.
2318
#[tokio::test(flavor = "multi_thread")]
2319
async fn a_declined_job_goes_to_another_runner_or_ends_unplaceable() {
2320
    let h = hub().await;
2321
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2322
    create(&h.app, "andy", "declines").await;
2323
    let url = format!("{}/andy/declines", h.base);
2324
    let work = tempfile::tempdir().unwrap();
2325
    let c = client(&url, work.path());
2326
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2327
    write(work.path(), "test.sh", "echo ok\n");
2328
    c.commit("Add a pipeline", &[]).unwrap();
2329
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2330
    let run = runs_of(&h.app, "andy", "declines").await[0].clone();
2331
    let claim_as = |token: &'static str, name: &'static str| {
2332
        let app = h.app.clone();
2333
        async move {
2334
            let body = serde_json::json!({ "runner": name, "runtimes": ["microvm"] }).to_string();
2335
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(token), Some(body)).await;
2336
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap())
2337
        }
2338
    };
2339
    let decline = |token: &'static str, id: i64, reason: &'static str| {
2340
        let app = h.app.clone();
2341
        async move {
2342
            let body = serde_json::json!({ "reason": reason }).to_string();
2343
            call(&app, "POST", &format!("/api/v1/flow/jobs/{id}/decline"), Some(token), Some(body)).await.0
2344
        }
2345
    };
2346
    let job = claim_as("runner-secret", "earth-1").await.expect("a job");
2347
    // The other runners are known to the hub before they decline anything.
2348
    assert_eq!(decline("runner-two", job, "not mine").await, StatusCode::CONFLICT, "only the runner it runs on may decline it");
2349
    assert_eq!(decline("runner-secret", job, "the MicroVM tier needs /dev/kvm").await, StatusCode::NO_CONTENT);
2350
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2351
    assert_eq!((j.status.as_str(), j.runner.as_str()), ("queued", ""));
2352
    assert_eq!(j.waiting, "declined by earth-1: the MicroVM tier needs /dev/kvm; waiting for another runner");
2353
    // earth-1 is offered the other ready job, not this one, while it stays the same.
2354
    let next = claim_as("runner-secret", "earth-1").await.expect("the other ready job");
2355
    assert_ne!(next, job);
2356
    let page = call(&h.app, "GET", &format!("/andy/declines/flow/{}", run.number), None, None).await.1;
2357
    assert!(page.contains("Waiting: declined by earth-1: the MicroVM tier needs /dev/kvm"), "{page}");
2358
    assert_eq!(claim_as("runner-two", "plex-1").await, Some(job), "another runner takes it");
2359
    assert_eq!(decline("runner-two", job, "rootfs 36fc4e323804 is not on this runner").await, StatusCode::NO_CONTENT);
2360
    assert_eq!(claim_as("runner-three", "narvi").await, Some(job));
2361
    assert_eq!(decline("runner-three", job, "rootfs 36fc4e323804 is for x86_64; this runner is riscv64").await, StatusCode::NO_CONTENT);
2362
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2363
    assert_eq!(j.status, "error");
2364
    assert_eq!(
2365
        j.error,
2366
        "unplaceable: declined by 3 runners: earth-1: the MicroVM tier needs /dev/kvm; plex-1: rootfs 36fc4e323804 is not on this runner; narvi: rootfs 36fc4e323804 is for x86_64; this runner is riscv64"
2367
    );
2368
    let r = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex-1").unwrap();
2369
    let declined = db::flow::declines_of_runner(&h.app.db, r.id, 10).await.unwrap();
2370
    assert_eq!(declined.len(), 1);
2371
    assert_eq!((declined[0].job_id, declined[0].reason.as_str()), (job, "rootfs 36fc4e323804 is not on this runner"));
2372
    assert_eq!(r.tier_list(), vec!["microvm"]);
2373
}
2374
2375
/// oxygenhub#113: a job's artifact named `coverage` (LCOV) is read when
2376
/// it is uploaded. The job's log says what it found; the Coverage tab,
2377
/// the file view, the badge and the run page show it.
2378
#[tokio::test(flavor = "multi_thread")]
2379
async fn a_coverage_artifact_becomes_a_coverage_report() {
2380
    let h = hub().await;
2381
    create(&h.app, "andy", "cov").await;
2382
    let url = format!("{}/andy/cov", h.base);
2383
    let work = tempfile::tempdir().unwrap();
2384
    let c = client(&url, work.path());
2385
    write(
2386
        work.path(),
2387
        ".flow/pipeline.kdl",
2388
        &format!(
2389
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"coverage\" {{\n    sandbox \"alpine\"\n    exec \"make\" \"coverage\"\n    output {{\n        artifact \"coverage\" {{\n            path \"/src/lcov.info\"\n        }}\n    }}\n}}\n"
2390
        ),
2391
    );
2392
    write(work.path(), "src/lib.rs", "pub fn add(a: u32, b: u32) -> u32 {\n    a + b\n}\n\npub fn unused() {\n    todo!()\n}\n");
2393
    c.snapshot("test").unwrap();
2394
    c.commit("Code and coverage", &[]).unwrap();
2395
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2396
    let run = runs_of(&h.app, "andy", "cov").await.remove(0);
2397
    assert!(!call(&h.app, "GET", "/andy/cov", None, None).await.1.contains(">Reports</a>"), "no tab before a report");
2398
    let id = claim(&h.app).await.unwrap()["job_id"].as_i64().unwrap();
2399
2400
    let (st, text) = upload(&h.app, id, "coverage", b"this is not a report").await;
2401
    assert_eq!(st, StatusCode::OK, "a bad report never fails the upload: {text}");
2402
    let lcov = "TN:\nSF:/src/src/lib.rs\nFN:1,add\nFN:5,unused\nFNDA:3,add\nFNDA:0,unused\nDA:1,3\nDA:2,3\nDA:5,0\nDA:6,0\nend_of_record\n\
2403
SF:/src/src/gone.rs\nDA:1,1\nend_of_record\nSF:/usr/lib/rustlib/x.rs\nDA:1,1\nend_of_record\n";
2404
    let (st, text) = upload(&h.app, id, "coverage", lcov.as_bytes()).await;
2405
    assert_eq!(st, StatusCode::OK, "{text}");
2406
    let log: Vec<String> = db::flow::log(&h.app.db, id, 0, 50).await.unwrap().into_iter().map(|l| l.text).collect();
2407
    assert!(log.iter().any(|l| l.contains("coverage: this is not an LCOV report")), "{log:?}");
2408
    assert!(
2409
        log.iter().any(|l| l == "coverage: 50.0% of lines (2 of 4) in 1 files (2 named files are not in this state and were left out)"),
2410
        "{log:?}"
2411
    );
2412
2413
    let (st, page) = call(&h.app, "GET", "/andy/cov/coverage", None, None).await;
2414
    assert_eq!(st, StatusCode::OK);
2415
    assert!(
2416
        page.contains(">Reports</a>")
2417
            && page.contains("50.0%")
2418
            && page.contains("<strong>2</strong> of <strong>4</strong> relevant lines covered"),
2419
        "{page}"
2420
    );
2421
    assert!(page.contains("1 of 2") && page.contains("/andy/cov/coverage/") && page.contains("/file/src/lib.rs"), "{page}");
2422
    let report = crate_report(&h.app, run.id).await;
2423
    let (st, file) = call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/lib.rs"), None, None).await;
2424
    assert_eq!(st, StatusCode::OK, "{file}");
2425
    assert_eq!(file.matches("class=\"cov-hit\"").count(), 2, "{file}");
2426
    assert_eq!(file.matches("class=\"cov-miss\"").count(), 2, "{file}");
2427
    assert!(file.contains("3×"), "{file}");
2428
    assert_eq!(call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/gone.rs"), None, None).await.0, StatusCode::NOT_FOUND);
2429
    let (_, badge) = call(&h.app, "GET", "/andy/cov/coverage/badge.svg", None, None).await;
2430
    assert!(badge.contains("coverage: 50.0%"), "{badge}");
2431
    let (_, run_page) = call(&h.app, "GET", &format!("/andy/cov/flow/{}", run.number), None, None).await;
2432
    assert!(run_page.contains("coverage 50.0%"), "{run_page}");
2433
    // The API (#113).
2434
    let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/cov/coverage", None, None).await;
2435
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
2436
    assert_eq!((list[0]["percent"].as_f64(), list[0]["format"].as_str()), (Some(50.0), Some("lcov")), "{list}");
2437
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/cov/coverage/{report}"), None, None).await;
2438
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
2439
    assert_eq!((one["files"][0]["path"].as_str(), one["files"][0]["lines_hit"].as_i64()), (Some("src/lib.rs"), Some(2)), "{one}");
2440
2441
    // The `coverage` check on the run's state: it reports, and with a
2442
    // minimum the repository sets, it fails below it.
2443
    let row = db::repos::get(&h.app.db, "andy", "cov").await.unwrap().unwrap();
2444
    let check = |checks: Vec<db::hooks::Check>| checks.into_iter().find(|c| c.name == "coverage").expect("a coverage check");
2445
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
2446
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "50.0%"));
2447
    assert!(c.url.ends_with(&format!("/andy/cov/coverage?report={report}")), "{}", c.url);
2448
    oxygenhub::coverage::set_rules(&h.app.db, row.id, oxygenhub::coverage::Rules { min: Some(60.0), max_drop: None }).await.unwrap();
2449
    assert_eq!(upload(&h.app, id, "coverage", lcov.as_bytes()).await.0, StatusCode::OK);
2450
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
2451
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "50.0%: below the minimum of 60%"));
2452
}
2453
2454
async fn crate_report(app: &Shared, run_id: i64) -> i64 {
2455
    oxygenhub::coverage::for_run(&app.db, run_id).await.unwrap()[0].id
2456
}
2457
2458
/// The Tests tab (#114): three runs' JUnit reports on a bookmark; a test
2459
/// breaks in the second and is fixed in the third.
2460
#[tokio::test(flavor = "multi_thread")]
2461
async fn junit_reports_make_a_tests_tab() {
2462
    let h = hub().await;
2463
    create(&h.app, "andy", "t").await;
2464
    let url = format!("{}/andy/t", h.base);
2465
    let work = tempfile::tempdir().unwrap();
2466
    let c = client(&url, work.path());
2467
    write(
2468
        work.path(),
2469
        ".flow/pipeline.kdl",
2470
        &format!(
2471
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"test\" {{\n    sandbox \"alpine\"\n    exec \"make\" \"test\"\n    output {{\n        artifact \"junit\" {{\n            path \"/src/junit.xml\"\n        }}\n    }}\n}}\n"
2472
        ),
2473
    );
2474
    assert!(!call(&h.app, "GET", "/andy/t", None, None).await.1.contains(">Reports</a>"));
2475
    let case = |name: &str, ok: bool, secs: &str| {
2476
        if ok {
2477
            format!(r#"<testcase classname="t.suite" name="{name}" time="{secs}"/>"#)
2478
        } else {
2479
            format!(
2480
                r#"<testcase classname="t.suite" name="{name}" time="{secs}"><failure message="{name} broke">AssertionError</failure></testcase>"#
2481
            )
2482
        }
2483
    };
2484
    let runs = [
2485
        vec![case("a", true, "0.1"), case("b", true, "2.5"), case("c", true, "0.2")],
2486
        vec![case("a", true, "0.1"), case("b", false, "2.6"), case("c", true, "0.2"), case("d", true, "0.3")],
2487
        vec![case("a", true, "0.1"), case("b", true, "2.4"), case("c", true, "0.2"), case("d", true, "0.3")],
2488
    ];
2489
    for (i, cases) in runs.iter().enumerate() {
2490
        write(work.path(), "n.txt", &i.to_string());
2491
        c.snapshot("test").unwrap();
2492
        c.commit(&format!("Run {i}"), &[]).unwrap();
2493
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2494
        // The run is made after the push answers.
2495
        let mut a = None;
2496
        for _ in 0..100 {
2497
            a = claim(&h.app).await;
2498
            if a.is_some() {
2499
                break;
2500
            }
2501
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2502
        }
2503
        let a = a.expect("a job to claim");
2504
        let id = a["job_id"].as_i64().unwrap();
2505
        let xml = format!("<testsuites><testsuite name=\"t\">{}</testsuite></testsuites>", cases.concat());
2506
        assert_eq!(upload(&h.app, id, "junit", xml.as_bytes()).await.0, StatusCode::OK);
2507
        let failed = cases.iter().any(|c| c.contains("<failure"));
2508
        let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), failed as u32);
2509
        if !failed {
2510
            r["outputs"] = serde_json::json!([oxy_core::repo::Repo::blob_ref(xml.as_bytes()).to_hex()]);
2511
        }
2512
        let code = failed as i32;
2513
        assert_eq!(
2514
            finish(&h.app, id, serde_json::json!({ "exit_code": code, "duration_ms": 700, "receipt": r })).await,
2515
            StatusCode::NO_CONTENT
2516
        );
2517
    }
2518
    let (st, page) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
2519
    assert_eq!(st, StatusCode::OK, "{page}");
2520
    if let Some(out) = std::env::var_os("OXYHUB_DUMP_TESTS_PAGE") {
2521
        std::fs::write(out, &page).unwrap();
2522
    }
2523
    assert!(page.contains(">Reports</a>"), "the tab");
2524
    assert!(page.contains("100%") && page.contains("of 4 tests passed"), "the latest run passes");
2525
    assert!(page.contains("1 fixed") && page.contains("t.suite::b"), "b fixed against the run before");
2526
    assert!(page.contains("1 ✕") && page.contains("2 ✓"), "b is flaky: {page}");
2527
    assert!(page.contains("<svg class=\"cov-chart\""), "charts");
2528
    // The slowest first.
2529
    let slow = page.find("Slowest tests").unwrap();
2530
    assert!(page[slow..].find("t.suite::b").unwrap() < page[slow..].find("t.suite::d").unwrap());
2531
    // The second run, picked: b newly failing, its failure listed.
2532
    let row = db::repos::get(&h.app.db, "andy", "t").await.unwrap().unwrap();
2533
    let second = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap()[1].id;
2534
    let (_, page) = call(&h.app, "GET", &format!("/andy/t/tests?report={second}"), None, None).await;
2535
    assert!(page.contains("1 failing") && page.contains("Newly failing") && page.contains("b broke"), "{page}");
2536
    assert!(page.contains("1 new tests"), "d is new");
2537
2538
    // The API (#114): the bookmark's reports newest first, and one with
2539
    // its failed cases.
2540
    let (st, list) = call(&h.app, "GET", "/api/v1/repos/andy/t/tests", None, None).await;
2541
    assert_eq!(st, StatusCode::OK, "{list}");
2542
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
2543
    assert_eq!(list.as_array().unwrap().len(), 3);
2544
    assert_eq!((list[0]["tests"].as_i64(), list[1]["failed"].as_i64()), (Some(4), Some(1)));
2545
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}?status=failed"), None, None).await;
2546
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
2547
    assert_eq!(one["cases"].as_array().unwrap().len(), 1);
2548
    assert_eq!((one["cases"][0]["name"].as_str(), one["cases"][0]["message"].as_str()), (Some("b"), Some("b broke")));
2549
    let (_, all) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}"), None, None).await;
2550
    assert_eq!(serde_json::from_str::<serde_json::Value>(&all).unwrap()["cases"].as_array().unwrap().len(), 4);
2551
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/t/tests/99999", None, None).await.0, StatusCode::NOT_FOUND);
2552
2553
    // The `tests` check names what broke against main.
2554
    let reports = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap();
2555
    let check = |state: String| {
2556
        let app = h.app.clone();
2557
        async move { db::hooks::checks_for_state(&app.db, row.id, &state).await.unwrap().into_iter().find(|c| c.name == "tests").unwrap() }
2558
    };
2559
    let c = check(reports[1].state.clone()).await;
2560
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "1 failing; 1 new against main: t.suite::b"));
2561
    let c = check(reports[0].state.clone()).await;
2562
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "4 passed"));
2563
2564
    // One test's history: b passed, failed, passed.
2565
    let (_, tab) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
2566
    assert!(
2567
        tab.contains("/andy/t/tests/case?classname=t.suite&amp;name=b") || tab.contains("/andy/t/tests/case?classname=t.suite&name=b"),
2568
        "linked"
2569
    );
2570
    let (st, hist) = call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=b", None, None).await;
2571
    assert_eq!(st, StatusCode::OK, "{hist}");
2572
    assert!(hist.contains("2 passed") && hist.contains("1 failed") && hist.contains("b broke"), "{hist}");
2573
    assert_eq!(call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=nope", None, None).await.0, StatusCode::NOT_FOUND);
2574
}
2575
2576
/// oxygenhub#28: a queued job no runner can take says why, in the API, on
2577
/// the run page (its panel open) and in its check.
2578
#[tokio::test(flavor = "multi_thread")]
2579
async fn a_job_no_runner_can_take_says_why() {
2580
    let h = hub().await;
2581
    create(&h.app, "andy", "demo").await;
2582
    let url = format!("{}/andy/demo", h.base);
2583
    let work = tempfile::tempdir().unwrap();
2584
    let c = client(&url, work.path());
2585
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2586
    write(work.path(), "test.sh", "echo ok\n");
2587
    c.commit("Add a pipeline", &[]).unwrap();
2588
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2589
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
2590
2591
    // One runner, online, holding another image only.
2592
    let r = db::runners::configured(&h.app.db, &blake3::hash(b"elsewhere").to_hex(), "earth-9").await.unwrap();
2593
    db::runners::seen(&h.app.db, r.id, None, None).await.unwrap();
2594
    let other = "ab".repeat(32);
2595
    db::runners::set_offer(&h.app.db, r.id, &["microvm".to_string()], Some(&[other]), false, "p").await.unwrap();
2596
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2597
2598
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2599
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
2600
    let build = v["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "build").unwrap().clone();
2601
    let why = build["waiting"].as_str().unwrap_or_default().to_string();
2602
    assert!(why.contains("earth-9 does not hold image") && why.contains(&ROOTFS[..12]), "{body}");
2603
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/1", None, None).await;
2604
    assert!(page.contains("data-waiting") && page.contains("does not hold image"), "the run page says it");
2605
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
2606
    let check = checks.iter().find(|c| c.name == "flow/build").unwrap();
2607
    assert!(check.summary.contains("does not hold image"), "{check:?}");
2608
}
2609
2610
async fn put_bytes(app: &Shared, path: &str, bearer: &str, bytes: Vec<u8>) -> (StatusCode, String) {
2611
    let req = Request::put(path)
2612
        .header(header::AUTHORIZATION, format!("Bearer {bearer}"))
2613
        .header(header::CONTENT_TYPE, "application/octet-stream")
2614
        .body(Body::from(bytes))
2615
        .unwrap();
2616
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
2617
    let st = res.status();
2618
    (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
2619
}
2620
2621
/// oxygenflow#39: an image is sent as the chunks the hub lacks and then its
2622
/// manifest, checked against its hash; runners fetch it; and a job whose
2623
/// image only the hub holds is offered to a runner that fetches, not to one
2624
/// that does not.
2625
#[tokio::test(flavor = "multi_thread")]
2626
async fn images_are_sent_by_chunk_and_offered_to_runners_that_fetch() {
2627
    let h = hub().await;
2628
    // The site token acts as the first site administrator.
2629
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2630
    // An image: bytes, a run of zeros, more bytes.
2631
    let mut image: Vec<u8> = (0..400_000u32).map(|i| (i % 251) as u8).collect();
2632
    image.extend(std::iter::repeat_n(0u8, 2 << 20));
2633
    image.extend((0..100_000u32).map(|i| (i % 239) as u8));
2634
    let mut chunks = std::collections::HashMap::new();
2635
    let m = jet::images::scan(&image[..], Some("x86_64".into()), |c, b| {
2636
        chunks.insert(c.hash().to_string(), b.to_vec());
2637
        Ok(())
2638
    })
2639
    .unwrap();
2640
    let hash = m.hash.clone();
2641
2642
    // Which chunks the hub lacks: every one but zeros; a manifest before them is refused.
2643
    let ask = serde_json::json!({ "chunks": m.needed() }).to_string();
2644
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask.clone())).await;
2645
    assert_eq!(st, StatusCode::OK, "{body}");
2646
    let missing: Vec<String> = serde_json::from_str::<serde_json::Value>(&body).unwrap()["missing"]
2647
        .as_array()
2648
        .unwrap()
2649
        .iter()
2650
        .map(|v| v.as_str().unwrap().to_string())
2651
        .collect();
2652
    assert_eq!(missing.len(), m.needed().len());
2653
    let manifest = serde_json::to_string(&m).unwrap();
2654
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest.clone())).await;
2655
    assert!(st == StatusCode::CONFLICT && body.contains("was not sent"), "{st} {body}");
2656
    // A chunk is checked against its name; a runner token may not send.
2657
    let first = &missing[0];
2658
    assert_eq!(put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "site", vec![1, 2, 3]).await.0, StatusCode::BAD_REQUEST);
2659
    assert_ne!(
2660
        put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "runner-secret", chunks[first].clone()).await.0,
2661
        StatusCode::NO_CONTENT
2662
    );
2663
    for c in &missing {
2664
        let (st, body) = put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
2665
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
2666
    }
2667
    let (_, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask)).await;
2668
    assert!(body.contains("\"missing\":[]"), "{body}");
2669
    // A large image's question fits (#147): 60,000 names, ~4 MB of JSON.
2670
    let many: Vec<String> = (0..60_000u32).map(|i| blake3::hash(&i.to_le_bytes()).to_hex().to_string()).collect();
2671
    let (st, body) =
2672
        call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(serde_json::json!({ "chunks": many }).to_string())).await;
2673
    assert_eq!(st, StatusCode::OK, "{}", &body[..body.len().min(200)]);
2674
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["missing"].as_array().unwrap().len(), 60_000);
2675
    // A manifest naming another hash is refused; the right one is kept.
2676
    let mut wrong = m.clone();
2677
    wrong.hash = "ab".repeat(32);
2678
    let (st, _) =
2679
        call(&h.app, "PUT", &format!("/api/v1/flow/images/{}", wrong.hash), Some("site"), Some(serde_json::to_string(&wrong).unwrap()))
2680
            .await;
2681
    assert_eq!(st, StatusCode::CONFLICT, "chunks that make another image");
2682
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest)).await;
2683
    assert_eq!(st, StatusCode::CREATED, "{body}");
2684
2685
    // A runner fetches the manifest and the chunks, and the image comes back whole.
2686
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), Some("runner-secret"), None).await;
2687
    assert_eq!(st, StatusCode::OK, "{body}");
2688
    let got: jet::images::Manifest = serde_json::from_str(&body).unwrap();
2689
    assert_eq!(got, m);
2690
    let dir = tempfile::tempdir().unwrap();
2691
    let out = dir.path().join("img.ext4");
2692
    let mut fetched = Vec::new();
2693
    for c in got.needed() {
2694
        let req = Request::get(format!("/api/v1/flow/images/chunks/{c}"))
2695
            .header(header::AUTHORIZATION, "Bearer runner-secret")
2696
            .body(Body::empty())
2697
            .unwrap();
2698
        let res = oxygenhub::router(h.app.clone()).oneshot(req).await.unwrap();
2699
        assert_eq!(res.status(), StatusCode::OK);
2700
        let bytes = res.into_body().collect().await.unwrap().to_bytes().to_vec();
2701
        fetched.push((c.to_string(), bytes));
2702
    }
2703
    jet::images::assemble(&got, &out, |c| Ok(fetched.iter().find(|(h, _)| h == c.hash()).unwrap().1.clone())).unwrap();
2704
    assert_eq!(std::fs::read(&out).unwrap(), image);
2705
    assert_eq!(
2706
        call(&h.app, "GET", &format!("/api/v1/flow/images/{}", "cd".repeat(32)), Some("runner-secret"), None).await.0,
2707
        StatusCode::NOT_FOUND
2708
    );
2709
    assert_ne!(call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), None, None).await.0, StatusCode::OK, "not anonymous");
2710
2711
    // A job on that image: a runner holding no images and not fetching
2712
    // is offered nothing; one that fetches is offered it.
2713
    create(&h.app, "andy", "demo").await;
2714
    let url = format!("{}/andy/demo", h.base);
2715
    let work = tempfile::tempdir().unwrap();
2716
    let c = client(&url, work.path());
2717
    write(
2718
        work.path(),
2719
        ".flow/pipeline.kdl",
2720
        &format!("schema-version 1\nsandbox \"img\" {{\n    rootfs \"cas://blob/{hash}\"\n}}\njob \"build\" {{\n    sandbox \"img\"\n    exec \"make\"\n}}\n"),
2721
    );
2722
    c.commit("Build on the image", &[]).unwrap();
2723
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2724
    runs_of(&h.app, "andy", "demo").await;
2725
    // #137: the run's images are held (by the hub), so no images check.
2726
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2727
    let run1 = db::flow::run(&h.app.db, row.id, 1).await.unwrap().unwrap();
2728
    let checks = checks_when(&h.app, row.id, &run1.state, 1).await;
2729
    assert!(checks.iter().all(|c| c.name != "pipeline/images"), "{checks:?}");
2730
    let ask = |fetches: bool| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":[],"fetches_images":{fetches}}}"#);
2731
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(false))).await;
2732
    assert_eq!(st, StatusCode::NO_CONTENT, "it lacks the image and does not fetch");
2733
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2734
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2735
    assert!(body.contains("does not hold image"), "{body}");
2736
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(true))).await;
2737
    assert_eq!(st, StatusCode::OK, "it fetches, and the hub holds the image: {body}");
2738
    // oxygenhub#135: once claimed, the old waiting reason is gone.
2739
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2740
    assert!(!body.contains("waiting"), "a running job keeps no waiting reason: {body}");
2741
}
2742
2743
/// oxygenhub#136: coverage measured on a workstation is uploaded for a
2744
/// bookmark's state, kept as uploaded by its account, shown so, and sets
2745
/// no check.
2746
#[tokio::test(flavor = "multi_thread")]
2747
async fn coverage_uploaded_from_a_workstation_says_so() {
2748
    let h = hub().await;
2749
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2750
    create(&h.app, "andy", "vk").await;
2751
    let url = format!("{}/andy/vk", h.base);
2752
    let work = tempfile::tempdir().unwrap();
2753
    let c = client(&url, work.path());
2754
    write(work.path(), "src/game.c", "int a;\nint b;\nint c;\nint d;\n");
2755
    c.commit("Game", &[]).unwrap();
2756
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2757
2758
    let lcov = "SF:src/game.c\nDA:1,3\nDA:2,1\nDA:3,0\nDA:4,5\nend_of_record\nSF:reference/rom.asm\nDA:1,1\nend_of_record\n";
2759
    let body = serde_json::json!({ "bookmark": "main", "content": lcov }).to_string();
2760
    let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", Some("site"), Some(body)).await;
2761
    assert_eq!(st, StatusCode::CREATED, "{out}");
2762
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
2763
    assert_eq!((v["uploaded_by"].as_str(), v["lines_hit"].as_i64(), v["lines_found"].as_i64()), (Some("andy"), Some(3), Some(4)));
2764
    assert_eq!(v["dropped"], 1, "a file outside the state is left out");
2765
    assert_eq!(v["bookmark"], "main");
2766
2767
    let (_, page) = call(&h.app, "GET", "/andy/vk/coverage", None, None).await;
2768
    assert!(page.contains("uploaded by andy") && page.contains("75.0%"), "the Coverage page says where it came from");
2769
    let (_, page) = call(&h.app, "GET", "/andy/vk/reports", None, None).await;
2770
    assert!(page.contains("uploaded by andy"), "and the Reports card");
2771
    let row = db::repos::get(&h.app.db, "andy", "vk").await.unwrap().unwrap();
2772
    let state = v["state"].as_str().unwrap();
2773
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, state).await.unwrap();
2774
    assert!(checks.iter().all(|c| c.name != "coverage"), "an upload sets no check: {checks:?}");
2775
2776
    // Readers cannot upload; bad reports and bookmarks are refused.
2777
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", None, Some(r#"{"content":"x"}"#.into())).await;
2778
    assert_ne!(st, StatusCode::CREATED);
2779
    let (st, _) = call(
2780
        &h.app,
2781
        "POST",
2782
        "/api/v1/repos/andy/vk/coverage",
2783
        Some("site"),
2784
        Some(r#"{"bookmark":"nope","content":"SF:a\nend_of_record\n"}"#.into()),
2785
    )
2786
    .await;
2787
    assert_eq!(st, StatusCode::BAD_REQUEST);
2788
}
2789
2790
/// oxygenflow#40: what a runner measured at its claim is kept and shown.
2791
#[tokio::test(flavor = "multi_thread")]
2792
async fn a_runners_facts_are_kept_from_its_claim() {
2793
    let h = hub().await;
2794
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2795
    let body = r#"{"runner":"test-1","runtimes":["microvm"],"facts":{"free_disk_mib":42000,"load_x100":112,"speed":100,"speed_class":3,"kernel":"7.0.0"}}"#;
2796
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.into())).await;
2797
    assert_eq!(st, StatusCode::NO_CONTENT, "nothing to run, but the facts are kept");
2798
    let (st, out) = call(&h.app, "GET", "/api/v1/runners", Some("site"), None).await;
2799
    assert_eq!(st, StatusCode::OK, "{out}");
2800
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
2801
    let r = &v[0];
2802
    assert_eq!(
2803
        (r["speed"].as_i64(), r["speed_class"].as_i64(), r["free_disk_mib"].as_i64(), r["load_x100"].as_i64()),
2804
        (Some(100), Some(3), Some(42000), Some(112))
2805
    );
2806
    let row = db::runners::list(&h.app.db).await.unwrap().remove(0);
2807
    assert_eq!(row.facts_line(), "speed 100 (class 3) · load 1.12 · 41 GiB free");
2808
}
2809
2810
/// oxygenflow#41: a job's peaks set what its next run needs; a runner
2811
/// without that much free disk is not offered it, and the reason says so.
2812
#[tokio::test(flavor = "multi_thread")]
2813
async fn a_jobs_next_run_needs_the_disk_its_last_took() {
2814
    let h = hub().await;
2815
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2816
    create(&h.app, "andy", "demo").await;
2817
    let url = format!("{}/andy/demo", h.base);
2818
    let work = tempfile::tempdir().unwrap();
2819
    let c = client(&url, work.path());
2820
    write(
2821
        work.path(),
2822
        ".flow/pipeline.kdl",
2823
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2824
    );
2825
    c.commit("Build", &[]).unwrap();
2826
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2827
    runs_of(&h.app, "andy", "demo").await;
2828
    let claim_with = |free: u64| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"facts":{{"free_disk_mib":{free}}}}}"#);
2829
2830
    // The first run has nothing to learn from: any runner takes it.
2831
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(500))).await;
2832
    assert_eq!(st, StatusCode::OK, "{body}");
2833
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2834
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 10, "peak_disk_mib": 8000, "peak_memory_mib": 900 });
2835
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
2836
    let job = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
2837
    assert_eq!((job.peak_disk_mib, job.peak_memory_mib), (Some(8000), Some(900)));
2838
2839
    // The next run needs 8000 MiB and a quarter more.
2840
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
2841
    assert_eq!(st, StatusCode::CREATED);
2842
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2843
    let run2 = db::flow::run(&h.app.db, repo.id, 2).await.unwrap().unwrap();
2844
    let next = db::flow::jobs(&h.app.db, run2.id).await.unwrap().remove(0);
2845
    assert_eq!(next.need_disk_mib, Some(8000 + 2000 + 64));
2846
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(9000))).await;
2847
    assert_eq!(st, StatusCode::NO_CONTENT, "9000 MiB free is not enough");
2848
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2849
    let waiting = db::flow::job(&h.app.db, next.id).await.unwrap().unwrap().waiting;
2850
    assert!(waiting.contains("8.8 GiB free; the job needs ~9.8 GiB"), "{waiting}");
2851
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(20_000))).await;
2852
    assert_eq!(st, StatusCode::OK, "a roomier runner takes it: {body}");
2853
}
2854
2855
/// oxygenflow#42: a job another free runner would do better (it holds the
2856
/// image) is held from a runner that would fetch it, the better runner
2857
/// takes it, and the job says why it ran there.
2858
#[tokio::test(flavor = "multi_thread")]
2859
async fn a_job_waits_briefly_for_a_runner_that_holds_its_image() {
2860
    let h = hub().await;
2861
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2862
    // A second runner, with a token of its own.
2863
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
2864
    let ask = |images: &str| {
2865
        format!(
2866
            r#"{{"runner":"r","runtimes":["microvm"],"images":[{images}],"fetches_images":true,"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
2867
        )
2868
    };
2869
    let holder = ask(&format!("\"{ROOTFS}\""));
2870
    // earth-9 holds the image and is polling; nothing is queued yet.
2871
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder.clone())).await;
2872
    assert_eq!(st, StatusCode::NO_CONTENT);
2873
    // The hub holds the image too, so test-1 could fetch it.
2874
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES ($1, 1, 'x86_64', 1, 'andy', 0)")
2875
        .bind(ROOTFS)
2876
        .execute(&h.app.db)
2877
        .await
2878
        .unwrap();
2879
2880
    create(&h.app, "andy", "demo").await;
2881
    let url = format!("{}/andy/demo", h.base);
2882
    let work = tempfile::tempdir().unwrap();
2883
    let c = client(&url, work.path());
2884
    write(
2885
        work.path(),
2886
        ".flow/pipeline.kdl",
2887
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2888
    );
2889
    c.commit("Build", &[]).unwrap();
2890
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2891
    runs_of(&h.app, "andy", "demo").await;
2892
2893
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
2894
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner that holds the image");
2895
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
2896
    assert_eq!(st, StatusCode::OK, "{body}");
2897
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2898
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
2899
    assert!(placed.starts_with("holds the image, idle, speed 100 (class 3)"), "{placed}");
2900
    assert!(placed.contains("held for a better runner"), "{placed}");
2901
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2902
    assert!(body.contains("\"placed\":\"holds the image"), "{body}");
2903
}
2904
2905
/// oxygenflow#51: a job waits briefly for the runner holding its build
2906
/// cache, even when the other one holds its image too.
2907
#[tokio::test(flavor = "multi_thread")]
2908
async fn a_job_waits_briefly_for_the_runner_holding_its_build_cache() {
2909
    let h = hub().await;
2910
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2911
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
2912
    let slot = flow_core::api::cache_slot("andy/demo", "build");
2913
    let ask = |caches: &str| {
2914
        format!(
2915
            r#"{{"runner":"r","runtimes":["microvm"],"images":["{ROOTFS}"],"fetches_images":true,"caches":[{caches}],"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
2916
        )
2917
    };
2918
    let holder = ask(&format!("\"{slot}\""));
2919
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder.clone())).await;
2920
    assert_eq!(st, StatusCode::NO_CONTENT);
2921
2922
    create(&h.app, "andy", "demo").await;
2923
    let url = format!("{}/andy/demo", h.base);
2924
    let work = tempfile::tempdir().unwrap();
2925
    let c = client(&url, work.path());
2926
    write(
2927
        work.path(),
2928
        ".flow/pipeline.kdl",
2929
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2930
    );
2931
    c.commit("Build", &[]).unwrap();
2932
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2933
    runs_of(&h.app, "andy", "demo").await;
2934
2935
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
2936
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner holding the build cache");
2937
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
2938
    assert_eq!(st, StatusCode::OK, "{body}");
2939
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2940
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
2941
    assert!(placed.starts_with("holds its build cache, holds the image"), "{placed}");
2942
}
2943
2944
/// oxygenflow#54: when both runners hold a job's build cache, the job waits
2945
/// briefly for the one whose copy is fresher.
2946
#[tokio::test(flavor = "multi_thread")]
2947
async fn a_job_waits_briefly_for_the_fresher_build_cache() {
2948
    let h = hub().await;
2949
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2950
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
2951
    let slot = flow_core::api::cache_slot("andy/demo", "build");
2952
    let now = db::now_ms();
2953
    let ask = |kept: i64| {
2954
        format!(
2955
            r#"{{"runner":"r","runtimes":["microvm"],"images":["{ROOTFS}"],"fetches_images":true,"caches":["{slot}"],"cache_times":{{"{slot}":{kept}}},"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
2956
        )
2957
    };
2958
    // earth-9 kept its copy a minute ago; the other runner's is a day old.
2959
    let fresh = ask(now - 60_000);
2960
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(fresh.clone())).await;
2961
    assert_eq!(st, StatusCode::NO_CONTENT);
2962
2963
    create(&h.app, "andy", "demo").await;
2964
    let url = format!("{}/andy/demo", h.base);
2965
    let work = tempfile::tempdir().unwrap();
2966
    let c = client(&url, work.path());
2967
    write(
2968
        work.path(),
2969
        ".flow/pipeline.kdl",
2970
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2971
    );
2972
    c.commit("Build", &[]).unwrap();
2973
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2974
    runs_of(&h.app, "andy", "demo").await;
2975
2976
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(now - 86_400_000))).await;
2977
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the fresher copy");
2978
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(fresh)).await;
2979
    assert_eq!(st, StatusCode::OK, "{body}");
2980
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2981
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
2982
    assert!(placed.starts_with("holds its build cache (kept 1 min ago), holds the image"), "{placed}");
2983
}
2984
2985
/// oxygenhub#127 §3.3: report files expire beyond the newest 50 runs of a
2986
/// report on a bookmark other than the default; the default keeps all,
2987
/// and an expired report keeps its metrics.
2988
#[tokio::test(flavor = "multi_thread")]
2989
async fn report_files_expire_under_retention() {
2990
    let h = hub().await;
2991
    create(&h.app, "andy", "demo").await;
2992
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2993
    let add = |bookmark: &'static str, at: i64| {
2994
        let db = h.app.db.clone();
2995
        async move {
2996
            let id: i64 = sqlx::query_scalar(
2997
                "INSERT INTO reports (repo_id, name, kind, title, summary, context, job, bookmark, state, files, bytes, created_ms) \
2998
                 VALUES ($1, 'perf', 'performance', 'Perf', '', '{}', 'perf', $2, 's', 1, 1, $3) RETURNING id",
2999
            )
3000
            .bind(repo.id)
3001
            .bind(bookmark)
3002
            .bind(at)
3003
            .fetch_one(&db)
3004
            .await
3005
            .unwrap();
3006
            sqlx::query("INSERT INTO report_files (report_id, path, blob, size) VALUES ($1, 'report.toml', $2, 1)")
3007
                .bind(id)
3008
                .bind(format!("{:064x}", id))
3009
                .execute(&db)
3010
                .await
3011
                .unwrap();
3012
            sqlx::query("INSERT INTO report_metrics (report_id, key, value, unit, better) VALUES ($1, 'ms', 1, '', '')")
3013
                .bind(id)
3014
                .execute(&db)
3015
                .await
3016
                .unwrap();
3017
            id
3018
        }
3019
    };
3020
    let main_old = add("main", 1).await;
3021
    add("main", 2).await;
3022
    let mut feature = Vec::new();
3023
    for at in 0..52 {
3024
        feature.push(add("feature", 10 + at).await);
3025
    }
3026
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 2, "the two oldest feature runs");
3027
    let files = |id: i64| {
3028
        let db = h.app.db.clone();
3029
        async move {
3030
            sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM report_files WHERE report_id = $1").bind(id).fetch_one(&db).await.unwrap()
3031
        }
3032
    };
3033
    assert_eq!((files(feature[0]).await, files(feature[1]).await, files(feature[2]).await), (0, 0, 1));
3034
    assert_eq!(files(main_old).await, 1, "the default bookmark keeps every run");
3035
    assert_eq!(oxygenhub::reports::metrics(&h.app.db, feature[0]).await.unwrap().len(), 1, "metrics are kept");
3036
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 0, "once");
3037
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/perf?id={}", feature[0]), None, None).await;
3038
    assert!(page.contains("files have expired"), "the page says so");
3039
}
3040
3041
/// #137: a run pinning an image neither the hub nor any runner holds sets a
3042
/// failing `pipeline/images` check saying how to send it; once it is held,
3043
/// a run of the same state turns the check to passed.
3044
#[tokio::test(flavor = "multi_thread")]
3045
async fn a_pipeline_pinning_an_image_nobody_holds_fails_a_check() {
3046
    let h = hub().await;
3047
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3048
    // The one runner reports holding no images.
3049
    let none = r#"{"runner":"test-1","runtimes":["microvm"],"images":[]}"#;
3050
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(none.into())).await;
3051
    assert_eq!(st, StatusCode::NO_CONTENT);
3052
    create(&h.app, "andy", "demo").await;
3053
    let url = format!("{}/andy/demo", h.base);
3054
    let work = tempfile::tempdir().unwrap();
3055
    let c = client(&url, work.path());
3056
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3057
    write(work.path(), "test.sh", "echo ok\n");
3058
    c.commit("Add a pipeline", &[]).unwrap();
3059
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3060
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
3061
    let checks = checks_when(&h.app, run.repo_id, &run.state, 4).await;
3062
    let check = checks.iter().find(|c| c.name == "pipeline/images").expect("an images check");
3063
    assert!(check.status == "failed" && check.summary.contains(&ROOTFS[..12]) && check.summary.contains("flow rootfs push"), "{check:?}");
3064
    // Once a runner holds it, a run of the state passes the check.
3065
    let holds = format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":["{ROOTFS}"]}}"#);
3066
    call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(holds)).await;
3067
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
3068
    assert_eq!(st, StatusCode::CREATED);
3069
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
3070
    let check = checks.iter().find(|c| c.name == "pipeline/images").unwrap();
3071
    assert_eq!(check.status, "passed", "{check:?}");
3072
}
3073
3074
/// The swarm's tracker (#144): a fetching runner is given the peers in its
3075
/// site that hold the image or are fetching it, and a ticket signed with
3076
/// the hub key; a runner not in a swarm is told how to join one.
3077
#[tokio::test(flavor = "multi_thread")]
3078
async fn the_tracker_names_peers_in_the_same_site_and_signs_a_ticket() {
3079
    let h = hub().await;
3080
    let app = &h.app;
3081
    let image = "ab".repeat(32);
3082
    let claim_as = |token: &'static str, name: &'static str, body: serde_json::Value| async move {
3083
        let mut b = serde_json::json!({ "runner": name, "runtimes": ["microvm"] });
3084
        b.as_object_mut().unwrap().extend(body.as_object().unwrap().clone());
3085
        let (st, out) = call(app, "POST", "/api/v1/flow/claim", Some(token), Some(b.to_string())).await;
3086
        assert_eq!(st, StatusCode::NO_CONTENT, "{out}");
3087
    };
3088
    let announce = |token: &'static str, state: &'static str| {
3089
        let body = serde_json::json!({ "image": image, "state": state }).to_string();
3090
        async move { call(app, "POST", "/api/v1/flow/swarm/announce", Some(token), Some(body)).await }
3091
    };
3092
    // A holds the image; B and C hold nothing; all three are in site "lab".
3093
    claim_as(
3094
        "runner-secret",
3095
        "a",
3096
        serde_json::json!({ "images": [image], "swarm": { "addr": "10.0.0.1:7401", "site": "lab", "cert": "11".repeat(32) } }),
3097
    )
3098
    .await;
3099
    claim_as(
3100
        "runner-two",
3101
        "b",
3102
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.2:7401", "site": "lab", "cert": "22".repeat(32) } }),
3103
    )
3104
    .await;
3105
    claim_as(
3106
        "runner-three",
3107
        "c",
3108
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.3:7401", "site": "lab", "cert": "33".repeat(32) } }),
3109
    )
3110
    .await;
3111
3112
    let (st, body) = announce("runner-two", "fetching").await;
3113
    assert_eq!(st, StatusCode::OK, "{body}");
3114
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3115
    let names: Vec<(&str, bool)> = a.peers.iter().map(|p| (p.addr.as_str(), p.complete)).collect();
3116
    assert_eq!(names, vec![("10.0.0.1:7401", true)], "only A holds it so far");
3117
    assert_eq!(a.peers[0].cert, "11".repeat(32), "with the fingerprint peers check it by");
3118
    let t = jet::swarm::Ticket::open(&a.ticket, &app.hub_key.identity, oxygenhub::db::now_ms() as u64).unwrap();
3119
    assert_eq!((t.name.as_str(), t.site.as_str()), ("b", "lab"));
3120
3121
    // C, fetching too, is told of A (whole) and B (fetching).
3122
    let (_, body) = announce("runner-three", "fetching").await;
3123
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3124
    let mut peers: Vec<(&str, bool)> = a.peers.iter().map(|p| (p.addr.as_str(), p.complete)).collect();
3125
    peers.sort();
3126
    assert_eq!(peers, vec![("10.0.0.1:7401", true), ("10.0.0.2:7401", false)]);
3127
3128
    // B is done: no longer offered as fetching. C moves site: no peers.
3129
    announce("runner-two", "done").await;
3130
    claim_as(
3131
        "runner-three",
3132
        "c",
3133
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.3:7401", "site": "elsewhere", "cert": "33".repeat(32) } }),
3134
    )
3135
    .await;
3136
    let (_, body) = announce("runner-three", "fetching").await;
3137
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3138
    assert!(a.peers.is_empty(), "{:?}", a.peers);
3139
3140
    // A runner without a certificate (an older flow) is not in the swarm.
3141
    claim_as("runner-secret", "a", serde_json::json!({ "images": [image], "swarm": { "addr": "10.0.0.1:7401", "site": "elsewhere" } }))
3142
        .await;
3143
    let (st, _) = announce("runner-secret", "fetching").await;
3144
    assert_eq!(st, StatusCode::CONFLICT);
3145
3146
    // A runner that left the swarm is told how to join; nonsense is refused.
3147
    claim_as("runner-two", "b", serde_json::json!({ "images": [] })).await;
3148
    let (st, body) = announce("runner-two", "fetching").await;
3149
    assert_eq!(st, StatusCode::CONFLICT);
3150
    assert!(body.contains("[runner.swarm]"), "{body}");
3151
    let (st, _) =
3152
        call(app, "POST", "/api/v1/flow/swarm/announce", Some("runner-secret"), Some(r#"{"image":"nope","state":"fetching"}"#.into()))
3153
            .await;
3154
    assert_eq!(st, StatusCode::BAD_REQUEST);
3155
    let (st, _) = call(
3156
        app,
3157
        "POST",
3158
        "/api/v1/flow/swarm/announce",
3159
        None,
3160
        Some(serde_json::json!({ "image": image, "state": "fetching" }).to_string()),
3161
    )
3162
    .await;
3163
    assert_eq!(st, StatusCode::UNAUTHORIZED);
3164
}
3165
3166
/// Admin › Runners › Images (C0): each image, where it is and what uses it.
3167
#[tokio::test(flavor = "multi_thread")]
3168
async fn the_images_page_says_where_each_image_is_and_what_uses_it() {
3169
    let h = hub().await;
3170
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3171
    create(&h.app, "andy", "demo").await;
3172
    let work = tempfile::tempdir().unwrap();
3173
    let c = client(&format!("{}/andy/demo", h.base), work.path());
3174
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3175
    write(work.path(), "test.sh", "echo ok\n");
3176
    c.commit("Add a pipeline", &[]).unwrap();
3177
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3178
    // A runner holds another image and shares it; the hub keeps a third.
3179
    let held = "cd".repeat(32);
3180
    let kept = "ef".repeat(32);
3181
    let body = serde_json::json!({ "runner": "earth-1", "runtimes": ["wasm"], "images": [held], "swarm": { "addr": "10.0.0.1:7401", "site": "home", "cert": "11".repeat(32) } });
3182
    let (st, out) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
3183
    assert!(st == StatusCode::NO_CONTENT || st == StatusCode::OK, "{st} {out}");
3184
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES ($1, 1048576, 'x86_64', 9, 'andy', 1)")
3185
        .bind(&kept)
3186
        .execute(&h.app.db)
3187
        .await
3188
        .unwrap();
3189
3190
    let res = oxygenhub::router(h.app.clone())
3191
        .oneshot(
3192
            Request::post("/register")
3193
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
3194
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
3195
                .unwrap(),
3196
        )
3197
        .await
3198
        .unwrap();
3199
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
3200
    let carol = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
3201
    db::accounts::set_admin(&h.app.db, carol.id, true).await.unwrap();
3202
    let res = oxygenhub::router(h.app.clone())
3203
        .oneshot(Request::get("/admin/runners/images").header(header::COOKIE, cookie).body(Body::empty()).unwrap())
3204
        .await
3205
        .unwrap();
3206
    assert_eq!(res.status(), StatusCode::OK);
3207
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
3208
    let row = |hash: &str| {
3209
        let at = page.find(&format!("title=\"{hash}\"")).unwrap_or_else(|| panic!("{hash} is not on the page"));
3210
        let end = page[at..].find("</tr>").unwrap();
3211
        page[at..at + end].to_string()
3212
    };
3213
    let pinned = row(ROOTFS);
3214
    assert!(pinned.contains("nowhere") && pinned.contains("andy/demo") && pinned.contains("3 jobs"), "{pinned}");
3215
    let on_runner = row(&held);
3216
    assert!(on_runner.contains("img-holds") && on_runner.contains("earth-1") && !on_runner.contains("nowhere"), "{on_runner}");
3217
    let on_hub = row(&kept);
3218
    assert!(on_hub.contains("img-hub") && on_hub.contains("1.0 MiB") && on_hub.contains("x86_64"), "{on_hub}");
3219
    assert!(page.contains("earth-1 (home)"), "the swarm is named");
3220
    // The swarm backdrop (docs/backgrounds.md §2): the hub and the runners.
3221
    assert!(page.contains(r#"{"images":"#) && page.contains(r#""scene":"swarm""#) && page.contains(r#""earth-1""#), "the swarm's data");
3222
    assert_eq!(call(&h.app, "GET", "/admin/runners/images", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
3223
}
3224
3225
/// Diffusion D1 (#148): the reverse pin index. A repository that pins
3226
/// another as a subrepo is a consumer of it; the upstream's API and page
3227
/// say who, at which state, and how far behind its default bookmark.
3228
#[tokio::test(flavor = "multi_thread")]
3229
async fn consumers_of_a_subrepo_are_indexed_with_how_far_behind_they_are() {
3230
    let h = hub().await;
3231
    // The site token acts as the first site administrator.
3232
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3233
    create(&h.app, "andy", "api").await;
3234
    create(&h.app, "andy", "game").await;
3235
    let api_work = tempfile::tempdir().unwrap();
3236
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
3237
    write(api_work.path(), "api.h", "v1\n");
3238
    api.snapshot("t").unwrap();
3239
    api.commit("api v1", &[]).unwrap();
3240
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3241
3242
    let game_work = tempfile::tempdir().unwrap();
3243
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
3244
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3245
    write(game_work.path(), "game.c", "int main;\n");
3246
    game.snapshot("t").unwrap();
3247
    game.commit("game on api v1", &[]).unwrap();
3248
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3249
3250
    let consumers = || async {
3251
        let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
3252
        assert_eq!(st, StatusCode::OK, "{body}");
3253
        serde_json::from_str::<Vec<serde_json::Value>>(&body).unwrap()
3254
    };
3255
    // The index is written by the push's after-work, a moment after the
3256
    // client hears the push succeeded.
3257
    let settle = |want: &'static (dyn Fn(&[serde_json::Value]) -> bool + Sync)| {
3258
        let consumers = &consumers;
3259
        async move {
3260
            for _ in 0..100 {
3261
                let list = consumers().await;
3262
                if want(&list) {
3263
                    return list;
3264
                }
3265
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3266
            }
3267
            consumers().await
3268
        }
3269
    };
3270
    let list = settle(&|l| !l.is_empty()).await;
3271
    assert_eq!(list.len(), 1, "{list:?}");
3272
    assert_eq!(
3273
        (list[0]["name"].as_str(), list[0]["path"].as_str(), list[0]["bookmark"].as_str()),
3274
        (Some("game"), Some("deps/api"), Some("main"))
3275
    );
3276
    assert_eq!(list[0]["behind"], 0);
3277
3278
    // The upstream moves on: the consumer is one change behind.
3279
    write(api_work.path(), "api.c", "v2\n");
3280
    api.snapshot("t").unwrap();
3281
    api.commit("api v2", &[]).unwrap();
3282
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3283
    assert_eq!(settle(&|l| l.first().is_some_and(|c| c["behind"] == 1)).await[0]["behind"], 1);
3284
    let (_, page) = call(&h.app, "GET", "/andy/api", None, None).await;
3285
    assert!(page.contains("Diffuses to") && page.contains("andy/game") && page.contains("1 behind"), "the page shows it");
3286
3287
    // A private consumer is not shown to someone who cannot read it.
3288
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'game'").execute(&h.app.db).await.unwrap();
3289
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", None, None).await;
3290
    assert_eq!(body.trim(), "[]");
3291
    let (_, page) = call(&h.app, "GET", "/andy/api", None, None).await;
3292
    assert!(!page.contains("andy/game"));
3293
    sqlx::query("UPDATE repositories SET visibility = 'public' WHERE name = 'game'").execute(&h.app.db).await.unwrap();
3294
3295
    // A bump (DF3): one signed change on the target moving only the pin, on
3296
    // `diffusion/deps/api`; again with the same state, nothing new.
3297
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3298
    let api_row = db::repos::get(&h.app.db, "andy", "api").await.unwrap().unwrap();
3299
    let api_heads = api.bookmark_heads().unwrap();
3300
    let bumped = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, api_heads.clone()).await.unwrap();
3301
    let oxygenhub::diffusion::Bumped::Moved { bookmark, heads, .. } = bumped else { panic!("{bumped:?}") };
3302
    assert_eq!(bookmark, "diffusion/deps/api");
3303
    game.fetch("origin").unwrap();
3304
    let bump_state = game.load_state(&heads).unwrap().materialize();
3305
    let pin = match &bump_state.files["deps/api"].content {
3306
        oxy_core::state::FileContent::Opaque { blobs } => oxy_core::subrepo::Pin::decode(&game.read_blob(&blobs[0]).unwrap()).unwrap(),
3307
        other => panic!("{other:?}"),
3308
    };
3309
    assert!(
3310
        matches!(&pin, oxy_core::subrepo::Pin::Oxy { heads, .. } if { let mut a = heads.clone(); a.sort(); let mut b = api_heads.clone(); b.sort(); a == b }),
3311
        "{pin:?}"
3312
    );
3313
    assert!(bump_state.files.contains_key("game.c"), "the rest of the game is as it was");
3314
    assert!(matches!(
3315
        oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, api_heads.clone()).await.unwrap(),
3316
        oxygenhub::diffusion::Bumped::Already { .. }
3317
    ));
3318
    // A state lacking changes the pin has (as when the consumer pinned an
3319
    // upstream proposal not landed yet) is combined with the pin, never
3320
    // dropping what it relies on.
3321
    write(api_work.path(), "other.c", "v3\n");
3322
    api.snapshot("t").unwrap();
3323
    let v3 = api.commit("api v3, on its own", &[]).unwrap();
3324
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3325
    let only_v3 = api.load_state(&[v3]).unwrap().heads().to_vec();
3326
    let combined = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, only_v3).await.unwrap();
3327
    let oxygenhub::diffusion::Bumped::Moved { heads: ch, .. } = combined else { panic!("{combined:?}") };
3328
    game.fetch("origin").unwrap();
3329
    let st = game.load_state(&ch).unwrap().materialize();
3330
    let pin = match &st.files["deps/api"].content {
3331
        oxy_core::state::FileContent::Opaque { blobs } => oxy_core::subrepo::Pin::decode(&game.read_blob(&blobs[0]).unwrap()).unwrap(),
3332
        other => panic!("{other:?}"),
3333
    };
3334
    let oxy_core::subrepo::Pin::Oxy { heads: pinned, .. } = pin else { panic!() };
3335
    let all = api.load_state(&pinned).unwrap();
3336
    // The game's main still pins v1 alone; combined with v3, it is both.
3337
    assert!(all.contains(&v3) && all.len() == 2, "v1 and v3, {} changes", all.len());
3338
    // The upstream moves again: the same bookmark moves.
3339
    let newer = api.bookmark_heads().unwrap();
3340
    let again = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, newer).await.unwrap();
3341
    assert!(matches!(again, oxygenhub::diffusion::Bumped::Moved { ref bookmark, .. } if bookmark == "diffusion/deps/api"), "{again:?}");
3342
3343
    // Following is off by default; owners turn it on (DF2).
3344
    let put =
3345
        |body: &'static str, who: Option<&'static str>| call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", who, Some(body.into()));
3346
    let (st, body) = put(r#"{"follow":"green"}"#, Some("site")).await;
3347
    assert_eq!(st, StatusCode::OK, "{body}");
3348
    assert!(body.contains("\"follow\":\"green\"") && body.contains("\"from\":\"setting\""), "{body}");
3349
    assert_eq!(put(r#"{"follow":"sometimes"}"#, Some("site")).await.0, StatusCode::BAD_REQUEST);
3350
    assert_ne!(put(r#"{"follow":"any"}"#, None).await.0, StatusCode::OK, "not without a token");
3351
    let (_, body) = put(r#"{"follow":"default"}"#, Some("site")).await;
3352
    assert!(body.contains("\"follow\":\"off\"") && body.contains("\"from\":\"site\""), "{body}");
3353
3354
    // Dropping the subrepo drops the consumer.
3355
    game.submodule_remove("deps/api").unwrap();
3356
    std::fs::remove_dir_all(game_work.path().join("deps/api")).unwrap();
3357
    game.snapshot("t").unwrap();
3358
    game.commit("game without api", &[]).unwrap();
3359
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3360
    let left = settle(&|l| l.is_empty()).await;
3361
    assert!(left.is_empty(), "{left:?}");
3362
}
3363
3364
/// Diffusion D1 end to end (#148): a consumer that follows every move gets
3365
/// a bump proposal on a push; one that follows green gets it when the
3366
/// upstream's run passes. One proposal, kept up to date.
3367
#[tokio::test(flavor = "multi_thread")]
3368
async fn diffusion_proposes_a_bump_when_the_upstream_moves() {
3369
    let h = hub().await;
3370
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3371
    create(&h.app, "andy", "api").await;
3372
    create(&h.app, "andy", "game").await;
3373
    // Run every job of the upstream's newest run to a pass, keeping each claim.
3374
    let seen: std::sync::Mutex<Vec<serde_json::Value>> = std::sync::Mutex::new(Vec::new());
3375
    let seen = &seen;
3376
    let hub_app = &h.app;
3377
    let pass_all = move || async move {
3378
        let h_app = hub_app;
3379
        for _ in 0..20 {
3380
            let Some(a) = claim(h_app).await else {
3381
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3382
                if !jobs_left(h_app).await {
3383
                    break;
3384
                }
3385
                continue;
3386
            };
3387
            seen.lock().unwrap().push(a.clone());
3388
            let id = a["job_id"].as_i64().unwrap();
3389
            let (name, ph) = (a["job"]["name"].as_str().unwrap().to_string(), a["pipeline_hash"].as_str().unwrap().to_string());
3390
            assert_eq!(
3391
                finish(h_app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt(&name, &ph, 0) })).await,
3392
                StatusCode::NO_CONTENT
3393
            );
3394
        }
3395
    };
3396
    let api_work = tempfile::tempdir().unwrap();
3397
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
3398
    write(api_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3399
    write(api_work.path(), "test.sh", "echo ok\n");
3400
    write(api_work.path(), "api.h", "v1\n");
3401
    api.snapshot("t").unwrap();
3402
    api.commit("api v1", &[]).unwrap();
3403
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3404
    pass_all().await;
3405
3406
    let game_work = tempfile::tempdir().unwrap();
3407
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
3408
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3409
    write(game_work.path(), "game.c", "int main;\n");
3410
    write(game_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3411
    write(game_work.path(), "test.sh", "echo ok\n");
3412
    game.snapshot("t").unwrap();
3413
    game.commit("game on api v1", &[]).unwrap();
3414
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3415
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3416
    let bump = || async {
3417
        for _ in 0..100 {
3418
            let open = db::proposals::list(&h.app.db, game_row.id, &["open"]).await.unwrap();
3419
            if let Some(p) = open.into_iter().find(|p| p.source_bookmark == "diffusion/deps/api") {
3420
                return Some(p);
3421
            }
3422
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3423
        }
3424
        None
3425
    };
3426
3427
    // Off by default: an upstream move proposes nothing.
3428
    write(api_work.path(), "a2.c", "v2\n");
3429
    api.snapshot("t").unwrap();
3430
    api.commit("api v2: faster sprites", &[]).unwrap();
3431
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3432
    pass_all().await;
3433
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3434
    assert!(db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap().is_empty(), "off proposes nothing");
3435
3436
    // Turned on to follow every move: bumped at once to where the upstream
3437
    // is (v2), by the diffusion account; the next push updates it.
3438
    let put = |body: &'static str| call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(body.into()));
3439
    assert_eq!(put(r#"{"follow":"any"}"#).await.0, StatusCode::OK);
3440
    let first = bump().await.expect("caught up when turned on");
3441
    assert!(first.title.contains("1 change") && first.body.contains("api v2: faster sprites"), "{:?}", first.title);
3442
    // The bump's pipeline runs, as a push of it would, so the proposal is tested.
3443
    let mut ran = false;
3444
    for _ in 0..100 {
3445
        if runs_of(&h.app, "andy", "game").await.iter().any(|r| r.bookmark == "diffusion/deps/api") {
3446
            ran = true;
3447
            break;
3448
        }
3449
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3450
    }
3451
    assert!(ran, "a run of the bump");
3452
    pass_all().await;
3453
    write(api_work.path(), "a3.c", "v3\n");
3454
    api.snapshot("t").unwrap();
3455
    api.commit("api v3: save slots past ten", &[]).unwrap();
3456
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3457
    let mut p = first.clone();
3458
    for _ in 0..100 {
3459
        p = bump().await.unwrap();
3460
        if p.body.contains("api v3") {
3461
            break;
3462
        }
3463
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3464
    }
3465
    assert_eq!(p.number, first.number, "the same proposal");
3466
    assert_eq!((p.author.as_str(), p.target.as_str()), ("diffusion", "main"));
3467
    assert!(p.title.contains("deps/api") && p.title.contains("andy/api") && p.title.contains("2 changes"), "{}", p.title);
3468
    assert!(p.body.contains("api v2: faster sprites") && p.body.contains("api v3: save slots past ten"), "{}", p.body);
3469
    let labels = db::issues::proposal_labels(&h.app.db, p.id).await.unwrap();
3470
    assert!(labels.iter().any(|l| l.name == "dependencies"));
3471
    pass_all().await;
3472
3473
    // Following green: a push alone does not move it; the passing run does,
3474
    // and the same proposal is brought up to date.
3475
    assert_eq!(put(r#"{"follow":"green"}"#).await.0, StatusCode::OK);
3476
    write(api_work.path(), "a4.c", "v4\n");
3477
    api.snapshot("t").unwrap();
3478
    api.commit("api v4: rsm_set cheaper", &[]).unwrap();
3479
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3480
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3481
    assert!(!bump().await.unwrap().body.contains("api v4"), "not before its run passes");
3482
    pass_all().await;
3483
    let mut updated = None;
3484
    for _ in 0..100 {
3485
        let p2 = bump().await.unwrap();
3486
        if p2.body.contains("api v4") {
3487
            updated = Some(p2);
3488
            break;
3489
        }
3490
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3491
    }
3492
    let p2 = updated.expect("brought up to date once the run passed");
3493
    assert_eq!(p2.number, p.number, "the same proposal");
3494
    assert!(p2.title.contains("3 changes"), "{}", p2.title);
3495
    assert_eq!(db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap().len(), 1, "never a pile of bumps");
3496
3497
    // The views (#150): the upstream's Diffusion tab lists the game with its
3498
    // status; the game's tab and overview say what it follows.
3499
    pass_all().await;
3500
    let (st, page) = call(&h.app, "GET", "/andy/api/diffusion", None, None).await;
3501
    assert_eq!(st, StatusCode::OK);
3502
    assert!(page.contains("Diffuses to") && page.contains("andy/game") && page.contains(&format!("#{}", p2.number)), "the bump is listed");
3503
    assert!(page.contains("df-green"), "a passing run of a checked upstream is green");
3504
    // The ripples backdrop: the page's own repositories and tones.
3505
    assert!(
3506
        page.contains(r#""scene":"ripples""#) && page.contains(r#"["andy/game","#) && page.contains(r#""repo":"andy/api""#),
3507
        "the ripples' data"
3508
    );
3509
    let (_, page) = call(&h.app, "GET", "/andy/game/diffusion", None, None).await;
3510
    assert!(page.contains("Takes from") && page.contains("andy/api"));
3511
    let (_, overview) = call(&h.app, "GET", "/andy/game", None, None).await;
3512
    assert!(overview.contains("Takes from") && overview.contains(">Diffusion</a>"), "the tab and the panel");
3513
    // Both directions through the API (#153), as the extension reads them.
3514
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/game/diffusion", Some("site"), None).await;
3515
    assert_eq!(st, StatusCode::OK, "{body}");
3516
    let d: hub_api::Diffusion = serde_json::from_str(&body).unwrap();
3517
    assert!(d.diffuses_to.is_empty(), "nothing pins the game");
3518
    let pin = d.takes_from.first().expect("the game takes from the api");
3519
    assert_eq!((pin.upstream.as_str(), pin.consumer.as_str()), ("andy/api", "andy/game"));
3520
    assert_eq!(pin.bump, Some(p2.number));
3521
    assert_eq!(pin.upstream_state.tone, "green", "{body}");
3522
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/diffusion", Some("site"), None).await;
3523
    let d: hub_api::Diffusion = serde_json::from_str(&body).unwrap();
3524
    assert!(d.takes_from.is_empty() && d.diffuses_to.iter().any(|p| p.consumer == "andy/game"), "{body}");
3525
    let (st, _) = call(&h.app, "GET", "/admin/diffusion", None, None).await;
3526
    assert_eq!(st, StatusCode::NOT_FOUND, "administrators only");
3527
3528
    // Landing the bump on the hub moves the game's pin as a push would:
3529
    // the index follows, so it is no longer behind; even when the first
3530
    // write fails, as a busy database's would (#210: it is tried again).
3531
    let game = oxygenhub::db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3532
    oxygenhub::diffusion::fail_next_records(&h.app, game.id, 1);
3533
    let (st, body) =
3534
        call(&h.app, "POST", &format!("/api/v1/repos/andy/game/proposals/{}/land", p2.number), Some("site"), Some("{}".into())).await;
3535
    assert_eq!(st, StatusCode::OK, "{body}");
3536
    let mut behind = serde_json::Value::Null;
3537
    for _ in 0..100 {
3538
        let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
3539
        let list: Vec<serde_json::Value> = serde_json::from_str(&list).unwrap();
3540
        behind = list.iter().find(|c| c["name"] == "game").map(|c| c["behind"].clone()).unwrap_or_default();
3541
        if behind == 0 {
3542
            break;
3543
        }
3544
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3545
    }
3546
    assert_eq!(behind, 0, "the index followed the landing");
3547
    assert_eq!(oxygenhub::diffusion::forced_left(&h.app, game.id), 0, "the first write did fail");
3548
    // The reconciler (#210): an index left behind its bookmark (as when
3549
    // both writes failed) is mended from the bookmark itself, and a pass
3550
    // with nothing to mend changes nothing.
3551
    let pins_of = || async {
3552
        sqlx::query_scalar::<_, String>("SELECT heads FROM diffusion_pins WHERE consumer_id = $1")
3553
            .bind(game.id)
3554
            .fetch_one(&h.app.db)
3555
            .await
3556
            .unwrap()
3557
    };
3558
    let right = pins_of().await;
3559
    sqlx::query("UPDATE diffusion_pins SET heads = 'stale' WHERE consumer_id = $1").bind(game.id).execute(&h.app.db).await.unwrap();
3560
    sqlx::query("DELETE FROM diffusion_indexed WHERE consumer_id = $1").bind(game.id).execute(&h.app.db).await.unwrap();
3561
    let r = oxygenhub::diffusion::reconcile(&h.app).await;
3562
    assert!(r.reindexed >= 1, "{r:?}");
3563
    assert_eq!(pins_of().await, right, "the pin read again from the game's bookmark");
3564
    assert_eq!(oxygenhub::diffusion::reconcile(&h.app).await.reindexed, 0, "nothing left to mend");
3565
3566
    // A private upstream: the bump's run (started by the diffusion account,
3567
    // which cannot read it) still gets the subrepo it bumps.
3568
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'api'").execute(&h.app.db).await.unwrap();
3569
    seen.lock().unwrap().clear();
3570
    write(api_work.path(), "a6.c", "v6\n");
3571
    api.snapshot("t").unwrap();
3572
    api.commit("api v6", &[]).unwrap();
3573
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3574
    // The bump's run starts in the background: wait for its job, under a
3575
    // loaded test run as well as alone.
3576
    let mut bump_job = None;
3577
    for _ in 0..100 {
3578
        pass_all().await;
3579
        bump_job = seen.lock().unwrap().iter().find(|c| c["repo"] == "andy/game" && c["bookmark"] == "diffusion/deps/api").cloned();
3580
        if bump_job.is_some() {
3581
            break;
3582
        }
3583
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
3584
    }
3585
    let bump_job = bump_job.expect("the bump's job ran");
3586
    let subs: Vec<&str> = bump_job["subrepos"].as_array().unwrap().iter().filter_map(|s| s["path"].as_str()).collect();
3587
    assert_eq!(subs, vec!["deps/api"], "{bump_job}");
3588
3589
    // A consumer turning Diffusion on is bumped at once to the upstream's
3590
    // newest passing state, without waiting for it to move again.
3591
    create(&h.app, "andy", "game2").await;
3592
    let g2_work = tempfile::tempdir().unwrap();
3593
    let g2 = client(&format!("{}/andy/game2", h.base), g2_work.path());
3594
    g2.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3595
    g2.snapshot("t").unwrap();
3596
    g2.commit("game2 on api", &[]).unwrap();
3597
    assert!(g2.push("origin", false).unwrap().iter().all(|r| r.ok));
3598
    // Its pin is api's newest state already: move api on, pass the run.
3599
    write(api_work.path(), "a5.c", "v5\n");
3600
    api.snapshot("t").unwrap();
3601
    api.commit("api v5", &[]).unwrap();
3602
    let api_row = db::repos::get(&h.app.db, "andy", "api").await.unwrap().unwrap();
3603
    let runs_before = db::flow::runs(&h.app.db, api_row.id, 100, None).await.unwrap().len();
3604
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3605
    // The push's run is made in the background: wait for it, or pass_all
3606
    // can finish before it exists and v5 never passes (a flake under load).
3607
    for _ in 0..300 {
3608
        if db::flow::runs(&h.app.db, api_row.id, 100, None).await.unwrap().len() > runs_before {
3609
            break;
3610
        }
3611
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3612
    }
3613
    pass_all().await;
3614
    let g2_row = db::repos::get(&h.app.db, "andy", "game2").await.unwrap().unwrap();
3615
    for _ in 0..100 {
3616
        if sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
3617
            .bind(g2_row.id)
3618
            .fetch_one(&h.app.db)
3619
            .await
3620
            .unwrap()
3621
            > 0
3622
        {
3623
            break;
3624
        }
3625
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3626
    }
3627
    assert!(db::proposals::list(&h.app.db, g2_row.id, &[]).await.unwrap().is_empty(), "off until turned on");
3628
    let (st, _) = call(&h.app, "PUT", "/api/v1/repos/andy/game2/diffusion", Some("site"), Some(r#"{"follow":"green"}"#.into())).await;
3629
    assert_eq!(st, StatusCode::OK);
3630
    let mut caught = None;
3631
    // Up to 15 s: under a full parallel test run the bump can take a while.
3632
    for _ in 0..300 {
3633
        if let Some(p) = db::proposals::list(&h.app.db, g2_row.id, &["open"]).await.unwrap().into_iter().next() {
3634
            caught = Some(p);
3635
            break;
3636
        }
3637
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3638
    }
3639
    let caught = caught.expect("bumped as soon as it was turned on");
3640
    assert!(caught.body.contains("api v5") && caught.title.contains("1 change"), "{:?} {:?}", caught.title, caught.body);
3641
    // A bump someone closed is a "no": the reconciler does not open it again.
3642
    sqlx::query("UPDATE proposals SET state = 'closed' WHERE id = $1").bind(caught.id).execute(&h.app.db).await.unwrap();
3643
    // (The bump's own runs finishing may still propose again, as Diffusion
3644
    // does on an upstream's moves; the reconciler itself opens nothing.)
3645
    let r = oxygenhub::diffusion::reconcile(&h.app).await;
3646
    assert_eq!(r.caught_up, 0, "the reconciler respects the closed bump: {r:?}");
3647
}
3648
3649
/// Whether any job is queued or running.
3650
async fn jobs_left(app: &Shared) -> bool {
3651
    sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM flow_jobs WHERE status IN ('queued', 'running')")
3652
        .fetch_one(&app.db)
3653
        .await
3654
        .unwrap_or(0)
3655
        > 0
3656
}
3657
3658
/// An upstream with no checks never turns green: a consumer following green
3659
/// still gets its bumps, marked amber, `upstream unverified` (#148).
3660
#[tokio::test(flavor = "multi_thread")]
3661
async fn bumps_from_an_upstream_without_checks_are_marked_unverified() {
3662
    let h = hub().await;
3663
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3664
    create(&h.app, "andy", "lib").await;
3665
    create(&h.app, "andy", "app").await;
3666
    let lib_work = tempfile::tempdir().unwrap();
3667
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
3668
    write(lib_work.path(), "lib.h", "v1\n");
3669
    lib.snapshot("t").unwrap();
3670
    lib.commit("lib v1", &[]).unwrap();
3671
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
3672
    let app_work = tempfile::tempdir().unwrap();
3673
    let app = client(&format!("{}/andy/app", h.base), app_work.path());
3674
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
3675
    // It watches lib.c: upstream changes touching it are flagged.
3676
    let modules = std::fs::read_to_string(app_work.path().join(".oxymodules")).unwrap();
3677
    write(app_work.path(), ".oxymodules", &format!("{modules}watch = lib.c\n"));
3678
    app.snapshot("t").unwrap();
3679
    app.commit("app on lib", &[]).unwrap();
3680
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
3681
    let app_row = db::repos::get(&h.app.db, "andy", "app").await.unwrap().unwrap();
3682
    for _ in 0..100 {
3683
        if sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
3684
            .bind(app_row.id)
3685
            .fetch_one(&h.app.db)
3686
            .await
3687
            .unwrap()
3688
            > 0
3689
        {
3690
            break;
3691
        }
3692
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3693
    }
3694
    let (st, _) = call(&h.app, "PUT", "/api/v1/repos/andy/app/diffusion", Some("site"), Some(r#"{"follow":"green"}"#.into())).await;
3695
    assert_eq!(st, StatusCode::OK);
3696
    write(lib_work.path(), "lib.c", "v2\n");
3697
    lib.snapshot("t").unwrap();
3698
    lib.commit("lib v2", &[]).unwrap();
3699
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
3700
    let mut found = None;
3701
    for _ in 0..100 {
3702
        if let Some(p) = db::proposals::list(&h.app.db, app_row.id, &["open"]).await.unwrap().into_iter().next() {
3703
            found = Some(p);
3704
            break;
3705
        }
3706
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3707
    }
3708
    let p = found.expect("a bump although the upstream never goes green");
3709
    assert!(p.body.contains("Upstream unverified"), "{}", p.body);
3710
    assert!(p.body.contains("Touches what you watch") && p.body.contains("touches `lib.c`") && p.body.contains("⚑"), "{}", p.body);
3711
    let mut labels = Vec::new();
3712
    for _ in 0..100 {
3713
        labels = db::issues::proposal_labels(&h.app.db, p.id).await.unwrap().into_iter().map(|l| l.name).collect::<Vec<String>>();
3714
        if labels.len() == 2 {
3715
            break;
3716
        }
3717
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3718
    }
3719
    assert!(labels.contains(&"upstream unverified".to_string()) && labels.contains(&"dependencies".to_string()), "{labels:?}");
3720
}
3721
3722
/// #134: when a proposal's target moves, its projected state is new; the
3723
/// hub runs the pipeline on it, so its checks are never for an older one.
3724
#[tokio::test(flavor = "multi_thread")]
3725
async fn a_moved_target_runs_its_open_proposals_again() {
3726
    let h = hub().await;
3727
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3728
    create(&h.app, "andy", "demo").await;
3729
    let work = tempfile::tempdir().unwrap();
3730
    let mut c = client(&format!("{}/andy/demo", h.base), work.path());
3731
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3732
    write(work.path(), "test.sh", "echo ok\n");
3733
    c.snapshot("t").unwrap();
3734
    let base = c.commit("base", &[]).unwrap();
3735
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3736
    // Two proposals, each main plus one change.
3737
    for (b, file) in [("fix-a", "a.txt"), ("fix-b", "b.txt")] {
3738
        c.bookmark_create(b, Some(&[base])).unwrap();
3739
        c.bookmark_switch(b, true).unwrap();
3740
        write(work.path(), file, "x\n");
3741
        c.snapshot("t").unwrap();
3742
        c.commit(&format!("add {file}"), &[]).unwrap();
3743
        assert!(c.push_bookmark("origin", b, false).unwrap().iter().all(|r| r.ok));
3744
        let body = serde_json::json!({ "title": b, "target": "main", "source": b }).to_string();
3745
        let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/demo/proposals", Some("site"), Some(body)).await;
3746
        assert_eq!(st, StatusCode::CREATED, "{out}");
3747
    }
3748
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
3749
    let props = db::proposals::list(&h.app.db, row.id, &["open"]).await.unwrap();
3750
    let a = props.iter().find(|p| p.source_bookmark == "fix-a").unwrap().number;
3751
    let b = props.iter().find(|p| p.source_bookmark == "fix-b").unwrap().number;
3752
    // Landing fix-a moves main: fix-b's projected state gets a run.
3753
    let (st, out) = call(&h.app, "POST", &format!("/api/v1/repos/andy/demo/proposals/{a}/land"), Some("site"), Some("{}".into())).await;
3754
    assert_eq!(st, StatusCode::OK, "{out}");
3755
    let label = format!("proposal/{b}");
3756
    let mut found = None;
3757
    for _ in 0..100 {
3758
        if let Some(r) = runs_of(&h.app, "andy", "demo").await.into_iter().find(|r| r.bookmark == label) {
3759
            found = Some(r);
3760
            break;
3761
        }
3762
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3763
    }
3764
    let run = found.expect("a run of fix-b's new projected state");
3765
    let projected = db::proposals::get(&h.app.db, row.id, b).await.unwrap().unwrap();
3766
    assert_eq!((run.trigger.as_str(), run.state.as_str()), ("proposal", projected.projected_state.as_str()), "on its projected state");
3767
    // Moving main again by a push does it once more; the same state is not run twice.
3768
    let before = runs_of(&h.app, "andy", "demo").await.len();
3769
    oxygenhub::web::proposals::settle_after_push(&h.app, &row, "main", "andy").await;
3770
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), before, "not again for the same state");
3771
}
3772
3773
/// Send image bytes to the hub as their chunks and then a manifest that
3774
/// names no architecture; the manifest as the hub answers it.
3775
async fn send_image(app: &Shared, image: &[u8]) -> (String, serde_json::Value) {
3776
    let mut chunks = std::collections::HashMap::new();
3777
    let m = jet::images::scan(image, None, |c, b| {
3778
        chunks.insert(c.hash().to_string(), b.to_vec());
3779
        Ok(())
3780
    })
3781
    .unwrap();
3782
    for c in m.needed() {
3783
        let (st, body) = put_bytes(app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
3784
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
3785
    }
3786
    let (st, body) =
3787
        call(app, "PUT", &format!("/api/v1/flow/images/{}", m.hash), Some("site"), Some(serde_json::to_string(&m).unwrap())).await;
3788
    assert_eq!(st, StatusCode::CREATED, "{body}");
3789
    (m.hash.clone(), serde_json::from_str(&body).unwrap())
3790
}
3791
3792
/// oxygenhub#173 (OxygenFlow spec §11.2, Andy's "detect and learn"): an
3793
/// image sent with no architecture is read from its own files, so a
3794
/// riscv64 runner is never offered an x86_64 image's jobs; an image
3795
/// nobody can read takes the architecture its first pass ran on.
3796
#[tokio::test(flavor = "multi_thread")]
3797
async fn an_image_names_its_own_architecture_and_a_pass_teaches_the_rest() {
3798
    use oxy_core::identity::SecretKey;
3799
    let h = hub().await;
3800
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3801
    // An ext4 image whose shell is x86_64, as `flow rootfs import` makes one.
3802
    let dir = tempfile::tempdir().unwrap();
3803
    let tree = dir.path().join("tree");
3804
    std::fs::create_dir_all(tree.join("bin")).unwrap();
3805
    let mut elf = vec![0u8; 64];
3806
    elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
3807
    elf[18..20].copy_from_slice(&0x3Eu16.to_le_bytes());
3808
    std::fs::write(tree.join("bin/sh"), &elf).unwrap();
3809
    let img = dir.path().join("rootfs.ext4");
3810
    let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
3811
    if !made.is_ok_and(|s| s.success()) {
3812
        eprintln!("mkfs.ext4 not found: skipped");
3813
        return;
3814
    }
3815
    let (x86, answer) = send_image(&h.app, &std::fs::read(&img).unwrap()).await;
3816
    assert_eq!(answer["arch"], "x86_64", "read from its shell: {answer}");
3817
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{x86}"), Some("runner-secret"), None).await;
3818
    assert_eq!(serde_json::from_str::<jet::images::Manifest>(&body).unwrap().arch.as_deref(), Some("x86_64"), "runners fetch it named");
3819
    // One nobody can read: no ext4, no shell.
3820
    let blob: Vec<u8> = (0..300_000u32).map(|i| (i % 241) as u8).collect();
3821
    let (unread, answer) = send_image(&h.app, &blob).await;
3822
    assert!(answer["arch"].is_null(), "{answer}");
3823
    let archs = db::flow::image_archs(&h.app.db).await.unwrap();
3824
    assert_eq!((archs.get(&x86).map(String::as_str), archs.get(&unread)), (Some("x86_64"), None));
3825
    // Kept images with none are read once at start.
3826
    sqlx::query("UPDATE jet_images SET arch = ''").execute(&h.app.db).await.unwrap();
3827
    sqlx::query("DELETE FROM flow_images").execute(&h.app.db).await.unwrap();
3828
    assert_eq!(oxygenhub::images::learn_archs(&h.app).await.unwrap(), 1);
3829
    assert_eq!(db::flow::image_archs(&h.app.db).await.unwrap().get(&x86).map(String::as_str), Some("x86_64"));
3830
3831
    // A job on each image.
3832
    create(&h.app, "andy", "arch").await;
3833
    let work = tempfile::tempdir().unwrap();
3834
    let c = client(&format!("{}/andy/arch", h.base), work.path());
3835
    let kdl = format!(
3836
        "schema-version 1\nsandbox \"unread\" {{\n    rootfs \"cas://blob/{unread}\"\n}}\nsandbox \"x86\" {{\n    rootfs \"cas://blob/{x86}\"\n}}\n\
3837
         job \"first\" {{\n    sandbox \"unread\"\n    exec \"make\"\n}}\njob \"second\" {{\n    sandbox \"x86\"\n    exec \"make\"\n    depends-on \"first\"\n}}\n\
3838
         job \"third\" {{\n    sandbox \"unread\"\n    exec \"make\"\n    depends-on \"first\"\n}}\n"
3839
    );
3840
    write(work.path(), ".flow/pipeline.kdl", &kdl);
3841
    c.commit("Jobs on two images", &[]).unwrap();
3842
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3843
    runs_of(&h.app, "andy", "arch").await;
3844
3845
    // The x86_64 runner passes the first job: its image is x86_64 now.
3846
    let x86_info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
3847
    let x86_claim =
3848
        serde_json::json!({ "runner": "earth", "runtimes": ["microvm"], "images": [], "fetches_images": true, "info": x86_info });
3849
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(x86_claim.to_string())).await;
3850
    assert_eq!(st, StatusCode::OK, "{body}");
3851
    let first: serde_json::Value = serde_json::from_str(&body).unwrap();
3852
    assert_eq!(first["job"]["name"], "first");
3853
    let ph = first["pipeline_hash"].as_str().unwrap();
3854
    let id = first["job_id"].as_i64().unwrap();
3855
    assert_eq!(
3856
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("first", ph, 0) })).await,
3857
        StatusCode::NO_CONTENT
3858
    );
3859
    assert_eq!(db::flow::image_archs(&h.app.db).await.unwrap().get(&unread).map(String::as_str), Some("x86_64"), "learned");
3860
3861
    // A riscv64 runner is offered neither: one read, one learned.
3862
    let token = "flowreg_narvi";
3863
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
3864
    let identity = SecretKey::generate().identity("narvi", "", 1);
3865
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
3866
    let reg = serde_json::json!({ "token": token, "name": "narvi", "identity": hex::encode(identity.encode()), "info": info });
3867
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
3868
    assert_eq!(st, StatusCode::OK, "{body}");
3869
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
3870
    let narvi =
3871
        serde_json::json!({ "runner": "narvi", "runtimes": ["microvm"], "images": [], "fetches_images": true, "info": info }).to_string();
3872
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(narvi)).await;
3873
    assert_eq!(st, StatusCode::NO_CONTENT, "the second job's image is x86_64 and the third's learned so: {body}");
3874
    for _ in 0..2 {
3875
        let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(x86_claim.to_string())).await;
3876
        assert_eq!(st, StatusCode::OK, "both go to x86_64: {body}");
3877
    }
3878
}
3879
3880
/// Diffusion auto-land (docs/diffusion.md §4.2; Andy chose "opt-in, per
3881
/// repository", 2026-10-13): a consumer that chose `land = auto` has a bump
3882
/// landed by itself, as the diffusion account, once both halves are green;
3883
/// a bump from an upstream with no checks (amber) always waits.
3884
#[tokio::test(flavor = "multi_thread")]
3885
async fn a_consumer_that_chose_auto_lands_green_bumps_itself() {
3886
    let h = hub().await;
3887
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3888
    create(&h.app, "andy", "api").await;
3889
    create(&h.app, "andy", "game").await;
3890
    let hub_app = &h.app;
3891
    // Run every queued job to a pass.
3892
    let pass_all = move || async move {
3893
        for _ in 0..20 {
3894
            let Some(a) = claim(hub_app).await else {
3895
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3896
                if !jobs_left(hub_app).await {
3897
                    break;
3898
                }
3899
                continue;
3900
            };
3901
            let id = a["job_id"].as_i64().unwrap();
3902
            let (name, ph) = (a["job"]["name"].as_str().unwrap().to_string(), a["pipeline_hash"].as_str().unwrap().to_string());
3903
            assert_eq!(
3904
                finish(hub_app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt(&name, &ph, 0) })).await,
3905
                StatusCode::NO_CONTENT
3906
            );
3907
        }
3908
    };
3909
    let api_work = tempfile::tempdir().unwrap();
3910
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
3911
    write(api_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3912
    write(api_work.path(), "test.sh", "echo ok\n");
3913
    api.snapshot("t").unwrap();
3914
    api.commit("api v1", &[]).unwrap();
3915
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3916
    pass_all().await;
3917
    let game_work = tempfile::tempdir().unwrap();
3918
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
3919
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3920
    write(game_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3921
    write(game_work.path(), "test.sh", "echo ok\n");
3922
    game.snapshot("t").unwrap();
3923
    game.commit("game on api v1", &[]).unwrap();
3924
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3925
    pass_all().await;
3926
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3927
    for _ in 0..100 {
3928
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
3929
            .bind(game_row.id)
3930
            .fetch_one(&h.app.db)
3931
            .await
3932
            .unwrap();
3933
        if n > 0 {
3934
            break;
3935
        }
3936
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3937
    }
3938
    let (st, body) =
3939
        call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(r#"{"follow":"green","land":"auto"}"#.into())).await;
3940
    assert_eq!(st, StatusCode::OK, "{body}");
3941
    assert!(body.contains(r#""land":"auto""#), "{body}");
3942
    let (st, _) =
3943
        call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(r#"{"follow":"green","land":"soon"}"#.into())).await;
3944
    assert_eq!(st, StatusCode::BAD_REQUEST);
3945
3946
    // The upstream moves and passes: the bump is proposed, its run passes,
3947
    // and it lands by itself.
3948
    write(api_work.path(), "a2.c", "v2\n");
3949
    api.snapshot("t").unwrap();
3950
    api.commit("api v2: faster sprites", &[]).unwrap();
3951
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3952
    let mut landed = None;
3953
    for _ in 0..100 {
3954
        pass_all().await;
3955
        let all = db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap();
3956
        if let Some(p) = all.into_iter().find(|p| p.source_bookmark == "diffusion/deps/api" && p.state == "landed") {
3957
            landed = Some(p);
3958
            break;
3959
        }
3960
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3961
    }
3962
    let p = landed.expect("landed by itself once both halves were green");
3963
    assert!(p.body.contains("lands its bumps itself"), "{}", p.body);
3964
    let events = db::proposals::events(&h.app.db, p.id).await.unwrap();
3965
    let landing = events.iter().find(|e| e.event == "landed").expect("a landing on the timeline");
3966
    assert_eq!(landing.actor, "diffusion");
3967
    assert!(landing.detail.contains("Diffusion, both halves green"), "{}", landing.detail);
3968
    // The game's main now pins api v2.
3969
    let mut behind = serde_json::Value::Null;
3970
    for _ in 0..100 {
3971
        let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
3972
        let list: Vec<serde_json::Value> = serde_json::from_str(&list).unwrap();
3973
        behind = list.iter().find(|c| c["name"] == "game").map(|c| c["behind"].clone()).unwrap_or_default();
3974
        if behind == 0 {
3975
            break;
3976
        }
3977
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3978
    }
3979
    assert_eq!(behind, 0, "main moved to the bump");
3980
3981
    // An upstream with no checks: its bump passes in the consumer, but
3982
    // amber never lands by itself, whatever the setting.
3983
    create(&h.app, "andy", "lib").await;
3984
    create(&h.app, "andy", "app").await;
3985
    let lib_work = tempfile::tempdir().unwrap();
3986
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
3987
    write(lib_work.path(), "lib.h", "v1\n");
3988
    lib.snapshot("t").unwrap();
3989
    lib.commit("lib v1", &[]).unwrap();
3990
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
3991
    let app_work = tempfile::tempdir().unwrap();
3992
    let app = client(&format!("{}/andy/app", h.base), app_work.path());
3993
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
3994
    let modules = std::fs::read_to_string(app_work.path().join(".oxymodules")).unwrap();
3995
    write(app_work.path(), ".oxymodules", &format!("{modules}follow = green\nland = auto\n"));
3996
    write(app_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3997
    write(app_work.path(), "test.sh", "echo ok\n");
3998
    app.snapshot("t").unwrap();
3999
    app.commit("app on lib", &[]).unwrap();
4000
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
4001
    pass_all().await;
4002
    let app_row = db::repos::get(&h.app.db, "andy", "app").await.unwrap().unwrap();
4003
    for _ in 0..100 {
4004
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
4005
            .bind(app_row.id)
4006
            .fetch_one(&h.app.db)
4007
            .await
4008
            .unwrap();
4009
        if n > 0 {
4010
            break;
4011
        }
4012
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4013
    }
4014
    write(lib_work.path(), "lib.c", "v2\n");
4015
    lib.snapshot("t").unwrap();
4016
    lib.commit("lib v2", &[]).unwrap();
4017
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4018
    let mut passed = false;
4019
    for _ in 0..100 {
4020
        pass_all().await;
4021
        let s: Option<String> = sqlx::query_scalar(
4022
            "SELECT status FROM flow_runs WHERE repo_id = $1 AND bookmark = 'diffusion/deps/lib' ORDER BY id DESC LIMIT 1",
4023
        )
4024
        .bind(app_row.id)
4025
        .fetch_optional(&h.app.db)
4026
        .await
4027
        .unwrap();
4028
        if s.as_deref() == Some("passed") {
4029
            passed = true;
4030
            break;
4031
        }
4032
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4033
    }
4034
    assert!(passed, "the app's run on the bump passed");
4035
    assert_eq!(oxygenhub::diffusion::auto_land(&h.app, &app_row, "deps/lib").await, Err(oxygenhub::diffusion::Held::Unverified));
4036
    let open = db::proposals::list(&h.app.db, app_row.id, &["open"]).await.unwrap();
4037
    assert!(open.iter().any(|p| p.source_bookmark == "diffusion/deps/lib"), "amber waits for a person");
4038
}
4039
4040
/// oxygenflow#31: one finished job runs again in the same run, with the
4041
/// jobs that depend on it; what it depends on keeps its result, so a flaky
4042
/// test reruns without its build. Not while the run is live, and only a
4043
/// job the run has.
4044
#[tokio::test(flavor = "multi_thread")]
4045
async fn one_job_reruns_with_what_depends_on_it() {
4046
    let h = hub().await;
4047
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4048
    create(&h.app, "andy", "flaky").await;
4049
    let work = tempfile::tempdir().unwrap();
4050
    let c = client(&format!("{}/andy/flaky", h.base), work.path());
4051
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4052
    write(work.path(), "test.sh", "echo ok\n");
4053
    c.commit("Add a pipeline", &[]).unwrap();
4054
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4055
    let run = runs_of(&h.app, "andy", "flaky").await[0].clone();
4056
    // build and lint pass; test fails, as a flaky one does.
4057
    let (st, _) =
4058
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/test/rerun", run.number), Some("site"), None).await;
4059
    assert_eq!(st, StatusCode::CONFLICT, "not while the run is live");
4060
    while let Some(j) = claim(&h.app).await {
4061
        let id = j["job_id"].as_i64().unwrap();
4062
        let (name, ph) = (j["job"]["name"].as_str().unwrap().to_string(), j["pipeline_hash"].as_str().unwrap().to_string());
4063
        let exit = if name == "test" { 1 } else { 0 };
4064
        let log = serde_json::json!({ "records": [{ "t": 1, "stream": "out", "text": format!("{name} ran") }] });
4065
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(log.to_string())).await;
4066
        assert_eq!(
4067
            finish(&h.app, id, serde_json::json!({ "exit_code": exit, "duration_ms": 10, "receipt": receipt(&name, &ph, exit as u32) }))
4068
                .await,
4069
            StatusCode::NO_CONTENT
4070
        );
4071
    }
4072
    let status = |n: &'static str| {
4073
        let (app, run_id) = (h.app.clone(), run.id);
4074
        async move { db::flow::jobs(&app.db, run_id).await.unwrap().into_iter().find(|j| j.name == n).unwrap() }
4075
    };
4076
    assert_eq!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().status, "failed");
4077
    let failed_test = status("test").await;
4078
4079
    // The test again: build and lint keep their results.
4080
    let (st, body) =
4081
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/test/rerun", run.number), Some("site"), None).await;
4082
    assert_eq!(st, StatusCode::OK, "{body}");
4083
    assert!(body.contains(r#""queued":1"#), "{body}");
4084
    assert_eq!(
4085
        (status("build").await.status, status("lint").await.status, status("test").await.status),
4086
        ("passed".into(), "passed".into(), "queued".into())
4087
    );
4088
    assert!(db::flow::log(&h.app.db, failed_test.id, 0, 100).await.unwrap().is_empty(), "its old log is gone");
4089
    assert!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().live());
4090
    let checks = checks_when(&h.app, run.repo_id, &run.state, 3).await;
4091
    assert_eq!(checks.iter().find(|c| c.name == "flow/test").map(|c| c.status.as_str()), Some("queued"));
4092
    let j = claim(&h.app).await.expect("the test, queued again");
4093
    assert_eq!(j["job"]["name"], "test");
4094
    let ph = j["pipeline_hash"].as_str().unwrap().to_string();
4095
    let id = j["job_id"].as_i64().unwrap();
4096
    assert_eq!(
4097
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("test", &ph, 0) })).await,
4098
        StatusCode::NO_CONTENT
4099
    );
4100
    assert_eq!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().status, "passed", "the run is whole again");
4101
    // Andy owns it: told it failed, then that it is fixed (#183).
4102
    let andy_id = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap().id;
4103
    let kinds: Vec<String> = db::notify::inbox(&h.app.db, andy_id, 20).await.unwrap().into_iter().map(|n| n.kind).collect();
4104
    assert!(kinds.contains(&"flow.failed".to_string()) && kinds.contains(&"flow.fixed".to_string()), "{kinds:?}");
4105
4106
    // The build again brings the test that depends on it; lint stays.
4107
    let (_, body) =
4108
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/build/rerun", run.number), Some("site"), None).await;
4109
    assert!(body.contains(r#""queued":2"#), "{body}");
4110
    assert_eq!(
4111
        (status("build").await.status, status("lint").await.status, status("test").await.status),
4112
        ("queued".into(), "passed".into(), "queued".into())
4113
    );
4114
    let (st, _) =
4115
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/deploy/rerun", run.number), Some("site"), None).await;
4116
    assert_eq!(st, StatusCode::CONFLICT, "live again, and no such job either way");
4117
}
4118
4119
/// oxygenflow#30: a failed run tells its pusher and the repository's
4120
/// watchers; a runner whose last five jobs ended in infrastructure errors
4121
/// is drained and the administrators told, counting only since an
4122
/// administrator last made it active.
4123
#[tokio::test(flavor = "multi_thread")]
4124
async fn failed_runs_are_told_and_an_erroring_runner_is_drained() {
4125
    let h = hub().await;
4126
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4127
    let bob = db::accounts::create_account(&h.app.db, "bob", "[email protected]", "x", "salt", false).await.unwrap();
4128
    create(&h.app, "andy", "alerts").await;
4129
    let row = db::repos::get(&h.app.db, "andy", "alerts").await.unwrap().unwrap();
4130
    db::notify::set_watch(&h.app.db, bob.id, row.id, true).await.unwrap();
4131
    let work = tempfile::tempdir().unwrap();
4132
    let c = client(&format!("{}/andy/alerts", h.base), work.path());
4133
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4134
    write(work.path(), "test.sh", "exit 1\n");
4135
    c.commit("Add a pipeline", &[]).unwrap();
4136
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4137
    let run = runs_of(&h.app, "andy", "alerts").await[0].clone();
4138
    sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&h.app.db).await.unwrap();
4139
    while let Some(j) = claim(&h.app).await {
4140
        let id = j["job_id"].as_i64().unwrap();
4141
        let (name, ph) = (j["job"]["name"].as_str().unwrap().to_string(), j["pipeline_hash"].as_str().unwrap().to_string());
4142
        let exit = if name == "test" { 1 } else { 0 };
4143
        finish(&h.app, id, serde_json::json!({ "exit_code": exit, "duration_ms": 10, "receipt": receipt(&name, &ph, exit as u32) })).await;
4144
    }
4145
    let told = |id: i64| {
4146
        let db = h.app.db.clone();
4147
        async move { db::notify::inbox(&db, id, 20).await.unwrap().into_iter().filter(|n| n.kind == "flow.failed").collect::<Vec<_>>() }
4148
    };
4149
    let (for_andy, for_bob) = (told(andy.id).await, told(bob.id).await);
4150
    assert_eq!((for_andy.len(), for_bob.len()), (1, 1), "the pusher and a watcher");
4151
    assert!(for_andy[0].title.contains(&format!("run #{} on main failed (test)", run.number)), "{}", for_andy[0].title);
4152
    assert_eq!(for_andy[0].url, format!("/andy/alerts/flow/{}", run.number));
4153
4154
    // Five infrastructure errors in a row drain the runner.
4155
    let runner_id = || {
4156
        let db = h.app.db.clone();
4157
        async move { sqlx::query_scalar::<_, i64>("SELECT id FROM flow_runners WHERE name = 'test-1'").fetch_one(&db).await.unwrap() }
4158
    };
4159
    let mut errors = 0;
4160
    while errors < 5 {
4161
        let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/alerts/flow/runs", Some("site"), Some("{}".into())).await;
4162
        assert_eq!(st, StatusCode::CREATED);
4163
        while let Some(j) = claim(&h.app).await {
4164
            let id = j["job_id"].as_i64().unwrap();
4165
            let st = finish(
4166
                &h.app,
4167
                id,
4168
                serde_json::json!({ "exit_code": null, "duration_ms": 10, "error": "the microVM did not start: /dev/kvm busy" }),
4169
            )
4170
            .await;
4171
            assert_eq!(st, StatusCode::NO_CONTENT);
4172
            errors += 1;
4173
            if errors == 5 {
4174
                break;
4175
            }
4176
        }
4177
    }
4178
    let state = |id: i64| {
4179
        let db = h.app.db.clone();
4180
        async move { db::runners::get(&db, id).await.unwrap().unwrap().state }
4181
    };
4182
    let id = runner_id().await;
4183
    assert_eq!(state(id).await, "draining");
4184
    let drained: Vec<_> =
4185
        db::notify::inbox(&h.app.db, andy.id, 50).await.unwrap().into_iter().filter(|n| n.kind == "flow.runner_drained").collect();
4186
    assert_eq!(drained.len(), 1, "the administrator is told");
4187
    assert!(drained[0].title.contains("/dev/kvm busy"), "{}", drained[0].title);
4188
    assert!(
4189
        !told(bob.id).await.is_empty()
4190
            && db::notify::inbox(&h.app.db, bob.id, 50).await.unwrap().iter().all(|n| n.kind != "flow.runner_drained")
4191
    );
4192
    // Made active again, past errors no longer count.
4193
    db::runners::set_state(&h.app.db, id, "active").await.unwrap();
4194
    assert_eq!(db::runners::erroring(&h.app.db, id, 5).await.unwrap(), None);
4195
}
4196
4197
/// #225: an ordinary user turns Flow on for their repository on their own
4198
/// runner, and the site's runners never take its jobs.
4199
#[tokio::test(flavor = "multi_thread")]
4200
async fn owners_run_flow_on_their_own_runners_only() {
4201
    use oxy_core::identity::SecretKey;
4202
    let h = hub().await;
4203
    let register = |name: &'static str| {
4204
        let app = h.app.clone();
4205
        async move {
4206
            let body = format!("username={name}&email={name}%40example.com&password=correct-horse-battery&setup=test-setup");
4207
            let res = oxygenhub::router(app)
4208
                .oneshot(
4209
                    Request::post("/register")
4210
                        .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
4211
                        .body(Body::from(body))
4212
                        .unwrap(),
4213
                )
4214
                .await
4215
                .unwrap();
4216
            res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string()
4217
        }
4218
    };
4219
    register("andy").await; // the first account: the site's administrator
4220
    let bob = register("bob").await;
4221
    create(&h.app, "bob", "game").await;
4222
    let web = |method: &'static str, path: &str, body: Option<String>| {
4223
        let (app, cookie, path) = (h.app.clone(), bob.clone(), path.to_string());
4224
        async move {
4225
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
4226
            if body.is_some() {
4227
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
4228
            }
4229
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
4230
            String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned()
4231
        }
4232
    };
4233
    let csrf_of = |page: &str| {
4234
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
4235
        page[i..].split('"').next().unwrap().to_string()
4236
    };
4237
    // No runner of his own yet: he is told how, and cannot switch it on.
4238
    let page = web("GET", "/bob/game/settings", None).await;
4239
    assert!(page.contains("register a runner for this repository") && !page.contains("value=\"own\""), "{page}");
4240
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=own", csrf_of(&page)))).await;
4241
    assert!(page.contains("Register a runner for this repository"), "{page}");
4242
    // He registers one.
4243
    let page = web("GET", "/bob/game/settings", None).await;
4244
    let page = web("POST", "/bob/game/settings/runners/token", Some(format!("_csrf={}", csrf_of(&page)))).await;
4245
    let i = page.find("--token ").unwrap() + "--token ".len();
4246
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
4247
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
4248
    let identity = SecretKey::generate().identity("bobs", "", 1);
4249
    let reg = serde_json::json!({ "token": token, "name": "bobs", "identity": hex::encode(identity.encode()), "info": info });
4250
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
4251
    assert_eq!(st, StatusCode::OK, "{body}");
4252
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
4253
    // The site's runners stay a site administrator's to grant; his own he may choose.
4254
    let page = web("GET", "/bob/game/settings", None).await;
4255
    assert!(page.contains("value=\"own\"") && !page.contains("value=\"on\""), "{page}");
4256
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=on", csrf_of(&page)))).await;
4257
    assert!(page.contains("Only site administrators let the site's runners"), "{page}");
4258
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=own", csrf_of(&page)))).await;
4259
    assert!(page.contains("value=\"own\" checked") && page.contains("start runs"), "{page}");
4260
    assert_eq!(db::repos::get(&h.app.db, "bob", "game").await.unwrap().unwrap().flow, "own");
4261
    // A push starts a run; the site's runner is not offered it, his is.
4262
    let work = tempfile::tempdir().unwrap();
4263
    let c = client(&format!("{}/bob/game", h.base), work.path());
4264
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4265
    write(work.path(), "test.sh", "echo ok\n");
4266
    c.snapshot("t").unwrap();
4267
    c.commit("A pipeline", &[]).unwrap();
4268
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4269
    assert_eq!(runs_of(&h.app, "bob", "game").await.len(), 1, "a run started");
4270
    assert!(claim(&h.app).await.is_none(), "the site's runner is not offered it");
4271
    let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
4272
    let (st, job) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(body)).await;
4273
    assert_eq!(st, StatusCode::OK, "{job}");
4274
    assert_eq!(serde_json::from_str::<serde_json::Value>(&job).unwrap()["repo"], "bob/game");
4275
}
4276
4277
#[tokio::test(flavor = "multi_thread")]
4278
async fn a_job_takes_the_artifact_its_producer_kept() {
4279
    let h = hub().await;
4280
    create(&h.app, "andy", "demo").await;
4281
    let url = format!("{}/andy/demo", h.base);
4282
    let work = tempfile::tempdir().unwrap();
4283
    let c = client(&url, work.path());
4284
    write(
4285
        work.path(),
4286
        ".flow/pipeline.kdl",
4287
        &format!(
4288
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"plan\" {{\n    sandbox \"alpine\"\n    exec \"plan\"\n    output {{\n        artifact \"tfplan\" {{\n            path \"/src/out/tfplan\"\n        }}\n    }}\n}}\njob \"apply\" {{\n    sandbox \"alpine\"\n    depends-on \"plan\"\n    input {{\n        artifact \"tfplan\" from \"plan\"\n        path \"/src/tfplan\"\n    }}\n    exec \"apply\"\n}}\n"
4289
        ),
4290
    );
4291
    c.snapshot("test").unwrap();
4292
    c.commit("Plan, then apply that plan", &[]).unwrap();
4293
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4294
4295
    // The plan job runs and keeps its plan, named by its receipt.
4296
    let runs = runs_of(&h.app, "andy", "demo").await;
4297
    assert_eq!(runs.len(), 1, "a run");
4298
    let jobs = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap();
4299
    assert!(!jobs.is_empty(), "jobs: {:?}", runs[0]);
4300
    let p = claim(&h.app)
4301
        .await
4302
        .unwrap_or_else(|| panic!("nothing to claim: {:?}", jobs.iter().map(|j| (&j.name, &j.status, &j.error)).collect::<Vec<_>>()));
4303
    assert_eq!(p["job"]["name"], "plan");
4304
    let plan_id = p["job_id"].as_i64().unwrap();
4305
    let plan = b"the reviewed plan".to_vec();
4306
    let (st, text) = upload(&h.app, plan_id, "tfplan", &plan).await;
4307
    assert_eq!(st, StatusCode::OK, "{text}");
4308
    let blob = oxy_core::repo::Repo::blob_ref(&plan).to_hex();
4309
    let mut r = receipt("plan", p["pipeline_hash"].as_str().unwrap(), 0);
4310
    r["outputs"] = serde_json::json!([blob]);
4311
    assert_eq!(
4312
        finish(&h.app, plan_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r })).await,
4313
        StatusCode::NO_CONTENT
4314
    );
4315
4316
    // The apply job is told what to take and the blob to expect, and the
4317
    // runner fetches exactly those bytes.
4318
    let a = claim(&h.app).await.unwrap();
4319
    assert_eq!(a["job"]["name"], "apply");
4320
    let apply_id = a["job_id"].as_i64().unwrap();
4321
    assert_eq!(
4322
        a["inputs"],
4323
        serde_json::json!([{ "artifact": "tfplan", "from": "plan", "path": "/src/tfplan", "blob": blob }]),
4324
        "the claim names the producer's blob"
4325
    );
4326
    let req = Request::get(format!("/api/v1/flow/jobs/{apply_id}/inputs/0")).header(header::AUTHORIZATION, "Bearer runner-secret");
4327
    let res = oxygenhub::router(h.app.clone()).oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
4328
    assert_eq!(res.status(), StatusCode::OK);
4329
    assert_eq!(res.into_body().collect().await.unwrap().to_bytes().to_vec(), plan);
4330
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{apply_id}/inputs/1"), Some("runner-secret"), None).await;
4331
    assert_eq!(st, StatusCode::NOT_FOUND, "no second input");
4332
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{apply_id}/inputs/0"), None, None).await;
4333
    assert_eq!(st, StatusCode::UNAUTHORIZED, "runners only");
4334
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{plan_id}/inputs/0"), Some("runner-secret"), None).await;
4335
    assert_eq!(st, StatusCode::CONFLICT, "only a running job's");
4336
}
4337
4338
#[tokio::test(flavor = "multi_thread")]
4339
async fn a_job_waits_for_approval_and_is_approved_rejected_or_expires() {
4340
    let h = hub().await;
4341
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4342
    let bob = db::accounts::create_account(&h.app.db, "bob", "[email protected]", "x", "salt", false).await.unwrap();
4343
    let carol = db::accounts::create_account(&h.app.db, "carol", "[email protected]", "x", "salt", true).await.unwrap();
4344
    create(&h.app, "andy", "gated").await;
4345
    let row = db::repos::get(&h.app.db, "andy", "gated").await.unwrap().unwrap();
4346
    let work = tempfile::tempdir().unwrap();
4347
    let c = client(&format!("{}/andy/gated", h.base), work.path());
4348
    write(
4349
        work.path(),
4350
        ".flow/pipeline.kdl",
4351
        &format!(
4352
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"plan\" {{\n    sandbox \"alpine\"\n    exec \"plan\"\n}}\njob \"apply\" {{\n    sandbox \"alpine\"\n    depends-on \"plan\"\n    approval {{\n        by \"maintain\"\n        others-only #true\n        sealed #false\n    }}\n    environment \"prod\"\n    identity \"https://sts.example\" {{\n        mount-path \"/run/secrets/cloud\"\n    }}\n    exec \"apply\"\n}}\n"
4353
        ),
4354
    );
4355
    let mut n = 0;
4356
    let mut push = || {
4357
        n += 1;
4358
        write(work.path(), "n.txt", &format!("{n}\n"));
4359
        c.snapshot("test").unwrap();
4360
        c.commit(&format!("Push {n}"), &[]).unwrap();
4361
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4362
    };
4363
    // Runs `plan` to a pass; returns the run, its actor set to andy.
4364
    let plan_passes = |number: i64| {
4365
        let app = h.app.clone();
4366
        let row = row.clone();
4367
        async move {
4368
            let mut run = None;
4369
            for _ in 0..100 {
4370
                if let Some(r) = db::flow::run(&app.db, row.id, number).await.unwrap() {
4371
                    run = Some(r);
4372
                    break;
4373
                }
4374
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4375
            }
4376
            let run = run.expect("the run");
4377
            sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&app.db).await.unwrap();
4378
            let j = claim(&app).await.expect("plan is claimed");
4379
            assert_eq!(j["job"]["name"], "plan");
4380
            let (id, ph) = (j["job_id"].as_i64().unwrap(), j["pipeline_hash"].as_str().unwrap().to_string());
4381
            finish(&app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("plan", &ph, 0) })).await;
4382
            db::flow::run(&app.db, row.id, number).await.unwrap().unwrap()
4383
        }
4384
    };
4385
4386
    // Run 1: apply waits; only someone with the role, other than the pusher, approves it.
4387
    push();
4388
    let run = runs_of(&h.app, "andy", "gated").await[0].clone();
4389
    // Live pages hear of the push (oxygenhub#203).
4390
    let heard = |topic: String| match h.app.events.live.since(0, &[topic]) {
4391
        oxygenhub::events::Replay::Events(e) => e.into_iter().map(|e| e.kind).collect::<Vec<_>>(),
4392
        oxygenhub::events::Replay::Reload => vec!["reload".into()],
4393
    };
4394
    assert!(heard(oxygenhub::events::topic::repo(row.id)).contains(&"push".to_string()), "the push is on the repository's topic");
4395
    sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&h.app.db).await.unwrap();
4396
    let early = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true).await.unwrap_err();
4397
    assert!(early.contains("waits for plan first"), "{early}");
4398
    let run = plan_passes(run.number).await;
4399
    assert!(claim(&h.app).await.is_none(), "apply waits for a person, so no runner gets it");
4400
    assert!(heard(oxygenhub::events::topic::run(run.id)).contains(&"jobs".to_string()), "the run's topic hears its jobs");
4401
    // Those who may approve are told, once; the pusher (others-only) and
4402
    // someone without the role are not.
4403
    let told = |id: i64| {
4404
        let db = h.app.db.clone();
4405
        async move { db::notify::inbox(&db, id, 20).await.unwrap().into_iter().filter(|n| n.kind == "flow.approval").count() }
4406
    };
4407
    assert_eq!((told(carol.id).await, told(andy.id).await, told(bob.id).await), (1, 0, 0));
4408
    let (_, page) = call(&h.app, "GET", &format!("/andy/gated/flow/{}", run.number), None, None).await;
4409
    assert!(page.contains("waits for approval by someone with the <em>maintain</em> role, other than andy"), "the run page says so");
4410
    let own = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &andy, true).await.unwrap_err();
4411
    assert!(own.contains("someone other than andy"), "{own}");
4412
    let no_role = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &bob, true).await.unwrap_err();
4413
    assert!(no_role.contains("takes the maintain role"), "{no_role}");
4414
    assert_eq!(oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true).await.unwrap(), "apply: approved by carol");
4415
    assert_eq!(told(carol.id).await, 1, "told once");
4416
    let j = claim(&h.app).await.expect("approved, it runs");
4417
    assert_eq!(j["job"]["name"], "apply");
4418
    // Approved, its identity token names the environment (oxygenflow#59).
4419
    let token =
4420
        j["secrets"].as_array().unwrap().iter().find(|s| s["path"] == "/run/secrets/cloud").unwrap()["value"].as_str().unwrap().to_string();
4421
    let claims = h.app.oidc().await.unwrap().verify(&token, "https://sts.example", db::now_ms()).expect("a valid token");
4422
    assert_eq!(claims["environment"], "prod");
4423
    let (id, ph) = (j["job_id"].as_i64().unwrap(), j["pipeline_hash"].as_str().unwrap().to_string());
4424
    finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("apply", &ph, 0) })).await;
4425
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
4426
    assert!(audit.iter().any(|r| r.action == "flow.approved" && r.actor == "carol" && r.target.ends_with("#1 apply")), "audited");
4427
    let (_, page) = call(&h.app, "GET", &format!("/andy/gated/flow/{}", run.number), None, None).await;
4428
    assert!(page.contains("approved by carol"), "the run says who");
4429
    let (_, page) = call(&h.app, "GET", "/andy/gated/deployments", None, None).await;
4430
    assert!(page.contains("<strong>prod</strong>") && page.contains(">#1</a>") && page.contains("<td>carol</td>"), "the Deployments page");
4431
    let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/gated/deployments", Some("site"), None).await;
4432
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
4433
    assert_eq!((list[0]["environment"].as_str(), list[0]["approved_by"].as_str()), (Some("prod"), Some("carol")));
4434
4435
    // Run 2: rejected through the API's rules: the job ends cancelled, the run ends.
4436
    push();
4437
    let run = plan_passes(2).await;
4438
    assert_eq!(oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, false).await.unwrap(), "apply: rejected by carol");
4439
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
4440
    let apply = jobs.iter().find(|j| j.name == "apply").unwrap();
4441
    assert_eq!((apply.status.as_str(), apply.error.as_str()), ("cancelled", "rejected by carol"));
4442
    assert!(claim(&h.app).await.is_none());
4443
4444
    // Run 3: nobody decides in time.
4445
    push();
4446
    let run = plan_passes(3).await;
4447
    assert_eq!(oxygenhub::flow::expire_approvals(&h.app, db::now_ms() + 3_600_000).await.unwrap(), 0, "not yet");
4448
    assert_eq!(oxygenhub::flow::expire_approvals(&h.app, db::now_ms() + 25 * 3_600_000).await.unwrap(), 1);
4449
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
4450
    let apply = jobs.iter().find(|j| j.name == "apply").unwrap();
4451
    assert_eq!((apply.status.as_str(), apply.error.as_str()), ("cancelled", "no approval within 24h"));
4452
}
4453
4454
#[tokio::test(flavor = "multi_thread")]
4455
async fn live_streams_only_topics_the_viewer_may_hear_and_replays() {
4456
    let h = hub().await;
4457
    create(&h.app, "andy", "open").await;
4458
    h.app.repos.create(&RepoName::parse("andy/shut").unwrap(), None).unwrap();
4459
    db::repos::create(&h.app.db, "andy", "shut", "", hub_api::Visibility::Private).await.unwrap();
4460
    let open = db::repos::get(&h.app.db, "andy", "open").await.unwrap().unwrap();
4461
    let shut = db::repos::get(&h.app.db, "andy", "shut").await.unwrap().unwrap();
4462
    let live = &h.app.events.live;
4463
    let first = live.publish(&oxygenhub::events::topic::repo(open.id), "push");
4464
    live.publish(&oxygenhub::events::topic::repo(shut.id), "push");
4465
    live.publish(&oxygenhub::events::topic::proposal(open.id, 3), "review");
4466
4467
    // The first bytes of a stream, within a moment.
4468
    let read = |path: String, last: Option<u64>| {
4469
        let app = h.app.clone();
4470
        async move {
4471
            let mut req = Request::get(&path);
4472
            if let Some(l) = last {
4473
                req = req.header("last-event-id", l.to_string());
4474
            }
4475
            let res = oxygenhub::router(app).oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
4476
            let status = res.status();
4477
            let mut body = res.into_body();
4478
            let mut text = String::new();
4479
            while let Ok(Some(Ok(frame))) = tokio::time::timeout(std::time::Duration::from_millis(300), body.frame()).await {
4480
                if let Some(d) = frame.data_ref() {
4481
                    text.push_str(&String::from_utf8_lossy(d));
4482
                }
4483
            }
4484
            (status, text)
4485
        }
4486
    };
4487
    let topics = format!("/live?topics=repo:{},repo:{}/proposal:3", open.id, open.id);
4488
    // From the first event on: what came after it on these topics only.
4489
    let (st, text) = read(topics.clone(), Some(first.id)).await;
4490
    assert_eq!(st, StatusCode::OK);
4491
    assert!(text.contains("event: change") && text.contains(&format!("\"topic\":\"repo:{}/proposal:3\"", open.id)), "{text}");
4492
    assert!(!text.contains(&format!("\"topic\":\"repo:{}\"", shut.id)), "never another topic: {text}");
4493
    assert!(!text.contains(&format!("id: {}\n", first.id)), "not what was already seen: {text}");
4494
    // A private repository's topic, or someone else's, is refused whole.
4495
    let (st, _) = read(format!("/live?topics=repo:{},repo:{}", open.id, shut.id), None).await;
4496
    assert_eq!(st, StatusCode::FORBIDDEN);
4497
    assert_eq!(read("/live?topics=user:1".into(), None).await.0, StatusCode::FORBIDDEN);
4498
    assert_eq!(read("/live?topics=nonsense".into(), None).await.0, StatusCode::BAD_REQUEST);
4499
    assert_eq!(read("/live?topics=".into(), None).await.0, StatusCode::BAD_REQUEST);
4500
    // Too far behind: told to reload.
4501
    for _ in 0..oxygenhub::events::REPLAY {
4502
        live.publish("repo:999999", "push");
4503
    }
4504
    let (_, text) = read(topics, Some(first.id)).await;
4505
    assert!(text.contains("event: reload"), "{text}");
4506
}
4507
4508
#[tokio::test(flavor = "multi_thread")]
4509
async fn a_sealed_approval_releases_exactly_the_reviewed_plan() {
4510
    use oxy_core::approval::{SignedApproval, Statement};
4511
    use oxy_core::hash::ObjectRef;
4512
    use oxy_core::identity::SecretKey;
4513
    let h = hub().await;
4514
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4515
    let carol = db::accounts::create_account(&h.app.db, "carol", "[email protected]", "x", "salt", true).await.unwrap();
4516
    let sk = SecretKey::generate();
4517
    let carol_id = sk.identity("Carol", "[email protected]", 1);
4518
    db::accounts::link_identity(&h.app.db, carol.id, &carol_id.hash().to_hex(), "Carol", "[email protected]", &carol_id.encode())
4519
        .await
4520
        .unwrap();
4521
    create(&h.app, "andy", "infra").await;
4522
    let row = db::repos::get(&h.app.db, "andy", "infra").await.unwrap().unwrap();
4523
    let work = tempfile::tempdir().unwrap();
4524
    let c = client(&format!("{}/andy/infra", h.base), work.path());
4525
    write(
4526
        work.path(),
4527
        ".flow/pipeline.kdl",
4528
        &format!(
4529
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"plan\" {{\n    sandbox \"alpine\"\n    exec \"plan\"\n    output {{\n        artifact \"tfplan\" {{\n            path \"/src/out/tfplan\"\n        }}\n    }}\n}}\njob \"apply\" {{\n    sandbox \"alpine\"\n    depends-on \"plan\"\n    environment \"prod\"\n    approval\n    input {{\n        artifact \"tfplan\" from \"plan\"\n        path \"/src/tfplan\"\n    }}\n    identity \"https://sts.example\" {{\n        mount-path \"/run/secrets/cloud\"\n    }}\n    exec \"apply\"\n}}\n"
4530
        ),
4531
    );
4532
    c.snapshot("test").unwrap();
4533
    c.commit("Plan, then apply", &[]).unwrap();
4534
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4535
    let run = runs_of(&h.app, "andy", "infra").await[0].clone();
4536
    let p = claim(&h.app).await.unwrap();
4537
    let plan_id = p["job_id"].as_i64().unwrap();
4538
    let plan = b"the reviewed plan".to_vec();
4539
    upload(&h.app, plan_id, "tfplan", &plan).await;
4540
    let mut r = receipt("plan", p["pipeline_hash"].as_str().unwrap(), 0);
4541
    r["outputs"] = serde_json::json!([oxy_core::repo::Repo::blob_ref(&plan).to_hex()]);
4542
    finish(&h.app, plan_id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": r })).await;
4543
    let run = db::flow::run(&h.app.db, row.id, run.number).await.unwrap().unwrap();
4544
4545
    // An environment's gate takes a sealed approval: pressing Approve is not enough.
4546
    let plain = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true).await.unwrap_err();
4547
    assert!(plain.contains(&format!("oxy seal --flow {}/andy/infra/flow/{} --job apply", h.base, run.number)), "{plain}");
4548
    // What there is to sign.
4549
    let (st, body) =
4550
        call(&h.app, "GET", &format!("/api/v1/repos/andy/infra/flow/runs/{}/jobs/apply/approval", run.number), Some("site"), None).await;
4551
    assert_eq!(st, StatusCode::OK, "{body}");
4552
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
4553
    assert_eq!(v["environment"], "prod");
4554
    assert_eq!(v["inputs"], serde_json::json!([oxy_core::repo::Repo::blob_ref(&plan).to_hex()]), "the reviewed plan");
4555
    let mut repo = [0u8; 16];
4556
    repo.copy_from_slice(&hex::decode(v["repo"].as_str().unwrap()).unwrap());
4557
    let oref = |k: &str| ObjectRef::from_hex(v[k].as_str().unwrap()).unwrap();
4558
    let statement = Statement {
4559
        repo,
4560
        run: v["run"].as_str().unwrap().into(),
4561
        job: "apply".into(),
4562
        job_hash: oref("job_hash"),
4563
        state: oref("state"),
4564
        inputs: v["inputs"].as_array().unwrap().iter().map(|i| ObjectRef::from_hex(i.as_str().unwrap()).unwrap()).collect(),
4565
        environment: "prod".into(),
4566
        approve: true,
4567
    };
4568
    let seal = |s: &Statement, key: &SecretKey, id: &oxy_core::identity::Identity| {
4569
        let body = serde_json::json!({ "signed": hex::encode(SignedApproval::sign(s, id, key).encode()) }).to_string();
4570
        let app = h.app.clone();
4571
        let path = format!("/api/v1/repos/andy/infra/flow/runs/{}/jobs/apply/seal", run.number);
4572
        async move { call(&app, "POST", &path, Some("site"), Some(body)).await }
4573
    };
4574
    // Another plan, or a key linked to nobody (an agent's), is refused.
4575
    let other_plan = Statement { inputs: vec![ObjectRef([9; 32])], ..statement.clone() };
4576
    let (st, body) = seal(&other_plan, &sk, &carol_id).await;
4577
    assert!(st == StatusCode::CONFLICT && body.contains("approves something else"), "{st} {body}");
4578
    let agent = SecretKey::generate();
4579
    let agent_id = agent.identity("Claude Code", "[email protected]", 1);
4580
    let (st, body) = seal(&statement, &agent, &agent_id).await;
4581
    assert!(st == StatusCode::CONFLICT && body.contains("not linked to an account"), "{st} {body}");
4582
    assert!(claim(&h.app).await.is_none(), "still waiting");
4583
4584
    // Carol's seal releases it; it is kept in the repository; the token names her and it.
4585
    let (st, body) = seal(&statement, &sk, &carol_id).await;
4586
    assert_eq!(st, StatusCode::OK, "{body}");
4587
    assert!(body.contains("approved by carol, sealed"), "{body}");
4588
    let name = oxygenhub::repos::RepoName::parse("andy/infra").unwrap();
4589
    let state = statement.state;
4590
    let kept = h.app.repos.read(&name, move |r, _| Ok(r.store().approvals_for(&state)?)).await.unwrap();
4591
    assert_eq!(kept.len(), 1, "the approval is in the repository");
4592
    let j = claim(&h.app).await.expect("released");
4593
    assert_eq!(j["job"]["name"], "apply");
4594
    let token =
4595
        j["secrets"].as_array().unwrap().iter().find(|s| s["path"] == "/run/secrets/cloud").unwrap()["value"].as_str().unwrap().to_string();
4596
    let claims = h.app.oidc().await.unwrap().verify(&token, "https://sts.example", db::now_ms()).unwrap();
4597
    assert_eq!((claims["environment"].as_str(), claims["approved_by"].as_str()), (Some("prod"), Some("carol")));
4598
    assert_eq!(claims["approval"].as_str(), Some(kept[0].to_hex().as_str()));
4599
    let (_, page) = call(&h.app, "GET", &format!("/andy/infra/flow/{}", run.number), None, None).await;
4600
    assert!(page.contains("sealed with their key"), "the run page says so");
4601
}
4602
4603
/// Repositories take turns (oxygenhub#244): a repository with a job running
4604
/// waits behind one with none, so a burst can't hold up the rest.
4605
#[tokio::test(flavor = "multi_thread")]
4606
async fn repositories_take_turns_on_the_runners() {
4607
    let h = hub().await;
4608
    for name in ["busy", "quiet"] {
4609
        create(&h.app, "andy", name).await;
4610
        let work = tempfile::tempdir().unwrap();
4611
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
4612
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4613
        write(work.path(), "test.sh", "echo ok\n");
4614
        c.snapshot("test").unwrap();
4615
        c.commit("Add a pipeline", &[]).unwrap();
4616
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4617
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
4618
    }
4619
    // busy pushed first: its first job goes first; then quiet's turn, though
4620
    // busy's other independent job is older; then busy's again.
4621
    let order: Vec<String> = {
4622
        let mut out = Vec::new();
4623
        for _ in 0..3 {
4624
            let c = claim(&h.app).await.expect("a job to claim");
4625
            out.push(c["repo"].as_str().unwrap().to_string());
4626
        }
4627
        out
4628
    };
4629
    assert_eq!(order, ["andy/busy", "andy/quiet", "andy/busy"]);
4630
}
4631
4632
/// A pipeline lowers its jobs, never raises them (oxygenhub#244): a
4633
/// repository whose pipeline says `priority "low"` waits for another's
4634
/// everyday jobs, even set high itself; the queue says why; an expedited
4635
/// run is still urgent.
4636
#[tokio::test(flavor = "multi_thread")]
4637
async fn a_pipeline_lowers_its_jobs_and_expediting_still_wins() {
4638
    let h = hub().await;
4639
    for (name, extra) in [("nightly", "priority \"low\"\n"), ("everyday", "")] {
4640
        create(&h.app, "andy", name).await;
4641
        let work = tempfile::tempdir().unwrap();
4642
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
4643
        write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
4644
        write(work.path(), "test.sh", "echo ok\n");
4645
        c.snapshot("test").unwrap();
4646
        c.commit("Add a pipeline", &[]).unwrap();
4647
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4648
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
4649
    }
4650
    let nightly = db::repos::get(&h.app.db, "andy", "nightly").await.unwrap().unwrap();
4651
    db::repos::set_flow_priority(&h.app.db, nightly.id, "high").await.unwrap();
4652
    let q = db::flow::queue(&h.app.db).await.unwrap();
4653
    assert!(
4654
        q.iter().filter(|e| e.name == "nightly").all(|e| e.priority() == "low" && e.priority_note == "pipeline: low"),
4655
        "{:?}",
4656
        q.iter().map(|e| (&e.name, e.priority(), &e.priority_note)).collect::<Vec<_>>()
4657
    );
4658
    let repo_of = |c: serde_json::Value| c["repo"].as_str().unwrap().to_string();
4659
    // nightly pushed first and its repository is high, but its pipeline
4660
    // says low: everyday's jobs go first.
4661
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/everyday");
4662
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/everyday");
4663
    let run = &runs_of(&h.app, "andy", "nightly").await[0];
4664
    assert!(db::flow::expedite(&h.app.db, run.id, "expedited by andy: needed now").await.unwrap());
4665
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/nightly", "an expedited run is urgent whatever its jobs say");
4666
}
4667
4668
/// Priority comes before taking turns (oxygenhub#244): a low repository's
4669
/// jobs wait for a normal one's, and an expedited run goes first of all.
4670
#[tokio::test(flavor = "multi_thread")]
4671
async fn priority_then_turns_and_an_expedited_run_first() {
4672
    let h = hub().await;
4673
    for name in ["early", "later"] {
4674
        create(&h.app, "andy", name).await;
4675
        let work = tempfile::tempdir().unwrap();
4676
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
4677
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4678
        write(work.path(), "test.sh", "echo ok\n");
4679
        c.snapshot("test").unwrap();
4680
        c.commit("Add a pipeline", &[]).unwrap();
4681
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4682
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
4683
    }
4684
    let early = db::repos::get(&h.app.db, "andy", "early").await.unwrap().unwrap();
4685
    db::repos::set_flow_priority(&h.app.db, early.id, "low").await.unwrap();
4686
    // early pushed first, but it is low: later's jobs go first.
4687
    let repo_of = |c: serde_json::Value| c["repo"].as_str().unwrap().to_string();
4688
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/later");
4689
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/later");
4690
    // Expedited, early's run goes before anything else.
4691
    let run = &runs_of(&h.app, "andy", "early").await[0];
4692
    assert!(db::flow::expedite(&h.app.db, run.id, "expedited by andy: an incident").await.unwrap());
4693
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/early");
4694
    let q = db::flow::queue(&h.app.db).await.unwrap();
4695
    assert!(
4696
        q.iter().any(|e| e.name == "early" && e.priority() == "urgent" && e.priority_note.contains("an incident")),
4697
        "{:?}",
4698
        q.iter().map(|e| (&e.name, e.priority())).collect::<Vec<_>>()
4699
    );
4700
    // The site's level is the default for everyone else.
4701
    db::accounts::set_setting(&h.app.db, "flow_priority", "high").await.unwrap();
4702
    let q = db::flow::queue(&h.app.db).await.unwrap();
4703
    assert!(q.iter().filter(|e| e.name == "later").all(|e| e.priority() == "high"));
4704
}
4705
4706
/// Keyless (oxygenhub#241): a running job's token gets a ten-minute
4707
/// certificate for a fresh key from the hub, signed with the hub's key and
4708
/// naming the job's repository and bookmark; a proof made for another
4709
/// credential, an OIDC token for another audience, and a finished job's
4710
/// token get nothing.
4711
#[tokio::test(flavor = "multi_thread")]
4712
async fn a_running_job_gets_a_short_certificate_for_a_fresh_key() {
4713
    use oxy_core::cert::{certify_challenge, SignedCertificate};
4714
    use oxy_core::identity::{Scope, SecretKey};
4715
    let h = hub().await;
4716
    create(&h.app, "andy", "demo").await;
4717
    let work = tempfile::tempdir().unwrap();
4718
    let c = client(&format!("{}/andy/demo", h.base), work.path());
4719
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4720
    write(work.path(), "test.sh", "echo ok\n");
4721
    c.snapshot("test").unwrap();
4722
    c.commit("Add a pipeline", &[]).unwrap();
4723
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4724
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
4725
    let job = claim(&h.app).await.expect("a job");
4726
    let token = job["token"].as_str().unwrap().to_string();
4727
    let job_id = job["job_id"].as_i64().unwrap();
4728
4729
    let sk = SecretKey::generate();
4730
    let id = sk.identity("job", "[email protected]", 1);
4731
    let ask = |credential: &str, signed_for: &str| {
4732
        let proof = sk.sign_challenge(&id.hash(), &certify_challenge(signed_for)).unwrap();
4733
        let body = serde_json::json!({
4734
            "identity": oxy_core::dsse::base64(&id.encode()),
4735
            "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
4736
            "scope": "changes,refs",
4737
        });
4738
        let (credential, app) = (credential.to_string(), h.app.clone());
4739
        async move { call(&app, "POST", "/api/v1/keyless/certify", Some(&credential), Some(body.to_string())).await }
4740
    };
4741
    let (st, body) = ask(&token, &token).await;
4742
    assert_eq!(st, StatusCode::OK, "{body}");
4743
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
4744
    let sc = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
4745
    assert!(sc.verify(&h.app.hub_key.identity).is_ok(), "signed with the hub's key");
4746
    assert_eq!(sc.cert.key_id(), id.hash());
4747
    assert_eq!(sc.cert.subject, "repo:andy/demo:bookmark:main");
4748
    assert_eq!(sc.cert.claim("repository"), Some("andy/demo"));
4749
    assert!(sc.cert.claim("job").is_some() && sc.cert.claim("run") == Some("1"));
4750
    assert_eq!(sc.cert.scope, Scope::CHANGES | Scope::REFS);
4751
    assert!(sc.cert.expires - sc.cert.not_before <= 10 * 60_000 + 30_000, "ten minutes");
4752
4753
    // A proof made for another credential is not this one's.
4754
    let (st, body) = ask(&token, "flowjob_someone_else").await;
4755
    assert_eq!(st, StatusCode::UNAUTHORIZED, "{body}");
4756
    assert!(body.contains("the proof does not show"), "{body}");
4757
4758
    // The hub's own OIDC token, for the keyless audience, works too; for
4759
    // another audience it does not.
4760
    let issuer = h.app.oidc().await.unwrap();
4761
    let now = oxygenhub::db::now_ms();
4762
    let aud = oxygenhub::keyless::audience(h.app.config.base_url());
4763
    let good = issuer.mint_for(h.app.config.base_url(), "agent:claude@andy", &aud, now, 600);
4764
    let (st, body) = ask(&good, &good).await;
4765
    assert_eq!(st, StatusCode::OK, "{body}");
4766
    assert!(body.contains("\"subject\":\"agent:claude@andy\""), "{body}");
4767
    let other = issuer.mint_for(h.app.config.base_url(), "agent:claude@andy", "sts.amazonaws.com", now, 600);
4768
    let (st, _) = ask(&other, &other).await;
4769
    assert_eq!(st, StatusCode::UNAUTHORIZED);
4770
4771
    // A job that has finished asks with a token that no longer counts.
4772
    sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE id = $1").bind(job_id).execute(&h.app.db).await.unwrap();
4773
    let (st, body) = ask(&token, &token).await;
4774
    assert_eq!(st, StatusCode::UNAUTHORIZED, "{body}");
4775
}
4776
4777
/// Keyless step 3 (oxygenhub#241): a job signs its receipt with a fresh
4778
/// key the hub certified for it, and the hub keeps the receipt without
4779
/// binding any runner key; a certificate for another job, or from another
4780
/// issuer, is not this job's.
4781
#[tokio::test(flavor = "multi_thread")]
4782
async fn a_receipt_signed_by_a_certified_key_is_kept() {
4783
    use oxy_core::cert::{certify_challenge, SignedCertificate};
4784
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
4785
    use oxy_core::identity::SecretKey;
4786
    use oxy_core::objects::StateObject;
4787
    use oxy_core::receipt::SignedReceipt;
4788
    let h = hub().await;
4789
    create(&h.app, "andy", "demo").await;
4790
    let url = format!("{}/andy/demo", h.base);
4791
    let work = tempfile::tempdir().unwrap();
4792
    let c = client(&url, work.path());
4793
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4794
    c.snapshot("test").unwrap();
4795
    c.commit("Add a pipeline", &[]).unwrap();
4796
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4797
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
4798
    let heads: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
4799
    let state = hash_object(ObjectType::State, &StateObject::new(heads.clone()).encode());
4800
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
4801
4802
    // Certify a fresh key with a job's token, as a runner does just before
4803
    // it signs the receipt.
4804
    let certify = |token: String| {
4805
        let app = h.app.clone();
4806
        async move {
4807
            let sk = SecretKey::generate();
4808
            let id = sk.identity("test-1 job", "", 1);
4809
            let proof = sk.sign_challenge(&id.hash(), &certify_challenge(&token)).unwrap();
4810
            let body = serde_json::json!({
4811
                "identity": oxy_core::dsse::base64(&id.encode()),
4812
                "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
4813
                "scope": "seal",
4814
            });
4815
            let (st, body) = call(&app, "POST", "/api/v1/keyless/certify", Some(&token), Some(body.to_string())).await;
4816
            assert_eq!(st, StatusCode::OK, "{body}");
4817
            let v: serde_json::Value = serde_json::from_str(&body).unwrap();
4818
            let cert = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
4819
            (sk, id, cert)
4820
        }
4821
    };
4822
    let sign = |r: &serde_json::Value,
4823
                sk: &SecretKey,
4824
                id: &oxy_core::identity::Identity,
4825
                cert: SignedCertificate,
4826
                issuer: oxy_core::identity::Identity| {
4827
        let r: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
4828
        let run_url = format!("{url}/flow/{}", run.number);
4829
        hex::encode(SignedReceipt::sign(r.to_oxy(), repo_id, state, &run_url, id, sk).with_certificate(cert, issuer).encode())
4830
    };
4831
    let hub_id = h.app.hub_key.identity.clone();
4832
4833
    let a = claim(&h.app).await.unwrap();
4834
    let b = claim(&h.app).await.unwrap();
4835
    let ph = a["pipeline_hash"].as_str().unwrap().to_string();
4836
    let (a_name, b_name) = (a["job"]["name"].as_str().unwrap().to_string(), b["job"]["name"].as_str().unwrap().to_string());
4837
    let (a_id, b_id) = (a["job_id"].as_i64().unwrap(), b["job_id"].as_i64().unwrap());
4838
    let (sk_a, id_a, cert_a) = certify(a["token"].as_str().unwrap().to_string()).await;
4839
4840
    // Job b's receipt signed with job a's certified key: another job's.
4841
    let rb = receipt(&b_name, &ph, 0);
4842
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 300, "receipt": rb, "signed_receipt": sign(&rb, &sk_a, &id_a, cert_a.clone(), hub_id.clone()) });
4843
    assert_eq!(finish(&h.app, b_id, body).await, StatusCode::NO_CONTENT);
4844
    // Job a's, with its own certificate: kept.
4845
    let ra = receipt(&a_name, &ph, 0);
4846
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": ra, "signed_receipt": sign(&ra, &sk_a, &id_a, cert_a, hub_id.clone()) });
4847
    assert_eq!(finish(&h.app, a_id, body).await, StatusCode::NO_CONTENT);
4848
4849
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
4850
    let job = |n: &str| jobs.iter().find(|j| j.name == n).unwrap().clone();
4851
    assert_eq!(job(&a_name).receipt_attest.len(), 64, "{}", job(&a_name).receipt_note);
4852
    assert!(job(&a_name).receipt_signer.ends_with("(short-lived key)"), "{}", job(&a_name).receipt_signer);
4853
    assert!(job(&b_name).receipt_attest.is_empty());
4854
    assert!(job(&b_name).receipt_note.contains("another run or job"), "{}", job(&b_name).receipt_note);
4855
    // The kept receipt carries its certificate, and verifies on its own.
4856
    let kept = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().receipts(&heads).unwrap();
4857
    assert_eq!(kept.len(), 1);
4858
    assert!(kept[0].problem.is_none() && kept[0].signed.certificate.is_some());
4859
4860
    // A certificate from another issuer, for the third job: not this hub's.
4861
    let t = claim(&h.app).await.unwrap();
4862
    let t_name = t["job"]["name"].as_str().unwrap().to_string();
4863
    let fake_sk = SecretKey::generate();
4864
    let fake = fake_sk.identity("not the hub", "", 1);
4865
    let (sk_t, id_t, mut cert_t) = certify(t["token"].as_str().unwrap().to_string()).await;
4866
    cert_t.cert.issuer = fake.hash();
4867
    let cert_t = SignedCertificate::sign(cert_t.cert, &fake, &fake_sk);
4868
    let rt = receipt(&t_name, &ph, 0);
4869
    let body =
4870
        serde_json::json!({ "exit_code": 0, "duration_ms": 500, "receipt": rt, "signed_receipt": sign(&rt, &sk_t, &id_t, cert_t, fake) });
4871
    assert_eq!(finish(&h.app, t["job_id"].as_i64().unwrap(), body).await, StatusCode::NO_CONTENT);
4872
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
4873
    let t_job = jobs.iter().find(|j| j.name == t_name).unwrap();
4874
    assert!(t_job.receipt_note.contains("not issued by this hub"), "{}", t_job.receipt_note);
4875
}
4876
4877
/// Keyless step 4c (oxygenhub#241): when a key the hub certified moves a
4878
/// bookmark, the hub signs when it accepted the update and serves that
4879
/// with the bookmark, so a fetch checks the certificate at the hub's time
4880
/// rather than the time the key claimed.
4881
#[tokio::test(flavor = "multi_thread")]
4882
async fn the_hub_countersigns_an_update_by_a_key_it_certified() {
4883
    use oxy_core::attest::AttestBody;
4884
    use oxy_core::cert::{Certificate, SignedCertificate};
4885
    use oxy_core::identity::Scope;
4886
    use oxy_core::repo::IdentityScope;
4887
    let h = hub().await;
4888
    create(&h.app, "andy", "demo").await;
4889
    let url = format!("{}/andy/demo", h.base);
4890
    let work = tempfile::tempdir().unwrap();
4891
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
4892
    a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
4893
    write(&work.path().join("a"), "a.txt", "a\n");
4894
    a.commit("a", &[]).unwrap();
4895
    a.policy_init().unwrap();
4896
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
4897
    let hub_id = h.app.hub_key.identity.clone();
4898
    a.policy_grant_subject("agent:claude@andy", hub_id.clone(), Scope::CHANGES | Scope::REFS, None).unwrap();
4899
    assert!(a.push("origin", false).unwrap().iter().any(|r| r.name == "policy" && r.ok));
4900
4901
    // An agent whose fresh key the hub certified pushes.
4902
    let mut b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(work.path().join("home-b"));
4903
    b.config.set("remote.origin.token", "site").unwrap();
4904
    b.save_config().unwrap();
4905
    let (_, key) = b.create_identity("claude", "[email protected]", IdentityScope::User).unwrap();
4906
    let (_, secret) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
4907
    let now = db::now_ms() as u64;
4908
    let cert = SignedCertificate::sign(
4909
        Certificate {
4910
            key,
4911
            issuer: hub_id.hash(),
4912
            subject: "agent:claude@andy".into(),
4913
            claims: vec![],
4914
            scope: Scope::CHANGES | Scope::REFS,
4915
            not_before: now - 60_000,
4916
            expires: now + 600_000,
4917
        },
4918
        &hub_id,
4919
        &secret,
4920
    );
4921
    b.store().put_identity(&hub_id).unwrap();
4922
    b.store().put_certificate(&cert).unwrap();
4923
    write(&work.path().join("b"), "b.txt", "agent work\n");
4924
    b.commit("work", &[]).unwrap();
4925
    let r = b.push("origin", false).unwrap();
4926
    assert!(r.iter().all(|x| x.ok), "{r:?}");
4927
4928
    // The hub serves its acceptance of that update, signed by its key.
4929
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
4930
    let main = refs.refs.iter().find(|r| r.name == "main").unwrap();
4931
    let (attest, acc) = (main.attestation.clone().unwrap(), main.accepted.clone().expect("an acceptance"));
4932
    assert!(matches!(acc.attest.body, AttestBody::Accepted { attest: r } if r == attest.attest.hash()));
4933
    assert_eq!(acc.sigs[0].key, hub_id.hash());
4934
    assert!(acc.attest.hlc.wall_ms >= now);
4935
    // An update signed by a long-lived key gets none.
4936
    a.pull("origin").unwrap();
4937
    write(&work.path().join("a"), "a.txt", "again\n");
4938
    a.commit("again", &[]).unwrap();
4939
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
4940
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
4941
    assert!(refs.refs.iter().find(|r| r.name == "main").unwrap().accepted.is_none());
4942
}