OXYGENHUB
# 0ee5c3fb32eb oxygenhub / crates / hub / tests / flow.rs
301.6 KiB · Rust · last changed Newest run wins: a proposal's new run supersedes its older ones 17 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
    // Provenance (#239): only for a job whose signed receipt the hub kept;
909
    // then an in-toto statement in a DSSE envelope the hub's key verifies.
910
    let prov = format!("{link}/provenance");
911
    assert_eq!(get_bytes(&h.app, &prov).await.0, StatusCode::BAD_REQUEST, "no kept receipt, no provenance");
912
    sqlx::query("UPDATE flow_jobs SET receipt_attest = 'a1b2', receipt_signer = 'test-1 runner' WHERE id = $1")
913
        .bind(id)
914
        .execute(&h.app.db)
915
        .await
916
        .unwrap();
917
    let (st, env) = get_bytes(&h.app, &prov).await;
918
    assert_eq!(st, StatusCode::OK);
919
    let env: serde_json::Value = serde_json::from_slice(&env).unwrap();
920
    assert_eq!(env["payloadType"], "application/vnd.in-toto+json");
921
    let unb64 = |t: &str| -> Vec<u8> {
922
        let val = |c: u8| match c {
923
            b'A'..=b'Z' => c - b'A',
924
            b'a'..=b'z' => c - b'a' + 26,
925
            b'0'..=b'9' => c - b'0' + 52,
926
            b'+' => 62,
927
            _ => 63,
928
        };
929
        let clean: Vec<u8> = t.bytes().filter(|c| *c != b'=').collect();
930
        let mut out = Vec::new();
931
        for chunk in clean.chunks(4) {
932
            let n = chunk.iter().enumerate().fold(0u32, |acc, (i, c)| acc | (val(*c) as u32) << (18 - 6 * i));
933
            for i in 0..chunk.len() - 1 {
934
                out.push((n >> (16 - 8 * i)) as u8);
935
            }
936
        }
937
        out
938
    };
939
    let payload = unb64(env["payload"].as_str().unwrap());
940
    let sig = unb64(env["signatures"][0]["sig"].as_str().unwrap());
941
    let signed = oxygenhub::provenance::pae("application/vnd.in-toto+json", &payload);
942
    ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, h.app.hub_key.identity.ed25519_pk)
943
        .verify(&signed, &sig)
944
        .expect("the hub's key signed the envelope");
945
    let statement: serde_json::Value = serde_json::from_slice(&payload).unwrap();
946
    use sha2::Digest;
947
    assert_eq!(statement["subject"][0]["digest"]["sha256"], hex::encode(sha2::Sha256::digest(&body)));
948
    assert_eq!(statement["predicateType"], "https://slsa.dev/provenance/v1");
949
    assert_eq!(statement["predicate"]["buildDefinition"]["externalParameters"]["job"], "build");
950
    assert_eq!(statement["predicate"]["runDetails"]["byproducts"][0]["digest"]["oxygen-attestation"], "a1b2");
951
    let (_, pem) = get_bytes(&h.app, "/.well-known/oxyhub-signing.pem").await;
952
    let pem = String::from_utf8(pem).unwrap();
953
    let der = unb64(pem.lines().filter(|l| !l.starts_with("-----")).collect::<String>().as_str());
954
    assert_eq!(&der[der.len() - 32..], &h.app.hub_key.identity.ed25519_pk[..], "the PEM holds the hub's key");
955
    sqlx::query("UPDATE flow_jobs SET receipt_attest = '', receipt_signer = '' WHERE id = $1").bind(id).execute(&h.app.db).await.unwrap();
956
957
    // The nightly gc keeps it (#126): only the database names it, so with
958
    // no grace period a gc that did not root it would prune it at once.
959
    {
960
        let name = RepoName::parse("andy/demo").unwrap();
961
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
962
        hosted.config.set("core.gc-grace", "0").unwrap();
963
        hosted.save_config().unwrap();
964
    }
965
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
966
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
967
    let (st, got) = get_bytes(&h.app, &link).await;
968
    assert_eq!((st, got == body), (StatusCode::OK, true), "the artifact survives gc");
969
970
    // A writer attaches the artifact to a release from the run page; the
971
    // release then names the run and job that built it, as does the API.
972
    let form = |f: String| {
973
        Request::post("/register").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(Body::from(f)).unwrap()
974
    };
975
    let res = oxygenhub::router(h.app.clone())
976
        .oneshot(form("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup".into()))
977
        .await
978
        .unwrap();
979
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
980
    let with_cookie = |method: &str, path: &str, body: Option<String>| {
981
        let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie.clone());
982
        if body.is_some() {
983
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
984
        }
985
        req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()
986
    };
987
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
988
    db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
989
    let res = oxygenhub::router(h.app.clone()).oneshot(with_cookie("GET", &format!("/andy/demo/flow/{}", run.number), None)).await.unwrap();
990
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
991
    let attach = format!("/andy/demo/flow/{}/artifacts/build/tool/attach", run.number);
992
    assert!(page.contains(&attach), "a writer is offered the release");
993
    let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
994
    let csrf = page[i..].split('"').next().unwrap().to_string();
995
    let release_id = db::releases::list(&h.app.db, row.id).await.unwrap()[0].id;
996
    let res = oxygenhub::router(h.app.clone())
997
        .oneshot(with_cookie("POST", &attach, Some(format!("_csrf={csrf}&release={release_id}"))))
998
        .await
999
        .unwrap();
1000
    assert_eq!(res.status(), StatusCode::SEE_OTHER);
1001
    let (_, page) = call(&h.app, "GET", "/andy/demo/releases/tag/v1", None, None).await;
1002
    assert!(
1003
        page.contains(">tool</a>") && page.contains(&format!("built by <a href=\"/andy/demo/flow/{0}\">run #{0}</a> build", run.number)),
1004
        "{page}"
1005
    );
1006
    let (_, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases", None, None).await;
1007
    let api: serde_json::Value = serde_json::from_str(&api).unwrap();
1008
    let asset = &api[0]["assets"][0];
1009
    assert_eq!(
1010
        (asset["name"].as_str(), asset["built_by"]["run"].as_i64(), asset["built_by"]["job"].as_str()),
1011
        (Some("tool"), Some(run.number), Some("build"))
1012
    );
1013
    assert!(asset["built_by"]["receipt"].is_null(), "that receipt was not signed");
1014
}
1015
1016
/// oxygenflow#37: a failing job keeps a `when "always"` artifact; its
1017
/// receipt names none, and the run page says the file is outside it.
1018
async fn upload_report_file(app: &Shared, job: i64, name: &str, path: &str, bytes: &[u8]) -> (StatusCode, String) {
1019
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/reports/{name}/files"))
1020
        .header(header::AUTHORIZATION, "Bearer runner-secret")
1021
        .header(header::CONTENT_TYPE, "application/octet-stream")
1022
        .header("X-Flow-Report-Path", path)
1023
        .body(Body::from(bytes.to_vec()))
1024
        .unwrap();
1025
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
1026
    let status = res.status();
1027
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1028
}
1029
1030
/// #127: a report's files arrive one by one, then its manifest as the
1031
/// report's artifact; the hub indexes the declaration, metrics and files,
1032
/// and gc keeps every file.
1033
#[tokio::test(flavor = "multi_thread")]
1034
async fn reports_are_kept_file_by_file_and_indexed() {
1035
    let h = hub().await;
1036
    create(&h.app, "andy", "demo").await;
1037
    let url = format!("{}/andy/demo", h.base);
1038
    let work = tempfile::tempdir().unwrap();
1039
    let c = client(&url, work.path());
1040
    write(
1041
        work.path(),
1042
        ".flow/pipeline.kdl",
1043
        &format!(
1044
            "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"
1045
        ),
1046
    );
1047
    c.snapshot("test").unwrap();
1048
    c.commit("Measure frames", &[]).unwrap();
1049
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1050
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1051
    let a = claim(&h.app).await.unwrap();
1052
    let id = a["job_id"].as_i64().unwrap();
1053
1054
    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";
1055
    let page = b"<p>frames</p>".to_vec();
1056
    let data: Vec<u8> = (0..100_000u32).map(|i| (i % 241) as u8).collect();
1057
    let (page_bytes, data_bytes) = (page.clone(), data.clone());
1058
    let files: [(&str, &[u8]); 3] = [("data/frames.csv", &data), ("index.html", &page), ("report.toml", toml)];
1059
1060
    assert_eq!(upload_report_file(&h.app, id, "tool", "report.toml", toml).await.0, StatusCode::BAD_REQUEST, "not a report");
1061
    assert_eq!(upload_report_file(&h.app, id, "frame-timing", "../x", toml).await.0, StatusCode::BAD_REQUEST, "not a clean path");
1062
    let mut listed = vec![];
1063
    for (path, bytes) in files {
1064
        let (st, text) = upload_report_file(&h.app, id, "frame-timing", path, bytes).await;
1065
        assert_eq!(st, StatusCode::OK, "{text}");
1066
        let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1067
        assert_eq!(blob, oxy_core::repo::Repo::blob_ref(bytes).to_hex());
1068
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1069
    }
1070
    let mut missing = listed.clone();
1071
    missing.push(serde_json::json!({ "path": "assets/x.js", "blob": "ab".repeat(32), "size": 1 }));
1072
    let (st, text) =
1073
        upload(&h.app, id, "frame-timing", &serde_json::to_vec(&serde_json::json!({ "version": 1, "files": missing })).unwrap()).await;
1074
    assert_eq!(st, StatusCode::BAD_REQUEST, "a file never uploaded: {text}");
1075
    assert!(text.contains("assets/x.js"), "{text}");
1076
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed })).unwrap();
1077
    let (st, text) = upload(&h.app, id, "frame-timing", &manifest).await;
1078
    assert_eq!(st, StatusCode::OK, "{text}");
1079
1080
    let (kind, title, summary, files_n, bytes): (String, String, String, i64, i64) =
1081
        sqlx::query_as("SELECT kind, title, summary, files, bytes FROM reports WHERE job_id = $1 AND name = 'frame-timing'")
1082
            .bind(id)
1083
            .fetch_one(&h.app.db)
1084
            .await
1085
            .unwrap();
1086
    assert_eq!((kind.as_str(), title.as_str(), summary.as_str()), ("performance", "Frame timing", "Median 16.4 ms"));
1087
    assert_eq!((files_n, bytes), (3, (data.len() + page.len() + toml.len()) as i64));
1088
    let rid: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE job_id = $1").bind(id).fetch_one(&h.app.db).await.unwrap();
1089
    let m = oxygenhub::reports::metrics(&h.app.db, rid).await.unwrap();
1090
    assert_eq!((m[0].key.as_str(), m[0].value, m[0].fail_above), ("median_ms", 16.4, Some(20.0)));
1091
    let log = db::flow::log(&h.app.db, id, 0, 1000).await.unwrap();
1092
    assert!(log.iter().any(|r| r.text.contains("report frame-timing: performance \"Frame timing\", 1 metric")), "{log:?}");
1093
1094
    // The threshold is a check on the run's state, passing at 16.4.
1095
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
1096
    let c = checks.iter().find(|c| c.name == "report/frame-timing/median_ms").expect("a check per threshold");
1097
    assert_eq!(c.status, "passed", "{c:?}");
1098
    assert!(c.summary.contains("16.4 ms") && c.url.contains("/reports/frame-timing?id="), "{c:?}");
1099
1100
    // The Reports tab, the report's page, and its own page in a sandbox.
1101
    let (_, page) = call(&h.app, "GET", "/andy/demo", None, None).await;
1102
    assert!(page.contains(">Reports</a>"), "the tab");
1103
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports", None, None).await;
1104
    assert!(st == StatusCode::OK && page.contains("Frame timing") && page.contains("median_ms"), "{st}");
1105
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1106
    assert!(st == StatusCode::OK && page.contains("fails above 20") && page.contains("sandbox=\"allow-scripts\""), "{st}");
1107
    let src = page.split("class=\"rep-frame\" src=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
1108
    assert!(src.ends_with("/index.html"), "{src}");
1109
    let res = oxygenhub::router(h.app.clone()).oneshot(Request::get(&src).body(Body::empty()).unwrap()).await.unwrap();
1110
    assert_eq!(res.status(), StatusCode::OK);
1111
    let csp = res.headers()[header::CONTENT_SECURITY_POLICY].to_str().unwrap().to_string();
1112
    assert!(csp.starts_with("sandbox allow-scripts;") && csp.contains("default-src 'none'"), "{csp}");
1113
    // The site's own policy and frame refusal stay off it: report frames are framed (#222).
1114
    assert!(
1115
        res.headers().get(header::X_FRAME_OPTIONS).is_none() && res.headers().get(header::CONTENT_SECURITY_POLICY_REPORT_ONLY).is_none()
1116
    );
1117
    assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
1118
    assert_eq!(res.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*");
1119
    // The page as kept, with the frame script that sizes the frame added.
1120
    let served = res.into_body().collect().await.unwrap().to_bytes().to_vec();
1121
    assert!(served.starts_with(&page_bytes), "the report's page");
1122
    assert!(String::from_utf8_lossy(&served).contains("/static/report-frame.js"), "with the frame script");
1123
    let (st, _) = get_bytes(&h.app, "/static/report.css").await;
1124
    assert_eq!(st, StatusCode::OK, "the stylesheet a report may link");
1125
    let data = src.replace("/index.html", "/data/frames.csv");
1126
    assert_eq!(get_bytes(&h.app, &data).await, (StatusCode::OK, data_bytes.clone()));
1127
    // A link with another report's MAC, or a file it lacks, finds nothing.
1128
    // A second run of the report: the timeline has two stops, and the
1129
    // first can be compared with it (RP4).
1130
    let first: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE name = 'frame-timing'").fetch_one(&h.app.db).await.unwrap();
1131
    let second: i64 = sqlx::query_scalar(
1132
        "INSERT INTO reports (repo_id, name, kind, title, summary, context, run_id, job_id, run_number, job, bookmark, state, manifest, files, bytes, created_ms) \
1133
         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",
1134
    )
1135
    .bind(first)
1136
    .fetch_one(&h.app.db)
1137
    .await
1138
    .unwrap();
1139
    sqlx::query(
1140
        "INSERT INTO report_metrics (report_id, key, value, unit, better, fail_above) VALUES ($1, 'median_ms', 18.0, 'ms', 'lower', 20)",
1141
    )
1142
    .bind(second)
1143
    .execute(&h.app.db)
1144
    .await
1145
    .unwrap();
1146
    let (_, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1147
    assert_eq!(page.matches("data-tl-stop").count(), 2, "a stop per run");
1148
    assert!(page.contains("Median 18.0 ms"), "the newest run is shown");
1149
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/frame-timing?id={first}&compare={second}&play=3"), None, None).await;
1150
    assert!(page.contains("This run against run #2") && page.contains("-1.6"), "every metric against the other run");
1151
    let stop = page.split("data-tl-stop").next().unwrap_or("").rsplit("href=").next().unwrap_or("").to_string();
1152
    assert!(page.contains("data-play=\"3\""), "playing");
1153
    assert!(stop.contains("play") && stop.contains('3'), "playing carries on from stop to stop: {stop}");
1154
    assert!(page.contains("data-report-runs="), "the frame interface knows the runs");
1155
    let forged = src.replacen("/files/", "/files/9", 1);
1156
    assert_eq!(get_bytes(&h.app, &forged).await.0, StatusCode::NOT_FOUND);
1157
    assert_eq!(get_bytes(&h.app, &src.replace("/index.html", "/secret.txt")).await.0, StatusCode::NOT_FOUND);
1158
    let _ = run;
1159
1160
    // gc keeps every file: only the database names them.
1161
    {
1162
        let name = RepoName::parse("andy/demo").unwrap();
1163
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
1164
        hosted.config.set("core.gc-grace", "0").unwrap();
1165
        hosted.save_config().unwrap();
1166
    }
1167
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
1168
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
1169
    let hosted = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
1170
    for (path, bytes) in files {
1171
        assert_eq!(hosted.read_blob(&oxy_core::repo::Repo::blob_ref(bytes)).unwrap(), bytes, "{path} survives gc");
1172
    }
1173
}
1174
1175
#[tokio::test(flavor = "multi_thread")]
1176
async fn a_failing_job_keeps_an_artifact_outside_its_receipt() {
1177
    let h = hub().await;
1178
    create(&h.app, "andy", "demo").await;
1179
    let url = format!("{}/andy/demo", h.base);
1180
    let work = tempfile::tempdir().unwrap();
1181
    let c = client(&url, work.path());
1182
    write(
1183
        work.path(),
1184
        ".flow/pipeline.kdl",
1185
        &format!(
1186
            "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"
1187
        ),
1188
    );
1189
    c.snapshot("test").unwrap();
1190
    c.commit("Test", &[]).unwrap();
1191
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1192
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1193
    let a = claim(&h.app).await.unwrap();
1194
    assert_eq!(a["job"]["outputs"][0]["always"], true, "the runner is told to keep it from a failing job");
1195
    let id = a["job_id"].as_i64().unwrap();
1196
    // A JUnit report (#114): parsed on upload, counted, failures listed.
1197
    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>"#;
1198
    let (st, text) = upload(&h.app, id, "junit", xml).await;
1199
    assert_eq!(st, StatusCode::OK, "{text}");
1200
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1201
    let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), 1);
1202
    r["outputs"] = serde_json::json!([blob]);
1203
    assert_eq!(
1204
        finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r.clone() })).await,
1205
        StatusCode::BAD_REQUEST,
1206
        "a failing receipt names no outputs"
1207
    );
1208
    r["outputs"] = serde_json::json!([]);
1209
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r })).await, StatusCode::NO_CONTENT);
1210
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
1211
    assert!(page.contains(&format!("/andy/demo/flow/{}/artifacts/test/junit", run.number)), "listed");
1212
    assert!(page.contains("not in its receipt"), "marked");
1213
    assert!(page.contains("2 tests: 1 failed"), "counts beside the job");
1214
    assert!(page.contains("tests.test_io::test_write") && page.contains("disk full") && page.contains("OSError"), "the failure");
1215
    assert!(page.contains("tests: 2 tests: 1 failed in 2.0 s"), "said in the job's log");
1216
}
1217
1218
/// A release's trust report (hub spec §9.1): a signed tag, an asset built
1219
/// by a job with a signed receipt from the tagged state, and one uploaded
1220
/// by hand; the page, its JSON export and the API.
1221
#[tokio::test(flavor = "multi_thread")]
1222
async fn a_release_is_audited_from_authors_to_receipts() {
1223
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
1224
    use oxy_core::identity::SecretKey;
1225
    use oxy_core::objects::StateObject;
1226
    use oxy_core::receipt::SignedReceipt;
1227
    let h = hub().await;
1228
    create(&h.app, "andy", "demo").await;
1229
    let url = format!("{}/andy/demo", h.base);
1230
    let work = tempfile::tempdir().unwrap();
1231
    let mut c = client(&url, work.path());
1232
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
1233
    write(
1234
        work.path(),
1235
        ".flow/pipeline.kdl",
1236
        &format!(
1237
            "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"
1238
        ),
1239
    );
1240
    c.snapshot("test").unwrap();
1241
    c.commit("Build a tool", &[]).unwrap();
1242
    let heads = c.bookmark_heads().unwrap();
1243
    c.tag_create("v1", &heads, "first").unwrap();
1244
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1245
1246
    // The runner builds, uploads the artifact and signs its receipt.
1247
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1248
    let a = claim(&h.app).await.unwrap();
1249
    let id = a["job_id"].as_i64().unwrap();
1250
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
1251
    let (_, text) = upload(&h.app, id, "tool", &body).await;
1252
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1253
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
1254
    r["outputs"] = serde_json::json!([blob]);
1255
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
1256
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
1257
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
1258
    let sk = SecretKey::generate();
1259
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
1260
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
1261
    let signed = hex::encode(SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/1"), &runner, &sk).encode());
1262
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
1263
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
1264
1265
    // A release with the built asset and a file uploaded by hand.
1266
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1267
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
1268
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
1269
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "notes.txt", "", b"by hand\n").await.unwrap();
1270
1271
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
1272
    assert_eq!(st, StatusCode::OK);
1273
    for want in [
1274
        "Tag v1 is signed",
1275
        "The one change in the release is authenticated",
1276
        "tool: signed receipt from run #1 build",
1277
        "a runner key of this hub",
1278
        "tool: built from the tagged state",
1279
        "tool: pinned environment",
1280
        "notes.txt: no build found",
1281
        "<svg class=\"trust-graph\"",
1282
        // oxygenhub#79: a summary of badges, badges in the graph, and the
1283
        // graph drawn at its own size rather than stretched to the page.
1284
        "Tag signed by",
1285
        "1 of 1 changes signed or sealed",
1286
        "1 of 2 assets built and attested by OxygenFlow",
1287
        "attested build",
1288
        "uploaded by hand",
1289
        "receipt verified",
1290
        "class=\"shackle\"",
1291
        "<title>notes.txt:",
1292
    ] {
1293
        assert!(page.contains(want), "missing {want:?}");
1294
    }
1295
    let svg = &page[page.find("<svg class=\"trust-graph\"").unwrap()..];
1296
    assert!(svg[..200].contains(" width=\"") && svg[..200].contains(" height=\""), "the graph has its own size: {}", &svg[..200]);
1297
    let (_, releases) = call(&h.app, "GET", "/andy/demo/releases", None, None).await;
1298
    assert!(releases.contains("/andy/demo/releases/trust/v1"), "the release links its audit");
1299
1300
    // The export carries the signed receipt, which checks on its own.
1301
    let (st, json) = call(&h.app, "GET", "/andy/demo/releases/trust/v1?format=json", None, None).await;
1302
    assert_eq!(st, StatusCode::OK);
1303
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
1304
    assert_eq!((t["tag"].as_str(), t["tag_signature"].as_str(), t["changes"].as_i64()), (Some("v1"), Some("valid"), Some(1)));
1305
    assert_eq!(t["authors"][0]["who"]["name"], "Andy");
1306
    let tool = t["assets"].as_array().unwrap().iter().find(|a| a["name"] == "tool").unwrap();
1307
    let hex_receipt = tool["build"]["signed_receipt"].as_str().unwrap();
1308
    let sr = SignedReceipt::decode(&hex::decode(hex_receipt).unwrap()).unwrap();
1309
    sr.verify().unwrap();
1310
    assert_eq!(sr.receipt.outputs[0].to_hex(), blob);
1311
    let audit = t["audit"].as_array().unwrap();
1312
    assert!(audit.iter().any(|c| c["verdict"] == "warn" && c["title"].as_str().unwrap().starts_with("notes.txt")));
1313
    assert!(!audit.iter().any(|c| c["verdict"] == "fail"), "{audit:?}");
1314
    // The API gives the same report; an unknown release is a 404.
1315
    let (st, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v1", None, None).await;
1316
    assert_eq!(st, StatusCode::OK);
1317
    assert_eq!(serde_json::from_str::<serde_json::Value>(&api).unwrap()["assets"].as_array().unwrap().len(), 2);
1318
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1319
    assert_eq!(call(&h.app, "GET", "/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1320
}
1321
1322
/// Runners (hub spec §13.2): an administrator makes a registration token,
1323
/// a runner registers with it (binding its key), claims, shows on Admin →
1324
/// Runners with its history, and is drained, disabled and removed.
1325
#[tokio::test(flavor = "multi_thread")]
1326
async fn runners_register_show_their_history_and_are_drained_and_removed() {
1327
    use oxy_core::identity::SecretKey;
1328
    let h = hub().await;
1329
    create(&h.app, "andy", "demo").await;
1330
    // A signed-in site administrator.
1331
    let res = oxygenhub::router(h.app.clone())
1332
        .oneshot(
1333
            Request::post("/register")
1334
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1335
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
1336
                .unwrap(),
1337
        )
1338
        .await
1339
        .unwrap();
1340
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1341
    let admin = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
1342
    db::accounts::set_admin(&h.app.db, admin.id, true).await.unwrap();
1343
    let web = |method: &'static str, path: String, body: Option<String>| {
1344
        let (app, cookie) = (h.app.clone(), cookie.clone());
1345
        async move {
1346
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1347
            if body.is_some() {
1348
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1349
            }
1350
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1351
            let st = res.status();
1352
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1353
        }
1354
    };
1355
    let csrf_of = |page: &str| {
1356
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1357
        page[i..].split('"').next().unwrap().to_string()
1358
    };
1359
    let (st, page) = web("GET", "/admin/runners".into(), None).await;
1360
    assert_eq!(st, StatusCode::OK);
1361
    assert!(page.contains("No runners yet"));
1362
    assert_eq!(call(&h.app, "GET", "/admin/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1363
1364
    // A one-time registration token, shown once with the command.
1365
    let (_, page) = web("POST", "/admin/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1366
    let i = page.find("--token ").unwrap() + "--token ".len();
1367
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1368
    assert!(token.starts_with("flowreg_"), "{token}");
1369
1370
    // The runner registers, binding its key; the token then is spent.
1371
    let sk = SecretKey::generate();
1372
    let identity = sk.identity("plex (OxygenFlow runner)", "", 1);
1373
    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 });
1374
    let reg = serde_json::json!({ "token": token, "name": "plex", "identity": hex::encode(identity.encode()), "info": info });
1375
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1376
    assert_eq!(st, StatusCode::OK, "{body}");
1377
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1378
    assert!(credential.starts_with("flowrunner_"));
1379
    assert_eq!(
1380
        call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0,
1381
        StatusCode::FORBIDDEN,
1382
        "used once"
1383
    );
1384
1385
    // It claims with its credential; the hub.toml runner shows too.
1386
    let claim_as = |who: String| {
1387
        let app = h.app.clone();
1388
        let info = info.clone();
1389
        async move {
1390
            let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
1391
            call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await
1392
        }
1393
    };
1394
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "nothing queued");
1395
    assert_eq!(claim(&h.app).await, None);
1396
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1397
    assert!(
1398
        page.contains(">plex</strong>") && page.contains("st-online") && page.contains("x86_64 · linux") && page.contains("big-disk"),
1399
        "{page}"
1400
    );
1401
    assert!(page.contains(">test-1</strong>") && page.contains("hub.toml"), "the configured runner, by its claimed name");
1402
    let plex = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1403
    assert_eq!(plex.key, identity.hash().to_hex(), "bound at registration");
1404
1405
    // A run: plex takes a job, and its history shows it.
1406
    let url = format!("{}/andy/demo", h.base);
1407
    let work = tempfile::tempdir().unwrap();
1408
    let c = client(&url, work.path());
1409
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1410
    c.snapshot("test").unwrap();
1411
    c.commit("Add a pipeline", &[]).unwrap();
1412
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1413
    runs_of(&h.app, "andy", "demo").await;
1414
    let (st, body) = claim_as(credential.clone()).await;
1415
    assert_eq!(st, StatusCode::OK, "{body}");
1416
    let job: serde_json::Value = serde_json::from_str(&body).unwrap();
1417
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1418
    assert!(
1419
        page.contains("andy/demo") && page.contains(job["job"]["name"].as_str().unwrap()) && page.contains("Running now</dt><dd>1 job"),
1420
        "{page}"
1421
    );
1422
    // The queue on Admin → Runners and through the API (#41, part 4).
1423
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1424
    assert!(page.contains("id=\"queue\"") && page.contains(">plex</a></td>"), "{page}");
1425
    // Connectivity and what it is doing, kept apart (#243); its status
1426
    // opens the queue filtered to it, and the filters keep and drop jobs.
1427
    assert!(page.contains("running 1 of ") && page.contains("/admin/runners?runner=plex#queue"), "{page}");
1428
    let (_, only) = web("GET", "/admin/runners?runner=plex".into(), None).await;
1429
    assert!(only.contains(">plex</a></td>") && only.contains(" of ") && only.contains(">all</a>"), "{only}");
1430
    let (_, none) = web("GET", "/admin/runners?runner=nobody&status=running".into(), None).await;
1431
    assert!(none.contains("Nothing matches."), "{none}");
1432
    // A busy runner claims nothing; its heartbeat keeps it online.
1433
    sqlx::query("UPDATE flow_runners SET last_seen_ms = 0 WHERE id = $1").bind(plex.id).execute(&h.app.db).await.unwrap();
1434
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1435
    assert!(page.contains("st-offline"), "quiet for long: offline");
1436
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/heartbeat", Some(&credential), None).await.0, StatusCode::NO_CONTENT);
1437
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/heartbeat", Some("flowrunner_nope"), None).await.0, StatusCode::UNAUTHORIZED);
1438
    let plex_now = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1439
    assert_eq!(plex_now.connectivity(), "online");
1440
    let (_, tokens) = web("GET", "/settings/tokens".into(), None).await;
1441
    let (_, made) = web("POST", "/settings/tokens".into(), Some(format!("_csrf={}&name=admin&scopes=user%3Aread", csrf_of(&tokens)))).await;
1442
    let i = made.find("oxyhub_").unwrap();
1443
    let admin_token: String = made[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
1444
    let (st, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1445
    assert_eq!(st, StatusCode::OK, "{body}");
1446
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1447
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1448
    assert_eq!((plex_row["running"].as_i64(), plex_row["arch"].as_str()), (Some(1), Some("x86_64")));
1449
    // A runner's own labels and time limit from its page (#98).
1450
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1451
    let (st, _) = web(
1452
        "POST",
1453
        format!("/admin/runners/{}/limits", plex.id),
1454
        Some(format!("_csrf={}&labels=gpu%2C+plex&timeout_minutes=5", csrf_of(&page))),
1455
    )
1456
    .await;
1457
    assert_eq!(st, StatusCode::SEE_OTHER);
1458
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1459
    assert!(page.contains(">gpu<") && page.contains("5 min for its jobs"), "{page}");
1460
    let (_, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1461
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1462
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1463
    assert!(plex_row["labels"].as_array().unwrap().iter().any(|l| l == "gpu"), "{plex_row}");
1464
    let (st, _) = web(
1465
        "POST",
1466
        format!("/admin/runners/{}/limits", plex.id),
1467
        Some(format!("_csrf={}&labels=bad%20label%21&timeout_minutes=", csrf_of(&page))),
1468
    )
1469
    .await;
1470
    assert_eq!(st, StatusCode::BAD_REQUEST, "a label with a space or punctuation is refused");
1471
    let (_, body) = call(&h.app, "GET", "/api/v1/runners/queue", Some(&admin_token), None).await;
1472
    let queue: serde_json::Value = serde_json::from_str(&body).unwrap();
1473
    assert!(queue.as_array().unwrap().iter().any(|q| q["status"] == "running" && q["runner"] == "plex"), "{queue}");
1474
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/runners/{}/jobs", plex.id), Some(&admin_token), None).await;
1475
    let jobs: serde_json::Value = serde_json::from_str(&body).unwrap();
1476
    assert_eq!(jobs[0]["repo"], "andy/demo", "{jobs}");
1477
    assert_eq!(call(&h.app, "GET", "/api/v1/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1478
1479
    // Draining: no new work; removing while busy is refused.
1480
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1481
    let csrf = csrf_of(&page);
1482
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=draining"))).await;
1483
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "a draining runner takes nothing");
1484
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1485
    assert!(page.contains("is running jobs: drain it first"), "{page}");
1486
    // Its job finishes; disabled, it is refused; removed, its credential is dead.
1487
    let id = job["job_id"].as_i64().unwrap();
1488
    let done = call(
1489
        &h.app,
1490
        "POST",
1491
        &format!("/api/v1/flow/jobs/{id}/finish"),
1492
        Some(&credential),
1493
        Some(r#"{"exit_code":0,"duration_ms":5}"#.into()),
1494
    )
1495
    .await;
1496
    assert_eq!(done.0, StatusCode::NO_CONTENT);
1497
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=disabled"))).await;
1498
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::FORBIDDEN);
1499
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1500
    assert!(page.contains("Removed plex."), "{page}");
1501
    assert_eq!(claim_as(credential).await.0, StatusCode::UNAUTHORIZED);
1502
}
1503
1504
/// Runner scopes (oxygenhub#41): a runner registered for one repository, or
1505
/// one owner, takes only those jobs; a site runner takes any.
1506
#[tokio::test(flavor = "multi_thread")]
1507
async fn scoped_runners_take_only_their_scope() {
1508
    use oxy_core::identity::SecretKey;
1509
    let h = hub().await;
1510
    create(&h.app, "andy", "demo").await;
1511
    create(&h.app, "andy", "other").await;
1512
    let register = |scope: db::runners::Scope, name: &'static str| {
1513
        let app = h.app.clone();
1514
        async move {
1515
            let token = format!("flowreg_{name}");
1516
            db::runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &scope).await.unwrap();
1517
            let identity = SecretKey::generate().identity(name, "", 1);
1518
            let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1519
            let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
1520
            let (st, body) = call(&app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1521
            assert_eq!(st, StatusCode::OK, "{body}");
1522
            serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string()
1523
        }
1524
    };
1525
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1526
    let only_demo = register(db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) }, "demo-runner").await;
1527
    let carols = register(db::runners::Scope { owner: "carol".into(), repo_id: None }, "carol-runner").await;
1528
    let andys = register(db::runners::Scope { owner: "andy".into(), repo_id: None }, "andy-runner").await;
1529
    let claim_as = |who: String| {
1530
        let app = h.app.clone();
1531
        async move {
1532
            let body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"] }).to_string();
1533
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await;
1534
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["repo"].as_str().unwrap().to_string())
1535
        }
1536
    };
1537
    // Jobs queued in andy/other only.
1538
    let work = tempfile::tempdir().unwrap();
1539
    let c = client(&format!("{}/andy/other", h.base), work.path());
1540
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1541
    c.snapshot("t").unwrap();
1542
    c.commit("pipeline", &[]).unwrap();
1543
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1544
    assert!(!runs_of(&h.app, "andy", "other").await.is_empty());
1545
    assert_eq!(claim_as(only_demo.clone()).await, None, "nothing of andy/demo is queued");
1546
    assert_eq!(claim_as(carols).await, None, "nothing of carol's");
1547
    assert_eq!(claim_as(andys).await.as_deref(), Some("andy/other"), "the owner's runner takes its repositories' jobs");
1548
    // The site runner (hub.toml) takes any.
1549
    assert_eq!(claim(&h.app).await.unwrap()["repo"], "andy/other");
1550
    assert_eq!(claim_as(only_demo).await, None, "still nothing of its own");
1551
}
1552
1553
/// Settings → Runners (oxygenhub#41, part 2b): a repository's admin adds a
1554
/// runner for that repository alone, sees which runners serve it, and
1555
/// removes only its own.
1556
#[tokio::test(flavor = "multi_thread")]
1557
async fn repository_admins_add_and_remove_their_own_runners() {
1558
    use oxy_core::identity::SecretKey;
1559
    let h = hub().await;
1560
    let res = oxygenhub::router(h.app.clone())
1561
        .oneshot(
1562
            Request::post("/register")
1563
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1564
                .body(Body::from("username=andy&email=andy%40example.com&password=correct-horse-battery&setup=test-setup"))
1565
                .unwrap(),
1566
        )
1567
        .await
1568
        .unwrap();
1569
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1570
    create(&h.app, "andy", "demo").await;
1571
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1572
    let web = |method: &'static str, path: String, body: Option<String>| {
1573
        let (app, cookie) = (h.app.clone(), cookie.clone());
1574
        async move {
1575
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1576
            if body.is_some() {
1577
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1578
            }
1579
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1580
            let st = res.status();
1581
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1582
        }
1583
    };
1584
    let csrf_of = |page: &str| {
1585
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1586
        page[i..].split('"').next().unwrap().to_string()
1587
    };
1588
    let (st, page) = web("GET", "/andy/demo/settings".into(), None).await;
1589
    assert_eq!(st, StatusCode::OK);
1590
    assert!(page.contains("<h2>Runners</h2>"), "the owner sees the section");
1591
    let (_, page) = web("POST", "/andy/demo/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1592
    let i = page.find("--token ").unwrap() + "--token ".len();
1593
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1594
    let identity = SecretKey::generate().identity("mine", "", 1);
1595
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1596
    let reg = serde_json::json!({ "token": token, "name": "mine", "identity": hex::encode(identity.encode()), "info": info });
1597
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1598
    assert_eq!(st, StatusCode::OK, "{body}");
1599
    let mine = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "mine").unwrap();
1600
    assert_eq!(mine.scope(), db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) });
1601
    // The site's runner (hub.toml, from its first claim) serves it too, but is not the owner's to remove.
1602
    claim(&h.app).await;
1603
    let site = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "test-1").unwrap();
1604
    let (_, page) = web("GET", "/andy/demo/settings".into(), None).await;
1605
    assert!(page.contains("<strong>mine</strong>") && page.contains("this repository"), "{page}");
1606
    assert!(page.contains("<strong>test-1</strong>") && page.contains("the whole site"), "{page}");
1607
    let csrf = csrf_of(&page);
1608
    let (st, _) = web("POST", format!("/andy/demo/settings/runners/{}/remove", site.id), Some(format!("_csrf={csrf}"))).await;
1609
    assert_eq!(st, StatusCode::NOT_FOUND, "not the repository's own");
1610
    let (_, page) = web("POST", format!("/andy/demo/settings/runners/{}/remove", mine.id), Some(format!("_csrf={csrf}"))).await;
1611
    assert!(page.contains("mine removed"), "{page}");
1612
    assert!(db::runners::get(&h.app.db, mine.id).await.unwrap().is_none());
1613
1614
    // The same for an organisation's owner.
1615
    let (_, page) = web("GET", "/orgs/new".into(), None).await;
1616
    web("POST", "/orgs/new".into(), Some(format!("_csrf={}&name=acme&display_name=Acme", csrf_of(&page)))).await;
1617
    let (st, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1618
    assert_eq!(st, StatusCode::OK);
1619
    let (_, page) = web("POST", "/orgs/acme/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1620
    let i = page.find("--token ").unwrap() + "--token ".len();
1621
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1622
    let identity = SecretKey::generate().identity("acme-runner", "", 1);
1623
    let reg = serde_json::json!({ "token": token, "name": "acme-runner", "identity": hex::encode(identity.encode()), "info": info });
1624
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0, StatusCode::OK);
1625
    let acme = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "acme-runner").unwrap();
1626
    assert_eq!(acme.scope(), db::runners::Scope { owner: "acme".into(), repo_id: None });
1627
    let (_, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1628
    assert!(page.contains("<strong>acme-runner</strong>") && page.contains("the organisation's repositories"), "{page}");
1629
    let (_, page) = web("POST", format!("/orgs/acme/settings/runners/{}/remove", acme.id), Some(format!("_csrf={}", csrf_of(&page)))).await;
1630
    assert!(page.contains("acme-runner removed"), "{page}");
1631
}
1632
1633
/// runs-on (oxygenhub#41, part 3): a job that asks for a label goes only to
1634
/// a runner that has it, and waits for one otherwise.
1635
#[tokio::test(flavor = "multi_thread")]
1636
async fn jobs_that_ask_for_labels_wait_for_a_runner_with_them() {
1637
    use oxy_core::identity::SecretKey;
1638
    let h = hub().await;
1639
    create(&h.app, "andy", "demo").await;
1640
    let work = tempfile::tempdir().unwrap();
1641
    let c = client(&format!("{}/andy/demo", h.base), work.path());
1642
    let cross = "job \"cross\" {\n    sandbox \"alpine\"\n    runs-on \"riscv64\"\n    exec \"true\"\n}\n";
1643
    write(work.path(), ".flow/pipeline.kdl", &pipeline(cross));
1644
    c.snapshot("t").unwrap();
1645
    c.commit("pipeline", &[]).unwrap();
1646
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1647
    assert!(!runs_of(&h.app, "andy", "demo").await.is_empty());
1648
    // The site runner has no labels: it takes the others, never cross.
1649
    let mut taken = Vec::new();
1650
    while let Some(j) = claim(&h.app).await {
1651
        taken.push(j["job"]["name"].as_str().unwrap().to_string());
1652
    }
1653
    assert!(!taken.contains(&"cross".to_string()) && taken.contains(&"lint".to_string()), "{taken:?}");
1654
    let queue = db::flow::queue(&h.app.db).await.unwrap();
1655
    let waiting = queue.iter().find(|q| q.job == "cross").unwrap();
1656
    assert_eq!((waiting.status.as_str(), waiting.needs()), ("queued", vec!["riscv64".to_string()]));
1657
    // A runner registered with the label takes it.
1658
    let token = "flowreg_riscv";
1659
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
1660
    let identity = SecretKey::generate().identity("visionfive", "", 1);
1661
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": ["riscv64"], "max_jobs": 1 });
1662
    let reg = serde_json::json!({ "token": token, "name": "visionfive", "identity": hex::encode(identity.encode()), "info": info });
1663
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1664
    assert_eq!(st, StatusCode::OK, "{body}");
1665
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1666
    let claim_body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"], "info": info }).to_string();
1667
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(claim_body)).await;
1668
    assert_eq!(st, StatusCode::OK, "{body}");
1669
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"], "cross");
1670
}
1671
1672
/// oxygenhub#71: a job its runner stopped reporting (restarted, or lost
1673
/// the hub as the job ended) is ended once it has run past the time limit
1674
/// and a grace: an error with the reason, its dependents skipped and its
1675
/// run settled, as if the runner had reported the error.
1676
#[tokio::test(flavor = "multi_thread")]
1677
async fn a_job_no_runner_reports_is_ended_after_the_time_limit() {
1678
    let h = hub().await;
1679
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1680
    create(&h.app, "andy", "lost").await;
1681
    let url = format!("{}/andy/lost", h.base);
1682
    let work = tempfile::tempdir().unwrap();
1683
    let c = client(&url, work.path());
1684
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1685
    write(work.path(), "test.sh", "echo ok\n");
1686
    c.commit("Add a pipeline", &[]).unwrap();
1687
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1688
    assert_eq!(runs_of(&h.app, "andy", "lost").await.len(), 1);
1689
    let job = claim(&h.app).await.expect("a job to claim");
1690
    let id = job["job_id"].as_i64().unwrap();
1691
1692
    // Running, but well within the limit: left alone.
1693
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 0);
1694
    // Started long ago and never reported: ended.
1695
    let old = db::now_ms() - 24 * 3600 * 1000;
1696
    sqlx::query("UPDATE flow_jobs SET started_ms = $1 WHERE id = $2").bind(old).bind(id).execute(&h.app.db).await.unwrap();
1697
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 1);
1698
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1699
    assert_eq!(j.status, "error");
1700
    assert!(j.error.starts_with("lost:"), "{}", j.error);
1701
    let run = &runs_of(&h.app, "andy", "lost").await[0];
1702
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
1703
    assert!(jobs.iter().all(|j| j.status != "running"), "nothing left running");
1704
    // A late report, should one come, does not overwrite the ending.
1705
    assert_ne!(finish(&h.app, id, serde_json::json!({ "exit_code": 0 })).await, StatusCode::NO_CONTENT);
1706
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "error");
1707
}
1708
1709
/// oxygenhub#73: a runner that lists the images it holds is offered only
1710
/// the jobs whose rootfs is among them; one that does not say gets any.
1711
#[tokio::test(flavor = "multi_thread")]
1712
async fn a_runner_is_offered_only_jobs_whose_image_it_holds() {
1713
    let h = hub().await;
1714
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1715
    create(&h.app, "andy", "images").await;
1716
    let url = format!("{}/andy/images", h.base);
1717
    let work = tempfile::tempdir().unwrap();
1718
    let c = client(&url, work.path());
1719
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1720
    write(work.path(), "test.sh", "echo ok\n");
1721
    c.commit("Add a pipeline", &[]).unwrap();
1722
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1723
    assert_eq!(runs_of(&h.app, "andy", "images").await.len(), 1);
1724
    let claim_with = |images: Vec<String>| {
1725
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "images": images }).to_string();
1726
        let app = h.app.clone();
1727
        async move {
1728
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await;
1729
            (st, body)
1730
        }
1731
    };
1732
    let (st, _) = claim_with(vec!["ab".repeat(32)]).await;
1733
    assert_eq!(st, StatusCode::NO_CONTENT, "no job for a runner without the image");
1734
    let jobs = db::flow::jobs(&h.app.db, runs_of(&h.app, "andy", "images").await[0].id).await.unwrap();
1735
    let rootfs: serde_json::Value = serde_json::from_str(&jobs[0].sandbox).unwrap();
1736
    let rootfs = rootfs["rootfs"].as_str().unwrap().to_string();
1737
    let (st, body) = claim_with(vec!["ab".repeat(32), rootfs]).await;
1738
    assert_eq!(st, StatusCode::OK, "{body}");
1739
}
1740
1741
/// oxygenhub#71: a runner that lists the jobs it holds has the others it
1742
/// was given ended at once (it restarted, or never received them), not at
1743
/// the time limit; a held job is left alone.
1744
#[tokio::test(flavor = "multi_thread")]
1745
async fn a_job_its_runner_no_longer_holds_is_ended_at_its_next_claim() {
1746
    let h = hub().await;
1747
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1748
    create(&h.app, "andy", "held").await;
1749
    let url = format!("{}/andy/held", h.base);
1750
    let work = tempfile::tempdir().unwrap();
1751
    let c = client(&url, work.path());
1752
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1753
    write(work.path(), "test.sh", "echo ok\n");
1754
    c.commit("Add a pipeline", &[]).unwrap();
1755
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1756
    assert_eq!(runs_of(&h.app, "andy", "held").await.len(), 1);
1757
    let id = claim(&h.app).await.expect("a job to claim")["job_id"].as_i64().unwrap();
1758
    let claim_holding = |holding: Vec<i64>| {
1759
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "holding": holding }).to_string();
1760
        let app = h.app.clone();
1761
        async move { call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await.0 }
1762
    };
1763
    claim_holding(vec![id]).await;
1764
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "running", "a held job stays");
1765
    claim_holding(vec![]).await;
1766
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1767
    assert_eq!(j.status, "error");
1768
    assert!(j.error.starts_with("lost:") && j.error.contains("no longer holds"), "{}", j.error);
1769
    let run = &runs_of(&h.app, "andy", "held").await[0];
1770
    assert!(db::flow::jobs(&h.app.db, run.id).await.unwrap().iter().all(|j| j.status != "running"), "the run settles");
1771
}
1772
1773
/// oxygen#59: a job with a `scope` runs on a push only when the push's
1774
/// changes touch a path it names (a release job, when Cargo.toml's version
1775
/// moves); a bookmark's first run and manual runs have every job.
1776
#[tokio::test(flavor = "multi_thread")]
1777
async fn a_scoped_job_runs_only_when_a_push_touches_its_paths() {
1778
    let h = hub().await;
1779
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1780
    create(&h.app, "andy", "scoped").await;
1781
    let url = format!("{}/andy/scoped", h.base);
1782
    let work = tempfile::tempdir().unwrap();
1783
    let c = client(&url, work.path());
1784
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\" \"packaging/**\"\n    exec \"true\"\n}\n";
1785
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1786
    write(work.path(), "test.sh", "echo ok\n");
1787
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1788
    c.commit("Start", &[]).unwrap();
1789
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1790
    let names = |app: Shared, n: usize| async move {
1791
        let mut runs = Vec::new();
1792
        for _ in 0..100 {
1793
            runs = runs_of(&app, "andy", "scoped").await;
1794
            if runs.len() >= n {
1795
                break;
1796
            }
1797
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1798
        }
1799
        assert_eq!(runs.len(), n, "runs");
1800
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1801
        j.sort();
1802
        // Passed, so the next push is scoped against it, not superseding it.
1803
        sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(runs[0].id).execute(&app.db).await.unwrap();
1804
        j
1805
    };
1806
    assert_eq!(names(h.app.clone(), 1).await, ["build", "dist", "lint", "test"], "the first run has every job");
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
    assert_eq!(names(h.app.clone(), 2).await, ["build", "lint", "test"], "dist is out of scope");
1811
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1812
    c.commit("Release 0.1.1", &[]).unwrap();
1813
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1814
    assert_eq!(names(h.app.clone(), 3).await, ["build", "dist", "lint", "test"], "a version bump runs dist");
1815
}
1816
1817
/// oxygenflow#32: a run still going is cancelled from the API, the web or
1818
/// by a newer push to its bookmark; its runner is refused from then on,
1819
/// and the next push is scoped past the cancelled run.
1820
#[tokio::test(flavor = "multi_thread")]
1821
async fn runs_are_cancelled_by_hand_or_by_a_newer_push() {
1822
    let h = hub().await;
1823
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1824
    create(&h.app, "andy", "stop").await;
1825
    let url = format!("{}/andy/stop", h.base);
1826
    let work = tempfile::tempdir().unwrap();
1827
    let c = client(&url, work.path());
1828
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\"\n    exec \"true\"\n}\n";
1829
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1830
    write(work.path(), "test.sh", "echo ok\n");
1831
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1832
    c.commit("Start", &[]).unwrap();
1833
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1834
    let wait_runs = |app: Shared, n: usize| async move {
1835
        for _ in 0..100 {
1836
            let runs = runs_of(&app, "andy", "stop").await;
1837
            if runs.len() >= n {
1838
                return runs;
1839
            }
1840
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1841
        }
1842
        panic!("no run {n}");
1843
    };
1844
    let first = wait_runs(h.app.clone(), 1).await;
1845
    sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(first[0].id).execute(&h.app.db).await.unwrap();
1846
    sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE run_id = $1").bind(first[0].id).execute(&h.app.db).await.unwrap();
1847
1848
    // Run 2 (a version bump) has a job running when run 3 is pushed.
1849
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1850
    c.commit("Release 0.1.1", &[]).unwrap();
1851
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1852
    wait_runs(h.app.clone(), 2).await;
1853
    let job = claim(&h.app).await.expect("a job of run 2");
1854
    let id = job["job_id"].as_i64().unwrap();
1855
    write(work.path(), "test.sh", "echo still ok\n");
1856
    c.commit("Edit the test", &[]).unwrap();
1857
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1858
    let runs = wait_runs(h.app.clone(), 3).await;
1859
    let third = &runs[0];
1860
    let mut second = runs[1].clone();
1861
    for _ in 0..100 {
1862
        second = db::flow::run_by_id(&h.app.db, runs[1].id).await.unwrap().unwrap();
1863
        if !second.live() {
1864
            break;
1865
        }
1866
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1867
    }
1868
    assert_eq!(second.status, "cancelled", "a newer push supersedes a run still going");
1869
    let jobs = db::flow::jobs(&h.app.db, second.id).await.unwrap();
1870
    assert!(jobs.iter().all(|j| j.status == "cancelled" && j.error == "superseded by run #3"), "{jobs:?}");
1871
    let mut names: Vec<String> = db::flow::jobs(&h.app.db, third.id).await.unwrap().into_iter().map(|j| j.name).collect();
1872
    names.sort();
1873
    assert_eq!(names, ["build", "dist", "lint", "test"], "run 3 also checks what run 2 would have: the version bump");
1874
    let mut checks = vec![];
1875
    for _ in 0..100 {
1876
        checks = db::hooks::checks_for_state(&h.app.db, second.repo_id, &second.state).await.unwrap();
1877
        if checks.iter().all(|c| c.status == "cancelled") {
1878
            break;
1879
        }
1880
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1881
    }
1882
    assert!(checks.iter().all(|c| c.status == "cancelled"), "{checks:?}");
1883
    // The runner of the cancelled job is refused, so it stops the job.
1884
    let (st, _) =
1885
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(r#"{"records":[]}"#.into())).await;
1886
    assert_eq!(st, StatusCode::CONFLICT);
1887
1888
    // By hand: the API, then a run already ended is refused.
1889
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
1890
    assert_eq!(st, StatusCode::OK, "{body}");
1891
    let third = db::flow::run_by_id(&h.app.db, third.id).await.unwrap().unwrap();
1892
    assert_eq!(third.status, "cancelled");
1893
    assert!(db::flow::jobs(&h.app.db, third.id).await.unwrap().iter().all(|j| j.error == "cancelled by andy"));
1894
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
1895
    assert!(st == StatusCode::CONFLICT && body.contains("already cancelled"), "{st} {body}");
1896
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", None, None).await;
1897
    assert_ne!(st, StatusCode::OK, "anonymous callers cannot cancel");
1898
    let (_, page) = call(&h.app, "GET", "/andy/stop/flow/3", None, None).await;
1899
    assert!(page.contains("⊘") && !page.contains("CANCEL</button>"), "a cancelled run shows so, with no button");
1900
}
1901
1902
/// oxygenflow#23 and oxygenhub#89: a job runs under its pipeline's
1903
/// timeout, capped at the site's maximum, else the site's default; and the
1904
/// hub gives a job up only past its own limit.
1905
#[tokio::test(flavor = "multi_thread")]
1906
async fn a_job_runs_under_its_own_time_limit_within_the_sites() {
1907
    let h = hub().await;
1908
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1909
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_DEFAULT, "30").await.unwrap();
1910
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_MAX, "120").await.unwrap();
1911
    create(&h.app, "andy", "limits").await;
1912
    let url = format!("{}/andy/limits", h.base);
1913
    let work = tempfile::tempdir().unwrap();
1914
    let c = client(&url, work.path());
1915
    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";
1916
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1917
    write(work.path(), "test.sh", "echo ok\n");
1918
    c.commit("Add a pipeline", &[]).unwrap();
1919
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1920
    assert_eq!(runs_of(&h.app, "andy", "limits").await.len(), 1);
1921
    let mut limits = std::collections::HashMap::new();
1922
    let mut ids = std::collections::HashMap::new();
1923
    while let Some(j) = claim(&h.app).await {
1924
        let name = j["job"]["name"].as_str().unwrap().to_string();
1925
        limits.insert(name.clone(), j["timeout_s"].as_u64().unwrap());
1926
        ids.insert(name, j["job_id"].as_i64().unwrap());
1927
    }
1928
    assert_eq!(limits["slow"], 5400, "its own");
1929
    assert_eq!(limits["huge"], 7200, "cut to the site's maximum");
1930
    assert_eq!(limits["build"], 1800, "the site's default");
1931
    // 40 minutes in: past the default and its grace, within slow's limit.
1932
    let started = db::now_ms() - 40 * 60 * 1000;
1933
    sqlx::query("UPDATE flow_jobs SET started_ms = $1").bind(started).execute(&h.app.db).await.unwrap();
1934
    oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap();
1935
    let status = |id: i64| {
1936
        let app = h.app.clone();
1937
        async move { db::flow::job(&app.db, id).await.unwrap().unwrap().status }
1938
    };
1939
    assert_eq!(status(ids["build"]).await, "error", "past its 30 minutes");
1940
    assert_eq!(status(ids["slow"]).await, "running", "within its 90");
1941
    assert_eq!(status(ids["huge"]).await, "running", "within its 120");
1942
}
1943
1944
/// oxygenflow#24: a job's `on` decides which events start it: a pushed
1945
/// tag runs only the jobs that name it; a push to a bookmark the pipeline
1946
/// does not name starts no run; a rerun repeats its run's event.
1947
#[tokio::test(flavor = "multi_thread")]
1948
async fn on_decides_which_events_start_a_job() {
1949
    let h = hub().await;
1950
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1951
    create(&h.app, "andy", "events").await;
1952
    let url = format!("{}/andy/events", h.base);
1953
    let work = tempfile::tempdir().unwrap();
1954
    let c = client(&url, work.path());
1955
    let text = format!(
1956
        "on {{\n    push \"main\"\n    manual\n}}\n{}job \"dist\" {{\n    sandbox \"alpine\"\n    on {{\n        tag \"v*\"\n    }}\n    exec \"true\"\n}}\n",
1957
        pipeline("")
1958
    );
1959
    // `on` must come after schema-version; pipeline() starts with it.
1960
    let text = text.replacen(
1961
        "on {\n    push \"main\"\n    manual\n}\nschema-version 1\n",
1962
        "schema-version 1\non {\n    push \"main\"\n    manual\n}\n",
1963
        1,
1964
    );
1965
    write(work.path(), ".flow/pipeline.kdl", &text);
1966
    write(work.path(), "test.sh", "echo ok\n");
1967
    c.commit("Start", &[]).unwrap();
1968
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1969
    let jobs_of_latest = |app: Shared, n: usize| async move {
1970
        let mut runs = Vec::new();
1971
        for _ in 0..100 {
1972
            runs = runs_of(&app, "andy", "events").await;
1973
            if runs.len() >= n {
1974
                break;
1975
            }
1976
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1977
        }
1978
        assert_eq!(runs.len(), n, "runs");
1979
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1980
        j.sort();
1981
        (runs[0].clone(), j)
1982
    };
1983
    let (_, j) = jobs_of_latest(h.app.clone(), 1).await;
1984
    assert_eq!(j, ["build", "lint", "test"], "a push to main: no dist");
1985
    // A tag: only dist.
1986
    let heads = c.bookmark_heads().unwrap();
1987
    c.tag_create("v1.0.0", &heads, "first").unwrap();
1988
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1989
    let (run, j) = jobs_of_latest(h.app.clone(), 2).await;
1990
    assert_eq!(j, ["dist"], "a tag runs only what names it");
1991
    assert_eq!(run.trigger, "tag:v1.0.0");
1992
    // A rerun repeats the tag's event.
1993
    let row = db::repos::get(&h.app.db, "andy", "events").await.unwrap().unwrap();
1994
    db::flow::finish(
1995
        &h.app.db,
1996
        db::flow::jobs(&h.app.db, run.id).await.unwrap()[0].id,
1997
        db::flow::Outcome { status: "passed", exit_code: Some(0), error: "", receipt: "", receipt_hash: "" },
1998
    )
1999
    .await
2000
    .unwrap();
2001
    let run = db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap();
2002
    oxygenhub::flow::rerun(&h.app, &row, &run, "andy").await.unwrap();
2003
    let (_, j) = jobs_of_latest(h.app.clone(), 3).await;
2004
    assert_eq!(j, ["dist"], "the rerun is the tag's run again");
2005
    // A bookmark the pipeline does not name starts nothing.
2006
    c.bookmark_create("develop", None).unwrap();
2007
    assert!(c.push_bookmark("origin", "develop", false).unwrap().iter().all(|r| r.ok));
2008
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
2009
    assert_eq!(runs_of(&h.app, "andy", "events").await.len(), 3, "no run for develop");
2010
}
2011
2012
/// oxygenflow#24: a job with a `schedule` line runs on the default
2013
/// bookmark when the line comes due, and only then; other jobs stay out.
2014
#[tokio::test(flavor = "multi_thread")]
2015
async fn scheduled_jobs_run_when_due() {
2016
    let h = hub().await;
2017
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2018
    create(&h.app, "andy", "nightly").await;
2019
    let url = format!("{}/andy/nightly", h.base);
2020
    let work = tempfile::tempdir().unwrap();
2021
    let c = client(&url, work.path());
2022
    // An odd minute, so the hub's own ticker cannot fire it during the test.
2023
    let extra = "job \"nightly\" {\n    sandbox \"alpine\"\n    on {\n        schedule \"17 4 29 2 *\"\n    }\n    exec \"true\"\n}\n";
2024
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
2025
    write(work.path(), "test.sh", "echo ok\n");
2026
    c.commit("Start", &[]).unwrap();
2027
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2028
    assert_eq!(runs_of(&h.app, "andy", "nightly").await.len(), 1);
2029
    let first = runs_of(&h.app, "andy", "nightly").await;
2030
    let names: Vec<String> = db::flow::jobs(&h.app.db, first[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
2031
    assert!(!names.contains(&"nightly".to_string()), "a push does not run a scheduled job");
2032
    use flow_core::pipeline::When;
2033
    let not_yet = When { minute: 16, hour: 4, day: 29, month: 2, weekday: 4 };
2034
    assert_eq!(oxygenhub::flow::run_due(&h.app, not_yet).await, 0);
2035
    let due = When { minute: 17, ..not_yet };
2036
    assert_eq!(oxygenhub::flow::run_due(&h.app, due).await, 1);
2037
    let runs = runs_of(&h.app, "andy", "nightly").await;
2038
    assert_eq!(runs.len(), 2);
2039
    assert_eq!(runs[0].trigger, "schedule");
2040
    let names: Vec<String> = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
2041
    assert_eq!(names, ["nightly"]);
2042
    assert_eq!(runs[0].bookmark, "main", "on the default bookmark");
2043
}
2044
2045
#[tokio::test(flavor = "multi_thread")]
2046
async fn variables_from_three_levels_reach_a_job_inner_overriding_outer() {
2047
    use oxygenhub::levels::Scope;
2048
    use oxygenhub::variables;
2049
    let h = hub().await;
2050
    let app = &h.app;
2051
    // Andy, the site's administrator, owns the acme organisation.
2052
    let res = oxygenhub::router(app.clone())
2053
        .oneshot(
2054
            Request::post("/register")
2055
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
2056
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
2057
                .unwrap(),
2058
        )
2059
        .await
2060
        .unwrap();
2061
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
2062
    let andy = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
2063
    db::accounts::create_org(&app.db, "acme", "Acme", andy.id).await.unwrap();
2064
    create(app, "acme", "app").await;
2065
    let page = |path: &str, form: Option<String>| {
2066
        let mut req =
2067
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2068
        if form.is_some() {
2069
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2070
        }
2071
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
2072
        let app = app.clone();
2073
        async move {
2074
            let res = oxygenhub::router(app).oneshot(req).await.unwrap();
2075
            let status = res.status();
2076
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2077
            (status, body)
2078
        }
2079
    };
2080
    let csrf_of = |page: &str| {
2081
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2082
        page[i..].split('"').next().unwrap().to_string()
2083
    };
2084
2085
    // The site sets CC and LANG, the organisation its own CC, the
2086
    // repository RUST_LOG from its settings page.
2087
    variables::set(&app.db, Scope::Site, "CC", "gcc").await.unwrap();
2088
    variables::set(&app.db, Scope::Site, "LANG", "C").await.unwrap();
2089
    let org = db::accounts::org_by_name(&app.db, "acme").await.unwrap().unwrap();
2090
    variables::set(&app.db, Scope::Org(org.id), "CC", "clang").await.unwrap();
2091
    let (st, settings) = page("/acme/app/settings", None).await;
2092
    assert_eq!(st, StatusCode::OK, "{settings}");
2093
    assert!(settings.contains("Inherited") && settings.contains("the acme organisation") && settings.contains("overridden"), "{settings}");
2094
    let csrf = csrf_of(&settings);
2095
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=RUST_LOG&value=debug"))).await;
2096
    assert!(body.contains("RUST_LOG set.") && body.contains("<code>debug</code>"), "{body}");
2097
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=FLOW_REPO&value=x"))).await;
2098
    assert!(body.contains("not FLOW_"), "{body}");
2099
    let repo = db::repos::get(&app.db, "acme", "app").await.unwrap().unwrap();
2100
    db::repos::set_flow(&app.db, repo.id, "on").await.unwrap();
2101
    let env = variables::env_for_repo(&app.db, &repo).await.unwrap();
2102
    assert_eq!(
2103
        env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect::<Vec<_>>(),
2104
        [("CC", "clang"), ("LANG", "C"), ("RUST_LOG", "debug")],
2105
        "the organisation's CC wins over the site's"
2106
    );
2107
2108
    // A claim carries them.
2109
    let url = format!("{}/acme/app", h.base);
2110
    let work = tempfile::tempdir().unwrap();
2111
    let c = client(&url, work.path());
2112
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2113
    write(work.path(), "test.sh", "echo ok\n");
2114
    c.snapshot("test").unwrap();
2115
    c.commit("Add a pipeline", &[]).unwrap();
2116
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2117
    let runs = runs_of(app, "acme", "app").await;
2118
    assert_eq!(runs.len(), 1, "{runs:?}");
2119
    let got = claim(app).await.unwrap_or_else(|| panic!("a job: {:?}", runs[0]));
2120
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "LANG": "C", "RUST_LOG": "debug" }), "{got}");
2121
2122
    // Removing a site variable from the admin page takes effect at the next claim.
2123
    let (_, admin) = page("/admin", None).await;
2124
    assert!(admin.contains("Variables") && admin.contains("<code>gcc</code>"), "{admin}");
2125
    let (_, body) = page("/admin/variables", Some(format!("_csrf={}&action=delete&name=LANG", csrf_of(&admin)))).await;
2126
    assert!(body.contains("LANG removed."), "{body}");
2127
    let got = claim(app).await.expect("another job");
2128
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "RUST_LOG": "debug" }), "{got}");
2129
}
2130
2131
#[tokio::test(flavor = "multi_thread")]
2132
async fn secrets_a_job_declares_come_with_the_claim_and_never_reach_the_log() {
2133
    let h = hub().await;
2134
    let app = &h.app;
2135
    let res = oxygenhub::router(app.clone())
2136
        .oneshot(
2137
            Request::post("/register")
2138
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
2139
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
2140
                .unwrap(),
2141
        )
2142
        .await
2143
        .unwrap();
2144
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
2145
    let page = |path: &str, form: Option<String>| {
2146
        let mut req =
2147
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2148
        if form.is_some() {
2149
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2150
        }
2151
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
2152
        let app = app.clone();
2153
        async move {
2154
            let res = oxygenhub::router(app).oneshot(req).await.unwrap();
2155
            let status = res.status();
2156
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2157
            (status, body)
2158
        }
2159
    };
2160
    let csrf_of = |page: &str| {
2161
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2162
        page[i..].split('"').next().unwrap().to_string()
2163
    };
2164
    create(app, "andy", "demo").await;
2165
    // The site sets deploy-token; the repository overrides it. Neither
2166
    // page shows a value, only that it is set.
2167
    let (_, admin) = page("/admin", None).await;
2168
    let csrf = csrf_of(&admin);
2169
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=deploy-token&value=site-level-value"))).await;
2170
    assert!(body.contains("deploy-token set.") && !body.contains("site-level-value"), "{body}");
2171
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=bad+name&value=x"))).await;
2172
    assert!(body.contains("name is 1 to 64 of"), "{body}");
2173
    let (_, settings) = page("/andy/demo/settings", None).await;
2174
    assert!(
2175
        settings.contains("Secrets") && settings.contains("<code>deploy-token</code>") && settings.contains("the site</td>"),
2176
        "{settings}"
2177
    );
2178
    let csrf_r = csrf_of(&settings);
2179
    let (_, body) =
2180
        page("/andy/demo/settings/secrets", Some(format!("_csrf={csrf_r}&action=set&name=deploy-token&value=hunter22-repo-value"))).await;
2181
    assert!(body.contains("deploy-token set.") && body.contains("overridden") && !body.contains("hunter22"), "{body}");
2182
    let repo = db::repos::get(&app.db, "andy", "demo").await.unwrap().unwrap();
2183
    assert!(
2184
        !String::from_utf8_lossy(&oxygenhub::secrets::list(&app.db, oxygenhub::levels::Scope::Repo(repo.id)).await.unwrap()[0].value)
2185
            .contains("hunter22"),
2186
        "sealed at rest"
2187
    );
2188
2189
    // A job that declares the secret, and one the levels do not hold.
2190
    let url = format!("{}/andy/demo", h.base);
2191
    let work = tempfile::tempdir().unwrap();
2192
    let c = client(&url, work.path());
2193
    write(
2194
        work.path(),
2195
        ".flow/pipeline.kdl",
2196
        &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"),
2197
    );
2198
    write(work.path(), "test.sh", "echo ok\n");
2199
    c.snapshot("test").unwrap();
2200
    c.commit("Add a pipeline", &[]).unwrap();
2201
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2202
    let runs = runs_of(app, "andy", "demo").await;
2203
    let jobs = match runs.first() {
2204
        Some(r) => db::flow::jobs(&app.db, r.id).await.unwrap().iter().map(|j| format!("{}:{}", j.name, j.status)).collect::<Vec<_>>(),
2205
        None => vec![],
2206
    };
2207
    let mut deploy = None;
2208
    for _ in 0..50 {
2209
        let Some(got) = claim(app).await else {
2210
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2211
            continue;
2212
        };
2213
        if got["job"]["name"] == "deploy" {
2214
            deploy = Some(got);
2215
            break;
2216
        }
2217
        assert_eq!(got["secrets"], serde_json::Value::Null, "{got}");
2218
    }
2219
    let got = deploy.unwrap_or_else(|| panic!("the deploy job: runs {runs:?} jobs {jobs:?}"));
2220
    assert_eq!(
2221
        got["secrets"],
2222
        serde_json::json!([{ "name": "deploy-token", "path": "/run/secrets/token", "value": "hunter22-repo-value" }]),
2223
        "the repository's value, the missing one left out: {got}"
2224
    );
2225
    let id = got["job_id"].as_i64().unwrap();
2226
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2227
    assert!(log.iter().any(|l| l.stream == "flow" && l.text.contains("secret \"missing\" is not set")), "{log:?}");
2228
2229
    // The value never reaches the stored log, plain or base64.
2230
    let records = serde_json::json!({ "records": [
2231
        { "t": 1, "stream": "out", "text": "token=hunter22-repo-value" },
2232
        { "t": 2, "stream": "err", "text": "b64 aHVudGVyMjItcmVwby12YWx1ZQ== end" },
2233
    ] });
2234
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2235
    assert_eq!(st, StatusCode::NO_CONTENT);
2236
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2237
    let texts: Vec<&str> = log.iter().map(|l| l.text.as_str()).collect();
2238
    assert!(texts.contains(&"token=***") && texts.contains(&"b64 *** end"), "{texts:?}");
2239
    assert!(!texts.iter().any(|t| t.contains("hunter22")), "{texts:?}");
2240
}
2241
2242
#[tokio::test(flavor = "multi_thread")]
2243
async fn a_job_s_identity_is_a_signed_token_the_discovery_document_lets_anyone_verify() {
2244
    let h = hub().await;
2245
    let app = &h.app;
2246
    let (st, disc) = call(app, "GET", "/.well-known/openid-configuration", None, None).await;
2247
    assert_eq!(st, StatusCode::OK, "{disc}");
2248
    let disc: serde_json::Value = serde_json::from_str(&disc).unwrap();
2249
    assert_eq!(disc["issuer"], h.base.as_str());
2250
    assert_eq!(disc["jwks_uri"], format!("{}/.well-known/jwks.json", h.base));
2251
    let (st, jwks) = call(app, "GET", "/.well-known/jwks.json", None, None).await;
2252
    assert_eq!(st, StatusCode::OK, "{jwks}");
2253
    let jwks: serde_json::Value = serde_json::from_str(&jwks).unwrap();
2254
    assert_eq!(jwks["keys"][0]["alg"], "RS256");
2255
    let kid = jwks["keys"][0]["kid"].as_str().unwrap().to_string();
2256
2257
    create(app, "andy", "demo").await;
2258
    let url = format!("{}/andy/demo", h.base);
2259
    let work = tempfile::tempdir().unwrap();
2260
    let c = client(&url, work.path());
2261
    write(
2262
        work.path(),
2263
        ".flow/pipeline.kdl",
2264
        &pipeline("job \"deploy\" {\n    sandbox \"alpine\"\n    identity \"sts.amazonaws.com\" {\n        mount-path \"/run/secrets/aws-token\"\n    }\n    exec \"deploy\"\n}\n"),
2265
    );
2266
    write(work.path(), "test.sh", "echo ok\n");
2267
    c.snapshot("test").unwrap();
2268
    c.commit("Add a pipeline", &[]).unwrap();
2269
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2270
    let mut deploy = None;
2271
    for _ in 0..50 {
2272
        let Some(got) = claim(app).await else {
2273
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2274
            continue;
2275
        };
2276
        if got["job"]["name"] == "deploy" {
2277
            deploy = Some(got);
2278
            break;
2279
        }
2280
    }
2281
    let got = deploy.expect("the deploy job");
2282
    let secrets = got["secrets"].as_array().expect("secrets");
2283
    assert_eq!(secrets.len(), 1);
2284
    assert_eq!(
2285
        (secrets[0]["name"].as_str(), secrets[0]["path"].as_str()),
2286
        (Some("identity:sts.amazonaws.com"), Some("/run/secrets/aws-token"))
2287
    );
2288
    let token = secrets[0]["value"].as_str().unwrap().to_string();
2289
    let issuer = app.oidc().await.unwrap();
2290
    assert_eq!(issuer.kid, kid, "the key the JWKS publishes signed it");
2291
    let claims = issuer.verify(&token, "sts.amazonaws.com", db::now_ms()).expect("verifies");
2292
    assert_eq!(claims["sub"], "repo:andy/demo:bookmark:main");
2293
    assert_eq!(claims["repository"], "andy/demo");
2294
    assert_eq!(claims["job"], "deploy");
2295
    assert_eq!(claims["run_number"], 1);
2296
    assert_eq!(claims["runner"], "test-1");
2297
    assert_eq!(claims["iss"], h.base.as_str());
2298
    assert!(claims["state"].as_str().unwrap().len() == 64);
2299
    // A job that prints its token leaves *** in the log.
2300
    let id = got["job_id"].as_i64().unwrap();
2301
    let records = serde_json::json!({ "records": [{ "t": 1, "stream": "out", "text": format!("TOKEN={token} end") }] });
2302
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2303
    assert_eq!(st, StatusCode::NO_CONTENT);
2304
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2305
    assert!(log.iter().any(|l| l.text == "TOKEN=*** end"), "{log:?}");
2306
}
2307
2308
#[tokio::test(flavor = "multi_thread")]
2309
async fn jobs_are_offered_only_to_runners_of_their_architecture() {
2310
    let h = hub().await;
2311
    let app = &h.app;
2312
    create(app, "andy", "demo").await;
2313
    let url = format!("{}/andy/demo", h.base);
2314
    let work = tempfile::tempdir().unwrap();
2315
    let c = client(&url, work.path());
2316
    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)));
2317
    write(work.path(), "test.sh", "echo ok\n");
2318
    c.snapshot("test").unwrap();
2319
    c.commit("Add a pipeline", &[]).unwrap();
2320
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2321
    let claim_as = |arch: &'static str, archs: serde_json::Value| {
2322
        let app = app.clone();
2323
        async move {
2324
            let body = serde_json::json!({
2325
                "runner": format!("{arch}-1"), "runtimes": ["microvm"],
2326
                "info": { "arch": arch, "os": "linux", "version": "t", "labels": [], "max_jobs": 1 },
2327
                "image_archs": archs,
2328
            });
2329
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
2330
            match st {
2331
                StatusCode::NO_CONTENT => None,
2332
                StatusCode::OK => {
2333
                    Some(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"].as_str().unwrap().to_string())
2334
                }
2335
                other => panic!("claim: {other} {body}"),
2336
            }
2337
        }
2338
    };
2339
    // An x86_64 runner that says the alpine image is x86_64: it takes the
2340
    // alpine jobs, never the one that asks for riscv64.
2341
    let rootfs = pipeline("").split("cas://blob/").nth(1).unwrap()[..64].to_string();
2342
    for _ in 0..50 {
2343
        if !runs_of(app, "andy", "demo").await.is_empty() {
2344
            break;
2345
        }
2346
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2347
    }
2348
    let runs = runs_of(app, "andy", "demo").await;
2349
    assert_eq!(runs.len(), 1, "{runs:?}");
2350
    let mut taken = vec![];
2351
    while let Some(j) = claim_as("x86_64", serde_json::json!({ rootfs.clone(): "x86_64" })).await {
2352
        taken.push(j);
2353
    }
2354
    assert_eq!(taken, ["build", "lint"], "test waits for build; flash is for riscv64");
2355
    // A riscv64 runner: the alpine image is known to be x86_64, so only flash.
2356
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await.as_deref(), Some("flash"));
2357
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await, None);
2358
    let (_, queue) = call(app, "GET", "/admin/runners", None, None).await;
2359
    let _ = queue;
2360
}
2361
2362
/// OxygenFlow spec §11.5: a runner hands back a job it cannot run. The
2363
/// job is queued again and not offered to that runner again, the decline
2364
/// shows on the run's page and is kept for the runner's, and once three
2365
/// runners have declined it the job ends as unplaceable with their reasons.
2366
#[tokio::test(flavor = "multi_thread")]
2367
async fn a_declined_job_goes_to_another_runner_or_ends_unplaceable() {
2368
    let h = hub().await;
2369
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2370
    create(&h.app, "andy", "declines").await;
2371
    let url = format!("{}/andy/declines", h.base);
2372
    let work = tempfile::tempdir().unwrap();
2373
    let c = client(&url, work.path());
2374
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2375
    write(work.path(), "test.sh", "echo ok\n");
2376
    c.commit("Add a pipeline", &[]).unwrap();
2377
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2378
    let run = runs_of(&h.app, "andy", "declines").await[0].clone();
2379
    let claim_as = |token: &'static str, name: &'static str| {
2380
        let app = h.app.clone();
2381
        async move {
2382
            let body = serde_json::json!({ "runner": name, "runtimes": ["microvm"] }).to_string();
2383
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(token), Some(body)).await;
2384
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap())
2385
        }
2386
    };
2387
    let decline = |token: &'static str, id: i64, reason: &'static str| {
2388
        let app = h.app.clone();
2389
        async move {
2390
            let body = serde_json::json!({ "reason": reason }).to_string();
2391
            call(&app, "POST", &format!("/api/v1/flow/jobs/{id}/decline"), Some(token), Some(body)).await.0
2392
        }
2393
    };
2394
    let job = claim_as("runner-secret", "earth-1").await.expect("a job");
2395
    // The other runners are known to the hub before they decline anything.
2396
    assert_eq!(decline("runner-two", job, "not mine").await, StatusCode::CONFLICT, "only the runner it runs on may decline it");
2397
    assert_eq!(decline("runner-secret", job, "the MicroVM tier needs /dev/kvm").await, StatusCode::NO_CONTENT);
2398
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2399
    assert_eq!((j.status.as_str(), j.runner.as_str()), ("queued", ""));
2400
    assert_eq!(j.waiting, "declined by earth-1: the MicroVM tier needs /dev/kvm; waiting for another runner");
2401
    // earth-1 is offered the other ready job, not this one, while it stays the same.
2402
    let next = claim_as("runner-secret", "earth-1").await.expect("the other ready job");
2403
    assert_ne!(next, job);
2404
    let page = call(&h.app, "GET", &format!("/andy/declines/flow/{}", run.number), None, None).await.1;
2405
    assert!(page.contains("Waiting: declined by earth-1: the MicroVM tier needs /dev/kvm"), "{page}");
2406
    assert_eq!(claim_as("runner-two", "plex-1").await, Some(job), "another runner takes it");
2407
    assert_eq!(decline("runner-two", job, "rootfs 36fc4e323804 is not on this runner").await, StatusCode::NO_CONTENT);
2408
    assert_eq!(claim_as("runner-three", "narvi").await, Some(job));
2409
    assert_eq!(decline("runner-three", job, "rootfs 36fc4e323804 is for x86_64; this runner is riscv64").await, StatusCode::NO_CONTENT);
2410
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2411
    assert_eq!(j.status, "error");
2412
    assert_eq!(
2413
        j.error,
2414
        "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"
2415
    );
2416
    let r = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex-1").unwrap();
2417
    let declined = db::flow::declines_of_runner(&h.app.db, r.id, 10).await.unwrap();
2418
    assert_eq!(declined.len(), 1);
2419
    assert_eq!((declined[0].job_id, declined[0].reason.as_str()), (job, "rootfs 36fc4e323804 is not on this runner"));
2420
    assert_eq!(r.tier_list(), vec!["microvm"]);
2421
}
2422
2423
/// oxygenhub#113: a job's artifact named `coverage` (LCOV) is read when
2424
/// it is uploaded. The job's log says what it found; the Coverage tab,
2425
/// the file view, the badge and the run page show it.
2426
#[tokio::test(flavor = "multi_thread")]
2427
async fn a_coverage_artifact_becomes_a_coverage_report() {
2428
    let h = hub().await;
2429
    create(&h.app, "andy", "cov").await;
2430
    let url = format!("{}/andy/cov", h.base);
2431
    let work = tempfile::tempdir().unwrap();
2432
    let c = client(&url, work.path());
2433
    write(
2434
        work.path(),
2435
        ".flow/pipeline.kdl",
2436
        &format!(
2437
            "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"
2438
        ),
2439
    );
2440
    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");
2441
    c.snapshot("test").unwrap();
2442
    c.commit("Code and coverage", &[]).unwrap();
2443
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2444
    let run = runs_of(&h.app, "andy", "cov").await.remove(0);
2445
    assert!(!call(&h.app, "GET", "/andy/cov", None, None).await.1.contains(">Reports</a>"), "no tab before a report");
2446
    let id = claim(&h.app).await.unwrap()["job_id"].as_i64().unwrap();
2447
2448
    let (st, text) = upload(&h.app, id, "coverage", b"this is not a report").await;
2449
    assert_eq!(st, StatusCode::OK, "a bad report never fails the upload: {text}");
2450
    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\
2451
SF:/src/src/gone.rs\nDA:1,1\nend_of_record\nSF:/usr/lib/rustlib/x.rs\nDA:1,1\nend_of_record\n";
2452
    let (st, text) = upload(&h.app, id, "coverage", lcov.as_bytes()).await;
2453
    assert_eq!(st, StatusCode::OK, "{text}");
2454
    let log: Vec<String> = db::flow::log(&h.app.db, id, 0, 50).await.unwrap().into_iter().map(|l| l.text).collect();
2455
    assert!(log.iter().any(|l| l.contains("coverage: this is not an LCOV report")), "{log:?}");
2456
    assert!(
2457
        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)"),
2458
        "{log:?}"
2459
    );
2460
2461
    let (st, page) = call(&h.app, "GET", "/andy/cov/coverage", None, None).await;
2462
    assert_eq!(st, StatusCode::OK);
2463
    assert!(
2464
        page.contains(">Reports</a>")
2465
            && page.contains("50.0%")
2466
            && page.contains("<strong>2</strong> of <strong>4</strong> relevant lines covered"),
2467
        "{page}"
2468
    );
2469
    assert!(page.contains("1 of 2") && page.contains("/andy/cov/coverage/") && page.contains("/file/src/lib.rs"), "{page}");
2470
    let report = crate_report(&h.app, run.id).await;
2471
    let (st, file) = call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/lib.rs"), None, None).await;
2472
    assert_eq!(st, StatusCode::OK, "{file}");
2473
    assert_eq!(file.matches("class=\"cov-hit\"").count(), 2, "{file}");
2474
    assert_eq!(file.matches("class=\"cov-miss\"").count(), 2, "{file}");
2475
    assert!(file.contains("3×"), "{file}");
2476
    assert_eq!(call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/gone.rs"), None, None).await.0, StatusCode::NOT_FOUND);
2477
    let (_, badge) = call(&h.app, "GET", "/andy/cov/coverage/badge.svg", None, None).await;
2478
    assert!(badge.contains("coverage: 50.0%"), "{badge}");
2479
    let (_, run_page) = call(&h.app, "GET", &format!("/andy/cov/flow/{}", run.number), None, None).await;
2480
    assert!(run_page.contains("coverage 50.0%"), "{run_page}");
2481
    // The API (#113).
2482
    let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/cov/coverage", None, None).await;
2483
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
2484
    assert_eq!((list[0]["percent"].as_f64(), list[0]["format"].as_str()), (Some(50.0), Some("lcov")), "{list}");
2485
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/cov/coverage/{report}"), None, None).await;
2486
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
2487
    assert_eq!((one["files"][0]["path"].as_str(), one["files"][0]["lines_hit"].as_i64()), (Some("src/lib.rs"), Some(2)), "{one}");
2488
2489
    // The `coverage` check on the run's state: it reports, and with a
2490
    // minimum the repository sets, it fails below it.
2491
    let row = db::repos::get(&h.app.db, "andy", "cov").await.unwrap().unwrap();
2492
    let check = |checks: Vec<db::hooks::Check>| checks.into_iter().find(|c| c.name == "coverage").expect("a coverage check");
2493
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
2494
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "50.0%"));
2495
    assert!(c.url.ends_with(&format!("/andy/cov/coverage?report={report}")), "{}", c.url);
2496
    oxygenhub::coverage::set_rules(&h.app.db, row.id, oxygenhub::coverage::Rules { min: Some(60.0), max_drop: None }).await.unwrap();
2497
    assert_eq!(upload(&h.app, id, "coverage", lcov.as_bytes()).await.0, StatusCode::OK);
2498
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
2499
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "50.0%: below the minimum of 60%"));
2500
}
2501
2502
async fn crate_report(app: &Shared, run_id: i64) -> i64 {
2503
    oxygenhub::coverage::for_run(&app.db, run_id).await.unwrap()[0].id
2504
}
2505
2506
/// The Tests tab (#114): three runs' JUnit reports on a bookmark; a test
2507
/// breaks in the second and is fixed in the third.
2508
#[tokio::test(flavor = "multi_thread")]
2509
async fn junit_reports_make_a_tests_tab() {
2510
    let h = hub().await;
2511
    create(&h.app, "andy", "t").await;
2512
    let url = format!("{}/andy/t", h.base);
2513
    let work = tempfile::tempdir().unwrap();
2514
    let c = client(&url, work.path());
2515
    write(
2516
        work.path(),
2517
        ".flow/pipeline.kdl",
2518
        &format!(
2519
            "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"
2520
        ),
2521
    );
2522
    assert!(!call(&h.app, "GET", "/andy/t", None, None).await.1.contains(">Reports</a>"));
2523
    let case = |name: &str, ok: bool, secs: &str| {
2524
        if ok {
2525
            format!(r#"<testcase classname="t.suite" name="{name}" time="{secs}"/>"#)
2526
        } else {
2527
            format!(
2528
                r#"<testcase classname="t.suite" name="{name}" time="{secs}"><failure message="{name} broke">AssertionError</failure></testcase>"#
2529
            )
2530
        }
2531
    };
2532
    let runs = [
2533
        vec![case("a", true, "0.1"), case("b", true, "2.5"), case("c", true, "0.2")],
2534
        vec![case("a", true, "0.1"), case("b", false, "2.6"), case("c", true, "0.2"), case("d", true, "0.3")],
2535
        vec![case("a", true, "0.1"), case("b", true, "2.4"), case("c", true, "0.2"), case("d", true, "0.3")],
2536
    ];
2537
    for (i, cases) in runs.iter().enumerate() {
2538
        write(work.path(), "n.txt", &i.to_string());
2539
        c.snapshot("test").unwrap();
2540
        c.commit(&format!("Run {i}"), &[]).unwrap();
2541
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2542
        // The run is made after the push answers.
2543
        let mut a = None;
2544
        for _ in 0..100 {
2545
            a = claim(&h.app).await;
2546
            if a.is_some() {
2547
                break;
2548
            }
2549
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2550
        }
2551
        let a = a.expect("a job to claim");
2552
        let id = a["job_id"].as_i64().unwrap();
2553
        let xml = format!("<testsuites><testsuite name=\"t\">{}</testsuite></testsuites>", cases.concat());
2554
        assert_eq!(upload(&h.app, id, "junit", xml.as_bytes()).await.0, StatusCode::OK);
2555
        let failed = cases.iter().any(|c| c.contains("<failure"));
2556
        let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), failed as u32);
2557
        if !failed {
2558
            r["outputs"] = serde_json::json!([oxy_core::repo::Repo::blob_ref(xml.as_bytes()).to_hex()]);
2559
        }
2560
        let code = failed as i32;
2561
        assert_eq!(
2562
            finish(&h.app, id, serde_json::json!({ "exit_code": code, "duration_ms": 700, "receipt": r })).await,
2563
            StatusCode::NO_CONTENT
2564
        );
2565
    }
2566
    let (st, page) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
2567
    assert_eq!(st, StatusCode::OK, "{page}");
2568
    if let Some(out) = std::env::var_os("OXYHUB_DUMP_TESTS_PAGE") {
2569
        std::fs::write(out, &page).unwrap();
2570
    }
2571
    assert!(page.contains(">Reports</a>"), "the tab");
2572
    assert!(page.contains("100%") && page.contains("of 4 tests passed"), "the latest run passes");
2573
    assert!(page.contains("1 fixed") && page.contains("t.suite::b"), "b fixed against the run before");
2574
    assert!(page.contains("1 ✕") && page.contains("2 ✓"), "b is flaky: {page}");
2575
    assert!(page.contains("<svg class=\"cov-chart\""), "charts");
2576
    // The slowest first.
2577
    let slow = page.find("Slowest tests").unwrap();
2578
    assert!(page[slow..].find("t.suite::b").unwrap() < page[slow..].find("t.suite::d").unwrap());
2579
    // The second run, picked: b newly failing, its failure listed.
2580
    let row = db::repos::get(&h.app.db, "andy", "t").await.unwrap().unwrap();
2581
    let second = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap()[1].id;
2582
    let (_, page) = call(&h.app, "GET", &format!("/andy/t/tests?report={second}"), None, None).await;
2583
    assert!(page.contains("1 failing") && page.contains("Newly failing") && page.contains("b broke"), "{page}");
2584
    assert!(page.contains("1 new tests"), "d is new");
2585
2586
    // The API (#114): the bookmark's reports newest first, and one with
2587
    // its failed cases.
2588
    let (st, list) = call(&h.app, "GET", "/api/v1/repos/andy/t/tests", None, None).await;
2589
    assert_eq!(st, StatusCode::OK, "{list}");
2590
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
2591
    assert_eq!(list.as_array().unwrap().len(), 3);
2592
    assert_eq!((list[0]["tests"].as_i64(), list[1]["failed"].as_i64()), (Some(4), Some(1)));
2593
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}?status=failed"), None, None).await;
2594
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
2595
    assert_eq!(one["cases"].as_array().unwrap().len(), 1);
2596
    assert_eq!((one["cases"][0]["name"].as_str(), one["cases"][0]["message"].as_str()), (Some("b"), Some("b broke")));
2597
    let (_, all) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}"), None, None).await;
2598
    assert_eq!(serde_json::from_str::<serde_json::Value>(&all).unwrap()["cases"].as_array().unwrap().len(), 4);
2599
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/t/tests/99999", None, None).await.0, StatusCode::NOT_FOUND);
2600
2601
    // The `tests` check names what broke against main.
2602
    let reports = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap();
2603
    let check = |state: String| {
2604
        let app = h.app.clone();
2605
        async move { db::hooks::checks_for_state(&app.db, row.id, &state).await.unwrap().into_iter().find(|c| c.name == "tests").unwrap() }
2606
    };
2607
    let c = check(reports[1].state.clone()).await;
2608
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "1 failing; 1 new against main: t.suite::b"));
2609
    let c = check(reports[0].state.clone()).await;
2610
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "4 passed"));
2611
2612
    // One test's history: b passed, failed, passed.
2613
    let (_, tab) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
2614
    assert!(
2615
        tab.contains("/andy/t/tests/case?classname=t.suite&amp;name=b") || tab.contains("/andy/t/tests/case?classname=t.suite&name=b"),
2616
        "linked"
2617
    );
2618
    let (st, hist) = call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=b", None, None).await;
2619
    assert_eq!(st, StatusCode::OK, "{hist}");
2620
    assert!(hist.contains("2 passed") && hist.contains("1 failed") && hist.contains("b broke"), "{hist}");
2621
    assert_eq!(call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=nope", None, None).await.0, StatusCode::NOT_FOUND);
2622
}
2623
2624
/// oxygenhub#28: a queued job no runner can take says why, in the API, on
2625
/// the run page (its panel open) and in its check.
2626
#[tokio::test(flavor = "multi_thread")]
2627
async fn a_job_no_runner_can_take_says_why() {
2628
    let h = hub().await;
2629
    create(&h.app, "andy", "demo").await;
2630
    let url = format!("{}/andy/demo", h.base);
2631
    let work = tempfile::tempdir().unwrap();
2632
    let c = client(&url, work.path());
2633
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2634
    write(work.path(), "test.sh", "echo ok\n");
2635
    c.commit("Add a pipeline", &[]).unwrap();
2636
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2637
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
2638
2639
    // One runner, online, holding another image only.
2640
    let r = db::runners::configured(&h.app.db, &blake3::hash(b"elsewhere").to_hex(), "earth-9").await.unwrap();
2641
    db::runners::seen(&h.app.db, r.id, None, None).await.unwrap();
2642
    let other = "ab".repeat(32);
2643
    db::runners::set_offer(&h.app.db, r.id, &["microvm".to_string()], Some(&[other]), false, "p").await.unwrap();
2644
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2645
2646
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2647
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
2648
    let build = v["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "build").unwrap().clone();
2649
    let why = build["waiting"].as_str().unwrap_or_default().to_string();
2650
    assert!(why.contains("earth-9 does not hold image") && why.contains(&ROOTFS[..12]), "{body}");
2651
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/1", None, None).await;
2652
    assert!(page.contains("data-waiting") && page.contains("does not hold image"), "the run page says it");
2653
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
2654
    let check = checks.iter().find(|c| c.name == "flow/build").unwrap();
2655
    assert!(check.summary.contains("does not hold image"), "{check:?}");
2656
}
2657
2658
async fn put_bytes(app: &Shared, path: &str, bearer: &str, bytes: Vec<u8>) -> (StatusCode, String) {
2659
    let req = Request::put(path)
2660
        .header(header::AUTHORIZATION, format!("Bearer {bearer}"))
2661
        .header(header::CONTENT_TYPE, "application/octet-stream")
2662
        .body(Body::from(bytes))
2663
        .unwrap();
2664
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
2665
    let st = res.status();
2666
    (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
2667
}
2668
2669
/// oxygenflow#39: an image is sent as the chunks the hub lacks and then its
2670
/// manifest, checked against its hash; runners fetch it; and a job whose
2671
/// image only the hub holds is offered to a runner that fetches, not to one
2672
/// that does not.
2673
#[tokio::test(flavor = "multi_thread")]
2674
async fn images_are_sent_by_chunk_and_offered_to_runners_that_fetch() {
2675
    let h = hub().await;
2676
    // The site token acts as the first site administrator.
2677
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2678
    // An image: bytes, a run of zeros, more bytes.
2679
    let mut image: Vec<u8> = (0..400_000u32).map(|i| (i % 251) as u8).collect();
2680
    image.extend(std::iter::repeat_n(0u8, 2 << 20));
2681
    image.extend((0..100_000u32).map(|i| (i % 239) as u8));
2682
    let mut chunks = std::collections::HashMap::new();
2683
    let m = jet::images::scan(&image[..], Some("x86_64".into()), |c, b| {
2684
        chunks.insert(c.hash().to_string(), b.to_vec());
2685
        Ok(())
2686
    })
2687
    .unwrap();
2688
    let hash = m.hash.clone();
2689
2690
    // Which chunks the hub lacks: every one but zeros; a manifest before them is refused.
2691
    let ask = serde_json::json!({ "chunks": m.needed() }).to_string();
2692
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask.clone())).await;
2693
    assert_eq!(st, StatusCode::OK, "{body}");
2694
    let missing: Vec<String> = serde_json::from_str::<serde_json::Value>(&body).unwrap()["missing"]
2695
        .as_array()
2696
        .unwrap()
2697
        .iter()
2698
        .map(|v| v.as_str().unwrap().to_string())
2699
        .collect();
2700
    assert_eq!(missing.len(), m.needed().len());
2701
    let manifest = serde_json::to_string(&m).unwrap();
2702
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest.clone())).await;
2703
    assert!(st == StatusCode::CONFLICT && body.contains("was not sent"), "{st} {body}");
2704
    // A chunk is checked against its name; a runner token may not send.
2705
    let first = &missing[0];
2706
    assert_eq!(put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "site", vec![1, 2, 3]).await.0, StatusCode::BAD_REQUEST);
2707
    assert_ne!(
2708
        put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "runner-secret", chunks[first].clone()).await.0,
2709
        StatusCode::NO_CONTENT
2710
    );
2711
    for c in &missing {
2712
        let (st, body) = put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
2713
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
2714
    }
2715
    let (_, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask)).await;
2716
    assert!(body.contains("\"missing\":[]"), "{body}");
2717
    // A large image's question fits (#147): 60,000 names, ~4 MB of JSON.
2718
    let many: Vec<String> = (0..60_000u32).map(|i| blake3::hash(&i.to_le_bytes()).to_hex().to_string()).collect();
2719
    let (st, body) =
2720
        call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(serde_json::json!({ "chunks": many }).to_string())).await;
2721
    assert_eq!(st, StatusCode::OK, "{}", &body[..body.len().min(200)]);
2722
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["missing"].as_array().unwrap().len(), 60_000);
2723
    // A manifest naming another hash is refused; the right one is kept.
2724
    let mut wrong = m.clone();
2725
    wrong.hash = "ab".repeat(32);
2726
    let (st, _) =
2727
        call(&h.app, "PUT", &format!("/api/v1/flow/images/{}", wrong.hash), Some("site"), Some(serde_json::to_string(&wrong).unwrap()))
2728
            .await;
2729
    assert_eq!(st, StatusCode::CONFLICT, "chunks that make another image");
2730
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest)).await;
2731
    assert_eq!(st, StatusCode::CREATED, "{body}");
2732
2733
    // A runner fetches the manifest and the chunks, and the image comes back whole.
2734
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), Some("runner-secret"), None).await;
2735
    assert_eq!(st, StatusCode::OK, "{body}");
2736
    let got: jet::images::Manifest = serde_json::from_str(&body).unwrap();
2737
    assert_eq!(got, m);
2738
    let dir = tempfile::tempdir().unwrap();
2739
    let out = dir.path().join("img.ext4");
2740
    let mut fetched = Vec::new();
2741
    for c in got.needed() {
2742
        let req = Request::get(format!("/api/v1/flow/images/chunks/{c}"))
2743
            .header(header::AUTHORIZATION, "Bearer runner-secret")
2744
            .body(Body::empty())
2745
            .unwrap();
2746
        let res = oxygenhub::router(h.app.clone()).oneshot(req).await.unwrap();
2747
        assert_eq!(res.status(), StatusCode::OK);
2748
        let bytes = res.into_body().collect().await.unwrap().to_bytes().to_vec();
2749
        fetched.push((c.to_string(), bytes));
2750
    }
2751
    jet::images::assemble(&got, &out, |c| Ok(fetched.iter().find(|(h, _)| h == c.hash()).unwrap().1.clone())).unwrap();
2752
    assert_eq!(std::fs::read(&out).unwrap(), image);
2753
    assert_eq!(
2754
        call(&h.app, "GET", &format!("/api/v1/flow/images/{}", "cd".repeat(32)), Some("runner-secret"), None).await.0,
2755
        StatusCode::NOT_FOUND
2756
    );
2757
    assert_ne!(call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), None, None).await.0, StatusCode::OK, "not anonymous");
2758
2759
    // A job on that image: a runner holding no images and not fetching
2760
    // is offered nothing; one that fetches is offered it.
2761
    create(&h.app, "andy", "demo").await;
2762
    let url = format!("{}/andy/demo", h.base);
2763
    let work = tempfile::tempdir().unwrap();
2764
    let c = client(&url, work.path());
2765
    write(
2766
        work.path(),
2767
        ".flow/pipeline.kdl",
2768
        &format!("schema-version 1\nsandbox \"img\" {{\n    rootfs \"cas://blob/{hash}\"\n}}\njob \"build\" {{\n    sandbox \"img\"\n    exec \"make\"\n}}\n"),
2769
    );
2770
    c.commit("Build on the image", &[]).unwrap();
2771
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2772
    runs_of(&h.app, "andy", "demo").await;
2773
    // #137: the run's images are held (by the hub), so no images check.
2774
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2775
    let run1 = db::flow::run(&h.app.db, row.id, 1).await.unwrap().unwrap();
2776
    let checks = checks_when(&h.app, row.id, &run1.state, 1).await;
2777
    assert!(checks.iter().all(|c| c.name != "pipeline/images"), "{checks:?}");
2778
    let ask = |fetches: bool| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":[],"fetches_images":{fetches}}}"#);
2779
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(false))).await;
2780
    assert_eq!(st, StatusCode::NO_CONTENT, "it lacks the image and does not fetch");
2781
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2782
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2783
    assert!(body.contains("does not hold image"), "{body}");
2784
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(true))).await;
2785
    assert_eq!(st, StatusCode::OK, "it fetches, and the hub holds the image: {body}");
2786
    // oxygenhub#135: once claimed, the old waiting reason is gone.
2787
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2788
    assert!(!body.contains("waiting"), "a running job keeps no waiting reason: {body}");
2789
}
2790
2791
/// oxygenhub#136: coverage measured on a workstation is uploaded for a
2792
/// bookmark's state, kept as uploaded by its account, shown so, and sets
2793
/// no check.
2794
#[tokio::test(flavor = "multi_thread")]
2795
async fn coverage_uploaded_from_a_workstation_says_so() {
2796
    let h = hub().await;
2797
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2798
    create(&h.app, "andy", "vk").await;
2799
    let url = format!("{}/andy/vk", h.base);
2800
    let work = tempfile::tempdir().unwrap();
2801
    let c = client(&url, work.path());
2802
    write(work.path(), "src/game.c", "int a;\nint b;\nint c;\nint d;\n");
2803
    c.commit("Game", &[]).unwrap();
2804
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2805
2806
    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";
2807
    let body = serde_json::json!({ "bookmark": "main", "content": lcov }).to_string();
2808
    let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", Some("site"), Some(body)).await;
2809
    assert_eq!(st, StatusCode::CREATED, "{out}");
2810
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
2811
    assert_eq!((v["uploaded_by"].as_str(), v["lines_hit"].as_i64(), v["lines_found"].as_i64()), (Some("andy"), Some(3), Some(4)));
2812
    assert_eq!(v["dropped"], 1, "a file outside the state is left out");
2813
    assert_eq!(v["bookmark"], "main");
2814
2815
    let (_, page) = call(&h.app, "GET", "/andy/vk/coverage", None, None).await;
2816
    assert!(page.contains("uploaded by andy") && page.contains("75.0%"), "the Coverage page says where it came from");
2817
    let (_, page) = call(&h.app, "GET", "/andy/vk/reports", None, None).await;
2818
    assert!(page.contains("uploaded by andy"), "and the Reports card");
2819
    let row = db::repos::get(&h.app.db, "andy", "vk").await.unwrap().unwrap();
2820
    let state = v["state"].as_str().unwrap();
2821
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, state).await.unwrap();
2822
    assert!(checks.iter().all(|c| c.name != "coverage"), "an upload sets no check: {checks:?}");
2823
2824
    // Readers cannot upload; bad reports and bookmarks are refused.
2825
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", None, Some(r#"{"content":"x"}"#.into())).await;
2826
    assert_ne!(st, StatusCode::CREATED);
2827
    let (st, _) = call(
2828
        &h.app,
2829
        "POST",
2830
        "/api/v1/repos/andy/vk/coverage",
2831
        Some("site"),
2832
        Some(r#"{"bookmark":"nope","content":"SF:a\nend_of_record\n"}"#.into()),
2833
    )
2834
    .await;
2835
    assert_eq!(st, StatusCode::BAD_REQUEST);
2836
}
2837
2838
/// oxygenflow#40: what a runner measured at its claim is kept and shown.
2839
#[tokio::test(flavor = "multi_thread")]
2840
async fn a_runners_facts_are_kept_from_its_claim() {
2841
    let h = hub().await;
2842
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2843
    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"}}"#;
2844
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.into())).await;
2845
    assert_eq!(st, StatusCode::NO_CONTENT, "nothing to run, but the facts are kept");
2846
    let (st, out) = call(&h.app, "GET", "/api/v1/runners", Some("site"), None).await;
2847
    assert_eq!(st, StatusCode::OK, "{out}");
2848
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
2849
    let r = &v[0];
2850
    assert_eq!(
2851
        (r["speed"].as_i64(), r["speed_class"].as_i64(), r["free_disk_mib"].as_i64(), r["load_x100"].as_i64()),
2852
        (Some(100), Some(3), Some(42000), Some(112))
2853
    );
2854
    let row = db::runners::list(&h.app.db).await.unwrap().remove(0);
2855
    assert_eq!(row.facts_line(), "speed 100 (class 3) · load 1.12 · 41 GiB free");
2856
}
2857
2858
/// oxygenflow#41: a job's peaks set what its next run needs; a runner
2859
/// without that much free disk is not offered it, and the reason says so.
2860
#[tokio::test(flavor = "multi_thread")]
2861
async fn a_jobs_next_run_needs_the_disk_its_last_took() {
2862
    let h = hub().await;
2863
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2864
    create(&h.app, "andy", "demo").await;
2865
    let url = format!("{}/andy/demo", h.base);
2866
    let work = tempfile::tempdir().unwrap();
2867
    let c = client(&url, work.path());
2868
    write(
2869
        work.path(),
2870
        ".flow/pipeline.kdl",
2871
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2872
    );
2873
    c.commit("Build", &[]).unwrap();
2874
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2875
    runs_of(&h.app, "andy", "demo").await;
2876
    let claim_with = |free: u64| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"facts":{{"free_disk_mib":{free}}}}}"#);
2877
2878
    // The first run has nothing to learn from: any runner takes it.
2879
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(500))).await;
2880
    assert_eq!(st, StatusCode::OK, "{body}");
2881
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2882
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 10, "peak_disk_mib": 8000, "peak_memory_mib": 900 });
2883
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
2884
    let job = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
2885
    assert_eq!((job.peak_disk_mib, job.peak_memory_mib), (Some(8000), Some(900)));
2886
2887
    // The next run needs 8000 MiB and a quarter more.
2888
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
2889
    assert_eq!(st, StatusCode::CREATED);
2890
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2891
    let run2 = db::flow::run(&h.app.db, repo.id, 2).await.unwrap().unwrap();
2892
    let next = db::flow::jobs(&h.app.db, run2.id).await.unwrap().remove(0);
2893
    assert_eq!(next.need_disk_mib, Some(8000 + 2000 + 64));
2894
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(9000))).await;
2895
    assert_eq!(st, StatusCode::NO_CONTENT, "9000 MiB free is not enough");
2896
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2897
    let waiting = db::flow::job(&h.app.db, next.id).await.unwrap().unwrap().waiting;
2898
    assert!(waiting.contains("8.8 GiB free; the job needs ~9.8 GiB"), "{waiting}");
2899
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(20_000))).await;
2900
    assert_eq!(st, StatusCode::OK, "a roomier runner takes it: {body}");
2901
}
2902
2903
/// oxygenflow#42: a job another free runner would do better (it holds the
2904
/// image) is held from a runner that would fetch it, the better runner
2905
/// takes it, and the job says why it ran there.
2906
#[tokio::test(flavor = "multi_thread")]
2907
async fn a_job_waits_briefly_for_a_runner_that_holds_its_image() {
2908
    let h = hub().await;
2909
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2910
    // A second runner, with a token of its own.
2911
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
2912
    let ask = |images: &str| {
2913
        format!(
2914
            r#"{{"runner":"r","runtimes":["microvm"],"images":[{images}],"fetches_images":true,"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
2915
        )
2916
    };
2917
    let holder = ask(&format!("\"{ROOTFS}\""));
2918
    // earth-9 holds the image and is polling; nothing is queued yet.
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
    // The hub holds the image too, so test-1 could fetch it.
2922
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES ($1, 1, 'x86_64', 1, 'andy', 0)")
2923
        .bind(ROOTFS)
2924
        .execute(&h.app.db)
2925
        .await
2926
        .unwrap();
2927
2928
    create(&h.app, "andy", "demo").await;
2929
    let url = format!("{}/andy/demo", h.base);
2930
    let work = tempfile::tempdir().unwrap();
2931
    let c = client(&url, work.path());
2932
    write(
2933
        work.path(),
2934
        ".flow/pipeline.kdl",
2935
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2936
    );
2937
    c.commit("Build", &[]).unwrap();
2938
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2939
    runs_of(&h.app, "andy", "demo").await;
2940
2941
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
2942
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner that holds the image");
2943
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
2944
    assert_eq!(st, StatusCode::OK, "{body}");
2945
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2946
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
2947
    assert!(placed.starts_with("holds the image, idle, speed 100 (class 3)"), "{placed}");
2948
    assert!(placed.contains("held for a better runner"), "{placed}");
2949
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2950
    assert!(body.contains("\"placed\":\"holds the image"), "{body}");
2951
}
2952
2953
/// oxygenflow#51: a job waits briefly for the runner holding its build
2954
/// cache, even when the other one holds its image too.
2955
#[tokio::test(flavor = "multi_thread")]
2956
async fn a_job_waits_briefly_for_the_runner_holding_its_build_cache() {
2957
    let h = hub().await;
2958
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2959
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
2960
    let slot = flow_core::api::cache_slot("andy/demo", "build");
2961
    let ask = |caches: &str| {
2962
        format!(
2963
            r#"{{"runner":"r","runtimes":["microvm"],"images":["{ROOTFS}"],"fetches_images":true,"caches":[{caches}],"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
2964
        )
2965
    };
2966
    let holder = ask(&format!("\"{slot}\""));
2967
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder.clone())).await;
2968
    assert_eq!(st, StatusCode::NO_CONTENT);
2969
2970
    create(&h.app, "andy", "demo").await;
2971
    let url = format!("{}/andy/demo", h.base);
2972
    let work = tempfile::tempdir().unwrap();
2973
    let c = client(&url, work.path());
2974
    write(
2975
        work.path(),
2976
        ".flow/pipeline.kdl",
2977
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2978
    );
2979
    c.commit("Build", &[]).unwrap();
2980
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2981
    runs_of(&h.app, "andy", "demo").await;
2982
2983
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
2984
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner holding the build cache");
2985
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
2986
    assert_eq!(st, StatusCode::OK, "{body}");
2987
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2988
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
2989
    assert!(placed.starts_with("holds its build cache, holds the image"), "{placed}");
2990
}
2991
2992
/// oxygenflow#54: when both runners hold a job's build cache, the job waits
2993
/// briefly for the one whose copy is fresher.
2994
#[tokio::test(flavor = "multi_thread")]
2995
async fn a_job_waits_briefly_for_the_fresher_build_cache() {
2996
    let h = hub().await;
2997
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2998
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
2999
    let slot = flow_core::api::cache_slot("andy/demo", "build");
3000
    let now = db::now_ms();
3001
    let ask = |kept: i64| {
3002
        format!(
3003
            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}}}}"#
3004
        )
3005
    };
3006
    // earth-9 kept its copy a minute ago; the other runner's is a day old.
3007
    let fresh = ask(now - 60_000);
3008
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(fresh.clone())).await;
3009
    assert_eq!(st, StatusCode::NO_CONTENT);
3010
3011
    create(&h.app, "andy", "demo").await;
3012
    let url = format!("{}/andy/demo", h.base);
3013
    let work = tempfile::tempdir().unwrap();
3014
    let c = client(&url, work.path());
3015
    write(
3016
        work.path(),
3017
        ".flow/pipeline.kdl",
3018
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
3019
    );
3020
    c.commit("Build", &[]).unwrap();
3021
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3022
    runs_of(&h.app, "andy", "demo").await;
3023
3024
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(now - 86_400_000))).await;
3025
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the fresher copy");
3026
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(fresh)).await;
3027
    assert_eq!(st, StatusCode::OK, "{body}");
3028
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
3029
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
3030
    assert!(placed.starts_with("holds its build cache (kept 1 min ago), holds the image"), "{placed}");
3031
}
3032
3033
/// oxygenhub#127 §3.3: report files expire beyond the newest 50 runs of a
3034
/// report on a bookmark other than the default; the default keeps all,
3035
/// and an expired report keeps its metrics.
3036
#[tokio::test(flavor = "multi_thread")]
3037
async fn report_files_expire_under_retention() {
3038
    let h = hub().await;
3039
    create(&h.app, "andy", "demo").await;
3040
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
3041
    let add = |bookmark: &'static str, at: i64| {
3042
        let db = h.app.db.clone();
3043
        async move {
3044
            let id: i64 = sqlx::query_scalar(
3045
                "INSERT INTO reports (repo_id, name, kind, title, summary, context, job, bookmark, state, files, bytes, created_ms) \
3046
                 VALUES ($1, 'perf', 'performance', 'Perf', '', '{}', 'perf', $2, 's', 1, 1, $3) RETURNING id",
3047
            )
3048
            .bind(repo.id)
3049
            .bind(bookmark)
3050
            .bind(at)
3051
            .fetch_one(&db)
3052
            .await
3053
            .unwrap();
3054
            sqlx::query("INSERT INTO report_files (report_id, path, blob, size) VALUES ($1, 'report.toml', $2, 1)")
3055
                .bind(id)
3056
                .bind(format!("{:064x}", id))
3057
                .execute(&db)
3058
                .await
3059
                .unwrap();
3060
            sqlx::query("INSERT INTO report_metrics (report_id, key, value, unit, better) VALUES ($1, 'ms', 1, '', '')")
3061
                .bind(id)
3062
                .execute(&db)
3063
                .await
3064
                .unwrap();
3065
            id
3066
        }
3067
    };
3068
    let main_old = add("main", 1).await;
3069
    add("main", 2).await;
3070
    let mut feature = Vec::new();
3071
    for at in 0..52 {
3072
        feature.push(add("feature", 10 + at).await);
3073
    }
3074
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 2, "the two oldest feature runs");
3075
    let files = |id: i64| {
3076
        let db = h.app.db.clone();
3077
        async move {
3078
            sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM report_files WHERE report_id = $1").bind(id).fetch_one(&db).await.unwrap()
3079
        }
3080
    };
3081
    assert_eq!((files(feature[0]).await, files(feature[1]).await, files(feature[2]).await), (0, 0, 1));
3082
    assert_eq!(files(main_old).await, 1, "the default bookmark keeps every run");
3083
    assert_eq!(oxygenhub::reports::metrics(&h.app.db, feature[0]).await.unwrap().len(), 1, "metrics are kept");
3084
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 0, "once");
3085
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/perf?id={}", feature[0]), None, None).await;
3086
    assert!(page.contains("files have expired"), "the page says so");
3087
}
3088
3089
/// #137: a run pinning an image neither the hub nor any runner holds sets a
3090
/// failing `pipeline/images` check saying how to send it; once it is held,
3091
/// a run of the same state turns the check to passed.
3092
#[tokio::test(flavor = "multi_thread")]
3093
async fn a_pipeline_pinning_an_image_nobody_holds_fails_a_check() {
3094
    let h = hub().await;
3095
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3096
    // The one runner reports holding no images.
3097
    let none = r#"{"runner":"test-1","runtimes":["microvm"],"images":[]}"#;
3098
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(none.into())).await;
3099
    assert_eq!(st, StatusCode::NO_CONTENT);
3100
    create(&h.app, "andy", "demo").await;
3101
    let url = format!("{}/andy/demo", h.base);
3102
    let work = tempfile::tempdir().unwrap();
3103
    let c = client(&url, work.path());
3104
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3105
    write(work.path(), "test.sh", "echo ok\n");
3106
    c.commit("Add a pipeline", &[]).unwrap();
3107
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3108
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
3109
    let checks = checks_when(&h.app, run.repo_id, &run.state, 4).await;
3110
    let check = checks.iter().find(|c| c.name == "pipeline/images").expect("an images check");
3111
    assert!(check.status == "failed" && check.summary.contains(&ROOTFS[..12]) && check.summary.contains("flow rootfs push"), "{check:?}");
3112
    // Once a runner holds it, a run of the state passes the check.
3113
    let holds = format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":["{ROOTFS}"]}}"#);
3114
    call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(holds)).await;
3115
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
3116
    assert_eq!(st, StatusCode::CREATED);
3117
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
3118
    let check = checks.iter().find(|c| c.name == "pipeline/images").unwrap();
3119
    assert_eq!(check.status, "passed", "{check:?}");
3120
}
3121
3122
/// The swarm's tracker (#144): a fetching runner is given the peers in its
3123
/// site that hold the image or are fetching it, and a ticket signed with
3124
/// the hub key; a runner not in a swarm is told how to join one.
3125
#[tokio::test(flavor = "multi_thread")]
3126
async fn the_tracker_names_peers_in_the_same_site_and_signs_a_ticket() {
3127
    let h = hub().await;
3128
    let app = &h.app;
3129
    let image = "ab".repeat(32);
3130
    let claim_as = |token: &'static str, name: &'static str, body: serde_json::Value| async move {
3131
        let mut b = serde_json::json!({ "runner": name, "runtimes": ["microvm"] });
3132
        b.as_object_mut().unwrap().extend(body.as_object().unwrap().clone());
3133
        let (st, out) = call(app, "POST", "/api/v1/flow/claim", Some(token), Some(b.to_string())).await;
3134
        assert_eq!(st, StatusCode::NO_CONTENT, "{out}");
3135
    };
3136
    let announce = |token: &'static str, state: &'static str| {
3137
        let body = serde_json::json!({ "image": image, "state": state }).to_string();
3138
        async move { call(app, "POST", "/api/v1/flow/swarm/announce", Some(token), Some(body)).await }
3139
    };
3140
    // A holds the image; B and C hold nothing; all three are in site "lab".
3141
    claim_as(
3142
        "runner-secret",
3143
        "a",
3144
        serde_json::json!({ "images": [image], "swarm": { "addr": "10.0.0.1:7401", "site": "lab", "cert": "11".repeat(32) } }),
3145
    )
3146
    .await;
3147
    claim_as(
3148
        "runner-two",
3149
        "b",
3150
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.2:7401", "site": "lab", "cert": "22".repeat(32) } }),
3151
    )
3152
    .await;
3153
    claim_as(
3154
        "runner-three",
3155
        "c",
3156
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.3:7401", "site": "lab", "cert": "33".repeat(32) } }),
3157
    )
3158
    .await;
3159
3160
    let (st, body) = announce("runner-two", "fetching").await;
3161
    assert_eq!(st, StatusCode::OK, "{body}");
3162
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3163
    let names: Vec<(&str, bool)> = a.peers.iter().map(|p| (p.addr.as_str(), p.complete)).collect();
3164
    assert_eq!(names, vec![("10.0.0.1:7401", true)], "only A holds it so far");
3165
    assert_eq!(a.peers[0].cert, "11".repeat(32), "with the fingerprint peers check it by");
3166
    let t = jet::swarm::Ticket::open(&a.ticket, &app.hub_key.identity, oxygenhub::db::now_ms() as u64).unwrap();
3167
    assert_eq!((t.name.as_str(), t.site.as_str()), ("b", "lab"));
3168
3169
    // C, fetching too, is told of A (whole) and B (fetching).
3170
    let (_, body) = announce("runner-three", "fetching").await;
3171
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3172
    let mut peers: Vec<(&str, bool)> = a.peers.iter().map(|p| (p.addr.as_str(), p.complete)).collect();
3173
    peers.sort();
3174
    assert_eq!(peers, vec![("10.0.0.1:7401", true), ("10.0.0.2:7401", false)]);
3175
3176
    // B is done: no longer offered as fetching. C moves site: no peers.
3177
    announce("runner-two", "done").await;
3178
    claim_as(
3179
        "runner-three",
3180
        "c",
3181
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.3:7401", "site": "elsewhere", "cert": "33".repeat(32) } }),
3182
    )
3183
    .await;
3184
    let (_, body) = announce("runner-three", "fetching").await;
3185
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3186
    assert!(a.peers.is_empty(), "{:?}", a.peers);
3187
3188
    // A runner without a certificate (an older flow) is not in the swarm.
3189
    claim_as("runner-secret", "a", serde_json::json!({ "images": [image], "swarm": { "addr": "10.0.0.1:7401", "site": "elsewhere" } }))
3190
        .await;
3191
    let (st, _) = announce("runner-secret", "fetching").await;
3192
    assert_eq!(st, StatusCode::CONFLICT);
3193
3194
    // A runner that left the swarm is told how to join; nonsense is refused.
3195
    claim_as("runner-two", "b", serde_json::json!({ "images": [] })).await;
3196
    let (st, body) = announce("runner-two", "fetching").await;
3197
    assert_eq!(st, StatusCode::CONFLICT);
3198
    assert!(body.contains("[runner.swarm]"), "{body}");
3199
    let (st, _) =
3200
        call(app, "POST", "/api/v1/flow/swarm/announce", Some("runner-secret"), Some(r#"{"image":"nope","state":"fetching"}"#.into()))
3201
            .await;
3202
    assert_eq!(st, StatusCode::BAD_REQUEST);
3203
    let (st, _) = call(
3204
        app,
3205
        "POST",
3206
        "/api/v1/flow/swarm/announce",
3207
        None,
3208
        Some(serde_json::json!({ "image": image, "state": "fetching" }).to_string()),
3209
    )
3210
    .await;
3211
    assert_eq!(st, StatusCode::UNAUTHORIZED);
3212
}
3213
3214
/// Admin › Runners › Images (C0): each image, where it is and what uses it.
3215
#[tokio::test(flavor = "multi_thread")]
3216
async fn the_images_page_says_where_each_image_is_and_what_uses_it() {
3217
    let h = hub().await;
3218
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3219
    create(&h.app, "andy", "demo").await;
3220
    let work = tempfile::tempdir().unwrap();
3221
    let c = client(&format!("{}/andy/demo", h.base), work.path());
3222
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3223
    write(work.path(), "test.sh", "echo ok\n");
3224
    c.commit("Add a pipeline", &[]).unwrap();
3225
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3226
    // A runner holds another image and shares it; the hub keeps a third.
3227
    let held = "cd".repeat(32);
3228
    let kept = "ef".repeat(32);
3229
    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) } });
3230
    let (st, out) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
3231
    assert!(st == StatusCode::NO_CONTENT || st == StatusCode::OK, "{st} {out}");
3232
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES ($1, 1048576, 'x86_64', 9, 'andy', 1)")
3233
        .bind(&kept)
3234
        .execute(&h.app.db)
3235
        .await
3236
        .unwrap();
3237
3238
    let res = oxygenhub::router(h.app.clone())
3239
        .oneshot(
3240
            Request::post("/register")
3241
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
3242
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
3243
                .unwrap(),
3244
        )
3245
        .await
3246
        .unwrap();
3247
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
3248
    let carol = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
3249
    db::accounts::set_admin(&h.app.db, carol.id, true).await.unwrap();
3250
    let res = oxygenhub::router(h.app.clone())
3251
        .oneshot(Request::get("/admin/runners/images").header(header::COOKIE, cookie).body(Body::empty()).unwrap())
3252
        .await
3253
        .unwrap();
3254
    assert_eq!(res.status(), StatusCode::OK);
3255
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
3256
    let row = |hash: &str| {
3257
        let at = page.find(&format!("title=\"{hash}\"")).unwrap_or_else(|| panic!("{hash} is not on the page"));
3258
        let end = page[at..].find("</tr>").unwrap();
3259
        page[at..at + end].to_string()
3260
    };
3261
    let pinned = row(ROOTFS);
3262
    assert!(pinned.contains("nowhere") && pinned.contains("andy/demo") && pinned.contains("3 jobs"), "{pinned}");
3263
    let on_runner = row(&held);
3264
    assert!(on_runner.contains("img-holds") && on_runner.contains("earth-1") && !on_runner.contains("nowhere"), "{on_runner}");
3265
    let on_hub = row(&kept);
3266
    assert!(on_hub.contains("img-hub") && on_hub.contains("1.0 MiB") && on_hub.contains("x86_64"), "{on_hub}");
3267
    assert!(page.contains("earth-1 (home)"), "the swarm is named");
3268
    // The swarm backdrop (docs/backgrounds.md §2): the hub and the runners.
3269
    assert!(page.contains(r#"{"images":"#) && page.contains(r#""scene":"swarm""#) && page.contains(r#""earth-1""#), "the swarm's data");
3270
    assert_eq!(call(&h.app, "GET", "/admin/runners/images", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
3271
}
3272
3273
/// Diffusion D1 (#148): the reverse pin index. A repository that pins
3274
/// another as a subrepo is a consumer of it; the upstream's API and page
3275
/// say who, at which state, and how far behind its default bookmark.
3276
#[tokio::test(flavor = "multi_thread")]
3277
async fn consumers_of_a_subrepo_are_indexed_with_how_far_behind_they_are() {
3278
    let h = hub().await;
3279
    // The site token acts as the first site administrator.
3280
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3281
    create(&h.app, "andy", "api").await;
3282
    create(&h.app, "andy", "game").await;
3283
    let api_work = tempfile::tempdir().unwrap();
3284
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
3285
    write(api_work.path(), "api.h", "v1\n");
3286
    api.snapshot("t").unwrap();
3287
    api.commit("api v1", &[]).unwrap();
3288
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3289
3290
    let game_work = tempfile::tempdir().unwrap();
3291
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
3292
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3293
    write(game_work.path(), "game.c", "int main;\n");
3294
    game.snapshot("t").unwrap();
3295
    game.commit("game on api v1", &[]).unwrap();
3296
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3297
3298
    let consumers = || async {
3299
        let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
3300
        assert_eq!(st, StatusCode::OK, "{body}");
3301
        serde_json::from_str::<Vec<serde_json::Value>>(&body).unwrap()
3302
    };
3303
    // The index is written by the push's after-work, a moment after the
3304
    // client hears the push succeeded.
3305
    let settle = |want: &'static (dyn Fn(&[serde_json::Value]) -> bool + Sync)| {
3306
        let consumers = &consumers;
3307
        async move {
3308
            for _ in 0..100 {
3309
                let list = consumers().await;
3310
                if want(&list) {
3311
                    return list;
3312
                }
3313
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3314
            }
3315
            consumers().await
3316
        }
3317
    };
3318
    let list = settle(&|l| !l.is_empty()).await;
3319
    assert_eq!(list.len(), 1, "{list:?}");
3320
    assert_eq!(
3321
        (list[0]["name"].as_str(), list[0]["path"].as_str(), list[0]["bookmark"].as_str()),
3322
        (Some("game"), Some("deps/api"), Some("main"))
3323
    );
3324
    assert_eq!(list[0]["behind"], 0);
3325
3326
    // The upstream moves on: the consumer is one change behind.
3327
    write(api_work.path(), "api.c", "v2\n");
3328
    api.snapshot("t").unwrap();
3329
    api.commit("api v2", &[]).unwrap();
3330
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3331
    assert_eq!(settle(&|l| l.first().is_some_and(|c| c["behind"] == 1)).await[0]["behind"], 1);
3332
    let (_, page) = call(&h.app, "GET", "/andy/api", None, None).await;
3333
    assert!(page.contains("Diffuses to") && page.contains("andy/game") && page.contains("1 behind"), "the page shows it");
3334
3335
    // A private consumer is not shown to someone who cannot read it.
3336
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'game'").execute(&h.app.db).await.unwrap();
3337
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", None, None).await;
3338
    assert_eq!(body.trim(), "[]");
3339
    let (_, page) = call(&h.app, "GET", "/andy/api", None, None).await;
3340
    assert!(!page.contains("andy/game"));
3341
    sqlx::query("UPDATE repositories SET visibility = 'public' WHERE name = 'game'").execute(&h.app.db).await.unwrap();
3342
3343
    // A bump (DF3): one signed change on the target moving only the pin, on
3344
    // `diffusion/deps/api`; again with the same state, nothing new.
3345
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3346
    let api_row = db::repos::get(&h.app.db, "andy", "api").await.unwrap().unwrap();
3347
    let api_heads = api.bookmark_heads().unwrap();
3348
    let bumped = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, api_heads.clone()).await.unwrap();
3349
    let oxygenhub::diffusion::Bumped::Moved { bookmark, heads, .. } = bumped else { panic!("{bumped:?}") };
3350
    assert_eq!(bookmark, "diffusion/deps/api");
3351
    game.fetch("origin").unwrap();
3352
    let bump_state = game.load_state(&heads).unwrap().materialize();
3353
    let pin = match &bump_state.files["deps/api"].content {
3354
        oxy_core::state::FileContent::Opaque { blobs } => oxy_core::subrepo::Pin::decode(&game.read_blob(&blobs[0]).unwrap()).unwrap(),
3355
        other => panic!("{other:?}"),
3356
    };
3357
    assert!(
3358
        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 }),
3359
        "{pin:?}"
3360
    );
3361
    assert!(bump_state.files.contains_key("game.c"), "the rest of the game is as it was");
3362
    assert!(matches!(
3363
        oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, api_heads.clone()).await.unwrap(),
3364
        oxygenhub::diffusion::Bumped::Already { .. }
3365
    ));
3366
    // A state lacking changes the pin has (as when the consumer pinned an
3367
    // upstream proposal not landed yet) is combined with the pin, never
3368
    // dropping what it relies on.
3369
    write(api_work.path(), "other.c", "v3\n");
3370
    api.snapshot("t").unwrap();
3371
    let v3 = api.commit("api v3, on its own", &[]).unwrap();
3372
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3373
    let only_v3 = api.load_state(&[v3]).unwrap().heads().to_vec();
3374
    let combined = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, only_v3).await.unwrap();
3375
    let oxygenhub::diffusion::Bumped::Moved { heads: ch, .. } = combined else { panic!("{combined:?}") };
3376
    game.fetch("origin").unwrap();
3377
    let st = game.load_state(&ch).unwrap().materialize();
3378
    let pin = match &st.files["deps/api"].content {
3379
        oxy_core::state::FileContent::Opaque { blobs } => oxy_core::subrepo::Pin::decode(&game.read_blob(&blobs[0]).unwrap()).unwrap(),
3380
        other => panic!("{other:?}"),
3381
    };
3382
    let oxy_core::subrepo::Pin::Oxy { heads: pinned, .. } = pin else { panic!() };
3383
    let all = api.load_state(&pinned).unwrap();
3384
    // The game's main still pins v1 alone; combined with v3, it is both.
3385
    assert!(all.contains(&v3) && all.len() == 2, "v1 and v3, {} changes", all.len());
3386
    // The upstream moves again: the same bookmark moves.
3387
    let newer = api.bookmark_heads().unwrap();
3388
    let again = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, newer).await.unwrap();
3389
    assert!(matches!(again, oxygenhub::diffusion::Bumped::Moved { ref bookmark, .. } if bookmark == "diffusion/deps/api"), "{again:?}");
3390
3391
    // Following is off by default; owners turn it on (DF2).
3392
    let put =
3393
        |body: &'static str, who: Option<&'static str>| call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", who, Some(body.into()));
3394
    let (st, body) = put(r#"{"follow":"green"}"#, Some("site")).await;
3395
    assert_eq!(st, StatusCode::OK, "{body}");
3396
    assert!(body.contains("\"follow\":\"green\"") && body.contains("\"from\":\"setting\""), "{body}");
3397
    assert_eq!(put(r#"{"follow":"sometimes"}"#, Some("site")).await.0, StatusCode::BAD_REQUEST);
3398
    assert_ne!(put(r#"{"follow":"any"}"#, None).await.0, StatusCode::OK, "not without a token");
3399
    let (_, body) = put(r#"{"follow":"default"}"#, Some("site")).await;
3400
    assert!(body.contains("\"follow\":\"off\"") && body.contains("\"from\":\"site\""), "{body}");
3401
3402
    // Dropping the subrepo drops the consumer.
3403
    game.submodule_remove("deps/api").unwrap();
3404
    std::fs::remove_dir_all(game_work.path().join("deps/api")).unwrap();
3405
    game.snapshot("t").unwrap();
3406
    game.commit("game without api", &[]).unwrap();
3407
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3408
    let left = settle(&|l| l.is_empty()).await;
3409
    assert!(left.is_empty(), "{left:?}");
3410
}
3411
3412
/// Diffusion D1 end to end (#148): a consumer that follows every move gets
3413
/// a bump proposal on a push; one that follows green gets it when the
3414
/// upstream's run passes. One proposal, kept up to date.
3415
#[tokio::test(flavor = "multi_thread")]
3416
async fn diffusion_proposes_a_bump_when_the_upstream_moves() {
3417
    let h = hub().await;
3418
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3419
    create(&h.app, "andy", "api").await;
3420
    create(&h.app, "andy", "game").await;
3421
    // Run every job of the upstream's newest run to a pass, keeping each claim.
3422
    let seen: std::sync::Mutex<Vec<serde_json::Value>> = std::sync::Mutex::new(Vec::new());
3423
    let seen = &seen;
3424
    let hub_app = &h.app;
3425
    let pass_all = move || async move {
3426
        let h_app = hub_app;
3427
        for _ in 0..20 {
3428
            let Some(a) = claim(h_app).await else {
3429
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3430
                if !jobs_left(h_app).await {
3431
                    break;
3432
                }
3433
                continue;
3434
            };
3435
            seen.lock().unwrap().push(a.clone());
3436
            let id = a["job_id"].as_i64().unwrap();
3437
            let (name, ph) = (a["job"]["name"].as_str().unwrap().to_string(), a["pipeline_hash"].as_str().unwrap().to_string());
3438
            assert_eq!(
3439
                finish(h_app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt(&name, &ph, 0) })).await,
3440
                StatusCode::NO_CONTENT
3441
            );
3442
        }
3443
    };
3444
    let api_work = tempfile::tempdir().unwrap();
3445
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
3446
    write(api_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3447
    write(api_work.path(), "test.sh", "echo ok\n");
3448
    write(api_work.path(), "api.h", "v1\n");
3449
    api.snapshot("t").unwrap();
3450
    api.commit("api v1", &[]).unwrap();
3451
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3452
    pass_all().await;
3453
3454
    let game_work = tempfile::tempdir().unwrap();
3455
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
3456
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3457
    write(game_work.path(), "game.c", "int main;\n");
3458
    write(game_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3459
    write(game_work.path(), "test.sh", "echo ok\n");
3460
    game.snapshot("t").unwrap();
3461
    game.commit("game on api v1", &[]).unwrap();
3462
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3463
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3464
    let bump = || async {
3465
        for _ in 0..100 {
3466
            let open = db::proposals::list(&h.app.db, game_row.id, &["open"]).await.unwrap();
3467
            if let Some(p) = open.into_iter().find(|p| p.source_bookmark == "diffusion/deps/api") {
3468
                return Some(p);
3469
            }
3470
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3471
        }
3472
        None
3473
    };
3474
3475
    // Off by default: an upstream move proposes nothing.
3476
    write(api_work.path(), "a2.c", "v2\n");
3477
    api.snapshot("t").unwrap();
3478
    api.commit("api v2: faster sprites", &[]).unwrap();
3479
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3480
    pass_all().await;
3481
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3482
    assert!(db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap().is_empty(), "off proposes nothing");
3483
3484
    // Turned on to follow every move: bumped at once to where the upstream
3485
    // is (v2), by the diffusion account; the next push updates it.
3486
    let put = |body: &'static str| call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(body.into()));
3487
    assert_eq!(put(r#"{"follow":"any"}"#).await.0, StatusCode::OK);
3488
    let first = bump().await.expect("caught up when turned on");
3489
    assert!(first.title.contains("1 change") && first.body.contains("api v2: faster sprites"), "{:?}", first.title);
3490
    // The bump's pipeline runs, as a push of it would, so the proposal is tested.
3491
    let mut ran = false;
3492
    for _ in 0..100 {
3493
        if runs_of(&h.app, "andy", "game").await.iter().any(|r| r.bookmark == "diffusion/deps/api") {
3494
            ran = true;
3495
            break;
3496
        }
3497
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3498
    }
3499
    assert!(ran, "a run of the bump");
3500
    pass_all().await;
3501
    write(api_work.path(), "a3.c", "v3\n");
3502
    api.snapshot("t").unwrap();
3503
    api.commit("api v3: save slots past ten", &[]).unwrap();
3504
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3505
    let mut p = first.clone();
3506
    for _ in 0..100 {
3507
        p = bump().await.unwrap();
3508
        if p.body.contains("api v3") {
3509
            break;
3510
        }
3511
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3512
    }
3513
    assert_eq!(p.number, first.number, "the same proposal");
3514
    assert_eq!((p.author.as_str(), p.target.as_str()), ("diffusion", "main"));
3515
    assert!(p.title.contains("deps/api") && p.title.contains("andy/api") && p.title.contains("2 changes"), "{}", p.title);
3516
    assert!(p.body.contains("api v2: faster sprites") && p.body.contains("api v3: save slots past ten"), "{}", p.body);
3517
    let labels = db::issues::proposal_labels(&h.app.db, p.id).await.unwrap();
3518
    assert!(labels.iter().any(|l| l.name == "dependencies"));
3519
    pass_all().await;
3520
3521
    // Following green: a push alone does not move it; the passing run does,
3522
    // and the same proposal is brought up to date.
3523
    assert_eq!(put(r#"{"follow":"green"}"#).await.0, StatusCode::OK);
3524
    write(api_work.path(), "a4.c", "v4\n");
3525
    api.snapshot("t").unwrap();
3526
    api.commit("api v4: rsm_set cheaper", &[]).unwrap();
3527
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3528
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3529
    assert!(!bump().await.unwrap().body.contains("api v4"), "not before its run passes");
3530
    pass_all().await;
3531
    let mut updated = None;
3532
    for _ in 0..100 {
3533
        let p2 = bump().await.unwrap();
3534
        if p2.body.contains("api v4") {
3535
            updated = Some(p2);
3536
            break;
3537
        }
3538
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3539
    }
3540
    let p2 = updated.expect("brought up to date once the run passed");
3541
    assert_eq!(p2.number, p.number, "the same proposal");
3542
    assert!(p2.title.contains("3 changes"), "{}", p2.title);
3543
    assert_eq!(db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap().len(), 1, "never a pile of bumps");
3544
3545
    // The views (#150): the upstream's Diffusion tab lists the game with its
3546
    // status; the game's tab and overview say what it follows.
3547
    pass_all().await;
3548
    let (st, page) = call(&h.app, "GET", "/andy/api/diffusion", None, None).await;
3549
    assert_eq!(st, StatusCode::OK);
3550
    assert!(page.contains("Diffuses to") && page.contains("andy/game") && page.contains(&format!("#{}", p2.number)), "the bump is listed");
3551
    assert!(page.contains("df-green"), "a passing run of a checked upstream is green");
3552
    // The ripples backdrop: the page's own repositories and tones.
3553
    assert!(
3554
        page.contains(r#""scene":"ripples""#) && page.contains(r#"["andy/game","#) && page.contains(r#""repo":"andy/api""#),
3555
        "the ripples' data"
3556
    );
3557
    let (_, page) = call(&h.app, "GET", "/andy/game/diffusion", None, None).await;
3558
    assert!(page.contains("Takes from") && page.contains("andy/api"));
3559
    let (_, overview) = call(&h.app, "GET", "/andy/game", None, None).await;
3560
    assert!(overview.contains("Takes from") && overview.contains(">Diffusion</a>"), "the tab and the panel");
3561
    // Both directions through the API (#153), as the extension reads them.
3562
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/game/diffusion", Some("site"), None).await;
3563
    assert_eq!(st, StatusCode::OK, "{body}");
3564
    let d: hub_api::Diffusion = serde_json::from_str(&body).unwrap();
3565
    assert!(d.diffuses_to.is_empty(), "nothing pins the game");
3566
    let pin = d.takes_from.first().expect("the game takes from the api");
3567
    assert_eq!((pin.upstream.as_str(), pin.consumer.as_str()), ("andy/api", "andy/game"));
3568
    assert_eq!(pin.bump, Some(p2.number));
3569
    assert_eq!(pin.upstream_state.tone, "green", "{body}");
3570
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/diffusion", Some("site"), None).await;
3571
    let d: hub_api::Diffusion = serde_json::from_str(&body).unwrap();
3572
    assert!(d.takes_from.is_empty() && d.diffuses_to.iter().any(|p| p.consumer == "andy/game"), "{body}");
3573
    let (st, _) = call(&h.app, "GET", "/admin/diffusion", None, None).await;
3574
    assert_eq!(st, StatusCode::NOT_FOUND, "administrators only");
3575
3576
    // Landing the bump on the hub moves the game's pin as a push would:
3577
    // the index follows, so it is no longer behind; even when the first
3578
    // write fails, as a busy database's would (#210: it is tried again).
3579
    let game = oxygenhub::db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3580
    oxygenhub::diffusion::fail_next_records(&h.app, game.id, 1);
3581
    let (st, body) =
3582
        call(&h.app, "POST", &format!("/api/v1/repos/andy/game/proposals/{}/land", p2.number), Some("site"), Some("{}".into())).await;
3583
    assert_eq!(st, StatusCode::OK, "{body}");
3584
    let mut behind = serde_json::Value::Null;
3585
    for _ in 0..100 {
3586
        let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
3587
        let list: Vec<serde_json::Value> = serde_json::from_str(&list).unwrap();
3588
        behind = list.iter().find(|c| c["name"] == "game").map(|c| c["behind"].clone()).unwrap_or_default();
3589
        if behind == 0 {
3590
            break;
3591
        }
3592
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3593
    }
3594
    assert_eq!(behind, 0, "the index followed the landing");
3595
    assert_eq!(oxygenhub::diffusion::forced_left(&h.app, game.id), 0, "the first write did fail");
3596
    // The reconciler (#210): an index left behind its bookmark (as when
3597
    // both writes failed) is mended from the bookmark itself, and a pass
3598
    // with nothing to mend changes nothing.
3599
    let pins_of = || async {
3600
        sqlx::query_scalar::<_, String>("SELECT heads FROM diffusion_pins WHERE consumer_id = $1")
3601
            .bind(game.id)
3602
            .fetch_one(&h.app.db)
3603
            .await
3604
            .unwrap()
3605
    };
3606
    let right = pins_of().await;
3607
    sqlx::query("UPDATE diffusion_pins SET heads = 'stale' WHERE consumer_id = $1").bind(game.id).execute(&h.app.db).await.unwrap();
3608
    sqlx::query("DELETE FROM diffusion_indexed WHERE consumer_id = $1").bind(game.id).execute(&h.app.db).await.unwrap();
3609
    let r = oxygenhub::diffusion::reconcile(&h.app).await;
3610
    assert!(r.reindexed >= 1, "{r:?}");
3611
    assert_eq!(pins_of().await, right, "the pin read again from the game's bookmark");
3612
    assert_eq!(oxygenhub::diffusion::reconcile(&h.app).await.reindexed, 0, "nothing left to mend");
3613
3614
    // A private upstream: the bump's run (started by the diffusion account,
3615
    // which cannot read it) still gets the subrepo it bumps.
3616
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'api'").execute(&h.app.db).await.unwrap();
3617
    seen.lock().unwrap().clear();
3618
    write(api_work.path(), "a6.c", "v6\n");
3619
    api.snapshot("t").unwrap();
3620
    api.commit("api v6", &[]).unwrap();
3621
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3622
    // The bump's run starts in the background: wait for its job, under a
3623
    // loaded test run as well as alone.
3624
    let mut bump_job = None;
3625
    for _ in 0..100 {
3626
        pass_all().await;
3627
        bump_job = seen.lock().unwrap().iter().find(|c| c["repo"] == "andy/game" && c["bookmark"] == "diffusion/deps/api").cloned();
3628
        if bump_job.is_some() {
3629
            break;
3630
        }
3631
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
3632
    }
3633
    let bump_job = bump_job.expect("the bump's job ran");
3634
    let subs: Vec<&str> = bump_job["subrepos"].as_array().unwrap().iter().filter_map(|s| s["path"].as_str()).collect();
3635
    assert_eq!(subs, vec!["deps/api"], "{bump_job}");
3636
3637
    // A consumer turning Diffusion on is bumped at once to the upstream's
3638
    // newest passing state, without waiting for it to move again.
3639
    create(&h.app, "andy", "game2").await;
3640
    let g2_work = tempfile::tempdir().unwrap();
3641
    let g2 = client(&format!("{}/andy/game2", h.base), g2_work.path());
3642
    g2.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3643
    g2.snapshot("t").unwrap();
3644
    g2.commit("game2 on api", &[]).unwrap();
3645
    assert!(g2.push("origin", false).unwrap().iter().all(|r| r.ok));
3646
    // Its pin is api's newest state already: move api on, pass the run.
3647
    write(api_work.path(), "a5.c", "v5\n");
3648
    api.snapshot("t").unwrap();
3649
    api.commit("api v5", &[]).unwrap();
3650
    let api_row = db::repos::get(&h.app.db, "andy", "api").await.unwrap().unwrap();
3651
    let runs_before = db::flow::runs(&h.app.db, api_row.id, 100, None).await.unwrap().len();
3652
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3653
    // The push's run is made in the background: wait for it, or pass_all
3654
    // can finish before it exists and v5 never passes (a flake under load).
3655
    for _ in 0..300 {
3656
        if db::flow::runs(&h.app.db, api_row.id, 100, None).await.unwrap().len() > runs_before {
3657
            break;
3658
        }
3659
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3660
    }
3661
    pass_all().await;
3662
    let g2_row = db::repos::get(&h.app.db, "andy", "game2").await.unwrap().unwrap();
3663
    for _ in 0..100 {
3664
        if sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
3665
            .bind(g2_row.id)
3666
            .fetch_one(&h.app.db)
3667
            .await
3668
            .unwrap()
3669
            > 0
3670
        {
3671
            break;
3672
        }
3673
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3674
    }
3675
    assert!(db::proposals::list(&h.app.db, g2_row.id, &[]).await.unwrap().is_empty(), "off until turned on");
3676
    let (st, _) = call(&h.app, "PUT", "/api/v1/repos/andy/game2/diffusion", Some("site"), Some(r#"{"follow":"green"}"#.into())).await;
3677
    assert_eq!(st, StatusCode::OK);
3678
    let mut caught = None;
3679
    // Up to 15 s: under a full parallel test run the bump can take a while.
3680
    for _ in 0..300 {
3681
        if let Some(p) = db::proposals::list(&h.app.db, g2_row.id, &["open"]).await.unwrap().into_iter().next() {
3682
            caught = Some(p);
3683
            break;
3684
        }
3685
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3686
    }
3687
    let caught = caught.expect("bumped as soon as it was turned on");
3688
    assert!(caught.body.contains("api v5") && caught.title.contains("1 change"), "{:?} {:?}", caught.title, caught.body);
3689
    // A bump someone closed is a "no": the reconciler does not open it again.
3690
    sqlx::query("UPDATE proposals SET state = 'closed' WHERE id = $1").bind(caught.id).execute(&h.app.db).await.unwrap();
3691
    // (The bump's own runs finishing may still propose again, as Diffusion
3692
    // does on an upstream's moves; the reconciler itself opens nothing.)
3693
    let r = oxygenhub::diffusion::reconcile(&h.app).await;
3694
    assert_eq!(r.caught_up, 0, "the reconciler respects the closed bump: {r:?}");
3695
}
3696
3697
/// Whether any job is queued or running.
3698
async fn jobs_left(app: &Shared) -> bool {
3699
    sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM flow_jobs WHERE status IN ('queued', 'running')")
3700
        .fetch_one(&app.db)
3701
        .await
3702
        .unwrap_or(0)
3703
        > 0
3704
}
3705
3706
/// An upstream with no checks never turns green: a consumer following green
3707
/// still gets its bumps, marked amber, `upstream unverified` (#148).
3708
#[tokio::test(flavor = "multi_thread")]
3709
async fn bumps_from_an_upstream_without_checks_are_marked_unverified() {
3710
    let h = hub().await;
3711
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3712
    create(&h.app, "andy", "lib").await;
3713
    create(&h.app, "andy", "app").await;
3714
    let lib_work = tempfile::tempdir().unwrap();
3715
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
3716
    write(lib_work.path(), "lib.h", "v1\n");
3717
    lib.snapshot("t").unwrap();
3718
    lib.commit("lib v1", &[]).unwrap();
3719
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
3720
    let app_work = tempfile::tempdir().unwrap();
3721
    let app = client(&format!("{}/andy/app", h.base), app_work.path());
3722
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
3723
    // It watches lib.c: upstream changes touching it are flagged.
3724
    let modules = std::fs::read_to_string(app_work.path().join(".oxymodules")).unwrap();
3725
    write(app_work.path(), ".oxymodules", &format!("{modules}watch = lib.c\n"));
3726
    app.snapshot("t").unwrap();
3727
    app.commit("app on lib", &[]).unwrap();
3728
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
3729
    let app_row = db::repos::get(&h.app.db, "andy", "app").await.unwrap().unwrap();
3730
    for _ in 0..100 {
3731
        if sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
3732
            .bind(app_row.id)
3733
            .fetch_one(&h.app.db)
3734
            .await
3735
            .unwrap()
3736
            > 0
3737
        {
3738
            break;
3739
        }
3740
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3741
    }
3742
    let (st, _) = call(&h.app, "PUT", "/api/v1/repos/andy/app/diffusion", Some("site"), Some(r#"{"follow":"green"}"#.into())).await;
3743
    assert_eq!(st, StatusCode::OK);
3744
    write(lib_work.path(), "lib.c", "v2\n");
3745
    lib.snapshot("t").unwrap();
3746
    lib.commit("lib v2", &[]).unwrap();
3747
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
3748
    let mut found = None;
3749
    for _ in 0..100 {
3750
        if let Some(p) = db::proposals::list(&h.app.db, app_row.id, &["open"]).await.unwrap().into_iter().next() {
3751
            found = Some(p);
3752
            break;
3753
        }
3754
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3755
    }
3756
    let p = found.expect("a bump although the upstream never goes green");
3757
    assert!(p.body.contains("Upstream unverified"), "{}", p.body);
3758
    assert!(p.body.contains("Touches what you watch") && p.body.contains("touches `lib.c`") && p.body.contains("⚑"), "{}", p.body);
3759
    let mut labels = Vec::new();
3760
    for _ in 0..100 {
3761
        labels = db::issues::proposal_labels(&h.app.db, p.id).await.unwrap().into_iter().map(|l| l.name).collect::<Vec<String>>();
3762
        if labels.len() == 2 {
3763
            break;
3764
        }
3765
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3766
    }
3767
    assert!(labels.contains(&"upstream unverified".to_string()) && labels.contains(&"dependencies".to_string()), "{labels:?}");
3768
}
3769
3770
/// #134: when a proposal's target moves, its projected state is new; the
3771
/// hub runs the pipeline on it, so its checks are never for an older one.
3772
#[tokio::test(flavor = "multi_thread")]
3773
async fn a_moved_target_runs_its_open_proposals_again() {
3774
    let h = hub().await;
3775
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3776
    create(&h.app, "andy", "demo").await;
3777
    let work = tempfile::tempdir().unwrap();
3778
    let mut c = client(&format!("{}/andy/demo", h.base), work.path());
3779
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3780
    write(work.path(), "test.sh", "echo ok\n");
3781
    c.snapshot("t").unwrap();
3782
    let base = c.commit("base", &[]).unwrap();
3783
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3784
    // Two proposals, each main plus one change.
3785
    for (b, file) in [("fix-a", "a.txt"), ("fix-b", "b.txt")] {
3786
        c.bookmark_create(b, Some(&[base])).unwrap();
3787
        c.bookmark_switch(b, true).unwrap();
3788
        write(work.path(), file, "x\n");
3789
        c.snapshot("t").unwrap();
3790
        c.commit(&format!("add {file}"), &[]).unwrap();
3791
        assert!(c.push_bookmark("origin", b, false).unwrap().iter().all(|r| r.ok));
3792
        let body = serde_json::json!({ "title": b, "target": "main", "source": b }).to_string();
3793
        let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/demo/proposals", Some("site"), Some(body)).await;
3794
        assert_eq!(st, StatusCode::CREATED, "{out}");
3795
    }
3796
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
3797
    let props = db::proposals::list(&h.app.db, row.id, &["open"]).await.unwrap();
3798
    let a = props.iter().find(|p| p.source_bookmark == "fix-a").unwrap().number;
3799
    let b = props.iter().find(|p| p.source_bookmark == "fix-b").unwrap().number;
3800
    // Landing fix-a moves main: fix-b's projected state gets a run.
3801
    let (st, out) = call(&h.app, "POST", &format!("/api/v1/repos/andy/demo/proposals/{a}/land"), Some("site"), Some("{}".into())).await;
3802
    assert_eq!(st, StatusCode::OK, "{out}");
3803
    let label = format!("proposal/{b}");
3804
    let mut found = None;
3805
    for _ in 0..100 {
3806
        if let Some(r) = runs_of(&h.app, "andy", "demo").await.into_iter().find(|r| r.bookmark == label) {
3807
            found = Some(r);
3808
            break;
3809
        }
3810
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3811
    }
3812
    let run = found.expect("a run of fix-b's new projected state");
3813
    let projected = db::proposals::get(&h.app.db, row.id, b).await.unwrap().unwrap();
3814
    assert_eq!((run.trigger.as_str(), run.state.as_str()), ("proposal", projected.projected_state.as_str()), "on its projected state");
3815
    // Moving main again by a push does it once more; the same state is not run twice.
3816
    let before = runs_of(&h.app, "andy", "demo").await.len();
3817
    oxygenhub::web::proposals::settle_after_push(&h.app, &row, "main", "andy").await;
3818
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), before, "not again for the same state");
3819
}
3820
3821
/// Send image bytes to the hub as their chunks and then a manifest that
3822
/// names no architecture; the manifest as the hub answers it.
3823
async fn send_image(app: &Shared, image: &[u8]) -> (String, serde_json::Value) {
3824
    let mut chunks = std::collections::HashMap::new();
3825
    let m = jet::images::scan(image, None, |c, b| {
3826
        chunks.insert(c.hash().to_string(), b.to_vec());
3827
        Ok(())
3828
    })
3829
    .unwrap();
3830
    for c in m.needed() {
3831
        let (st, body) = put_bytes(app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
3832
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
3833
    }
3834
    let (st, body) =
3835
        call(app, "PUT", &format!("/api/v1/flow/images/{}", m.hash), Some("site"), Some(serde_json::to_string(&m).unwrap())).await;
3836
    assert_eq!(st, StatusCode::CREATED, "{body}");
3837
    (m.hash.clone(), serde_json::from_str(&body).unwrap())
3838
}
3839
3840
/// oxygenhub#173 (OxygenFlow spec §11.2, Andy's "detect and learn"): an
3841
/// image sent with no architecture is read from its own files, so a
3842
/// riscv64 runner is never offered an x86_64 image's jobs; an image
3843
/// nobody can read takes the architecture its first pass ran on.
3844
#[tokio::test(flavor = "multi_thread")]
3845
async fn an_image_names_its_own_architecture_and_a_pass_teaches_the_rest() {
3846
    use oxy_core::identity::SecretKey;
3847
    let h = hub().await;
3848
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3849
    // An ext4 image whose shell is x86_64, as `flow rootfs import` makes one.
3850
    let dir = tempfile::tempdir().unwrap();
3851
    let tree = dir.path().join("tree");
3852
    std::fs::create_dir_all(tree.join("bin")).unwrap();
3853
    let mut elf = vec![0u8; 64];
3854
    elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
3855
    elf[18..20].copy_from_slice(&0x3Eu16.to_le_bytes());
3856
    std::fs::write(tree.join("bin/sh"), &elf).unwrap();
3857
    let img = dir.path().join("rootfs.ext4");
3858
    let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
3859
    if !made.is_ok_and(|s| s.success()) {
3860
        eprintln!("mkfs.ext4 not found: skipped");
3861
        return;
3862
    }
3863
    let (x86, answer) = send_image(&h.app, &std::fs::read(&img).unwrap()).await;
3864
    assert_eq!(answer["arch"], "x86_64", "read from its shell: {answer}");
3865
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{x86}"), Some("runner-secret"), None).await;
3866
    assert_eq!(serde_json::from_str::<jet::images::Manifest>(&body).unwrap().arch.as_deref(), Some("x86_64"), "runners fetch it named");
3867
    // One nobody can read: no ext4, no shell.
3868
    let blob: Vec<u8> = (0..300_000u32).map(|i| (i % 241) as u8).collect();
3869
    let (unread, answer) = send_image(&h.app, &blob).await;
3870
    assert!(answer["arch"].is_null(), "{answer}");
3871
    let archs = db::flow::image_archs(&h.app.db).await.unwrap();
3872
    assert_eq!((archs.get(&x86).map(String::as_str), archs.get(&unread)), (Some("x86_64"), None));
3873
    // Kept images with none are read once at start.
3874
    sqlx::query("UPDATE jet_images SET arch = ''").execute(&h.app.db).await.unwrap();
3875
    sqlx::query("DELETE FROM flow_images").execute(&h.app.db).await.unwrap();
3876
    assert_eq!(oxygenhub::images::learn_archs(&h.app).await.unwrap(), 1);
3877
    assert_eq!(db::flow::image_archs(&h.app.db).await.unwrap().get(&x86).map(String::as_str), Some("x86_64"));
3878
3879
    // A job on each image.
3880
    create(&h.app, "andy", "arch").await;
3881
    let work = tempfile::tempdir().unwrap();
3882
    let c = client(&format!("{}/andy/arch", h.base), work.path());
3883
    let kdl = format!(
3884
        "schema-version 1\nsandbox \"unread\" {{\n    rootfs \"cas://blob/{unread}\"\n}}\nsandbox \"x86\" {{\n    rootfs \"cas://blob/{x86}\"\n}}\n\
3885
         job \"first\" {{\n    sandbox \"unread\"\n    exec \"make\"\n}}\njob \"second\" {{\n    sandbox \"x86\"\n    exec \"make\"\n    depends-on \"first\"\n}}\n\
3886
         job \"third\" {{\n    sandbox \"unread\"\n    exec \"make\"\n    depends-on \"first\"\n}}\n"
3887
    );
3888
    write(work.path(), ".flow/pipeline.kdl", &kdl);
3889
    c.commit("Jobs on two images", &[]).unwrap();
3890
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3891
    runs_of(&h.app, "andy", "arch").await;
3892
3893
    // The x86_64 runner passes the first job: its image is x86_64 now.
3894
    let x86_info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
3895
    let x86_claim =
3896
        serde_json::json!({ "runner": "earth", "runtimes": ["microvm"], "images": [], "fetches_images": true, "info": x86_info });
3897
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(x86_claim.to_string())).await;
3898
    assert_eq!(st, StatusCode::OK, "{body}");
3899
    let first: serde_json::Value = serde_json::from_str(&body).unwrap();
3900
    assert_eq!(first["job"]["name"], "first");
3901
    let ph = first["pipeline_hash"].as_str().unwrap();
3902
    let id = first["job_id"].as_i64().unwrap();
3903
    assert_eq!(
3904
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("first", ph, 0) })).await,
3905
        StatusCode::NO_CONTENT
3906
    );
3907
    assert_eq!(db::flow::image_archs(&h.app.db).await.unwrap().get(&unread).map(String::as_str), Some("x86_64"), "learned");
3908
3909
    // A riscv64 runner is offered neither: one read, one learned.
3910
    let token = "flowreg_narvi";
3911
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
3912
    let identity = SecretKey::generate().identity("narvi", "", 1);
3913
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
3914
    let reg = serde_json::json!({ "token": token, "name": "narvi", "identity": hex::encode(identity.encode()), "info": info });
3915
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
3916
    assert_eq!(st, StatusCode::OK, "{body}");
3917
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
3918
    let narvi =
3919
        serde_json::json!({ "runner": "narvi", "runtimes": ["microvm"], "images": [], "fetches_images": true, "info": info }).to_string();
3920
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(narvi)).await;
3921
    assert_eq!(st, StatusCode::NO_CONTENT, "the second job's image is x86_64 and the third's learned so: {body}");
3922
    for _ in 0..2 {
3923
        let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(x86_claim.to_string())).await;
3924
        assert_eq!(st, StatusCode::OK, "both go to x86_64: {body}");
3925
    }
3926
}
3927
3928
/// Diffusion auto-land (docs/diffusion.md §4.2; Andy chose "opt-in, per
3929
/// repository", 2026-10-13): a consumer that chose `land = auto` has a bump
3930
/// landed by itself, as the diffusion account, once both halves are green;
3931
/// a bump from an upstream with no checks (amber) always waits.
3932
#[tokio::test(flavor = "multi_thread")]
3933
async fn a_consumer_that_chose_auto_lands_green_bumps_itself() {
3934
    let h = hub().await;
3935
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3936
    create(&h.app, "andy", "api").await;
3937
    create(&h.app, "andy", "game").await;
3938
    let hub_app = &h.app;
3939
    // Run every queued job to a pass.
3940
    let pass_all = move || async move {
3941
        for _ in 0..20 {
3942
            let Some(a) = claim(hub_app).await else {
3943
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3944
                if !jobs_left(hub_app).await {
3945
                    break;
3946
                }
3947
                continue;
3948
            };
3949
            let id = a["job_id"].as_i64().unwrap();
3950
            let (name, ph) = (a["job"]["name"].as_str().unwrap().to_string(), a["pipeline_hash"].as_str().unwrap().to_string());
3951
            assert_eq!(
3952
                finish(hub_app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt(&name, &ph, 0) })).await,
3953
                StatusCode::NO_CONTENT
3954
            );
3955
        }
3956
    };
3957
    let api_work = tempfile::tempdir().unwrap();
3958
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
3959
    write(api_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3960
    write(api_work.path(), "test.sh", "echo ok\n");
3961
    api.snapshot("t").unwrap();
3962
    api.commit("api v1", &[]).unwrap();
3963
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3964
    pass_all().await;
3965
    let game_work = tempfile::tempdir().unwrap();
3966
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
3967
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3968
    write(game_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3969
    write(game_work.path(), "test.sh", "echo ok\n");
3970
    game.snapshot("t").unwrap();
3971
    game.commit("game on api v1", &[]).unwrap();
3972
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3973
    pass_all().await;
3974
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3975
    for _ in 0..100 {
3976
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
3977
            .bind(game_row.id)
3978
            .fetch_one(&h.app.db)
3979
            .await
3980
            .unwrap();
3981
        if n > 0 {
3982
            break;
3983
        }
3984
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3985
    }
3986
    let (st, body) =
3987
        call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(r#"{"follow":"green","land":"auto"}"#.into())).await;
3988
    assert_eq!(st, StatusCode::OK, "{body}");
3989
    assert!(body.contains(r#""land":"auto""#), "{body}");
3990
    let (st, _) =
3991
        call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(r#"{"follow":"green","land":"soon"}"#.into())).await;
3992
    assert_eq!(st, StatusCode::BAD_REQUEST);
3993
3994
    // The upstream moves and passes: the bump is proposed, its run passes,
3995
    // and it lands by itself.
3996
    write(api_work.path(), "a2.c", "v2\n");
3997
    api.snapshot("t").unwrap();
3998
    api.commit("api v2: faster sprites", &[]).unwrap();
3999
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4000
    let mut landed = None;
4001
    for _ in 0..100 {
4002
        pass_all().await;
4003
        let all = db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap();
4004
        if let Some(p) = all.into_iter().find(|p| p.source_bookmark == "diffusion/deps/api" && p.state == "landed") {
4005
            landed = Some(p);
4006
            break;
4007
        }
4008
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4009
    }
4010
    let p = landed.expect("landed by itself once both halves were green");
4011
    assert!(p.body.contains("lands its bumps itself"), "{}", p.body);
4012
    let events = db::proposals::events(&h.app.db, p.id).await.unwrap();
4013
    let landing = events.iter().find(|e| e.event == "landed").expect("a landing on the timeline");
4014
    assert_eq!(landing.actor, "diffusion");
4015
    assert!(landing.detail.contains("Diffusion, both halves green"), "{}", landing.detail);
4016
    // The game's main now pins api v2.
4017
    let mut behind = serde_json::Value::Null;
4018
    for _ in 0..100 {
4019
        let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
4020
        let list: Vec<serde_json::Value> = serde_json::from_str(&list).unwrap();
4021
        behind = list.iter().find(|c| c["name"] == "game").map(|c| c["behind"].clone()).unwrap_or_default();
4022
        if behind == 0 {
4023
            break;
4024
        }
4025
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4026
    }
4027
    assert_eq!(behind, 0, "main moved to the bump");
4028
4029
    // An upstream with no checks: its bump passes in the consumer, but
4030
    // amber never lands by itself, whatever the setting.
4031
    create(&h.app, "andy", "lib").await;
4032
    create(&h.app, "andy", "app").await;
4033
    let lib_work = tempfile::tempdir().unwrap();
4034
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
4035
    write(lib_work.path(), "lib.h", "v1\n");
4036
    lib.snapshot("t").unwrap();
4037
    lib.commit("lib v1", &[]).unwrap();
4038
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4039
    let app_work = tempfile::tempdir().unwrap();
4040
    let app = client(&format!("{}/andy/app", h.base), app_work.path());
4041
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
4042
    let modules = std::fs::read_to_string(app_work.path().join(".oxymodules")).unwrap();
4043
    write(app_work.path(), ".oxymodules", &format!("{modules}follow = green\nland = auto\n"));
4044
    write(app_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4045
    write(app_work.path(), "test.sh", "echo ok\n");
4046
    app.snapshot("t").unwrap();
4047
    app.commit("app on lib", &[]).unwrap();
4048
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
4049
    pass_all().await;
4050
    let app_row = db::repos::get(&h.app.db, "andy", "app").await.unwrap().unwrap();
4051
    for _ in 0..100 {
4052
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
4053
            .bind(app_row.id)
4054
            .fetch_one(&h.app.db)
4055
            .await
4056
            .unwrap();
4057
        if n > 0 {
4058
            break;
4059
        }
4060
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4061
    }
4062
    write(lib_work.path(), "lib.c", "v2\n");
4063
    lib.snapshot("t").unwrap();
4064
    lib.commit("lib v2", &[]).unwrap();
4065
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4066
    let mut passed = false;
4067
    for _ in 0..100 {
4068
        pass_all().await;
4069
        let s: Option<String> = sqlx::query_scalar(
4070
            "SELECT status FROM flow_runs WHERE repo_id = $1 AND bookmark = 'diffusion/deps/lib' ORDER BY id DESC LIMIT 1",
4071
        )
4072
        .bind(app_row.id)
4073
        .fetch_optional(&h.app.db)
4074
        .await
4075
        .unwrap();
4076
        if s.as_deref() == Some("passed") {
4077
            passed = true;
4078
            break;
4079
        }
4080
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4081
    }
4082
    assert!(passed, "the app's run on the bump passed");
4083
    assert_eq!(oxygenhub::diffusion::auto_land(&h.app, &app_row, "deps/lib").await, Err(oxygenhub::diffusion::Held::Unverified));
4084
    let open = db::proposals::list(&h.app.db, app_row.id, &["open"]).await.unwrap();
4085
    assert!(open.iter().any(|p| p.source_bookmark == "diffusion/deps/lib"), "amber waits for a person");
4086
}
4087
4088
/// oxygenflow#31: one finished job runs again in the same run, with the
4089
/// jobs that depend on it; what it depends on keeps its result, so a flaky
4090
/// test reruns without its build. Not while the run is live, and only a
4091
/// job the run has.
4092
#[tokio::test(flavor = "multi_thread")]
4093
async fn one_job_reruns_with_what_depends_on_it() {
4094
    let h = hub().await;
4095
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4096
    create(&h.app, "andy", "flaky").await;
4097
    let work = tempfile::tempdir().unwrap();
4098
    let c = client(&format!("{}/andy/flaky", h.base), work.path());
4099
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4100
    write(work.path(), "test.sh", "echo ok\n");
4101
    c.commit("Add a pipeline", &[]).unwrap();
4102
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4103
    let run = runs_of(&h.app, "andy", "flaky").await[0].clone();
4104
    // build and lint pass; test fails, as a flaky one does.
4105
    let (st, _) =
4106
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/test/rerun", run.number), Some("site"), None).await;
4107
    assert_eq!(st, StatusCode::CONFLICT, "not while the run is live");
4108
    while let Some(j) = claim(&h.app).await {
4109
        let id = j["job_id"].as_i64().unwrap();
4110
        let (name, ph) = (j["job"]["name"].as_str().unwrap().to_string(), j["pipeline_hash"].as_str().unwrap().to_string());
4111
        let exit = if name == "test" { 1 } else { 0 };
4112
        let log = serde_json::json!({ "records": [{ "t": 1, "stream": "out", "text": format!("{name} ran") }] });
4113
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(log.to_string())).await;
4114
        assert_eq!(
4115
            finish(&h.app, id, serde_json::json!({ "exit_code": exit, "duration_ms": 10, "receipt": receipt(&name, &ph, exit as u32) }))
4116
                .await,
4117
            StatusCode::NO_CONTENT
4118
        );
4119
    }
4120
    let status = |n: &'static str| {
4121
        let (app, run_id) = (h.app.clone(), run.id);
4122
        async move { db::flow::jobs(&app.db, run_id).await.unwrap().into_iter().find(|j| j.name == n).unwrap() }
4123
    };
4124
    assert_eq!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().status, "failed");
4125
    let failed_test = status("test").await;
4126
4127
    // The test again: build and lint keep their results.
4128
    let (st, body) =
4129
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/test/rerun", run.number), Some("site"), None).await;
4130
    assert_eq!(st, StatusCode::OK, "{body}");
4131
    assert!(body.contains(r#""queued":1"#), "{body}");
4132
    assert_eq!(
4133
        (status("build").await.status, status("lint").await.status, status("test").await.status),
4134
        ("passed".into(), "passed".into(), "queued".into())
4135
    );
4136
    assert!(db::flow::log(&h.app.db, failed_test.id, 0, 100).await.unwrap().is_empty(), "its old log is gone");
4137
    assert!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().live());
4138
    let checks = checks_when(&h.app, run.repo_id, &run.state, 3).await;
4139
    assert_eq!(checks.iter().find(|c| c.name == "flow/test").map(|c| c.status.as_str()), Some("queued"));
4140
    let j = claim(&h.app).await.expect("the test, queued again");
4141
    assert_eq!(j["job"]["name"], "test");
4142
    let ph = j["pipeline_hash"].as_str().unwrap().to_string();
4143
    let id = j["job_id"].as_i64().unwrap();
4144
    assert_eq!(
4145
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("test", &ph, 0) })).await,
4146
        StatusCode::NO_CONTENT
4147
    );
4148
    assert_eq!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().status, "passed", "the run is whole again");
4149
    // Andy owns it: told it failed, then that it is fixed (#183).
4150
    let andy_id = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap().id;
4151
    let kinds: Vec<String> = db::notify::inbox(&h.app.db, andy_id, 20).await.unwrap().into_iter().map(|n| n.kind).collect();
4152
    assert!(kinds.contains(&"flow.failed".to_string()) && kinds.contains(&"flow.fixed".to_string()), "{kinds:?}");
4153
4154
    // The build again brings the test that depends on it; lint stays.
4155
    let (_, body) =
4156
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/build/rerun", run.number), Some("site"), None).await;
4157
    assert!(body.contains(r#""queued":2"#), "{body}");
4158
    assert_eq!(
4159
        (status("build").await.status, status("lint").await.status, status("test").await.status),
4160
        ("queued".into(), "passed".into(), "queued".into())
4161
    );
4162
    let (st, _) =
4163
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/deploy/rerun", run.number), Some("site"), None).await;
4164
    assert_eq!(st, StatusCode::CONFLICT, "live again, and no such job either way");
4165
}
4166
4167
/// oxygenflow#30: a failed run tells its pusher and the repository's
4168
/// watchers; a runner whose last five jobs ended in infrastructure errors
4169
/// is drained and the administrators told, counting only since an
4170
/// administrator last made it active.
4171
#[tokio::test(flavor = "multi_thread")]
4172
async fn failed_runs_are_told_and_an_erroring_runner_is_drained() {
4173
    let h = hub().await;
4174
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4175
    let bob = db::accounts::create_account(&h.app.db, "bob", "[email protected]", "x", "salt", false).await.unwrap();
4176
    create(&h.app, "andy", "alerts").await;
4177
    let row = db::repos::get(&h.app.db, "andy", "alerts").await.unwrap().unwrap();
4178
    db::notify::set_watch(&h.app.db, bob.id, row.id, true).await.unwrap();
4179
    let work = tempfile::tempdir().unwrap();
4180
    let c = client(&format!("{}/andy/alerts", h.base), work.path());
4181
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4182
    write(work.path(), "test.sh", "exit 1\n");
4183
    c.commit("Add a pipeline", &[]).unwrap();
4184
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4185
    let run = runs_of(&h.app, "andy", "alerts").await[0].clone();
4186
    sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&h.app.db).await.unwrap();
4187
    while let Some(j) = claim(&h.app).await {
4188
        let id = j["job_id"].as_i64().unwrap();
4189
        let (name, ph) = (j["job"]["name"].as_str().unwrap().to_string(), j["pipeline_hash"].as_str().unwrap().to_string());
4190
        let exit = if name == "test" { 1 } else { 0 };
4191
        finish(&h.app, id, serde_json::json!({ "exit_code": exit, "duration_ms": 10, "receipt": receipt(&name, &ph, exit as u32) })).await;
4192
    }
4193
    let told = |id: i64| {
4194
        let db = h.app.db.clone();
4195
        async move { db::notify::inbox(&db, id, 20).await.unwrap().into_iter().filter(|n| n.kind == "flow.failed").collect::<Vec<_>>() }
4196
    };
4197
    let (for_andy, for_bob) = (told(andy.id).await, told(bob.id).await);
4198
    assert_eq!((for_andy.len(), for_bob.len()), (1, 1), "the pusher and a watcher");
4199
    assert!(for_andy[0].title.contains(&format!("run #{} on main failed (test)", run.number)), "{}", for_andy[0].title);
4200
    assert_eq!(for_andy[0].url, format!("/andy/alerts/flow/{}", run.number));
4201
4202
    // Five infrastructure errors in a row drain the runner.
4203
    let runner_id = || {
4204
        let db = h.app.db.clone();
4205
        async move { sqlx::query_scalar::<_, i64>("SELECT id FROM flow_runners WHERE name = 'test-1'").fetch_one(&db).await.unwrap() }
4206
    };
4207
    let mut errors = 0;
4208
    while errors < 5 {
4209
        let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/alerts/flow/runs", Some("site"), Some("{}".into())).await;
4210
        assert_eq!(st, StatusCode::CREATED);
4211
        while let Some(j) = claim(&h.app).await {
4212
            let id = j["job_id"].as_i64().unwrap();
4213
            let st = finish(
4214
                &h.app,
4215
                id,
4216
                serde_json::json!({ "exit_code": null, "duration_ms": 10, "error": "the microVM did not start: /dev/kvm busy" }),
4217
            )
4218
            .await;
4219
            assert_eq!(st, StatusCode::NO_CONTENT);
4220
            errors += 1;
4221
            if errors == 5 {
4222
                break;
4223
            }
4224
        }
4225
    }
4226
    let state = |id: i64| {
4227
        let db = h.app.db.clone();
4228
        async move { db::runners::get(&db, id).await.unwrap().unwrap().state }
4229
    };
4230
    let id = runner_id().await;
4231
    assert_eq!(state(id).await, "draining");
4232
    let drained: Vec<_> =
4233
        db::notify::inbox(&h.app.db, andy.id, 50).await.unwrap().into_iter().filter(|n| n.kind == "flow.runner_drained").collect();
4234
    assert_eq!(drained.len(), 1, "the administrator is told");
4235
    assert!(drained[0].title.contains("/dev/kvm busy"), "{}", drained[0].title);
4236
    assert!(
4237
        !told(bob.id).await.is_empty()
4238
            && db::notify::inbox(&h.app.db, bob.id, 50).await.unwrap().iter().all(|n| n.kind != "flow.runner_drained")
4239
    );
4240
    // Made active again, past errors no longer count.
4241
    db::runners::set_state(&h.app.db, id, "active").await.unwrap();
4242
    assert_eq!(db::runners::erroring(&h.app.db, id, 5).await.unwrap(), None);
4243
}
4244
4245
/// #225: an ordinary user turns Flow on for their repository on their own
4246
/// runner, and the site's runners never take its jobs.
4247
#[tokio::test(flavor = "multi_thread")]
4248
async fn owners_run_flow_on_their_own_runners_only() {
4249
    use oxy_core::identity::SecretKey;
4250
    let h = hub().await;
4251
    let register = |name: &'static str| {
4252
        let app = h.app.clone();
4253
        async move {
4254
            let body = format!("username={name}&email={name}%40example.com&password=correct-horse-battery&setup=test-setup");
4255
            let res = oxygenhub::router(app)
4256
                .oneshot(
4257
                    Request::post("/register")
4258
                        .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
4259
                        .body(Body::from(body))
4260
                        .unwrap(),
4261
                )
4262
                .await
4263
                .unwrap();
4264
            res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string()
4265
        }
4266
    };
4267
    register("andy").await; // the first account: the site's administrator
4268
    let bob = register("bob").await;
4269
    create(&h.app, "bob", "game").await;
4270
    let web = |method: &'static str, path: &str, body: Option<String>| {
4271
        let (app, cookie, path) = (h.app.clone(), bob.clone(), path.to_string());
4272
        async move {
4273
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
4274
            if body.is_some() {
4275
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
4276
            }
4277
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
4278
            String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned()
4279
        }
4280
    };
4281
    let csrf_of = |page: &str| {
4282
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
4283
        page[i..].split('"').next().unwrap().to_string()
4284
    };
4285
    // No runner of his own yet: he is told how, and cannot switch it on.
4286
    let page = web("GET", "/bob/game/settings", None).await;
4287
    assert!(page.contains("register a runner for this repository") && !page.contains("value=\"own\""), "{page}");
4288
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=own", csrf_of(&page)))).await;
4289
    assert!(page.contains("Register a runner for this repository"), "{page}");
4290
    // He registers one.
4291
    let page = web("GET", "/bob/game/settings", None).await;
4292
    let page = web("POST", "/bob/game/settings/runners/token", Some(format!("_csrf={}", csrf_of(&page)))).await;
4293
    let i = page.find("--token ").unwrap() + "--token ".len();
4294
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
4295
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
4296
    let identity = SecretKey::generate().identity("bobs", "", 1);
4297
    let reg = serde_json::json!({ "token": token, "name": "bobs", "identity": hex::encode(identity.encode()), "info": info });
4298
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
4299
    assert_eq!(st, StatusCode::OK, "{body}");
4300
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
4301
    // The site's runners stay a site administrator's to grant; his own he may choose.
4302
    let page = web("GET", "/bob/game/settings", None).await;
4303
    assert!(page.contains("value=\"own\"") && !page.contains("value=\"on\""), "{page}");
4304
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=on", csrf_of(&page)))).await;
4305
    assert!(page.contains("Only site administrators let the site's runners"), "{page}");
4306
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=own", csrf_of(&page)))).await;
4307
    assert!(page.contains("value=\"own\" checked") && page.contains("start runs"), "{page}");
4308
    assert_eq!(db::repos::get(&h.app.db, "bob", "game").await.unwrap().unwrap().flow, "own");
4309
    // A push starts a run; the site's runner is not offered it, his is.
4310
    let work = tempfile::tempdir().unwrap();
4311
    let c = client(&format!("{}/bob/game", h.base), work.path());
4312
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4313
    write(work.path(), "test.sh", "echo ok\n");
4314
    c.snapshot("t").unwrap();
4315
    c.commit("A pipeline", &[]).unwrap();
4316
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4317
    assert_eq!(runs_of(&h.app, "bob", "game").await.len(), 1, "a run started");
4318
    assert!(claim(&h.app).await.is_none(), "the site's runner is not offered it");
4319
    let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
4320
    let (st, job) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(body)).await;
4321
    assert_eq!(st, StatusCode::OK, "{job}");
4322
    assert_eq!(serde_json::from_str::<serde_json::Value>(&job).unwrap()["repo"], "bob/game");
4323
}
4324
4325
#[tokio::test(flavor = "multi_thread")]
4326
async fn a_job_takes_the_artifact_its_producer_kept() {
4327
    let h = hub().await;
4328
    create(&h.app, "andy", "demo").await;
4329
    let url = format!("{}/andy/demo", h.base);
4330
    let work = tempfile::tempdir().unwrap();
4331
    let c = client(&url, work.path());
4332
    write(
4333
        work.path(),
4334
        ".flow/pipeline.kdl",
4335
        &format!(
4336
            "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"
4337
        ),
4338
    );
4339
    c.snapshot("test").unwrap();
4340
    c.commit("Plan, then apply that plan", &[]).unwrap();
4341
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4342
4343
    // The plan job runs and keeps its plan, named by its receipt.
4344
    let runs = runs_of(&h.app, "andy", "demo").await;
4345
    assert_eq!(runs.len(), 1, "a run");
4346
    let jobs = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap();
4347
    assert!(!jobs.is_empty(), "jobs: {:?}", runs[0]);
4348
    let p = claim(&h.app)
4349
        .await
4350
        .unwrap_or_else(|| panic!("nothing to claim: {:?}", jobs.iter().map(|j| (&j.name, &j.status, &j.error)).collect::<Vec<_>>()));
4351
    assert_eq!(p["job"]["name"], "plan");
4352
    let plan_id = p["job_id"].as_i64().unwrap();
4353
    let plan = b"the reviewed plan".to_vec();
4354
    let (st, text) = upload(&h.app, plan_id, "tfplan", &plan).await;
4355
    assert_eq!(st, StatusCode::OK, "{text}");
4356
    let blob = oxy_core::repo::Repo::blob_ref(&plan).to_hex();
4357
    let mut r = receipt("plan", p["pipeline_hash"].as_str().unwrap(), 0);
4358
    r["outputs"] = serde_json::json!([blob]);
4359
    assert_eq!(
4360
        finish(&h.app, plan_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r })).await,
4361
        StatusCode::NO_CONTENT
4362
    );
4363
4364
    // The apply job is told what to take and the blob to expect, and the
4365
    // runner fetches exactly those bytes.
4366
    let a = claim(&h.app).await.unwrap();
4367
    assert_eq!(a["job"]["name"], "apply");
4368
    let apply_id = a["job_id"].as_i64().unwrap();
4369
    assert_eq!(
4370
        a["inputs"],
4371
        serde_json::json!([{ "artifact": "tfplan", "from": "plan", "path": "/src/tfplan", "blob": blob }]),
4372
        "the claim names the producer's blob"
4373
    );
4374
    let req = Request::get(format!("/api/v1/flow/jobs/{apply_id}/inputs/0")).header(header::AUTHORIZATION, "Bearer runner-secret");
4375
    let res = oxygenhub::router(h.app.clone()).oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
4376
    assert_eq!(res.status(), StatusCode::OK);
4377
    assert_eq!(res.into_body().collect().await.unwrap().to_bytes().to_vec(), plan);
4378
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{apply_id}/inputs/1"), Some("runner-secret"), None).await;
4379
    assert_eq!(st, StatusCode::NOT_FOUND, "no second input");
4380
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{apply_id}/inputs/0"), None, None).await;
4381
    assert_eq!(st, StatusCode::UNAUTHORIZED, "runners only");
4382
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{plan_id}/inputs/0"), Some("runner-secret"), None).await;
4383
    assert_eq!(st, StatusCode::CONFLICT, "only a running job's");
4384
}
4385
4386
#[tokio::test(flavor = "multi_thread")]
4387
async fn a_job_waits_for_approval_and_is_approved_rejected_or_expires() {
4388
    let h = hub().await;
4389
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4390
    let bob = db::accounts::create_account(&h.app.db, "bob", "[email protected]", "x", "salt", false).await.unwrap();
4391
    let carol = db::accounts::create_account(&h.app.db, "carol", "[email protected]", "x", "salt", true).await.unwrap();
4392
    create(&h.app, "andy", "gated").await;
4393
    let row = db::repos::get(&h.app.db, "andy", "gated").await.unwrap().unwrap();
4394
    let work = tempfile::tempdir().unwrap();
4395
    let c = client(&format!("{}/andy/gated", h.base), work.path());
4396
    write(
4397
        work.path(),
4398
        ".flow/pipeline.kdl",
4399
        &format!(
4400
            "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"
4401
        ),
4402
    );
4403
    let mut n = 0;
4404
    let mut push = || {
4405
        n += 1;
4406
        write(work.path(), "n.txt", &format!("{n}\n"));
4407
        c.snapshot("test").unwrap();
4408
        c.commit(&format!("Push {n}"), &[]).unwrap();
4409
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4410
    };
4411
    // Runs `plan` to a pass; returns the run, its actor set to andy.
4412
    let plan_passes = |number: i64| {
4413
        let app = h.app.clone();
4414
        let row = row.clone();
4415
        async move {
4416
            let mut run = None;
4417
            for _ in 0..100 {
4418
                if let Some(r) = db::flow::run(&app.db, row.id, number).await.unwrap() {
4419
                    run = Some(r);
4420
                    break;
4421
                }
4422
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4423
            }
4424
            let run = run.expect("the run");
4425
            sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&app.db).await.unwrap();
4426
            let j = claim(&app).await.expect("plan is claimed");
4427
            assert_eq!(j["job"]["name"], "plan");
4428
            let (id, ph) = (j["job_id"].as_i64().unwrap(), j["pipeline_hash"].as_str().unwrap().to_string());
4429
            finish(&app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("plan", &ph, 0) })).await;
4430
            db::flow::run(&app.db, row.id, number).await.unwrap().unwrap()
4431
        }
4432
    };
4433
4434
    // Run 1: apply waits; only someone with the role, other than the pusher, approves it.
4435
    push();
4436
    let run = runs_of(&h.app, "andy", "gated").await[0].clone();
4437
    // Live pages hear of the push (oxygenhub#203).
4438
    let heard = |topic: String| match h.app.events.live.since(0, &[topic]) {
4439
        oxygenhub::events::Replay::Events(e) => e.into_iter().map(|e| e.kind).collect::<Vec<_>>(),
4440
        oxygenhub::events::Replay::Reload => vec!["reload".into()],
4441
    };
4442
    assert!(heard(oxygenhub::events::topic::repo(row.id)).contains(&"push".to_string()), "the push is on the repository's topic");
4443
    sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&h.app.db).await.unwrap();
4444
    let early = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true, None).await.unwrap_err();
4445
    assert!(early.contains("waits for plan first"), "{early}");
4446
    let run = plan_passes(run.number).await;
4447
    assert!(claim(&h.app).await.is_none(), "apply waits for a person, so no runner gets it");
4448
    assert!(heard(oxygenhub::events::topic::run(run.id)).contains(&"jobs".to_string()), "the run's topic hears its jobs");
4449
    // Those who may approve are told, once; the pusher (others-only) and
4450
    // someone without the role are not.
4451
    let told = |id: i64| {
4452
        let db = h.app.db.clone();
4453
        async move { db::notify::inbox(&db, id, 20).await.unwrap().into_iter().filter(|n| n.kind == "flow.approval").count() }
4454
    };
4455
    assert_eq!((told(carol.id).await, told(andy.id).await, told(bob.id).await), (1, 0, 0));
4456
    let (_, page) = call(&h.app, "GET", &format!("/andy/gated/flow/{}", run.number), None, None).await;
4457
    assert!(page.contains("waits for approval by someone with the <em>maintain</em> role, other than andy"), "the run page says so");
4458
    let own = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &andy, true, None).await.unwrap_err();
4459
    assert!(own.contains("someone other than andy"), "{own}");
4460
    let no_role = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &bob, true, None).await.unwrap_err();
4461
    assert!(no_role.contains("takes the maintain role"), "{no_role}");
4462
    assert_eq!(oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true, None).await.unwrap(), "apply: approved by carol");
4463
    assert_eq!(told(carol.id).await, 1, "told once");
4464
    let j = claim(&h.app).await.expect("approved, it runs");
4465
    assert_eq!(j["job"]["name"], "apply");
4466
    // Approved, its identity token names the environment (oxygenflow#59).
4467
    let token =
4468
        j["secrets"].as_array().unwrap().iter().find(|s| s["path"] == "/run/secrets/cloud").unwrap()["value"].as_str().unwrap().to_string();
4469
    let claims = h.app.oidc().await.unwrap().verify(&token, "https://sts.example", db::now_ms()).expect("a valid token");
4470
    assert_eq!(claims["environment"], "prod");
4471
    let (id, ph) = (j["job_id"].as_i64().unwrap(), j["pipeline_hash"].as_str().unwrap().to_string());
4472
    finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("apply", &ph, 0) })).await;
4473
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
4474
    assert!(audit.iter().any(|r| r.action == "flow.approved" && r.actor == "carol" && r.target.ends_with("#1 apply")), "audited");
4475
    let (_, page) = call(&h.app, "GET", &format!("/andy/gated/flow/{}", run.number), None, None).await;
4476
    assert!(page.contains("approved by carol"), "the run says who");
4477
    let (_, page) = call(&h.app, "GET", "/andy/gated/deployments", None, None).await;
4478
    assert!(page.contains("<strong>prod</strong>") && page.contains(">#1</a>") && page.contains("<td>carol</td>"), "the Deployments page");
4479
    let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/gated/deployments", Some("site"), None).await;
4480
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
4481
    assert_eq!((list[0]["environment"].as_str(), list[0]["approved_by"].as_str()), (Some("prod"), Some("carol")));
4482
4483
    // Run 2: rejected through the API with carol's agent token: the job
4484
    // ends cancelled, the run ends, and it says the agent did it
4485
    // (oxygenhub#229).
4486
    push();
4487
    let run = plan_passes(2).await;
4488
    let (secret, hash) = oxygenhub::auth::new_token();
4489
    let tok = db::accounts::create_token(&h.app.db, carol.id, "claude-code", &hash, "repo:write", "", None).await.unwrap();
4490
    db::accounts::set_token_agent(&h.app.db, carol.id, tok.id, true).await.unwrap();
4491
    // An agent's token decides a gate only where the repository allows it
4492
    // (#258).
4493
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/gated/flow/runs/2/jobs/apply/reject", Some(&secret), Some("{}".into())).await;
4494
    assert_eq!(st, StatusCode::CONFLICT, "{body}");
4495
    assert!(body.contains("decided by a person here") && body.contains("Settings › OxygenFlow"), "{body}");
4496
    let gated = db::repos::get(&h.app.db, "andy", "gated").await.unwrap().unwrap();
4497
    db::repos::set_agents_decide_gates(&h.app.db, gated.id, true).await.unwrap();
4498
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/gated/flow/runs/2/jobs/apply/reject", Some(&secret), Some("{}".into())).await;
4499
    assert_eq!(st, StatusCode::OK, "{body}");
4500
    assert!(body.contains("rejected by carol via claude-code"), "{body}");
4501
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
4502
    let apply = jobs.iter().find(|j| j.name == "apply").unwrap();
4503
    assert_eq!((apply.status.as_str(), apply.error.as_str()), ("cancelled", "rejected by carol via claude-code"));
4504
    assert_eq!((apply.approved_by.as_str(), apply.approved_via.as_str()), ("carol", "claude-code"));
4505
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
4506
    assert!(
4507
        audit.iter().any(|r| r.action == "flow.rejected" && r.actor == "carol" && r.detail.contains("via claude-code")),
4508
        "audited with the agent"
4509
    );
4510
    assert!(claim(&h.app).await.is_none());
4511
4512
    // Run 3: nobody decides in time.
4513
    push();
4514
    let run = plan_passes(3).await;
4515
    assert_eq!(oxygenhub::flow::expire_approvals(&h.app, db::now_ms() + 3_600_000).await.unwrap(), 0, "not yet");
4516
    assert_eq!(oxygenhub::flow::expire_approvals(&h.app, db::now_ms() + 25 * 3_600_000).await.unwrap(), 1);
4517
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
4518
    let apply = jobs.iter().find(|j| j.name == "apply").unwrap();
4519
    assert_eq!((apply.status.as_str(), apply.error.as_str()), ("cancelled", "no approval within 24h"));
4520
}
4521
4522
#[tokio::test(flavor = "multi_thread")]
4523
async fn live_streams_only_topics_the_viewer_may_hear_and_replays() {
4524
    let h = hub().await;
4525
    create(&h.app, "andy", "open").await;
4526
    h.app.repos.create(&RepoName::parse("andy/shut").unwrap(), None).unwrap();
4527
    db::repos::create(&h.app.db, "andy", "shut", "", hub_api::Visibility::Private).await.unwrap();
4528
    let open = db::repos::get(&h.app.db, "andy", "open").await.unwrap().unwrap();
4529
    let shut = db::repos::get(&h.app.db, "andy", "shut").await.unwrap().unwrap();
4530
    let live = &h.app.events.live;
4531
    let first = live.publish(&oxygenhub::events::topic::repo(open.id), "push");
4532
    live.publish(&oxygenhub::events::topic::repo(shut.id), "push");
4533
    live.publish(&oxygenhub::events::topic::proposal(open.id, 3), "review");
4534
4535
    // The first bytes of a stream, within a moment.
4536
    let read = |path: String, last: Option<u64>| {
4537
        let app = h.app.clone();
4538
        async move {
4539
            let mut req = Request::get(&path);
4540
            if let Some(l) = last {
4541
                req = req.header("last-event-id", l.to_string());
4542
            }
4543
            let res = oxygenhub::router(app).oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
4544
            let status = res.status();
4545
            let mut body = res.into_body();
4546
            let mut text = String::new();
4547
            while let Ok(Some(Ok(frame))) = tokio::time::timeout(std::time::Duration::from_millis(300), body.frame()).await {
4548
                if let Some(d) = frame.data_ref() {
4549
                    text.push_str(&String::from_utf8_lossy(d));
4550
                }
4551
            }
4552
            (status, text)
4553
        }
4554
    };
4555
    let topics = format!("/live?topics=repo:{},repo:{}/proposal:3", open.id, open.id);
4556
    // From the first event on: what came after it on these topics only.
4557
    let (st, text) = read(topics.clone(), Some(first.id)).await;
4558
    assert_eq!(st, StatusCode::OK);
4559
    assert!(text.contains("event: change") && text.contains(&format!("\"topic\":\"repo:{}/proposal:3\"", open.id)), "{text}");
4560
    assert!(!text.contains(&format!("\"topic\":\"repo:{}\"", shut.id)), "never another topic: {text}");
4561
    assert!(!text.contains(&format!("id: {}\n", first.id)), "not what was already seen: {text}");
4562
    // A private repository's topic, or someone else's, is refused whole.
4563
    let (st, _) = read(format!("/live?topics=repo:{},repo:{}", open.id, shut.id), None).await;
4564
    assert_eq!(st, StatusCode::FORBIDDEN);
4565
    assert_eq!(read("/live?topics=user:1".into(), None).await.0, StatusCode::FORBIDDEN);
4566
    assert_eq!(read("/live?topics=nonsense".into(), None).await.0, StatusCode::BAD_REQUEST);
4567
    assert_eq!(read("/live?topics=".into(), None).await.0, StatusCode::BAD_REQUEST);
4568
    // Too far behind: told to reload.
4569
    for _ in 0..oxygenhub::events::REPLAY {
4570
        live.publish("repo:999999", "push");
4571
    }
4572
    let (_, text) = read(topics, Some(first.id)).await;
4573
    assert!(text.contains("event: reload"), "{text}");
4574
}
4575
4576
#[tokio::test(flavor = "multi_thread")]
4577
async fn a_sealed_approval_releases_exactly_the_reviewed_plan() {
4578
    use oxy_core::approval::{SignedApproval, Statement};
4579
    use oxy_core::hash::ObjectRef;
4580
    use oxy_core::identity::SecretKey;
4581
    let h = hub().await;
4582
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4583
    let carol = db::accounts::create_account(&h.app.db, "carol", "[email protected]", "x", "salt", true).await.unwrap();
4584
    let sk = SecretKey::generate();
4585
    let carol_id = sk.identity("Carol", "[email protected]", 1);
4586
    db::accounts::link_identity(&h.app.db, carol.id, &carol_id.hash().to_hex(), "Carol", "[email protected]", &carol_id.encode())
4587
        .await
4588
        .unwrap();
4589
    create(&h.app, "andy", "infra").await;
4590
    let row = db::repos::get(&h.app.db, "andy", "infra").await.unwrap().unwrap();
4591
    let work = tempfile::tempdir().unwrap();
4592
    let c = client(&format!("{}/andy/infra", h.base), work.path());
4593
    write(
4594
        work.path(),
4595
        ".flow/pipeline.kdl",
4596
        &format!(
4597
            "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"
4598
        ),
4599
    );
4600
    c.snapshot("test").unwrap();
4601
    c.commit("Plan, then apply", &[]).unwrap();
4602
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4603
    let run = runs_of(&h.app, "andy", "infra").await[0].clone();
4604
    let p = claim(&h.app).await.unwrap();
4605
    let plan_id = p["job_id"].as_i64().unwrap();
4606
    let plan = b"the reviewed plan".to_vec();
4607
    upload(&h.app, plan_id, "tfplan", &plan).await;
4608
    let mut r = receipt("plan", p["pipeline_hash"].as_str().unwrap(), 0);
4609
    r["outputs"] = serde_json::json!([oxy_core::repo::Repo::blob_ref(&plan).to_hex()]);
4610
    finish(&h.app, plan_id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": r })).await;
4611
    let run = db::flow::run(&h.app.db, row.id, run.number).await.unwrap().unwrap();
4612
4613
    // An environment's gate takes a sealed approval: pressing Approve is not enough.
4614
    let plain = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true, None).await.unwrap_err();
4615
    assert!(plain.contains(&format!("oxy seal --flow {}/andy/infra/flow/{} --job apply", h.base, run.number)), "{plain}");
4616
    // What there is to sign.
4617
    let (st, body) =
4618
        call(&h.app, "GET", &format!("/api/v1/repos/andy/infra/flow/runs/{}/jobs/apply/approval", run.number), Some("site"), None).await;
4619
    assert_eq!(st, StatusCode::OK, "{body}");
4620
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
4621
    assert_eq!(v["environment"], "prod");
4622
    assert_eq!(v["inputs"], serde_json::json!([oxy_core::repo::Repo::blob_ref(&plan).to_hex()]), "the reviewed plan");
4623
    let mut repo = [0u8; 16];
4624
    repo.copy_from_slice(&hex::decode(v["repo"].as_str().unwrap()).unwrap());
4625
    let oref = |k: &str| ObjectRef::from_hex(v[k].as_str().unwrap()).unwrap();
4626
    let statement = Statement {
4627
        repo,
4628
        run: v["run"].as_str().unwrap().into(),
4629
        job: "apply".into(),
4630
        job_hash: oref("job_hash"),
4631
        state: oref("state"),
4632
        inputs: v["inputs"].as_array().unwrap().iter().map(|i| ObjectRef::from_hex(i.as_str().unwrap()).unwrap()).collect(),
4633
        environment: "prod".into(),
4634
        approve: true,
4635
    };
4636
    let seal = |s: &Statement, key: &SecretKey, id: &oxy_core::identity::Identity| {
4637
        let body = serde_json::json!({ "signed": hex::encode(SignedApproval::sign(s, id, key).encode()) }).to_string();
4638
        let app = h.app.clone();
4639
        let path = format!("/api/v1/repos/andy/infra/flow/runs/{}/jobs/apply/seal", run.number);
4640
        async move { call(&app, "POST", &path, Some("site"), Some(body)).await }
4641
    };
4642
    // Another plan, or a key linked to nobody (an agent's), is refused.
4643
    let other_plan = Statement { inputs: vec![ObjectRef([9; 32])], ..statement.clone() };
4644
    let (st, body) = seal(&other_plan, &sk, &carol_id).await;
4645
    assert!(st == StatusCode::CONFLICT && body.contains("approves something else"), "{st} {body}");
4646
    let agent = SecretKey::generate();
4647
    let agent_id = agent.identity("Claude Code", "[email protected]", 1);
4648
    let (st, body) = seal(&statement, &agent, &agent_id).await;
4649
    assert!(st == StatusCode::CONFLICT && body.contains("not linked to an account"), "{st} {body}");
4650
    assert!(claim(&h.app).await.is_none(), "still waiting");
4651
4652
    // Carol's seal releases it; it is kept in the repository; the token names her and it.
4653
    let (st, body) = seal(&statement, &sk, &carol_id).await;
4654
    assert_eq!(st, StatusCode::OK, "{body}");
4655
    assert!(body.contains("approved by carol, sealed"), "{body}");
4656
    let name = oxygenhub::repos::RepoName::parse("andy/infra").unwrap();
4657
    let state = statement.state;
4658
    let kept = h.app.repos.read(&name, move |r, _| Ok(r.store().approvals_for(&state)?)).await.unwrap();
4659
    assert_eq!(kept.len(), 1, "the approval is in the repository");
4660
    let j = claim(&h.app).await.expect("released");
4661
    assert_eq!(j["job"]["name"], "apply");
4662
    let token =
4663
        j["secrets"].as_array().unwrap().iter().find(|s| s["path"] == "/run/secrets/cloud").unwrap()["value"].as_str().unwrap().to_string();
4664
    let claims = h.app.oidc().await.unwrap().verify(&token, "https://sts.example", db::now_ms()).unwrap();
4665
    assert_eq!((claims["environment"].as_str(), claims["approved_by"].as_str()), (Some("prod"), Some("carol")));
4666
    assert_eq!(claims["approval"].as_str(), Some(kept[0].to_hex().as_str()));
4667
    let (_, page) = call(&h.app, "GET", &format!("/andy/infra/flow/{}", run.number), None, None).await;
4668
    assert!(page.contains("sealed with their key"), "the run page says so");
4669
}
4670
4671
/// Repositories take turns (oxygenhub#244): a repository with a job running
4672
/// waits behind one with none, so a burst can't hold up the rest.
4673
#[tokio::test(flavor = "multi_thread")]
4674
async fn repositories_take_turns_on_the_runners() {
4675
    let h = hub().await;
4676
    for name in ["busy", "quiet"] {
4677
        create(&h.app, "andy", name).await;
4678
        let work = tempfile::tempdir().unwrap();
4679
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
4680
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4681
        write(work.path(), "test.sh", "echo ok\n");
4682
        c.snapshot("test").unwrap();
4683
        c.commit("Add a pipeline", &[]).unwrap();
4684
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4685
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
4686
    }
4687
    // busy pushed first: its first job goes first; then quiet's turn, though
4688
    // busy's other independent job is older; then busy's again.
4689
    let order: Vec<String> = {
4690
        let mut out = Vec::new();
4691
        for _ in 0..3 {
4692
            let c = claim(&h.app).await.expect("a job to claim");
4693
            out.push(c["repo"].as_str().unwrap().to_string());
4694
        }
4695
        out
4696
    };
4697
    assert_eq!(order, ["andy/busy", "andy/quiet", "andy/busy"]);
4698
}
4699
4700
/// A pipeline lowers its jobs, never raises them (oxygenhub#244): a
4701
/// repository whose pipeline says `priority "low"` waits for another's
4702
/// everyday jobs, even set high itself; the queue says why; an expedited
4703
/// run is still urgent.
4704
#[tokio::test(flavor = "multi_thread")]
4705
async fn a_pipeline_lowers_its_jobs_and_expediting_still_wins() {
4706
    let h = hub().await;
4707
    for (name, extra) in [("nightly", "priority \"low\"\n"), ("everyday", "")] {
4708
        create(&h.app, "andy", name).await;
4709
        let work = tempfile::tempdir().unwrap();
4710
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
4711
        write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
4712
        write(work.path(), "test.sh", "echo ok\n");
4713
        c.snapshot("test").unwrap();
4714
        c.commit("Add a pipeline", &[]).unwrap();
4715
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4716
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
4717
    }
4718
    let nightly = db::repos::get(&h.app.db, "andy", "nightly").await.unwrap().unwrap();
4719
    db::repos::set_flow_priority(&h.app.db, nightly.id, "high").await.unwrap();
4720
    let q = db::flow::queue(&h.app.db).await.unwrap();
4721
    assert!(
4722
        q.iter().filter(|e| e.name == "nightly").all(|e| e.priority() == "low" && e.priority_note == "pipeline: low"),
4723
        "{:?}",
4724
        q.iter().map(|e| (&e.name, e.priority(), &e.priority_note)).collect::<Vec<_>>()
4725
    );
4726
    let repo_of = |c: serde_json::Value| c["repo"].as_str().unwrap().to_string();
4727
    // nightly pushed first and its repository is high, but its pipeline
4728
    // says low: everyday's jobs go first.
4729
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/everyday");
4730
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/everyday");
4731
    let run = &runs_of(&h.app, "andy", "nightly").await[0];
4732
    assert!(db::flow::expedite(&h.app.db, run.id, "expedited by andy: needed now").await.unwrap());
4733
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/nightly", "an expedited run is urgent whatever its jobs say");
4734
}
4735
4736
/// Priority comes before taking turns (oxygenhub#244): a low repository's
4737
/// jobs wait for a normal one's, and an expedited run goes first of all.
4738
#[tokio::test(flavor = "multi_thread")]
4739
async fn priority_then_turns_and_an_expedited_run_first() {
4740
    let h = hub().await;
4741
    for name in ["early", "later"] {
4742
        create(&h.app, "andy", name).await;
4743
        let work = tempfile::tempdir().unwrap();
4744
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
4745
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4746
        write(work.path(), "test.sh", "echo ok\n");
4747
        c.snapshot("test").unwrap();
4748
        c.commit("Add a pipeline", &[]).unwrap();
4749
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4750
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
4751
    }
4752
    let early = db::repos::get(&h.app.db, "andy", "early").await.unwrap().unwrap();
4753
    db::repos::set_flow_priority(&h.app.db, early.id, "low").await.unwrap();
4754
    // early pushed first, but it is low: later's jobs go first.
4755
    let repo_of = |c: serde_json::Value| c["repo"].as_str().unwrap().to_string();
4756
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/later");
4757
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/later");
4758
    // Expedited, early's run goes before anything else.
4759
    let run = &runs_of(&h.app, "andy", "early").await[0];
4760
    assert!(db::flow::expedite(&h.app.db, run.id, "expedited by andy: an incident").await.unwrap());
4761
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/early");
4762
    let q = db::flow::queue(&h.app.db).await.unwrap();
4763
    assert!(
4764
        q.iter().any(|e| e.name == "early" && e.priority() == "urgent" && e.priority_note.contains("an incident")),
4765
        "{:?}",
4766
        q.iter().map(|e| (&e.name, e.priority())).collect::<Vec<_>>()
4767
    );
4768
    // The site's level is the default for everyone else.
4769
    db::accounts::set_setting(&h.app.db, "flow_priority", "high").await.unwrap();
4770
    let q = db::flow::queue(&h.app.db).await.unwrap();
4771
    assert!(q.iter().filter(|e| e.name == "later").all(|e| e.priority() == "high"));
4772
}
4773
4774
/// Keyless (oxygenhub#241): a running job's token gets a ten-minute
4775
/// certificate for a fresh key from the hub, signed with the hub's key and
4776
/// naming the job's repository and bookmark; a proof made for another
4777
/// credential, an OIDC token for another audience, and a finished job's
4778
/// token get nothing.
4779
#[tokio::test(flavor = "multi_thread")]
4780
async fn a_running_job_gets_a_short_certificate_for_a_fresh_key() {
4781
    use oxy_core::cert::{certify_challenge, SignedCertificate};
4782
    use oxy_core::identity::{Scope, SecretKey};
4783
    let h = hub().await;
4784
    create(&h.app, "andy", "demo").await;
4785
    let work = tempfile::tempdir().unwrap();
4786
    let c = client(&format!("{}/andy/demo", h.base), work.path());
4787
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4788
    write(work.path(), "test.sh", "echo ok\n");
4789
    c.snapshot("test").unwrap();
4790
    c.commit("Add a pipeline", &[]).unwrap();
4791
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4792
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
4793
    let job = claim(&h.app).await.expect("a job");
4794
    let token = job["token"].as_str().unwrap().to_string();
4795
    let job_id = job["job_id"].as_i64().unwrap();
4796
4797
    let sk = SecretKey::generate();
4798
    let id = sk.identity("job", "[email protected]", 1);
4799
    let ask = |credential: &str, signed_for: &str| {
4800
        let proof = sk.sign_challenge(&id.hash(), &certify_challenge(signed_for)).unwrap();
4801
        let body = serde_json::json!({
4802
            "identity": oxy_core::dsse::base64(&id.encode()),
4803
            "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
4804
            "scope": "changes,refs",
4805
        });
4806
        let (credential, app) = (credential.to_string(), h.app.clone());
4807
        async move { call(&app, "POST", "/api/v1/keyless/certify", Some(&credential), Some(body.to_string())).await }
4808
    };
4809
    let (st, body) = ask(&token, &token).await;
4810
    assert_eq!(st, StatusCode::OK, "{body}");
4811
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
4812
    let sc = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
4813
    assert!(sc.verify(&h.app.hub_key.identity).is_ok(), "signed with the hub's key");
4814
    assert_eq!(sc.cert.key_id(), id.hash());
4815
    assert_eq!(sc.cert.subject, "repo:andy/demo:bookmark:main");
4816
    assert_eq!(sc.cert.claim("repository"), Some("andy/demo"));
4817
    assert!(sc.cert.claim("job").is_some() && sc.cert.claim("run") == Some("1"));
4818
    assert_eq!(sc.cert.scope, Scope::CHANGES | Scope::REFS);
4819
    assert!(sc.cert.expires - sc.cert.not_before <= 10 * 60_000 + 30_000, "ten minutes");
4820
4821
    // A proof made for another credential is not this one's.
4822
    let (st, body) = ask(&token, "flowjob_someone_else").await;
4823
    assert_eq!(st, StatusCode::UNAUTHORIZED, "{body}");
4824
    assert!(body.contains("the proof does not show"), "{body}");
4825
4826
    // The hub's own OIDC token, for the keyless audience, works too; for
4827
    // another audience it does not.
4828
    let issuer = h.app.oidc().await.unwrap();
4829
    let now = oxygenhub::db::now_ms();
4830
    let aud = oxygenhub::keyless::audience(h.app.config.base_url());
4831
    let good = issuer.mint_for(h.app.config.base_url(), "agent:claude@andy", &aud, now, 600);
4832
    let (st, body) = ask(&good, &good).await;
4833
    assert_eq!(st, StatusCode::OK, "{body}");
4834
    assert!(body.contains("\"subject\":\"agent:claude@andy\""), "{body}");
4835
    let other = issuer.mint_for(h.app.config.base_url(), "agent:claude@andy", "sts.amazonaws.com", now, 600);
4836
    let (st, _) = ask(&other, &other).await;
4837
    assert_eq!(st, StatusCode::UNAUTHORIZED);
4838
4839
    // A job that has finished asks with a token that no longer counts.
4840
    sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE id = $1").bind(job_id).execute(&h.app.db).await.unwrap();
4841
    let (st, body) = ask(&token, &token).await;
4842
    assert_eq!(st, StatusCode::UNAUTHORIZED, "{body}");
4843
}
4844
4845
/// Keyless step 3 (oxygenhub#241): a job signs its receipt with a fresh
4846
/// key the hub certified for it, and the hub keeps the receipt without
4847
/// binding any runner key; a certificate for another job, or from another
4848
/// issuer, is not this job's.
4849
#[tokio::test(flavor = "multi_thread")]
4850
async fn a_receipt_signed_by_a_certified_key_is_kept() {
4851
    use oxy_core::cert::{certify_challenge, SignedCertificate};
4852
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
4853
    use oxy_core::identity::SecretKey;
4854
    use oxy_core::objects::StateObject;
4855
    use oxy_core::receipt::SignedReceipt;
4856
    let h = hub().await;
4857
    create(&h.app, "andy", "demo").await;
4858
    let url = format!("{}/andy/demo", h.base);
4859
    let work = tempfile::tempdir().unwrap();
4860
    let c = client(&url, work.path());
4861
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4862
    c.snapshot("test").unwrap();
4863
    c.commit("Add a pipeline", &[]).unwrap();
4864
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4865
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
4866
    let heads: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
4867
    let state = hash_object(ObjectType::State, &StateObject::new(heads.clone()).encode());
4868
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
4869
4870
    // Certify a fresh key with a job's token, as a runner does just before
4871
    // it signs the receipt.
4872
    let certify = |token: String| {
4873
        let app = h.app.clone();
4874
        async move {
4875
            let sk = SecretKey::generate();
4876
            let id = sk.identity("test-1 job", "", 1);
4877
            let proof = sk.sign_challenge(&id.hash(), &certify_challenge(&token)).unwrap();
4878
            let body = serde_json::json!({
4879
                "identity": oxy_core::dsse::base64(&id.encode()),
4880
                "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
4881
                "scope": "seal",
4882
            });
4883
            let (st, body) = call(&app, "POST", "/api/v1/keyless/certify", Some(&token), Some(body.to_string())).await;
4884
            assert_eq!(st, StatusCode::OK, "{body}");
4885
            let v: serde_json::Value = serde_json::from_str(&body).unwrap();
4886
            let cert = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
4887
            (sk, id, cert)
4888
        }
4889
    };
4890
    let sign = |r: &serde_json::Value,
4891
                sk: &SecretKey,
4892
                id: &oxy_core::identity::Identity,
4893
                cert: SignedCertificate,
4894
                issuer: oxy_core::identity::Identity| {
4895
        let r: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
4896
        let run_url = format!("{url}/flow/{}", run.number);
4897
        hex::encode(SignedReceipt::sign(r.to_oxy(), repo_id, state, &run_url, id, sk).with_certificate(cert, issuer).encode())
4898
    };
4899
    let hub_id = h.app.hub_key.identity.clone();
4900
4901
    let a = claim(&h.app).await.unwrap();
4902
    let b = claim(&h.app).await.unwrap();
4903
    let ph = a["pipeline_hash"].as_str().unwrap().to_string();
4904
    let (a_name, b_name) = (a["job"]["name"].as_str().unwrap().to_string(), b["job"]["name"].as_str().unwrap().to_string());
4905
    let (a_id, b_id) = (a["job_id"].as_i64().unwrap(), b["job_id"].as_i64().unwrap());
4906
    let (sk_a, id_a, cert_a) = certify(a["token"].as_str().unwrap().to_string()).await;
4907
4908
    // Job b's receipt signed with job a's certified key: another job's.
4909
    let rb = receipt(&b_name, &ph, 0);
4910
    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()) });
4911
    assert_eq!(finish(&h.app, b_id, body).await, StatusCode::NO_CONTENT);
4912
    // Job a's, with its own certificate: kept.
4913
    let ra = receipt(&a_name, &ph, 0);
4914
    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()) });
4915
    assert_eq!(finish(&h.app, a_id, body).await, StatusCode::NO_CONTENT);
4916
4917
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
4918
    let job = |n: &str| jobs.iter().find(|j| j.name == n).unwrap().clone();
4919
    assert_eq!(job(&a_name).receipt_attest.len(), 64, "{}", job(&a_name).receipt_note);
4920
    assert!(job(&a_name).receipt_signer.ends_with("(short-lived key)"), "{}", job(&a_name).receipt_signer);
4921
    assert!(job(&b_name).receipt_attest.is_empty());
4922
    assert!(job(&b_name).receipt_note.contains("another run or job"), "{}", job(&b_name).receipt_note);
4923
    // The kept receipt carries its certificate, and verifies on its own.
4924
    let kept = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().receipts(&heads).unwrap();
4925
    assert_eq!(kept.len(), 1);
4926
    assert!(kept[0].problem.is_none() && kept[0].signed.certificate.is_some());
4927
4928
    // A certificate from another issuer, for the third job: not this hub's.
4929
    let t = claim(&h.app).await.unwrap();
4930
    let t_name = t["job"]["name"].as_str().unwrap().to_string();
4931
    let fake_sk = SecretKey::generate();
4932
    let fake = fake_sk.identity("not the hub", "", 1);
4933
    let (sk_t, id_t, mut cert_t) = certify(t["token"].as_str().unwrap().to_string()).await;
4934
    cert_t.cert.issuer = fake.hash();
4935
    let cert_t = SignedCertificate::sign(cert_t.cert, &fake, &fake_sk);
4936
    let rt = receipt(&t_name, &ph, 0);
4937
    let body =
4938
        serde_json::json!({ "exit_code": 0, "duration_ms": 500, "receipt": rt, "signed_receipt": sign(&rt, &sk_t, &id_t, cert_t, fake) });
4939
    assert_eq!(finish(&h.app, t["job_id"].as_i64().unwrap(), body).await, StatusCode::NO_CONTENT);
4940
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
4941
    let t_job = jobs.iter().find(|j| j.name == t_name).unwrap();
4942
    assert!(t_job.receipt_note.contains("not issued by this hub"), "{}", t_job.receipt_note);
4943
}
4944
4945
/// oxygenhub#241: a release asset whose receipt a short-lived key signed,
4946
/// certified by this hub for the job, is an attested build of a known
4947
/// signer on the release's trust report (it was "not one this hub's
4948
/// runners use" with 0.4.5).
4949
#[tokio::test(flavor = "multi_thread")]
4950
async fn a_release_built_by_a_certified_key_is_attested() {
4951
    use oxy_core::cert::{certify_challenge, SignedCertificate};
4952
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
4953
    use oxy_core::identity::SecretKey;
4954
    use oxy_core::objects::StateObject;
4955
    use oxy_core::receipt::SignedReceipt;
4956
    let h = hub().await;
4957
    create(&h.app, "andy", "demo").await;
4958
    let url = format!("{}/andy/demo", h.base);
4959
    let work = tempfile::tempdir().unwrap();
4960
    let mut c = client(&url, work.path());
4961
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
4962
    write(
4963
        work.path(),
4964
        ".flow/pipeline.kdl",
4965
        &format!(
4966
            "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"
4967
        ),
4968
    );
4969
    c.snapshot("test").unwrap();
4970
    c.commit("Build a tool", &[]).unwrap();
4971
    let heads = c.bookmark_heads().unwrap();
4972
    c.tag_create("v1", &heads, "first").unwrap();
4973
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4974
4975
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
4976
    let a = claim(&h.app).await.unwrap();
4977
    let id = a["job_id"].as_i64().unwrap();
4978
    let token = a["token"].as_str().unwrap().to_string();
4979
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
4980
    let (_, text) = upload(&h.app, id, "tool", &body).await;
4981
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
4982
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
4983
    r["outputs"] = serde_json::json!([blob]);
4984
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
4985
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
4986
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
4987
    // The job's fresh key, certified with its token.
4988
    let sk = SecretKey::generate();
4989
    let key = sk.identity("test-1 job", "", 1);
4990
    let proof = sk.sign_challenge(&key.hash(), &certify_challenge(&token)).unwrap();
4991
    let ask = serde_json::json!({
4992
        "identity": oxy_core::dsse::base64(&key.encode()),
4993
        "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
4994
        "scope": "seal",
4995
    });
4996
    let (st, answer) = call(&h.app, "POST", "/api/v1/keyless/certify", Some(&token), Some(ask.to_string())).await;
4997
    assert_eq!(st, StatusCode::OK, "{answer}");
4998
    let v: serde_json::Value = serde_json::from_str(&answer).unwrap();
4999
    let cert = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
5000
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
5001
    let signed = hex::encode(
5002
        SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/{}", run.number), &key, &sk)
5003
            .with_certificate(cert, h.app.hub_key.identity.clone())
5004
            .encode(),
5005
    );
5006
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
5007
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
5008
5009
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
5010
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
5011
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
5012
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
5013
    assert_eq!(st, StatusCode::OK);
5014
    for want in [
5015
        "tool: signed receipt from run #1 build",
5016
        "a short-lived key this hub certified for repo:andy/demo:bookmark:main",
5017
        "1 of 1 assets built and attested by OxygenFlow",
5018
    ] {
5019
        assert!(page.contains(want), "missing {want:?}");
5020
    }
5021
    assert!(!page.contains("not one this hub"), "not an unknown key");
5022
}
5023
5024
/// The transparency log (oxygenhub#238): a push's reference attestation,
5025
/// seal and policy become entries; the checkpoint is signed by the hub's
5026
/// key; the tiles and entry bundles served rebuild the checkpoint's root;
5027
/// and the `/log` page lists them.
5028
#[tokio::test(flavor = "multi_thread")]
5029
async fn a_push_is_logged_and_the_log_checks_out() {
5030
    use oxy_core::tlog::{self, Checkpoint, Entry, Hash, Note, Tile};
5031
    let h = hub().await;
5032
    create(&h.app, "andy", "demo").await;
5033
    let url = format!("{}/andy/demo", h.base);
5034
    let work = tempfile::tempdir().unwrap();
5035
    let mut c = client(&url, work.path());
5036
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5037
    write(work.path(), "a.txt", "a\n");
5038
    c.commit("a", &[]).unwrap();
5039
    c.policy_init().unwrap();
5040
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5041
    let host = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
5042
    let (attest, _) = host.latest_ref_attest("main").unwrap().unwrap();
5043
5044
    // Sign a checkpoint now rather than wait for the next tick.
5045
    let (_, sk) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
5046
    h.app.tlog.refresh_checkpoint(&h.app.hub_key.identity, &sk).unwrap();
5047
    let (st, note) = call(&h.app, "GET", "/log/checkpoint", None, None).await;
5048
    assert_eq!(st, StatusCode::OK, "{note}");
5049
    let origin = oxygenhub::tlog::origin_of(h.app.config.base_url());
5050
    let cp = Checkpoint::verify(&Note::parse(&note).unwrap(), &origin, &h.app.hub_key.identity).unwrap();
5051
    assert!(cp.size >= 3, "ref, seal and policy: {}", cp.size);
5052
5053
    // The entries, from the bundle beside the partial level-0 tile.
5054
    let bundle_path = Tile { level: 0, n: 0, width: cp.size as u32 }.entries_path();
5055
    let (st, _) = call(&h.app, "GET", &format!("/log/{bundle_path}"), None, None).await;
5056
    assert_eq!(st, StatusCode::OK);
5057
    let res =
5058
        oxygenhub::router(h.app.clone()).oneshot(Request::get(format!("/log/{bundle_path}")).body(Body::empty()).unwrap()).await.unwrap();
5059
    assert_eq!(res.headers()[header::CACHE_CONTROL], "public, max-age=5", "a partial tile changes");
5060
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
5061
    let entries: Vec<Entry> = tlog::decode_bundle(&bytes).unwrap().iter().map(|b| Entry::decode(b).unwrap()).collect();
5062
    let kinds: Vec<&str> = entries.iter().map(|e| e.kind.as_str()).collect();
5063
    assert!(kinds.contains(&"ref") && kinds.contains(&"seal") && kinds.contains(&"policy"), "{kinds:?}");
5064
    let r = entries.iter().find(|e| e.kind == "ref").unwrap();
5065
    assert_eq!(r.object, attest);
5066
    assert_eq!(r.repo, c.id().unwrap());
5067
5068
    // The leaves rebuild the checkpoint's root, and the hash tile served
5069
    // is what they make.
5070
    let mut stored: Vec<Hash> = Vec::new();
5071
    for (n, e) in entries.iter().enumerate() {
5072
        stored.extend(tlog::stored_hashes_for_leaf(n as u64, e.leaf_hash(), &stored).unwrap());
5073
    }
5074
    assert_eq!(tlog::tree_hash(cp.size, &stored).unwrap(), cp.root);
5075
    let t = Tile { level: 0, n: 0, width: cp.size as u32 };
5076
    let res =
5077
        oxygenhub::router(h.app.clone()).oneshot(Request::get(format!("/log/{}", t.path())).body(Body::empty()).unwrap()).await.unwrap();
5078
    assert_eq!(res.status(), StatusCode::OK);
5079
    let data = res.into_body().collect().await.unwrap().to_bytes();
5080
    assert_eq!(data.to_vec(), t.read_data(&stored).unwrap());
5081
    let (st, _) = call(&h.app, "GET", "/log/tile/0/000.p/200", None, None).await;
5082
    assert_eq!(st, StatusCode::NOT_FOUND, "not held yet");
5083
5084
    // Pushing the same again logs nothing new.
5085
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5086
    assert_eq!(h.app.tlog.size(), cp.size);
5087
    let (st, page) = call(&h.app, "GET", "/log", None, None).await;
5088
    assert_eq!(st, StatusCode::OK);
5089
    assert!(page.contains("Transparency log") && page.contains("andy/demo") && page.contains(&origin), "{page}");
5090
}
5091
5092
/// Fetching checks the hub's log (oxygenhub#238, step A3): the checkpoint
5093
/// comes with the refs, each attestation with its entry and inclusion
5094
/// proof; a later checkpoint is proved to extend the one seen before, from
5095
/// the hub's tiles; an attestation not in a checkpoint yet is a note; and a
5096
/// log that does not extend what this user saw fails the fetch.
5097
#[tokio::test(flavor = "multi_thread")]
5098
async fn a_fetch_checks_the_hub_s_log_and_refuses_a_fork() {
5099
    use oxy_core::tlog::{Checkpoint, Note};
5100
    let h = hub().await;
5101
    create(&h.app, "andy", "demo").await;
5102
    let url = format!("{}/andy/demo", h.base);
5103
    let work = tempfile::tempdir().unwrap();
5104
    let mut a = client(&url, &work.path().join("a"));
5105
    a.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5106
    let (_, sk) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
5107
    let hub_id = h.app.hub_key.identity.clone();
5108
    let checkpoint = || h.app.tlog.refresh_checkpoint(&hub_id, &sk).unwrap();
5109
    let mut n = 0;
5110
    let mut push = |a: &Repo| {
5111
        n += 1;
5112
        write(&work.path().join("a"), "a.txt", &format!("{n}\n"));
5113
        a.commit(&format!("change {n}"), &[]).unwrap();
5114
        assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
5115
    };
5116
    push(&a);
5117
    checkpoint();
5118
5119
    let home = work.path().join("home-b");
5120
    let b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(home.clone());
5121
    let report = b.fetch("origin").unwrap();
5122
    assert!(report.log_notes.is_empty(), "{:?}", report.log_notes);
5123
    let pin = std::fs::read_dir(home.join("tlog")).unwrap().next().unwrap().unwrap().path();
5124
    let seen = |p: &std::path::Path| {
5125
        let t = std::fs::read_to_string(p).unwrap();
5126
        Checkpoint::parse(&Note::parse(t.split_once('\n').unwrap().1).unwrap().text).unwrap()
5127
    };
5128
    let first = seen(&pin);
5129
5130
    // A later checkpoint: proved to extend the first from the tiles.
5131
    push(&a);
5132
    checkpoint();
5133
    let report = b.fetch("origin").unwrap();
5134
    assert!(report.log_notes.is_empty(), "{:?}", report.log_notes);
5135
    assert!(seen(&pin).size > first.size);
5136
5137
    // Pushed after the last checkpoint: not provable yet, only a note.
5138
    push(&a);
5139
    let report = b.fetch("origin").unwrap();
5140
    assert!(report.log_notes.iter().any(|n| n.contains("not in its transparency log yet")), "{:?}", report.log_notes);
5141
5142
    // What this user saw replaced by another log of the same size, signed
5143
    // by the hub's own key: the hub's real log does not extend it.
5144
    let size = seen(&pin).size;
5145
    let forged = Checkpoint { origin: oxygenhub::tlog::origin_of(h.app.config.base_url()), size, root: [7; 32], extensions: vec![] };
5146
    let text = std::fs::read_to_string(&pin).unwrap();
5147
    let key = text.split_once('\n').unwrap().0;
5148
    std::fs::write(&pin, format!("{key}\n{}", forged.sign(&hub_id, &sk).unwrap().encode())).unwrap();
5149
    checkpoint();
5150
    let err = b.fetch("origin").unwrap_err().to_string();
5151
    assert!(err.contains("showed two histories") && err.contains("does not extend"), "{err}");
5152
}
5153
5154
/// Keyless step 4c (oxygenhub#241): when a key the hub certified moves a
5155
/// bookmark, the hub signs when it accepted the update and serves that
5156
/// with the bookmark, so a fetch checks the certificate at the hub's time
5157
/// rather than the time the key claimed.
5158
#[tokio::test(flavor = "multi_thread")]
5159
async fn the_hub_countersigns_an_update_by_a_key_it_certified() {
5160
    use oxy_core::attest::AttestBody;
5161
    use oxy_core::cert::{Certificate, SignedCertificate};
5162
    use oxy_core::identity::Scope;
5163
    use oxy_core::repo::IdentityScope;
5164
    let h = hub().await;
5165
    create(&h.app, "andy", "demo").await;
5166
    let url = format!("{}/andy/demo", h.base);
5167
    let work = tempfile::tempdir().unwrap();
5168
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
5169
    a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
5170
    write(&work.path().join("a"), "a.txt", "a\n");
5171
    a.commit("a", &[]).unwrap();
5172
    a.policy_init().unwrap();
5173
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
5174
    let hub_id = h.app.hub_key.identity.clone();
5175
    a.policy_grant_subject("agent:claude@andy", hub_id.clone(), Scope::CHANGES | Scope::REFS, None).unwrap();
5176
    assert!(a.push("origin", false).unwrap().iter().any(|r| r.name == "policy" && r.ok));
5177
5178
    // An agent whose fresh key the hub certified pushes.
5179
    let mut b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(work.path().join("home-b"));
5180
    b.config.set("remote.origin.token", "site").unwrap();
5181
    b.save_config().unwrap();
5182
    let (_, key) = b.create_identity("claude", "[email protected]", IdentityScope::User).unwrap();
5183
    let (_, secret) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
5184
    let now = db::now_ms() as u64;
5185
    let cert = SignedCertificate::sign(
5186
        Certificate {
5187
            key,
5188
            issuer: hub_id.hash(),
5189
            subject: "agent:claude@andy".into(),
5190
            claims: vec![],
5191
            scope: Scope::CHANGES | Scope::REFS,
5192
            not_before: now - 60_000,
5193
            expires: now + 600_000,
5194
            grant: None,
5195
        },
5196
        &hub_id,
5197
        &secret,
5198
    );
5199
    b.store().put_identity(&hub_id).unwrap();
5200
    b.store().put_certificate(&cert).unwrap();
5201
    write(&work.path().join("b"), "b.txt", "agent work\n");
5202
    b.commit("work", &[]).unwrap();
5203
    let r = b.push("origin", false).unwrap();
5204
    assert!(r.iter().all(|x| x.ok), "{r:?}");
5205
5206
    // The hub serves its acceptance of that update, signed by its key.
5207
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
5208
    let main = refs.refs.iter().find(|r| r.name == "main").unwrap();
5209
    let (attest, acc) = (main.attestation.clone().unwrap(), main.accepted.clone().expect("an acceptance"));
5210
    assert!(matches!(acc.attest.body, AttestBody::Accepted { attest: r } if r == attest.attest.hash()));
5211
    assert_eq!(acc.sigs[0].key, hub_id.hash());
5212
    assert!(acc.attest.hlc.wall_ms >= now);
5213
    // An update signed by a long-lived key gets none.
5214
    a.pull("origin").unwrap();
5215
    write(&work.path().join("a"), "a.txt", "again\n");
5216
    a.commit("again", &[]).unwrap();
5217
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
5218
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
5219
    assert!(refs.refs.iter().find(|r| r.name == "main").unwrap().accepted.is_none());
5220
}
5221
5222
/// Keyless step 5 (oxygenhub#241): Andy grants an agent with his own key;
5223
/// the agent, holding only the grant token, commits and pushes in Andy's
5224
/// name with fresh keys the hub certifies under the grant. A grant by a
5225
/// key not linked to the account, or for another account's agent, is
5226
/// refused; a revoked grant certifies no more.
5227
#[tokio::test(flavor = "multi_thread")]
5228
async fn an_agent_with_a_grant_pushes_in_its_owner_s_name() {
5229
    use oxy_core::cert::{Grant, SignedGrant};
5230
    use oxy_core::identity::{Identity, Scope, SecretKey};
5231
    use oxy_core::repo::{IdentityScope, SignatureStatus};
5232
    let h = hub().await;
5233
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
5234
    let (pat, pat_hash) = oxygenhub::auth::new_token();
5235
    db::accounts::create_token(&h.app.db, andy.id, "cli", &pat_hash, "repo:write", "", None).await.unwrap();
5236
    create(&h.app, "andy", "demo").await;
5237
    let url = format!("{}/andy/demo", h.base);
5238
    let work = tempfile::tempdir().unwrap();
5239
    // Andy's checkout, its policy granting the agent's subject.
5240
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
5241
    let (andy_key, andy_id) = a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
5242
    db::accounts::link_identity(&h.app.db, andy.id, &andy_key.to_hex(), "Andy", "[email protected]", &andy_id.encode()).await.unwrap();
5243
    write(&work.path().join("a"), "a.txt", "a\n");
5244
    a.commit("a", &[]).unwrap();
5245
    a.policy_init().unwrap();
5246
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
5247
    let hub_id = h.app.hub_key.identity.clone();
5248
    a.policy_grant_subject("agent:claude@andy", hub_id.clone(), Scope::CHANGES | Scope::REFS, None).unwrap();
5249
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
5250
5251
    // Andy grants the agent, as `oh agent grant claude` does.
5252
    let (_, andy_sk) = a.secret_key().unwrap().unwrap();
5253
    let now = db::now_ms() as u64;
5254
    let grant = |by: &Identity, sk: &SecretKey, subject: &str| {
5255
        SignedGrant::sign(
5256
            Grant {
5257
                grantor: by.hash(),
5258
                subject: subject.into(),
5259
                issuer: hub_id.hash(),
5260
                scope: Scope::CHANGES | Scope::SEAL | Scope::REFS,
5261
                not_before: now - 60_000,
5262
                expires: now + 86_400_000,
5263
            },
5264
            by,
5265
            sk,
5266
        )
5267
    };
5268
    let post = |g: SignedGrant| {
5269
        let (app, pat) = (h.app.clone(), pat.clone());
5270
        let body = serde_json::json!({ "grant": oxy_core::dsse::base64(&g.encode()) }).to_string();
5271
        async move { call(&app, "POST", "/api/v1/agents/grants", Some(&pat), Some(body)).await }
5272
    };
5273
    let stray_sk = SecretKey::generate();
5274
    let stray = stray_sk.identity("stray", "[email protected]", 1);
5275
    let (st, body) = post(grant(&stray, &stray_sk, "agent:claude@andy")).await;
5276
    assert_eq!(st, StatusCode::FORBIDDEN, "a key not linked to the account: {body}");
5277
    let (st, body) = post(grant(&andy_id, &andy_sk, "agent:claude@mallory")).await;
5278
    assert_eq!(st, StatusCode::BAD_REQUEST, "another account's agent: {body}");
5279
    let (st, body) = post(grant(&andy_id, &andy_sk, "agent:claude@andy")).await;
5280
    assert_eq!(st, StatusCode::CREATED, "{body}");
5281
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
5282
    let token = v["token"].as_str().unwrap().to_string();
5283
    assert!(token.starts_with("oxyagent_"));
5284
    let grant_id = v["id"].as_i64().unwrap();
5285
5286
    // The agent: a home holding only the grant token, Andy the author.
5287
    let agent_home = work.path().join("home-claude");
5288
    oxy_core::credentials::Credentials::at(&agent_home).save_grant(&h.base, &token).unwrap();
5289
    let agent = || {
5290
        let n = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
5291
        let dir = work.path().join(format!("claude-{n}"));
5292
        let mut r = Repo::clone(&url, &dir).unwrap().with_home(agent_home.clone());
5293
        // The grant token is its only credential: it pushes with it too.
5294
        r.config.set("remote.origin.token", &token).unwrap();
5295
        r.save_config().unwrap();
5296
        r.set_user_config("author.key", &andy_key.to_hex()).unwrap();
5297
        r.set_user_config("author.signer", "keyless").unwrap();
5298
        (r, dir)
5299
    };
5300
    let (claude, dir) = agent();
5301
    assert!(!agent_home.join("keys").exists(), "no key on disk");
5302
    write(&dir, "work.txt", "agent work\n");
5303
    let change = claude.commit("Agent work", &[]).unwrap();
5304
    let r = claude.push("origin", false).unwrap();
5305
    assert!(r.iter().all(|x| x.ok), "{r:?}");
5306
    let signer = claude.signing_key().expect("a certified key");
5307
    assert_ne!(signer, andy_key);
5308
    assert!(!agent_home.join("keys").exists(), "still no key on disk");
5309
5310
    // The hub holds it in Andy's name, sealed by the certified key, and
5311
    // countersigned when it accepted the update.
5312
    let host = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
5313
    assert_eq!(host.store().get_change_meta(&change).unwrap().author, andy_key);
5314
    assert!(matches!(
5315
        host.authenticate_change(&change).unwrap(),
5316
        SignatureStatus::Valid { key, sealed: true, .. } if key == signer
5317
    ));
5318
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
5319
    assert!(refs.refs.iter().find(|r| r.name == "main").unwrap().accepted.is_some());
5320
    a.pull("origin").unwrap();
5321
    assert!(matches!(a.authenticate_change(&change).unwrap(), SignatureStatus::Valid { .. }));
5322
5323
    // Revoked: the next command gets no certificate.
5324
    let (st, _) = call(&h.app, "DELETE", &format!("/api/v1/agents/grants/{grant_id}"), Some(&pat), None).await;
5325
    assert_eq!(st, StatusCode::NO_CONTENT);
5326
    let (late, dir) = agent();
5327
    write(&dir, "late.txt", "after the revocation\n");
5328
    late.commit("Late", &[]).unwrap();
5329
    let err = late.push("origin", false).unwrap_err().to_string();
5330
    assert!(err.contains("not valid") || err.contains("would not certify"), "{err}");
5331
    // The hub recorded the push as the agent's, for its owner.
5332
    let by_agent: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM pushes WHERE via = 'claude'").fetch_one(&h.app.db).await.unwrap();
5333
    assert!(by_agent >= 1, "recorded as via the agent");
5334
    let (_, body) = call(&h.app, "GET", "/api/v1/agents/grants", Some(&pat), None).await;
5335
    let list: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
5336
    assert!(list[0]["revoked_ms"].is_i64() && list[0].get("token").is_none(), "{body}");
5337
}
5338
5339
/// oxygenhub#267, newest run wins: a proposal's new run supersedes its
5340
/// older runs still live, as a push run does its bookmark's; a repository
5341
/// that keeps running runs has only the queued ones cancelled; manual
5342
/// runs and reruns supersede nothing and nothing supersedes them.
5343
#[tokio::test(flavor = "multi_thread")]
5344
async fn newest_run_wins() {
5345
    use oxy_core::hash::ChangeHash;
5346
    let h = hub().await;
5347
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
5348
    create(&h.app, "andy", "newest").await;
5349
    let url = format!("{}/andy/newest", h.base);
5350
    let work = tempfile::tempdir().unwrap();
5351
    let c = client(&url, work.path());
5352
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5353
    write(work.path(), "test.sh", "echo ok\n");
5354
    c.commit("Start", &[]).unwrap();
5355
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5356
    let pushed = runs_of(&h.app, "andy", "newest").await[0].clone();
5357
    assert_eq!((pushed.number, pushed.trigger.as_str()), (1, "push"));
5358
    let heads: Vec<ChangeHash> = pushed.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
5359
    let start = |row: db::repos::RepoRow, bookmark: &'static str, trigger: &'static str| {
5360
        let (app, state, heads) = (h.app.clone(), pushed.state.clone(), heads.clone());
5361
        async move {
5362
            oxygenhub::flow::start_run_scoped(&app, &row, bookmark, &state, &heads, "andy", trigger, None).await.unwrap().expect("a run")
5363
        }
5364
    };
5365
    let row = db::repos::get(&h.app.db, "andy", "newest").await.unwrap().unwrap();
5366
    let run = |n: i64| {
5367
        let (app, id) = (h.app.clone(), row.id);
5368
        async move { db::flow::run(&app.db, id, n).await.unwrap().unwrap() }
5369
    };
5370
    let superseded_by = |n: i64, by: i64| {
5371
        let app = h.app.clone();
5372
        let run = run(n);
5373
        async move {
5374
            let r = run.await;
5375
            assert_eq!(r.status, "cancelled", "run #{n} is superseded");
5376
            let jobs = db::flow::jobs(&app.db, r.id).await.unwrap();
5377
            let why = format!("superseded by run #{by}");
5378
            assert!(jobs.iter().all(|j| j.status == "cancelled" && j.error == why), "{jobs:?}");
5379
        }
5380
    };
5381
5382
    // A proposal's new run supersedes its older one, not another
5383
    // proposal's, nor the push run of a bookmark.
5384
    assert_eq!(start(row.clone(), "proposal/7", "proposal").await, 2);
5385
    assert_eq!(start(row.clone(), "proposal/7", "proposal").await, 3);
5386
    superseded_by(2, 3).await;
5387
    assert_eq!(start(row.clone(), "proposal/8", "proposal").await, 4);
5388
    assert!(run(3).await.live(), "another proposal's run is not superseded");
5389
    assert!(run(1).await.live(), "a proposal's run leaves push runs alone");
5390
5391
    // Manual runs and reruns supersede nothing, and a push supersedes
5392
    // only push runs.
5393
    assert_eq!(start(row.clone(), "main", "manual").await, 5);
5394
    assert_eq!(start(row.clone(), "main", "rerun:1:push").await, 6);
5395
    assert!(run(1).await.live(), "a manual run or a rerun supersedes nothing");
5396
    assert_eq!(start(row.clone(), "main", "push").await, 7);
5397
    superseded_by(1, 7).await;
5398
    assert!(run(5).await.live() && run(6).await.live(), "a push leaves manual runs and reruns alone");
5399
5400
    // Kept running: a superseded run already running finishes; queued
5401
    // ones are still cancelled.
5402
    db::repos::set_flow_keep_running(&h.app.db, row.id, true).await.unwrap();
5403
    let kept = db::repos::get(&h.app.db, "andy", "newest").await.unwrap().unwrap();
5404
    assert!(kept.flow_keep_running);
5405
    let three = run(3).await;
5406
    sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = $1").bind(three.id).execute(&h.app.db).await.unwrap();
5407
    sqlx::query("UPDATE flow_jobs SET status = 'running' WHERE run_id = $1 AND name = 'build'")
5408
        .bind(three.id)
5409
        .execute(&h.app.db)
5410
        .await
5411
        .unwrap();
5412
    assert_eq!(start(kept.clone(), "proposal/7", "proposal").await, 8);
5413
    assert_eq!(start(kept.clone(), "proposal/7", "proposal").await, 9);
5414
    assert_eq!(run(3).await.status, "running", "a running run is kept");
5415
    superseded_by(8, 9).await;
5416
    // The default again: running runs are cancelled too.
5417
    db::repos::set_flow_keep_running(&h.app.db, row.id, false).await.unwrap();
5418
    let row = db::repos::get(&h.app.db, "andy", "newest").await.unwrap().unwrap();
5419
    assert_eq!(start(row.clone(), "proposal/7", "proposal").await, 10);
5420
    superseded_by(3, 10).await;
5421
    superseded_by(9, 10).await;
5422
}