OXYGENHUB
# b1860d6090ec oxygenhub / crates / hub / tests / flow.rs
400.0 KiB · Rust · last changed Approval gates and expedite for clients: a run's jobs over the API say their approval, and POST …/flow/runs/N/expedite makes a run urgent as the run page does, sharing flow::expedite (refs oxygenhub-android#5) 8 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
    // So does the repository's Build artifacts page (#254), and the bar's
906
    // Artifacts menu leads there.
907
    let (_, list) = call(&h.app, "GET", "/andy/demo/artifacts", None, None).await;
908
    assert!(list.contains(&link) && list.contains(&format!("#{}</a>", run.number)), "{list}");
909
    assert!(list.contains("<summary class=\"on\">Artifacts</summary>") && list.contains("href=\"/andy/demo/images\""), "{list}");
910
    let (st, got) = get_bytes(&h.app, &link).await;
911
    assert_eq!((st, got == body), (StatusCode::OK, true));
912
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/flow/{}/artifacts/build/none", run.number)).await.0, StatusCode::NOT_FOUND);
913
    // Provenance (#239): only for a job whose signed receipt the hub kept;
914
    // then an in-toto statement in a DSSE envelope the hub's key verifies.
915
    let prov = format!("{link}/provenance");
916
    assert_eq!(get_bytes(&h.app, &prov).await.0, StatusCode::BAD_REQUEST, "no kept receipt, no provenance");
917
    sqlx::query("UPDATE flow_jobs SET receipt_attest = 'a1b2', receipt_signer = 'test-1 runner' WHERE id = $1")
918
        .bind(id)
919
        .execute(&h.app.db)
920
        .await
921
        .unwrap();
922
    let (st, env) = get_bytes(&h.app, &prov).await;
923
    assert_eq!(st, StatusCode::OK);
924
    let env: serde_json::Value = serde_json::from_slice(&env).unwrap();
925
    assert_eq!(env["payloadType"], "application/vnd.in-toto+json");
926
    let unb64 = |t: &str| -> Vec<u8> {
927
        let val = |c: u8| match c {
928
            b'A'..=b'Z' => c - b'A',
929
            b'a'..=b'z' => c - b'a' + 26,
930
            b'0'..=b'9' => c - b'0' + 52,
931
            b'+' => 62,
932
            _ => 63,
933
        };
934
        let clean: Vec<u8> = t.bytes().filter(|c| *c != b'=').collect();
935
        let mut out = Vec::new();
936
        for chunk in clean.chunks(4) {
937
            let n = chunk.iter().enumerate().fold(0u32, |acc, (i, c)| acc | (val(*c) as u32) << (18 - 6 * i));
938
            for i in 0..chunk.len() - 1 {
939
                out.push((n >> (16 - 8 * i)) as u8);
940
            }
941
        }
942
        out
943
    };
944
    let payload = unb64(env["payload"].as_str().unwrap());
945
    let sig = unb64(env["signatures"][0]["sig"].as_str().unwrap());
946
    let signed = oxygenhub::provenance::pae("application/vnd.in-toto+json", &payload);
947
    ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, h.app.hub_key.identity.ed25519_pk)
948
        .verify(&signed, &sig)
949
        .expect("the hub's key signed the envelope");
950
    let statement: serde_json::Value = serde_json::from_slice(&payload).unwrap();
951
    use sha2::Digest;
952
    assert_eq!(statement["subject"][0]["digest"]["sha256"], hex::encode(sha2::Sha256::digest(&body)));
953
    assert_eq!(statement["predicateType"], "https://slsa.dev/provenance/v1");
954
    assert_eq!(statement["predicate"]["buildDefinition"]["externalParameters"]["job"], "build");
955
    assert_eq!(statement["predicate"]["runDetails"]["byproducts"][0]["digest"]["oxygen-attestation"], "a1b2");
956
    let (_, pem) = get_bytes(&h.app, "/.well-known/oxyhub-signing.pem").await;
957
    let pem = String::from_utf8(pem).unwrap();
958
    let der = unb64(pem.lines().filter(|l| !l.starts_with("-----")).collect::<String>().as_str());
959
    assert_eq!(&der[der.len() - 32..], &h.app.hub_key.identity.ed25519_pk[..], "the PEM holds the hub's key");
960
    sqlx::query("UPDATE flow_jobs SET receipt_attest = '', receipt_signer = '' WHERE id = $1").bind(id).execute(&h.app.db).await.unwrap();
961
962
    // The nightly gc keeps it (#126): only the database names it, so with
963
    // no grace period a gc that did not root it would prune it at once.
964
    {
965
        let name = RepoName::parse("andy/demo").unwrap();
966
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
967
        hosted.config.set("core.gc-grace", "0").unwrap();
968
        hosted.save_config().unwrap();
969
    }
970
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
971
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
972
    let (st, got) = get_bytes(&h.app, &link).await;
973
    assert_eq!((st, got == body), (StatusCode::OK, true), "the artifact survives gc");
974
975
    // A writer attaches the artifact to a release from the run page; the
976
    // release then names the run and job that built it, as does the API.
977
    let form = |f: String| {
978
        Request::post("/register").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(Body::from(f)).unwrap()
979
    };
980
    let res = oxygenhub::router(h.app.clone())
981
        .oneshot(form("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup".into()))
982
        .await
983
        .unwrap();
984
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
985
    let with_cookie = |method: &str, path: &str, body: Option<String>| {
986
        let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie.clone());
987
        if body.is_some() {
988
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
989
        }
990
        req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()
991
    };
992
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
993
    db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
994
    let res = oxygenhub::router(h.app.clone()).oneshot(with_cookie("GET", &format!("/andy/demo/flow/{}", run.number), None)).await.unwrap();
995
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
996
    let attach = format!("/andy/demo/flow/{}/artifacts/build/tool/attach", run.number);
997
    assert!(page.contains(&attach), "a writer is offered the release");
998
    let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
999
    let csrf = page[i..].split('"').next().unwrap().to_string();
1000
    let release_id = db::releases::list(&h.app.db, row.id).await.unwrap()[0].id;
1001
    let res = oxygenhub::router(h.app.clone())
1002
        .oneshot(with_cookie("POST", &attach, Some(format!("_csrf={csrf}&release={release_id}"))))
1003
        .await
1004
        .unwrap();
1005
    assert_eq!(res.status(), StatusCode::SEE_OTHER);
1006
    let (_, page) = call(&h.app, "GET", "/andy/demo/releases/tag/v1", None, None).await;
1007
    assert!(
1008
        page.contains(">tool</a>") && page.contains(&format!("built by <a href=\"/andy/demo/flow/{0}\">run #{0}</a> build", run.number)),
1009
        "{page}"
1010
    );
1011
    let (_, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases", None, None).await;
1012
    let api: serde_json::Value = serde_json::from_str(&api).unwrap();
1013
    let asset = &api[0]["assets"][0];
1014
    assert_eq!(
1015
        (asset["name"].as_str(), asset["built_by"]["run"].as_i64(), asset["built_by"]["job"].as_str()),
1016
        (Some("tool"), Some(run.number), Some("build"))
1017
    );
1018
    assert!(asset["built_by"]["receipt"].is_null(), "that receipt was not signed");
1019
}
1020
1021
/// oxygenflow#37: a failing job keeps a `when "always"` artifact; its
1022
/// receipt names none, and the run page says the file is outside it.
1023
async fn upload_report_file(app: &Shared, job: i64, name: &str, path: &str, bytes: &[u8]) -> (StatusCode, String) {
1024
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/reports/{name}/files"))
1025
        .header(header::AUTHORIZATION, "Bearer runner-secret")
1026
        .header(header::CONTENT_TYPE, "application/octet-stream")
1027
        .header("X-Flow-Report-Path", path)
1028
        .body(Body::from(bytes.to_vec()))
1029
        .unwrap();
1030
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
1031
    let status = res.status();
1032
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1033
}
1034
1035
/// #127: a report's files arrive one by one, then its manifest as the
1036
/// report's artifact; the hub indexes the declaration, metrics and files,
1037
/// and gc keeps every file.
1038
#[tokio::test(flavor = "multi_thread")]
1039
async fn reports_are_kept_file_by_file_and_indexed() {
1040
    let h = hub().await;
1041
    create(&h.app, "andy", "demo").await;
1042
    let url = format!("{}/andy/demo", h.base);
1043
    let work = tempfile::tempdir().unwrap();
1044
    let c = client(&url, work.path());
1045
    write(
1046
        work.path(),
1047
        ".flow/pipeline.kdl",
1048
        &format!(
1049
            "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"
1050
        ),
1051
    );
1052
    c.snapshot("test").unwrap();
1053
    c.commit("Measure frames", &[]).unwrap();
1054
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1055
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1056
    let a = claim(&h.app).await.unwrap();
1057
    let id = a["job_id"].as_i64().unwrap();
1058
1059
    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";
1060
    let page = b"<p>frames</p>".to_vec();
1061
    let data: Vec<u8> = (0..100_000u32).map(|i| (i % 241) as u8).collect();
1062
    let (page_bytes, data_bytes) = (page.clone(), data.clone());
1063
    let files: [(&str, &[u8]); 3] = [("data/frames.csv", &data), ("index.html", &page), ("report.toml", toml)];
1064
1065
    assert_eq!(upload_report_file(&h.app, id, "tool", "report.toml", toml).await.0, StatusCode::BAD_REQUEST, "not a report");
1066
    assert_eq!(upload_report_file(&h.app, id, "frame-timing", "../x", toml).await.0, StatusCode::BAD_REQUEST, "not a clean path");
1067
    let mut listed = vec![];
1068
    for (path, bytes) in files {
1069
        let (st, text) = upload_report_file(&h.app, id, "frame-timing", path, bytes).await;
1070
        assert_eq!(st, StatusCode::OK, "{text}");
1071
        let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1072
        assert_eq!(blob, oxy_core::repo::Repo::blob_ref(bytes).to_hex());
1073
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1074
    }
1075
    let mut missing = listed.clone();
1076
    missing.push(serde_json::json!({ "path": "assets/x.js", "blob": "ab".repeat(32), "size": 1 }));
1077
    let (st, text) =
1078
        upload(&h.app, id, "frame-timing", &serde_json::to_vec(&serde_json::json!({ "version": 1, "files": missing })).unwrap()).await;
1079
    assert_eq!(st, StatusCode::BAD_REQUEST, "a file never uploaded: {text}");
1080
    assert!(text.contains("assets/x.js"), "{text}");
1081
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed })).unwrap();
1082
    let (st, text) = upload(&h.app, id, "frame-timing", &manifest).await;
1083
    assert_eq!(st, StatusCode::OK, "{text}");
1084
1085
    let (kind, title, summary, files_n, bytes): (String, String, String, i64, i64) =
1086
        sqlx::query_as("SELECT kind, title, summary, files, bytes FROM reports WHERE job_id = $1 AND name = 'frame-timing'")
1087
            .bind(id)
1088
            .fetch_one(&h.app.db)
1089
            .await
1090
            .unwrap();
1091
    assert_eq!((kind.as_str(), title.as_str(), summary.as_str()), ("performance", "Frame timing", "Median 16.4 ms"));
1092
    assert_eq!((files_n, bytes), (3, (data.len() + page.len() + toml.len()) as i64));
1093
    let rid: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE job_id = $1").bind(id).fetch_one(&h.app.db).await.unwrap();
1094
    let m = oxygenhub::reports::metrics(&h.app.db, rid).await.unwrap();
1095
    assert_eq!((m[0].key.as_str(), m[0].value, m[0].fail_above), ("median_ms", 16.4, Some(20.0)));
1096
    let log = db::flow::log(&h.app.db, id, 0, 1000).await.unwrap();
1097
    assert!(log.iter().any(|r| r.text.contains("report frame-timing: performance \"Frame timing\", 1 metric")), "{log:?}");
1098
1099
    // The threshold is a check on the run's state, passing at 16.4.
1100
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
1101
    let c = checks.iter().find(|c| c.name == "report/frame-timing/median_ms").expect("a check per threshold");
1102
    assert_eq!(c.status, "passed", "{c:?}");
1103
    assert!(c.summary.contains("16.4 ms") && c.url.contains("/reports/frame-timing?id="), "{c:?}");
1104
1105
    // The Reports tab, the report's page, and its own page in a sandbox.
1106
    let (_, page) = call(&h.app, "GET", "/andy/demo", None, None).await;
1107
    assert!(page.contains(">Reports</a>"), "the tab");
1108
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports", None, None).await;
1109
    assert!(st == StatusCode::OK && page.contains("Frame timing") && page.contains("median_ms"), "{st}");
1110
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1111
    assert!(st == StatusCode::OK && page.contains("fails above 20") && page.contains("sandbox=\"allow-scripts\""), "{st}");
1112
    let src = page.split("class=\"rep-frame\" src=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
1113
    assert!(src.ends_with("/index.html"), "{src}");
1114
    let res = oxygenhub::router(h.app.clone()).oneshot(Request::get(&src).body(Body::empty()).unwrap()).await.unwrap();
1115
    assert_eq!(res.status(), StatusCode::OK);
1116
    let csp = res.headers()[header::CONTENT_SECURITY_POLICY].to_str().unwrap().to_string();
1117
    assert!(csp.starts_with("sandbox allow-scripts;") && csp.contains("default-src 'none'"), "{csp}");
1118
    // The site's own policy and frame refusal stay off it: report frames are framed (#222).
1119
    assert!(
1120
        res.headers().get(header::X_FRAME_OPTIONS).is_none() && res.headers().get(header::CONTENT_SECURITY_POLICY_REPORT_ONLY).is_none()
1121
    );
1122
    assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
1123
    assert_eq!(res.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*");
1124
    // The page as kept, with the frame script that sizes the frame added.
1125
    let served = res.into_body().collect().await.unwrap().to_bytes().to_vec();
1126
    assert!(served.starts_with(&page_bytes), "the report's page");
1127
    assert!(String::from_utf8_lossy(&served).contains("/static/report-frame.js"), "with the frame script");
1128
    let (st, _) = get_bytes(&h.app, "/static/report.css").await;
1129
    assert_eq!(st, StatusCode::OK, "the stylesheet a report may link");
1130
    let data = src.replace("/index.html", "/data/frames.csv");
1131
    assert_eq!(get_bytes(&h.app, &data).await, (StatusCode::OK, data_bytes.clone()));
1132
    // A link with another report's MAC, or a file it lacks, finds nothing.
1133
    // A second run of the report: the timeline has two stops, and the
1134
    // first can be compared with it (RP4).
1135
    let first: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE name = 'frame-timing'").fetch_one(&h.app.db).await.unwrap();
1136
    let second: i64 = sqlx::query_scalar(
1137
        "INSERT INTO reports (repo_id, name, kind, title, summary, context, run_id, job_id, run_number, job, bookmark, state, manifest, files, bytes, created_ms) \
1138
         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",
1139
    )
1140
    .bind(first)
1141
    .fetch_one(&h.app.db)
1142
    .await
1143
    .unwrap();
1144
    sqlx::query(
1145
        "INSERT INTO report_metrics (report_id, key, value, unit, better, fail_above) VALUES ($1, 'median_ms', 18.0, 'ms', 'lower', 20)",
1146
    )
1147
    .bind(second)
1148
    .execute(&h.app.db)
1149
    .await
1150
    .unwrap();
1151
    let (_, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1152
    assert_eq!(page.matches("data-tl-stop").count(), 2, "a stop per run");
1153
    assert!(page.contains("Median 18.0 ms"), "the newest run is shown");
1154
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/frame-timing?id={first}&compare={second}&play=3"), None, None).await;
1155
    assert!(page.contains("This run against run #2") && page.contains("-1.6"), "every metric against the other run");
1156
    let stop = page.split("data-tl-stop").next().unwrap_or("").rsplit("href=").next().unwrap_or("").to_string();
1157
    assert!(page.contains("data-play=\"3\""), "playing");
1158
    assert!(stop.contains("play") && stop.contains('3'), "playing carries on from stop to stop: {stop}");
1159
    assert!(page.contains("data-report-runs="), "the frame interface knows the runs");
1160
    let forged = src.replacen("/files/", "/files/9", 1);
1161
    assert_eq!(get_bytes(&h.app, &forged).await.0, StatusCode::NOT_FOUND);
1162
    assert_eq!(get_bytes(&h.app, &src.replace("/index.html", "/secret.txt")).await.0, StatusCode::NOT_FOUND);
1163
    let _ = run;
1164
1165
    // gc keeps every file: only the database names them.
1166
    {
1167
        let name = RepoName::parse("andy/demo").unwrap();
1168
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
1169
        hosted.config.set("core.gc-grace", "0").unwrap();
1170
        hosted.save_config().unwrap();
1171
    }
1172
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
1173
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
1174
    let hosted = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
1175
    for (path, bytes) in files {
1176
        assert_eq!(hosted.read_blob(&oxy_core::repo::Repo::blob_ref(bytes)).unwrap(), bytes, "{path} survives gc");
1177
    }
1178
}
1179
1180
#[tokio::test(flavor = "multi_thread")]
1181
async fn a_failing_job_keeps_an_artifact_outside_its_receipt() {
1182
    let h = hub().await;
1183
    create(&h.app, "andy", "demo").await;
1184
    let url = format!("{}/andy/demo", h.base);
1185
    let work = tempfile::tempdir().unwrap();
1186
    let c = client(&url, work.path());
1187
    write(
1188
        work.path(),
1189
        ".flow/pipeline.kdl",
1190
        &format!(
1191
            "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"
1192
        ),
1193
    );
1194
    c.snapshot("test").unwrap();
1195
    c.commit("Test", &[]).unwrap();
1196
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1197
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1198
    let a = claim(&h.app).await.unwrap();
1199
    assert_eq!(a["job"]["outputs"][0]["always"], true, "the runner is told to keep it from a failing job");
1200
    let id = a["job_id"].as_i64().unwrap();
1201
    // A JUnit report (#114): parsed on upload, counted, failures listed.
1202
    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>"#;
1203
    let (st, text) = upload(&h.app, id, "junit", xml).await;
1204
    assert_eq!(st, StatusCode::OK, "{text}");
1205
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1206
    let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), 1);
1207
    r["outputs"] = serde_json::json!([blob]);
1208
    assert_eq!(
1209
        finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r.clone() })).await,
1210
        StatusCode::BAD_REQUEST,
1211
        "a failing receipt names no outputs"
1212
    );
1213
    r["outputs"] = serde_json::json!([]);
1214
    // oxygenflow#35: where its time went, as the runner reports it.
1215
    let phases = serde_json::json!({ "image": 9000, "prepare": 1200, "run": 3400, "finish": 500 });
1216
    assert_eq!(
1217
        finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r, "phases": phases })).await,
1218
        StatusCode::NO_CONTENT
1219
    );
1220
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
1221
    let at = page.find("Where its time went: ").expect("the job's phases");
1222
    let line = &page[at..at + 120];
1223
    let order: Vec<usize> = ["image", "prepare", "run", "finish"].iter().map(|p| line.find(p).expect(p)).collect();
1224
    assert!(order.windows(2).all(|w| w[0] < w[1]), "in the order they happened: {line}");
1225
    assert!(page.contains(&format!("/andy/demo/flow/{}/artifacts/test/junit", run.number)), "listed");
1226
    assert!(page.contains("not in its receipt"), "marked");
1227
    assert!(page.contains("2 tests: 1 failed"), "counts beside the job");
1228
    assert!(page.contains("tests.test_io::test_write") && page.contains("disk full") && page.contains("OSError"), "the failure");
1229
    assert!(page.contains("tests: 2 tests: 1 failed in 2.0 s"), "said in the job's log");
1230
}
1231
1232
/// A release's trust report (hub spec §9.1): a signed tag, an asset built
1233
/// by a job with a signed receipt from the tagged state, and one uploaded
1234
/// by hand; the page, its JSON export and the API.
1235
#[tokio::test(flavor = "multi_thread")]
1236
async fn a_release_is_audited_from_authors_to_receipts() {
1237
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
1238
    use oxy_core::identity::SecretKey;
1239
    use oxy_core::objects::StateObject;
1240
    use oxy_core::receipt::SignedReceipt;
1241
    let h = hub().await;
1242
    create(&h.app, "andy", "demo").await;
1243
    let url = format!("{}/andy/demo", h.base);
1244
    let work = tempfile::tempdir().unwrap();
1245
    let mut c = client(&url, work.path());
1246
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
1247
    write(
1248
        work.path(),
1249
        ".flow/pipeline.kdl",
1250
        &format!(
1251
            "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"
1252
        ),
1253
    );
1254
    c.snapshot("test").unwrap();
1255
    c.commit("Build a tool", &[]).unwrap();
1256
    let heads = c.bookmark_heads().unwrap();
1257
    c.tag_create("v1", &heads, "first").unwrap();
1258
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1259
1260
    // The runner builds, uploads the artifact and signs its receipt.
1261
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1262
    let a = claim(&h.app).await.unwrap();
1263
    let id = a["job_id"].as_i64().unwrap();
1264
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
1265
    let (_, text) = upload(&h.app, id, "tool", &body).await;
1266
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1267
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
1268
    r["outputs"] = serde_json::json!([blob]);
1269
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
1270
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
1271
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
1272
    let sk = SecretKey::generate();
1273
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
1274
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
1275
    let signed = hex::encode(SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/1"), &runner, &sk).encode());
1276
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
1277
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
1278
1279
    // A release with the built asset and a file uploaded by hand.
1280
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1281
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
1282
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
1283
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "notes.txt", "", b"by hand\n").await.unwrap();
1284
1285
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
1286
    assert_eq!(st, StatusCode::OK);
1287
    for want in [
1288
        "Tag v1 is signed",
1289
        "The one change in the release is authenticated",
1290
        "tool: signed receipt from run #1 build",
1291
        "a runner key of this hub",
1292
        "tool: built from the tagged state",
1293
        "tool: pinned environment",
1294
        "notes.txt: no build found",
1295
        "<svg class=\"trust-graph\"",
1296
        // oxygenhub#79: a summary of badges, badges in the graph, and the
1297
        // graph drawn at its own size rather than stretched to the page.
1298
        "Tag signed by",
1299
        "1 of 1 changes signed or sealed",
1300
        "1 of 2 assets built and attested by OxygenFlow",
1301
        "attested build",
1302
        "uploaded by hand",
1303
        "receipt verified",
1304
        "class=\"shackle\"",
1305
        "<title>notes.txt:",
1306
    ] {
1307
        assert!(page.contains(want), "missing {want:?}");
1308
    }
1309
    let svg = &page[page.find("<svg class=\"trust-graph\"").unwrap()..];
1310
    assert!(svg[..200].contains(" width=\"") && svg[..200].contains(" height=\""), "the graph has its own size: {}", &svg[..200]);
1311
    let (_, releases) = call(&h.app, "GET", "/andy/demo/releases", None, None).await;
1312
    assert!(releases.contains("/andy/demo/releases/trust/v1"), "the release links its audit");
1313
1314
    // The export carries the signed receipt, which checks on its own.
1315
    let (st, json) = call(&h.app, "GET", "/andy/demo/releases/trust/v1?format=json", None, None).await;
1316
    assert_eq!(st, StatusCode::OK);
1317
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
1318
    assert_eq!((t["tag"].as_str(), t["tag_signature"].as_str(), t["changes"].as_i64()), (Some("v1"), Some("valid"), Some(1)));
1319
    assert_eq!(t["authors"][0]["who"]["name"], "Andy");
1320
    let tool = t["assets"].as_array().unwrap().iter().find(|a| a["name"] == "tool").unwrap();
1321
    let hex_receipt = tool["build"]["signed_receipt"].as_str().unwrap();
1322
    let sr = SignedReceipt::decode(&hex::decode(hex_receipt).unwrap()).unwrap();
1323
    sr.verify().unwrap();
1324
    assert_eq!(sr.receipt.outputs[0].to_hex(), blob);
1325
    let audit = t["audit"].as_array().unwrap();
1326
    assert!(audit.iter().any(|c| c["verdict"] == "warn" && c["title"].as_str().unwrap().starts_with("notes.txt")));
1327
    assert!(!audit.iter().any(|c| c["verdict"] == "fail"), "{audit:?}");
1328
    // The API gives the same report; an unknown release is a 404.
1329
    let (st, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v1", None, None).await;
1330
    assert_eq!(st, StatusCode::OK);
1331
    assert_eq!(serde_json::from_str::<serde_json::Value>(&api).unwrap()["assets"].as_array().unwrap().len(), 2);
1332
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1333
    assert_eq!(call(&h.app, "GET", "/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1334
}
1335
1336
/// Runners (hub spec §13.2): an administrator makes a registration token,
1337
/// a runner registers with it (binding its key), claims, shows on Admin →
1338
/// Runners with its history, and is drained, disabled and removed.
1339
#[tokio::test(flavor = "multi_thread")]
1340
async fn runners_register_show_their_history_and_are_drained_and_removed() {
1341
    use oxy_core::identity::SecretKey;
1342
    let h = hub().await;
1343
    create(&h.app, "andy", "demo").await;
1344
    // A signed-in site administrator.
1345
    let res = oxygenhub::router(h.app.clone())
1346
        .oneshot(
1347
            Request::post("/register")
1348
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1349
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
1350
                .unwrap(),
1351
        )
1352
        .await
1353
        .unwrap();
1354
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1355
    let admin = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
1356
    db::accounts::set_admin(&h.app.db, admin.id, true).await.unwrap();
1357
    let web = |method: &'static str, path: String, body: Option<String>| {
1358
        let (app, cookie) = (h.app.clone(), cookie.clone());
1359
        async move {
1360
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1361
            if body.is_some() {
1362
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1363
            }
1364
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1365
            let st = res.status();
1366
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1367
        }
1368
    };
1369
    let csrf_of = |page: &str| {
1370
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1371
        page[i..].split('"').next().unwrap().to_string()
1372
    };
1373
    let (st, page) = web("GET", "/admin/runners".into(), None).await;
1374
    assert_eq!(st, StatusCode::OK);
1375
    assert!(page.contains("No runners yet"));
1376
    assert_eq!(call(&h.app, "GET", "/admin/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1377
1378
    // A one-time registration token, shown once with the command.
1379
    let (_, page) = web("POST", "/admin/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1380
    let i = page.find("--token ").unwrap() + "--token ".len();
1381
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1382
    assert!(token.starts_with("flowreg_"), "{token}");
1383
1384
    // The runner registers, binding its key; the token then is spent.
1385
    let sk = SecretKey::generate();
1386
    let identity = sk.identity("plex (OxygenFlow runner)", "", 1);
1387
    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 });
1388
    let reg = serde_json::json!({ "token": token, "name": "plex", "identity": hex::encode(identity.encode()), "info": info });
1389
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1390
    assert_eq!(st, StatusCode::OK, "{body}");
1391
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1392
    assert!(credential.starts_with("flowrunner_"));
1393
    assert_eq!(
1394
        call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0,
1395
        StatusCode::FORBIDDEN,
1396
        "used once"
1397
    );
1398
1399
    // It claims with its credential; the hub.toml runner shows too.
1400
    let claim_as = |who: String| {
1401
        let app = h.app.clone();
1402
        let info = info.clone();
1403
        async move {
1404
            let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
1405
            call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await
1406
        }
1407
    };
1408
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "nothing queued");
1409
    assert_eq!(claim(&h.app).await, None);
1410
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1411
    assert!(
1412
        page.contains(">plex</strong>") && page.contains("st-online") && page.contains("x86_64 · linux") && page.contains("big-disk"),
1413
        "{page}"
1414
    );
1415
    assert!(page.contains(">test-1</strong>") && page.contains("hub.toml"), "the configured runner, by its claimed name");
1416
    let plex = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1417
    assert_eq!(plex.key, identity.hash().to_hex(), "bound at registration");
1418
1419
    // A run: plex takes a job, and its history shows it.
1420
    let url = format!("{}/andy/demo", h.base);
1421
    let work = tempfile::tempdir().unwrap();
1422
    let c = client(&url, work.path());
1423
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1424
    c.snapshot("test").unwrap();
1425
    c.commit("Add a pipeline", &[]).unwrap();
1426
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1427
    runs_of(&h.app, "andy", "demo").await;
1428
    let (st, body) = claim_as(credential.clone()).await;
1429
    assert_eq!(st, StatusCode::OK, "{body}");
1430
    let job: serde_json::Value = serde_json::from_str(&body).unwrap();
1431
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1432
    assert!(
1433
        page.contains("andy/demo") && page.contains(job["job"]["name"].as_str().unwrap()) && page.contains("Running now</dt><dd>1 job"),
1434
        "{page}"
1435
    );
1436
    // The queue on Admin → Runners and through the API (#41, part 4).
1437
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1438
    assert!(page.contains("id=\"queue\"") && page.contains(">plex</a></td>"), "{page}");
1439
    // Connectivity and what it is doing, kept apart (#243); its status
1440
    // opens the queue filtered to it, and the filters keep and drop jobs.
1441
    assert!(page.contains("running 1 of ") && page.contains("/admin/runners?runner=plex#queue"), "{page}");
1442
    let (_, only) = web("GET", "/admin/runners?runner=plex".into(), None).await;
1443
    assert!(only.contains(">plex</a></td>") && only.contains(" of ") && only.contains(">all</a>"), "{only}");
1444
    let (_, none) = web("GET", "/admin/runners?runner=nobody&status=running".into(), None).await;
1445
    assert!(none.contains("Nothing matches."), "{none}");
1446
    // A busy runner claims nothing; its heartbeat keeps it online.
1447
    sqlx::query("UPDATE flow_runners SET last_seen_ms = 0 WHERE id = $1").bind(plex.id).execute(&h.app.db).await.unwrap();
1448
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1449
    assert!(page.contains("st-offline"), "quiet for long: offline");
1450
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/heartbeat", Some(&credential), None).await.0, StatusCode::NO_CONTENT);
1451
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/heartbeat", Some("flowrunner_nope"), None).await.0, StatusCode::UNAUTHORIZED);
1452
    let plex_now = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1453
    assert_eq!(plex_now.connectivity(), "online");
1454
    let (_, tokens) = web("GET", "/settings/tokens".into(), None).await;
1455
    let (_, made) = web("POST", "/settings/tokens".into(), Some(format!("_csrf={}&name=admin&scopes=user%3Aread", csrf_of(&tokens)))).await;
1456
    let i = made.find("oxyhub_").unwrap();
1457
    let admin_token: String = made[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
1458
    let (st, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1459
    assert_eq!(st, StatusCode::OK, "{body}");
1460
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1461
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1462
    assert_eq!((plex_row["running"].as_i64(), plex_row["arch"].as_str()), (Some(1), Some("x86_64")));
1463
    // A runner's own labels and time limit from its page (#98).
1464
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1465
    let (st, _) = web(
1466
        "POST",
1467
        format!("/admin/runners/{}/limits", plex.id),
1468
        Some(format!("_csrf={}&labels=gpu%2C+plex&timeout_minutes=5", csrf_of(&page))),
1469
    )
1470
    .await;
1471
    assert_eq!(st, StatusCode::SEE_OTHER);
1472
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1473
    assert!(page.contains(">gpu<") && page.contains("5 min for its jobs"), "{page}");
1474
    let (_, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1475
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1476
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1477
    assert!(plex_row["labels"].as_array().unwrap().iter().any(|l| l == "gpu"), "{plex_row}");
1478
    let (st, _) = web(
1479
        "POST",
1480
        format!("/admin/runners/{}/limits", plex.id),
1481
        Some(format!("_csrf={}&labels=bad%20label%21&timeout_minutes=", csrf_of(&page))),
1482
    )
1483
    .await;
1484
    assert_eq!(st, StatusCode::BAD_REQUEST, "a label with a space or punctuation is refused");
1485
    let (_, body) = call(&h.app, "GET", "/api/v1/runners/queue", Some(&admin_token), None).await;
1486
    let queue: serde_json::Value = serde_json::from_str(&body).unwrap();
1487
    assert!(queue.as_array().unwrap().iter().any(|q| q["status"] == "running" && q["runner"] == "plex"), "{queue}");
1488
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/runners/{}/jobs", plex.id), Some(&admin_token), None).await;
1489
    let jobs: serde_json::Value = serde_json::from_str(&body).unwrap();
1490
    assert_eq!(jobs[0]["repo"], "andy/demo", "{jobs}");
1491
    assert_eq!(call(&h.app, "GET", "/api/v1/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1492
1493
    // Draining: no new work; removing while busy is refused.
1494
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1495
    let csrf = csrf_of(&page);
1496
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=draining"))).await;
1497
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "a draining runner takes nothing");
1498
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1499
    assert!(page.contains("is running jobs: drain it first"), "{page}");
1500
    // Its job finishes; disabled, it is refused; removed, its credential is dead.
1501
    let id = job["job_id"].as_i64().unwrap();
1502
    let done = call(
1503
        &h.app,
1504
        "POST",
1505
        &format!("/api/v1/flow/jobs/{id}/finish"),
1506
        Some(&credential),
1507
        Some(r#"{"exit_code":0,"duration_ms":5}"#.into()),
1508
    )
1509
    .await;
1510
    assert_eq!(done.0, StatusCode::NO_CONTENT);
1511
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=disabled"))).await;
1512
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::FORBIDDEN);
1513
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1514
    assert!(page.contains("Removed plex."), "{page}");
1515
    assert_eq!(claim_as(credential).await.0, StatusCode::UNAUTHORIZED);
1516
}
1517
1518
/// Runner scopes (oxygenhub#41): a runner registered for one repository, or
1519
/// one owner, takes only those jobs; a site runner takes any.
1520
#[tokio::test(flavor = "multi_thread")]
1521
async fn scoped_runners_take_only_their_scope() {
1522
    use oxy_core::identity::SecretKey;
1523
    let h = hub().await;
1524
    create(&h.app, "andy", "demo").await;
1525
    create(&h.app, "andy", "other").await;
1526
    let register = |scope: db::runners::Scope, name: &'static str| {
1527
        let app = h.app.clone();
1528
        async move {
1529
            let token = format!("flowreg_{name}");
1530
            db::runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &scope).await.unwrap();
1531
            let identity = SecretKey::generate().identity(name, "", 1);
1532
            let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1533
            let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
1534
            let (st, body) = call(&app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1535
            assert_eq!(st, StatusCode::OK, "{body}");
1536
            serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string()
1537
        }
1538
    };
1539
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1540
    let only_demo = register(db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) }, "demo-runner").await;
1541
    let carols = register(db::runners::Scope { owner: "carol".into(), repo_id: None }, "carol-runner").await;
1542
    let andys = register(db::runners::Scope { owner: "andy".into(), repo_id: None }, "andy-runner").await;
1543
    let claim_as = |who: String| {
1544
        let app = h.app.clone();
1545
        async move {
1546
            let body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"] }).to_string();
1547
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await;
1548
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["repo"].as_str().unwrap().to_string())
1549
        }
1550
    };
1551
    // Jobs queued in andy/other only.
1552
    let work = tempfile::tempdir().unwrap();
1553
    let c = client(&format!("{}/andy/other", h.base), work.path());
1554
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1555
    c.snapshot("t").unwrap();
1556
    c.commit("pipeline", &[]).unwrap();
1557
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1558
    assert!(!runs_of(&h.app, "andy", "other").await.is_empty());
1559
    assert_eq!(claim_as(only_demo.clone()).await, None, "nothing of andy/demo is queued");
1560
    assert_eq!(claim_as(carols).await, None, "nothing of carol's");
1561
    assert_eq!(claim_as(andys).await.as_deref(), Some("andy/other"), "the owner's runner takes its repositories' jobs");
1562
    // The site runner (hub.toml) takes any.
1563
    assert_eq!(claim(&h.app).await.unwrap()["repo"], "andy/other");
1564
    assert_eq!(claim_as(only_demo).await, None, "still nothing of its own");
1565
}
1566
1567
/// oxygenhub-android#8: an app asks for a registration token for its
1568
/// user's own repositories; the runner it registers takes their jobs and
1569
/// no one else's.
1570
#[tokio::test(flavor = "multi_thread")]
1571
async fn a_user_registers_a_runner_for_their_own_repositories() {
1572
    use oxy_core::identity::SecretKey;
1573
    let h = hub().await;
1574
    create(&h.app, "andy", "demo").await;
1575
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "", "salt", false).await.unwrap();
1576
    let pat = "oxyhub_phone_test_token";
1577
    db::accounts::create_token(&h.app.db, andy.id, "phone", &oxygenhub::auth::token_hash(pat), "repo:read,repo:write", "", None)
1578
        .await
1579
        .unwrap();
1580
    let read_only = "oxyhub_read_only_token";
1581
    db::accounts::create_token(&h.app.db, andy.id, "ro", &oxygenhub::auth::token_hash(read_only), "repo:read", "", None).await.unwrap();
1582
    assert_eq!(call(&h.app, "POST", "/api/v1/user/runner-token", Some(read_only), None).await.0, StatusCode::FORBIDDEN);
1583
    assert_eq!(call(&h.app, "POST", "/api/v1/user/runner-token", None, None).await.0, StatusCode::UNAUTHORIZED);
1584
    let (st, body) = call(&h.app, "POST", "/api/v1/user/runner-token", Some(pat), None).await;
1585
    assert_eq!(st, StatusCode::CREATED, "{body}");
1586
    let got: serde_json::Value = serde_json::from_str(&body).unwrap();
1587
    let token = got["token"].as_str().unwrap().to_string();
1588
    assert!(token.starts_with("flowreg_") && got["owner"] == "andy", "{body}");
1589
    let identity = SecretKey::generate().identity("andy's phone", "", 1);
1590
    let info = serde_json::json!({ "arch": "aarch64", "os": "android", "version": "0.3.1", "labels": ["android"], "max_jobs": 1 });
1591
    let reg = serde_json::json!({ "token": token, "name": "pixel", "identity": hex::encode(identity.encode()), "info": info });
1592
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1593
    assert_eq!(st, StatusCode::OK, "{body}");
1594
    let phone = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "pixel").unwrap();
1595
    assert_eq!((phone.scope_owner.as_str(), phone.scope_repo_id), ("andy", None), "andy's repositories, all of them, and no one else's");
1596
}
1597
1598
/// Settings → Runners (oxygenhub#41, part 2b): a repository's admin adds a
1599
/// runner for that repository alone, sees which runners serve it, and
1600
/// removes only its own.
1601
#[tokio::test(flavor = "multi_thread")]
1602
async fn repository_admins_add_and_remove_their_own_runners() {
1603
    use oxy_core::identity::SecretKey;
1604
    let h = hub().await;
1605
    let res = oxygenhub::router(h.app.clone())
1606
        .oneshot(
1607
            Request::post("/register")
1608
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1609
                .body(Body::from("username=andy&email=andy%40example.com&password=correct-horse-battery&setup=test-setup"))
1610
                .unwrap(),
1611
        )
1612
        .await
1613
        .unwrap();
1614
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1615
    create(&h.app, "andy", "demo").await;
1616
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1617
    let web = |method: &'static str, path: String, body: Option<String>| {
1618
        let (app, cookie) = (h.app.clone(), cookie.clone());
1619
        async move {
1620
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1621
            if body.is_some() {
1622
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1623
            }
1624
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1625
            let st = res.status();
1626
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1627
        }
1628
    };
1629
    let csrf_of = |page: &str| {
1630
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1631
        page[i..].split('"').next().unwrap().to_string()
1632
    };
1633
    let (st, page) = web("GET", "/andy/demo/settings/runners".into(), None).await;
1634
    assert_eq!(st, StatusCode::OK);
1635
    assert!(page.contains("<h2>Runners</h2>"), "the owner sees the page");
1636
    let (_, page) = web("POST", "/andy/demo/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1637
    let i = page.find("--token ").unwrap() + "--token ".len();
1638
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1639
    let identity = SecretKey::generate().identity("mine", "", 1);
1640
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1641
    let reg = serde_json::json!({ "token": token, "name": "mine", "identity": hex::encode(identity.encode()), "info": info });
1642
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1643
    assert_eq!(st, StatusCode::OK, "{body}");
1644
    let mine = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "mine").unwrap();
1645
    assert_eq!(mine.scope(), db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) });
1646
    // The site's runner (hub.toml, from its first claim) serves it too, but is not the owner's to remove.
1647
    claim(&h.app).await;
1648
    let site = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "test-1").unwrap();
1649
    let (_, page) = web("GET", "/andy/demo/settings/runners".into(), None).await;
1650
    assert!(page.contains("<strong>mine</strong>") && page.contains("this repository"), "{page}");
1651
    assert!(page.contains("<strong>test-1</strong>") && page.contains("the whole site"), "{page}");
1652
    let csrf = csrf_of(&page);
1653
    let (st, _) = web("POST", format!("/andy/demo/settings/runners/{}/remove", site.id), Some(format!("_csrf={csrf}"))).await;
1654
    assert_eq!(st, StatusCode::NOT_FOUND, "not the repository's own");
1655
    let (st, _) = web("POST", format!("/andy/demo/settings/runners/{}/remove", mine.id), Some(format!("_csrf={csrf}"))).await;
1656
    assert_eq!(st, StatusCode::SEE_OTHER, "back to the Runners page");
1657
    let (_, page) = web("GET", "/andy/demo/settings/runners?notice=x".into(), None).await;
1658
    assert!(!page.contains("<strong>mine</strong>"), "{page}");
1659
    assert!(db::runners::get(&h.app.db, mine.id).await.unwrap().is_none());
1660
1661
    // The same for an organisation's owner.
1662
    let (_, page) = web("GET", "/orgs/new".into(), None).await;
1663
    web("POST", "/orgs/new".into(), Some(format!("_csrf={}&name=acme&display_name=Acme", csrf_of(&page)))).await;
1664
    let (st, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1665
    assert_eq!(st, StatusCode::OK);
1666
    let (_, page) = web("POST", "/orgs/acme/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1667
    let i = page.find("--token ").unwrap() + "--token ".len();
1668
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1669
    let identity = SecretKey::generate().identity("acme-runner", "", 1);
1670
    let reg = serde_json::json!({ "token": token, "name": "acme-runner", "identity": hex::encode(identity.encode()), "info": info });
1671
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0, StatusCode::OK);
1672
    let acme = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "acme-runner").unwrap();
1673
    assert_eq!(acme.scope(), db::runners::Scope { owner: "acme".into(), repo_id: None });
1674
    let (_, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1675
    assert!(page.contains("<strong>acme-runner</strong>") && page.contains("the organisation's repositories"), "{page}");
1676
    let (_, page) = web("POST", format!("/orgs/acme/settings/runners/{}/remove", acme.id), Some(format!("_csrf={}", csrf_of(&page)))).await;
1677
    assert!(page.contains("acme-runner removed"), "{page}");
1678
}
1679
1680
/// runs-on (oxygenhub#41, part 3): a job that asks for a label goes only to
1681
/// a runner that has it, and waits for one otherwise.
1682
#[tokio::test(flavor = "multi_thread")]
1683
async fn jobs_that_ask_for_labels_wait_for_a_runner_with_them() {
1684
    use oxy_core::identity::SecretKey;
1685
    let h = hub().await;
1686
    create(&h.app, "andy", "demo").await;
1687
    let work = tempfile::tempdir().unwrap();
1688
    let c = client(&format!("{}/andy/demo", h.base), work.path());
1689
    let cross = "job \"cross\" {\n    sandbox \"alpine\"\n    runs-on \"riscv64\"\n    exec \"true\"\n}\n";
1690
    write(work.path(), ".flow/pipeline.kdl", &pipeline(cross));
1691
    c.snapshot("t").unwrap();
1692
    c.commit("pipeline", &[]).unwrap();
1693
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1694
    assert!(!runs_of(&h.app, "andy", "demo").await.is_empty());
1695
    // The site runner has no labels: it takes the others, never cross.
1696
    let mut taken = Vec::new();
1697
    while let Some(j) = claim(&h.app).await {
1698
        taken.push(j["job"]["name"].as_str().unwrap().to_string());
1699
    }
1700
    assert!(!taken.contains(&"cross".to_string()) && taken.contains(&"lint".to_string()), "{taken:?}");
1701
    let queue = db::flow::queue(&h.app.db).await.unwrap();
1702
    let waiting = queue.iter().find(|q| q.job == "cross").unwrap();
1703
    assert_eq!((waiting.status.as_str(), waiting.needs()), ("queued", vec!["riscv64".to_string()]));
1704
    // A runner registered with the label takes it.
1705
    let token = "flowreg_riscv";
1706
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
1707
    let identity = SecretKey::generate().identity("visionfive", "", 1);
1708
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": ["riscv64"], "max_jobs": 1 });
1709
    let reg = serde_json::json!({ "token": token, "name": "visionfive", "identity": hex::encode(identity.encode()), "info": info });
1710
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1711
    assert_eq!(st, StatusCode::OK, "{body}");
1712
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1713
    let claim_body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"], "info": info }).to_string();
1714
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(claim_body)).await;
1715
    assert_eq!(st, StatusCode::OK, "{body}");
1716
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"], "cross");
1717
}
1718
1719
/// oxygenhub#71: a job its runner stopped reporting (restarted, or lost
1720
/// the hub as the job ended) is ended once it has run past the time limit
1721
/// and a grace: an error with the reason, its dependents skipped and its
1722
/// run settled, as if the runner had reported the error.
1723
#[tokio::test(flavor = "multi_thread")]
1724
async fn a_job_no_runner_reports_is_ended_after_the_time_limit() {
1725
    let h = hub().await;
1726
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1727
    create(&h.app, "andy", "lost").await;
1728
    let url = format!("{}/andy/lost", h.base);
1729
    let work = tempfile::tempdir().unwrap();
1730
    let c = client(&url, work.path());
1731
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1732
    write(work.path(), "test.sh", "echo ok\n");
1733
    c.commit("Add a pipeline", &[]).unwrap();
1734
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1735
    assert_eq!(runs_of(&h.app, "andy", "lost").await.len(), 1);
1736
    let job = claim(&h.app).await.expect("a job to claim");
1737
    let id = job["job_id"].as_i64().unwrap();
1738
1739
    // Running, but well within the limit: left alone.
1740
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 0);
1741
    // Started long ago and never reported: ended.
1742
    let old = db::now_ms() - 24 * 3600 * 1000;
1743
    sqlx::query("UPDATE flow_jobs SET started_ms = $1 WHERE id = $2").bind(old).bind(id).execute(&h.app.db).await.unwrap();
1744
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 1);
1745
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1746
    assert_eq!(j.status, "error");
1747
    assert!(j.error.starts_with("lost:"), "{}", j.error);
1748
    let run = &runs_of(&h.app, "andy", "lost").await[0];
1749
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
1750
    assert!(jobs.iter().all(|j| j.status != "running"), "nothing left running");
1751
    // A late report, should one come, does not overwrite the ending.
1752
    assert_ne!(finish(&h.app, id, serde_json::json!({ "exit_code": 0 })).await, StatusCode::NO_CONTENT);
1753
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "error");
1754
}
1755
1756
/// oxygenhub#73: a runner that lists the images it holds is offered only
1757
/// the jobs whose rootfs is among them; one that does not say gets any.
1758
#[tokio::test(flavor = "multi_thread")]
1759
async fn a_runner_is_offered_only_jobs_whose_image_it_holds() {
1760
    let h = hub().await;
1761
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1762
    create(&h.app, "andy", "images").await;
1763
    let url = format!("{}/andy/images", h.base);
1764
    let work = tempfile::tempdir().unwrap();
1765
    let c = client(&url, work.path());
1766
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1767
    write(work.path(), "test.sh", "echo ok\n");
1768
    c.commit("Add a pipeline", &[]).unwrap();
1769
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1770
    assert_eq!(runs_of(&h.app, "andy", "images").await.len(), 1);
1771
    let claim_with = |images: Vec<String>| {
1772
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "images": images }).to_string();
1773
        let app = h.app.clone();
1774
        async move {
1775
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await;
1776
            (st, body)
1777
        }
1778
    };
1779
    let (st, _) = claim_with(vec!["ab".repeat(32)]).await;
1780
    assert_eq!(st, StatusCode::NO_CONTENT, "no job for a runner without the image");
1781
    let jobs = db::flow::jobs(&h.app.db, runs_of(&h.app, "andy", "images").await[0].id).await.unwrap();
1782
    let rootfs: serde_json::Value = serde_json::from_str(&jobs[0].sandbox).unwrap();
1783
    let rootfs = rootfs["rootfs"].as_str().unwrap().to_string();
1784
    let (st, body) = claim_with(vec!["ab".repeat(32), rootfs]).await;
1785
    assert_eq!(st, StatusCode::OK, "{body}");
1786
}
1787
1788
/// oxygenhub#71: a runner that lists the jobs it holds has the others it
1789
/// was given ended at once (it restarted, or never received them), not at
1790
/// the time limit; a held job is left alone.
1791
#[tokio::test(flavor = "multi_thread")]
1792
async fn a_job_its_runner_no_longer_holds_is_ended_at_its_next_claim() {
1793
    let h = hub().await;
1794
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1795
    create(&h.app, "andy", "held").await;
1796
    let url = format!("{}/andy/held", h.base);
1797
    let work = tempfile::tempdir().unwrap();
1798
    let c = client(&url, work.path());
1799
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1800
    write(work.path(), "test.sh", "echo ok\n");
1801
    c.commit("Add a pipeline", &[]).unwrap();
1802
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1803
    assert_eq!(runs_of(&h.app, "andy", "held").await.len(), 1);
1804
    let id = claim(&h.app).await.expect("a job to claim")["job_id"].as_i64().unwrap();
1805
    let claim_holding = |holding: Vec<i64>| {
1806
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "holding": holding }).to_string();
1807
        let app = h.app.clone();
1808
        async move { call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await.0 }
1809
    };
1810
    claim_holding(vec![id]).await;
1811
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "running", "a held job stays");
1812
    claim_holding(vec![]).await;
1813
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1814
    assert_eq!(j.status, "error");
1815
    assert!(j.error.starts_with("lost:") && j.error.contains("no longer holds"), "{}", j.error);
1816
    let run = &runs_of(&h.app, "andy", "held").await[0];
1817
    assert!(db::flow::jobs(&h.app.db, run.id).await.unwrap().iter().all(|j| j.status != "running"), "the run settles");
1818
}
1819
1820
/// oxygen#59: a job with a `scope` runs on a push only when the push's
1821
/// changes touch a path it names (a release job, when Cargo.toml's version
1822
/// moves); a bookmark's first run and manual runs have every job.
1823
#[tokio::test(flavor = "multi_thread")]
1824
async fn a_scoped_job_runs_only_when_a_push_touches_its_paths() {
1825
    let h = hub().await;
1826
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1827
    create(&h.app, "andy", "scoped").await;
1828
    let url = format!("{}/andy/scoped", h.base);
1829
    let work = tempfile::tempdir().unwrap();
1830
    let c = client(&url, work.path());
1831
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\" \"packaging/**\"\n    exec \"true\"\n}\n";
1832
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1833
    write(work.path(), "test.sh", "echo ok\n");
1834
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1835
    c.commit("Start", &[]).unwrap();
1836
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1837
    let names = |app: Shared, n: usize| async move {
1838
        let mut runs = Vec::new();
1839
        for _ in 0..100 {
1840
            runs = runs_of(&app, "andy", "scoped").await;
1841
            if runs.len() >= n {
1842
                break;
1843
            }
1844
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1845
        }
1846
        assert_eq!(runs.len(), n, "runs");
1847
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1848
        j.sort();
1849
        // Passed, so the next push is scoped against it, not superseding it.
1850
        sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(runs[0].id).execute(&app.db).await.unwrap();
1851
        j
1852
    };
1853
    assert_eq!(names(h.app.clone(), 1).await, ["build", "dist", "lint", "test"], "the first run has every job");
1854
    write(work.path(), "test.sh", "echo still ok\n");
1855
    c.commit("Edit the test", &[]).unwrap();
1856
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1857
    assert_eq!(names(h.app.clone(), 2).await, ["build", "lint", "test"], "dist is out of scope");
1858
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1859
    c.commit("Release 0.1.1", &[]).unwrap();
1860
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1861
    assert_eq!(names(h.app.clone(), 3).await, ["build", "dist", "lint", "test"], "a version bump runs dist");
1862
}
1863
1864
/// oxygenhub#284: a push whose newest change says `[skip ci]` records a
1865
/// skipped run with no jobs; the next run's scope still covers what it
1866
/// brought; and a repository can refuse skips on its default bookmark.
1867
#[tokio::test(flavor = "multi_thread")]
1868
async fn a_push_can_skip_its_run() {
1869
    let h = hub().await;
1870
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1871
    create(&h.app, "andy", "skip").await;
1872
    let url = format!("{}/andy/skip", h.base);
1873
    let work = tempfile::tempdir().unwrap();
1874
    let c = client(&url, work.path());
1875
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\"\n    exec \"true\"\n}\n";
1876
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1877
    write(work.path(), "test.sh", "echo ok\n");
1878
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1879
    c.commit("Start", &[]).unwrap();
1880
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1881
    let newest = |app: Shared, n: usize| async move {
1882
        for _ in 0..100 {
1883
            let runs = runs_of(&app, "andy", "skip").await;
1884
            if runs.len() >= n {
1885
                assert_eq!(runs.len(), n, "runs");
1886
                let r = runs[0].clone();
1887
                let mut jobs: Vec<String> = db::flow::jobs(&app.db, r.id).await.unwrap().into_iter().map(|j| j.name).collect();
1888
                jobs.sort();
1889
                if r.status != "skipped" {
1890
                    sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(r.id).execute(&app.db).await.unwrap();
1891
                }
1892
                return (r, jobs);
1893
            }
1894
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1895
        }
1896
        panic!("no run {n}");
1897
    };
1898
    assert_eq!(newest(h.app.clone(), 1).await.1, ["build", "dist", "lint", "test"]);
1899
1900
    // Skipped: recorded, finished, no jobs, saying which change and who.
1901
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1902
    c.commit("Bump the version [Skip CI]", &[]).unwrap();
1903
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1904
    let (run, jobs) = newest(h.app.clone(), 2).await;
1905
    assert_eq!(run.status, "skipped");
1906
    assert!(jobs.is_empty(), "{jobs:?}");
1907
    assert!(run.error.starts_with("[skip ci] in change ") && run.error.contains(", pushed by "), "{}", run.error);
1908
    assert!(run.finished_ms.is_some());
1909
    let (_, page) = call(&h.app, "GET", "/andy/skip/flow/2", None, None).await;
1910
    assert!(page.contains("the push asked to skip this run"), "{page}");
1911
1912
    // The next run is scoped against run 1, so it still runs dist for the
1913
    // version the skipped push brought.
1914
    write(work.path(), "test.sh", "echo still ok\n");
1915
    c.commit("Edit the test", &[]).unwrap();
1916
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1917
    assert_eq!(newest(h.app.clone(), 3).await.1, ["build", "dist", "lint", "test"], "the skipped bump still runs dist");
1918
1919
    // Not on the default bookmark: the marker is ignored there.
1920
    let row = db::repos::get(&h.app.db, "andy", "skip").await.unwrap().unwrap();
1921
    db::repos::set_flow_skip(&h.app.db, row.id, "others").await.unwrap();
1922
    write(work.path(), "test.sh", "echo ok again\n");
1923
    c.commit("Docs only [skip flow]", &[]).unwrap();
1924
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1925
    let (run, jobs) = newest(h.app.clone(), 4).await;
1926
    assert_ne!(run.status, "skipped");
1927
    assert_eq!(jobs, ["build", "lint", "test"]);
1928
    let row = db::repos::get(&h.app.db, "andy", "skip").await.unwrap().unwrap();
1929
    assert!(oxygenhub::flow::skip_allowed(&row, "feature") && !oxygenhub::flow::skip_allowed(&row, "main"));
1930
    db::repos::set_flow_skip(&h.app.db, row.id, "never").await.unwrap();
1931
    let row = db::repos::get(&h.app.db, "andy", "skip").await.unwrap().unwrap();
1932
    assert!(!oxygenhub::flow::skip_allowed(&row, "feature"));
1933
}
1934
1935
/// oxygenhub#265: a push run on a state whose jobs already passed reuses
1936
/// those passes (same spec and sandbox), except a job behind a gate; a
1937
/// repository can turn reuse off.
1938
#[tokio::test(flavor = "multi_thread")]
1939
async fn a_push_reuses_a_pass_on_the_same_state() {
1940
    let h = hub().await;
1941
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1942
    create(&h.app, "andy", "reuse").await;
1943
    let url = format!("{}/andy/reuse", h.base);
1944
    let work = tempfile::tempdir().unwrap();
1945
    let c = client(&url, work.path());
1946
    let gated = "job \"deploy\" {\n    sandbox \"alpine\"\n    depends-on \"test\"\n    approval {\n        by \"maintain\"\n    }\n    exec \"true\"\n}\n";
1947
    write(work.path(), ".flow/pipeline.kdl", &pipeline(gated));
1948
    write(work.path(), "test.sh", "echo ok\n");
1949
    c.commit("Start", &[]).unwrap();
1950
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1951
    let first = runs_of(&h.app, "andy", "reuse").await.remove(0);
1952
    // Its jobs pass, the gated one too, each with a receipt.
1953
    sqlx::query("UPDATE flow_jobs SET status = 'passed', exit_code = 0, receipt_hash = 'r-' || name WHERE run_id = $1")
1954
        .bind(first.id)
1955
        .execute(&h.app.db)
1956
        .await
1957
        .unwrap();
1958
    sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(first.id).execute(&h.app.db).await.unwrap();
1959
    let heads: Vec<oxy_core::hash::ChangeHash> = first.head_list().into_iter().filter_map(oxy_core::hash::ChangeHash::from_hex).collect();
1960
    let row = db::repos::get(&h.app.db, "andy", "reuse").await.unwrap().unwrap();
1961
    assert!(row.flow_reuse, "on by default");
1962
    let again = |row: db::repos::RepoRow| {
1963
        let (app, state, heads) = (h.app.clone(), first.state.clone(), heads.clone());
1964
        async move {
1965
            let n =
1966
                oxygenhub::flow::start_run_scoped(&app, &row, "main", &state, &heads, "andy", "push", None).await.unwrap().expect("a run");
1967
            let run = db::flow::run(&app.db, row.id, n).await.unwrap().unwrap();
1968
            let jobs = db::flow::jobs(&app.db, run.id).await.unwrap();
1969
            (run, jobs)
1970
        }
1971
    };
1972
    let (run, jobs) = again(row.clone()).await;
1973
    let by = |name: &str| jobs.iter().find(|j| j.name == name).unwrap().clone();
1974
    for name in ["build", "test", "lint"] {
1975
        let j = by(name);
1976
        assert_eq!((j.status.as_str(), j.reused_from()), ("passed", Some(first.number)), "{name}: {j:?}");
1977
        assert_eq!(j.receipt_hash, format!("r-{name}"), "the pass's receipt stands for it");
1978
    }
1979
    let deploy = by("deploy");
1980
    assert!(deploy.status == "queued" && deploy.reused_from().is_none(), "a gated job runs again: {deploy:?}");
1981
    assert_eq!(run.status, "queued", "the run waits for the gated job");
1982
    let (_, page) = call(&h.app, "GET", &format!("/andy/reuse/flow/{}", run.number), None, None).await;
1983
    assert!(page.contains("data-reused") && page.contains(&format!("/andy/reuse/flow/{}", first.number)), "{page}");
1984
1985
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, &first.state).await.unwrap();
1986
    assert!(
1987
        checks.iter().any(|c| c.name == "flow/build" && c.status == "passed" && c.summary.contains("reused")),
1988
        "a reused pass reports its check: {checks:?}"
1989
    );
1990
1991
    // Turned off: every job runs.
1992
    db::repos::set_flow_reuse(&h.app.db, row.id, false).await.unwrap();
1993
    let row = db::repos::get(&h.app.db, "andy", "reuse").await.unwrap().unwrap();
1994
    let (_, jobs) = again(row).await;
1995
    assert!(jobs.iter().all(|j| j.status == "queued" && j.reused_from().is_none()), "{jobs:?}");
1996
}
1997
1998
/// oxygenhub#296: a fork starts green where upstream proved the same state:
1999
/// its push reuses upstream's passes, says whose, and links to them; never
2000
/// a private upstream's when the fork has another owner.
2001
#[tokio::test(flavor = "multi_thread")]
2002
async fn a_fork_reuses_what_upstream_proved() {
2003
    let h = hub().await;
2004
    for who in ["andy", "bob"] {
2005
        db::accounts::create_account(&h.app.db, who, &format!("{who}@example.com"), "x", "salt", true).await.unwrap();
2006
    }
2007
    create(&h.app, "andy", "game").await;
2008
    create(&h.app, "bob", "game").await;
2009
    let up = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
2010
    let fork = db::repos::get(&h.app.db, "bob", "game").await.unwrap().unwrap();
2011
    db::repos::set_forked_from(&h.app.db, fork.id, up.id).await.unwrap();
2012
    // Flow on for the fork (the test hub allows andy's repositories only).
2013
    sqlx::query("UPDATE repositories SET flow = 'on' WHERE id = $1").bind(fork.id).execute(&h.app.db).await.unwrap();
2014
    let work = tempfile::tempdir().unwrap();
2015
    let mut c = client(&format!("{}/andy/game", h.base), work.path());
2016
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2017
    write(work.path(), "test.sh", "echo ok\n");
2018
    c.commit("Start", &[]).unwrap();
2019
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2020
    let first = runs_of(&h.app, "andy", "game").await.remove(0);
2021
    sqlx::query("UPDATE flow_jobs SET status = 'passed', exit_code = 0, receipt_hash = 'r-' || name WHERE run_id = $1")
2022
        .bind(first.id)
2023
        .execute(&h.app.db)
2024
        .await
2025
        .unwrap();
2026
    // The same changes pushed to the fork: the same state.
2027
    c.config.set("remote.origin.url", &format!("{}/bob/game", h.base)).unwrap();
2028
    c.save_config().unwrap();
2029
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2030
    let run = runs_of(&h.app, "bob", "game").await.remove(0);
2031
    assert_eq!(run.state, first.state);
2032
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
2033
    for j in &jobs {
2034
        assert_eq!((j.status.as_str(), j.reused_from(), j.reused_repo()), ("passed", Some(first.number), Some("andy/game")), "{j:?}");
2035
        assert_eq!(j.receipt_hash, format!("r-{}", j.name));
2036
    }
2037
    let (_, page) = call(&h.app, "GET", &format!("/bob/game/flow/{}", run.number), None, None).await;
2038
    assert!(page.contains(&format!("href=\"/andy/game/flow/{}\">andy/game run #{}</a>", first.number, first.number)), "{page}");
2039
    let checks = db::hooks::checks_for_state(&h.app.db, fork.id, &run.state).await.unwrap();
2040
    assert!(checks.iter().any(|c| c.summary.contains("passed in andy/game run #")), "{checks:?}");
2041
2042
    // A private upstream of another owner: a new fork runs its own.
2043
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE id = $1").bind(up.id).execute(&h.app.db).await.unwrap();
2044
    create(&h.app, "bob", "game2").await;
2045
    let fork2 = db::repos::get(&h.app.db, "bob", "game2").await.unwrap().unwrap();
2046
    db::repos::set_forked_from(&h.app.db, fork2.id, up.id).await.unwrap();
2047
    sqlx::query("UPDATE repositories SET flow = 'on' WHERE id = $1").bind(fork2.id).execute(&h.app.db).await.unwrap();
2048
    c.config.set("remote.origin.url", &format!("{}/bob/game2", h.base)).unwrap();
2049
    c.save_config().unwrap();
2050
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2051
    let run2 = runs_of(&h.app, "bob", "game2").await.remove(0);
2052
    assert_eq!(run2.state, first.state);
2053
    let jobs = db::flow::jobs(&h.app.db, run2.id).await.unwrap();
2054
    assert!(jobs.iter().all(|j| j.status == "queued" && j.reused_from().is_none()), "{jobs:?}");
2055
}
2056
2057
#[test]
2058
fn skip_markers_are_the_forges_spellings_in_any_case() {
2059
    use oxygenhub::flow::skip_marker;
2060
    assert_eq!(skip_marker("Fix typo [skip flow]"), Some("[skip flow]"));
2061
    assert_eq!(skip_marker("[CI SKIP] docs"), Some("[ci skip]"));
2062
    assert_eq!(skip_marker("Docs\n\n[Skip CI]"), Some("[skip ci]"));
2063
    assert_eq!(skip_marker("skip ci without brackets"), None);
2064
    // Mentioned in code, not asked for (F1 of #284's follow-up).
2065
    assert_eq!(skip_marker("Document the `[skip flow]` marker"), None);
2066
    assert_eq!(skip_marker("Example:\n\n```\ngit commit -m 'x [skip ci]'\n```\n"), None);
2067
    assert_eq!(skip_marker("`code` then [skip ci]"), Some("[skip ci]"));
2068
    assert_eq!(skip_marker("an odd ` backtick [skip ci]"), Some("[skip ci]"));
2069
}
2070
2071
/// oxygenflow#32: a run still going is cancelled from the API, the web or
2072
/// by a newer push to its bookmark; its runner is refused from then on,
2073
/// and the next push is scoped past the cancelled run.
2074
#[tokio::test(flavor = "multi_thread")]
2075
async fn runs_are_cancelled_by_hand_or_by_a_newer_push() {
2076
    let h = hub().await;
2077
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2078
    create(&h.app, "andy", "stop").await;
2079
    let url = format!("{}/andy/stop", h.base);
2080
    let work = tempfile::tempdir().unwrap();
2081
    let c = client(&url, work.path());
2082
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\"\n    exec \"true\"\n}\n";
2083
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
2084
    write(work.path(), "test.sh", "echo ok\n");
2085
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
2086
    c.commit("Start", &[]).unwrap();
2087
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2088
    let wait_runs = |app: Shared, n: usize| async move {
2089
        for _ in 0..100 {
2090
            let runs = runs_of(&app, "andy", "stop").await;
2091
            if runs.len() >= n {
2092
                return runs;
2093
            }
2094
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2095
        }
2096
        panic!("no run {n}");
2097
    };
2098
    let first = wait_runs(h.app.clone(), 1).await;
2099
    sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(first[0].id).execute(&h.app.db).await.unwrap();
2100
    sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE run_id = $1").bind(first[0].id).execute(&h.app.db).await.unwrap();
2101
2102
    // Run 2 (a version bump) has a job running when run 3 is pushed.
2103
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
2104
    c.commit("Release 0.1.1", &[]).unwrap();
2105
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2106
    wait_runs(h.app.clone(), 2).await;
2107
    let job = claim(&h.app).await.expect("a job of run 2");
2108
    let id = job["job_id"].as_i64().unwrap();
2109
    write(work.path(), "test.sh", "echo still ok\n");
2110
    c.commit("Edit the test", &[]).unwrap();
2111
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2112
    let runs = wait_runs(h.app.clone(), 3).await;
2113
    let third = &runs[0];
2114
    let mut second = runs[1].clone();
2115
    for _ in 0..100 {
2116
        second = db::flow::run_by_id(&h.app.db, runs[1].id).await.unwrap().unwrap();
2117
        if !second.live() {
2118
            break;
2119
        }
2120
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2121
    }
2122
    assert_eq!(second.status, "cancelled", "a newer push supersedes a run still going");
2123
    let jobs = db::flow::jobs(&h.app.db, second.id).await.unwrap();
2124
    assert!(jobs.iter().all(|j| j.status == "cancelled" && j.error == "superseded by run #3"), "{jobs:?}");
2125
    let mut names: Vec<String> = db::flow::jobs(&h.app.db, third.id).await.unwrap().into_iter().map(|j| j.name).collect();
2126
    names.sort();
2127
    assert_eq!(names, ["build", "dist", "lint", "test"], "run 3 also checks what run 2 would have: the version bump");
2128
    let mut checks = vec![];
2129
    for _ in 0..100 {
2130
        checks = db::hooks::checks_for_state(&h.app.db, second.repo_id, &second.state).await.unwrap();
2131
        if checks.iter().all(|c| c.status == "cancelled") {
2132
            break;
2133
        }
2134
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2135
    }
2136
    assert!(checks.iter().all(|c| c.status == "cancelled"), "{checks:?}");
2137
    // The runner of the cancelled job is refused, so it stops the job.
2138
    let (st, _) =
2139
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(r#"{"records":[]}"#.into())).await;
2140
    assert_eq!(st, StatusCode::CONFLICT);
2141
2142
    // By hand: the API, then a run already ended is refused.
2143
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
2144
    assert_eq!(st, StatusCode::OK, "{body}");
2145
    let third = db::flow::run_by_id(&h.app.db, third.id).await.unwrap().unwrap();
2146
    assert_eq!(third.status, "cancelled");
2147
    assert!(db::flow::jobs(&h.app.db, third.id).await.unwrap().iter().all(|j| j.error == "cancelled by andy"));
2148
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
2149
    assert!(st == StatusCode::CONFLICT && body.contains("already cancelled"), "{st} {body}");
2150
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", None, None).await;
2151
    assert_ne!(st, StatusCode::OK, "anonymous callers cannot cancel");
2152
    let (_, page) = call(&h.app, "GET", "/andy/stop/flow/3", None, None).await;
2153
    assert!(page.contains("⊘") && !page.contains("CANCEL</button>"), "a cancelled run shows so, with no button");
2154
}
2155
2156
/// oxygenflow#23 and oxygenhub#89: a job runs under its pipeline's
2157
/// timeout, capped at the site's maximum, else the site's default; and the
2158
/// hub gives a job up only past its own limit.
2159
#[tokio::test(flavor = "multi_thread")]
2160
async fn a_job_runs_under_its_own_time_limit_within_the_sites() {
2161
    let h = hub().await;
2162
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2163
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_DEFAULT, "30").await.unwrap();
2164
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_MAX, "120").await.unwrap();
2165
    create(&h.app, "andy", "limits").await;
2166
    let url = format!("{}/andy/limits", h.base);
2167
    let work = tempfile::tempdir().unwrap();
2168
    let c = client(&url, work.path());
2169
    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";
2170
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
2171
    write(work.path(), "test.sh", "echo ok\n");
2172
    c.commit("Add a pipeline", &[]).unwrap();
2173
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2174
    assert_eq!(runs_of(&h.app, "andy", "limits").await.len(), 1);
2175
    let mut limits = std::collections::HashMap::new();
2176
    let mut ids = std::collections::HashMap::new();
2177
    while let Some(j) = claim(&h.app).await {
2178
        let name = j["job"]["name"].as_str().unwrap().to_string();
2179
        limits.insert(name.clone(), j["timeout_s"].as_u64().unwrap());
2180
        ids.insert(name, j["job_id"].as_i64().unwrap());
2181
    }
2182
    assert_eq!(limits["slow"], 5400, "its own");
2183
    assert_eq!(limits["huge"], 7200, "cut to the site's maximum");
2184
    assert_eq!(limits["build"], 1800, "the site's default");
2185
    // 40 minutes in: past the default and its grace, within slow's limit.
2186
    let started = db::now_ms() - 40 * 60 * 1000;
2187
    sqlx::query("UPDATE flow_jobs SET started_ms = $1").bind(started).execute(&h.app.db).await.unwrap();
2188
    oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap();
2189
    let status = |id: i64| {
2190
        let app = h.app.clone();
2191
        async move { db::flow::job(&app.db, id).await.unwrap().unwrap().status }
2192
    };
2193
    assert_eq!(status(ids["build"]).await, "error", "past its 30 minutes");
2194
    assert_eq!(status(ids["slow"]).await, "running", "within its 90");
2195
    assert_eq!(status(ids["huge"]).await, "running", "within its 120");
2196
}
2197
2198
/// oxygenflow#24: a job's `on` decides which events start it: a pushed
2199
/// tag runs only the jobs that name it; a push to a bookmark the pipeline
2200
/// does not name starts no run; a rerun repeats its run's event.
2201
#[tokio::test(flavor = "multi_thread")]
2202
async fn on_decides_which_events_start_a_job() {
2203
    let h = hub().await;
2204
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2205
    create(&h.app, "andy", "events").await;
2206
    let url = format!("{}/andy/events", h.base);
2207
    let work = tempfile::tempdir().unwrap();
2208
    let c = client(&url, work.path());
2209
    let text = format!(
2210
        "on {{\n    push \"main\"\n    manual\n}}\n{}job \"dist\" {{\n    sandbox \"alpine\"\n    on {{\n        tag \"v*\"\n    }}\n    exec \"true\"\n}}\n",
2211
        pipeline("")
2212
    );
2213
    // `on` must come after schema-version; pipeline() starts with it.
2214
    let text = text.replacen(
2215
        "on {\n    push \"main\"\n    manual\n}\nschema-version 1\n",
2216
        "schema-version 1\non {\n    push \"main\"\n    manual\n}\n",
2217
        1,
2218
    );
2219
    write(work.path(), ".flow/pipeline.kdl", &text);
2220
    write(work.path(), "test.sh", "echo ok\n");
2221
    c.commit("Start", &[]).unwrap();
2222
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2223
    let jobs_of_latest = |app: Shared, n: usize| async move {
2224
        let mut runs = Vec::new();
2225
        for _ in 0..100 {
2226
            runs = runs_of(&app, "andy", "events").await;
2227
            if runs.len() >= n {
2228
                break;
2229
            }
2230
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2231
        }
2232
        assert_eq!(runs.len(), n, "runs");
2233
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
2234
        j.sort();
2235
        (runs[0].clone(), j)
2236
    };
2237
    let (_, j) = jobs_of_latest(h.app.clone(), 1).await;
2238
    assert_eq!(j, ["build", "lint", "test"], "a push to main: no dist");
2239
    // A tag: only dist.
2240
    let heads = c.bookmark_heads().unwrap();
2241
    c.tag_create("v1.0.0", &heads, "first").unwrap();
2242
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2243
    let (run, j) = jobs_of_latest(h.app.clone(), 2).await;
2244
    assert_eq!(j, ["dist"], "a tag runs only what names it");
2245
    assert_eq!(run.trigger, "tag:v1.0.0");
2246
    // A rerun repeats the tag's event.
2247
    let row = db::repos::get(&h.app.db, "andy", "events").await.unwrap().unwrap();
2248
    db::flow::finish(
2249
        &h.app.db,
2250
        db::flow::jobs(&h.app.db, run.id).await.unwrap()[0].id,
2251
        db::flow::Outcome { status: "passed", exit_code: Some(0), error: "", receipt: "", receipt_hash: "" },
2252
    )
2253
    .await
2254
    .unwrap();
2255
    let run = db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap();
2256
    oxygenhub::flow::rerun(&h.app, &row, &run, "andy").await.unwrap();
2257
    let (_, j) = jobs_of_latest(h.app.clone(), 3).await;
2258
    assert_eq!(j, ["dist"], "the rerun is the tag's run again");
2259
    // A bookmark the pipeline does not name starts nothing.
2260
    c.bookmark_create("develop", None).unwrap();
2261
    assert!(c.push_bookmark("origin", "develop", false).unwrap().iter().all(|r| r.ok));
2262
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
2263
    assert_eq!(runs_of(&h.app, "andy", "events").await.len(), 3, "no run for develop");
2264
}
2265
2266
/// oxygenflow#24: a job with a `schedule` line runs on the default
2267
/// bookmark when the line comes due, and only then; other jobs stay out.
2268
#[tokio::test(flavor = "multi_thread")]
2269
async fn scheduled_jobs_run_when_due() {
2270
    let h = hub().await;
2271
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2272
    create(&h.app, "andy", "nightly").await;
2273
    let url = format!("{}/andy/nightly", h.base);
2274
    let work = tempfile::tempdir().unwrap();
2275
    let c = client(&url, work.path());
2276
    // An odd minute, so the hub's own ticker cannot fire it during the test.
2277
    let extra = "job \"nightly\" {\n    sandbox \"alpine\"\n    on {\n        schedule \"17 4 29 2 *\"\n    }\n    exec \"true\"\n}\n";
2278
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
2279
    write(work.path(), "test.sh", "echo ok\n");
2280
    c.commit("Start", &[]).unwrap();
2281
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2282
    assert_eq!(runs_of(&h.app, "andy", "nightly").await.len(), 1);
2283
    let first = runs_of(&h.app, "andy", "nightly").await;
2284
    let names: Vec<String> = db::flow::jobs(&h.app.db, first[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
2285
    assert!(!names.contains(&"nightly".to_string()), "a push does not run a scheduled job");
2286
    use flow_core::pipeline::When;
2287
    let not_yet = When { minute: 16, hour: 4, day: 29, month: 2, weekday: 4 };
2288
    assert_eq!(oxygenhub::flow::run_due(&h.app, not_yet).await, 0);
2289
    let due = When { minute: 17, ..not_yet };
2290
    assert_eq!(oxygenhub::flow::run_due(&h.app, due).await, 1);
2291
    let runs = runs_of(&h.app, "andy", "nightly").await;
2292
    assert_eq!(runs.len(), 2);
2293
    assert_eq!(runs[0].trigger, "schedule");
2294
    let names: Vec<String> = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
2295
    assert_eq!(names, ["nightly"]);
2296
    assert_eq!(runs[0].bookmark, "main", "on the default bookmark");
2297
    // #321: a pipeline that does not parse fails its push's run once, and
2298
    // the scheduler records nothing for it, minute after minute.
2299
    write(work.path(), ".flow/pipeline.kdl", "schema-version 1\n");
2300
    c.commit("No jobs", &[]).unwrap();
2301
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2302
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
2303
    let runs = runs_of(&h.app, "andy", "nightly").await;
2304
    assert_eq!(runs.len(), 3);
2305
    assert!(runs[0].error.contains("at least one job"), "{}", runs[0].error);
2306
    assert_eq!(oxygenhub::flow::run_due(&h.app, due).await, 0);
2307
    assert_eq!(oxygenhub::flow::run_due(&h.app, not_yet).await, 0);
2308
    assert_eq!(runs_of(&h.app, "andy", "nightly").await.len(), 3, "no scheduled runs of a broken pipeline");
2309
}
2310
2311
#[tokio::test(flavor = "multi_thread")]
2312
async fn variables_from_three_levels_reach_a_job_inner_overriding_outer() {
2313
    use oxygenhub::levels::Scope;
2314
    use oxygenhub::variables;
2315
    let h = hub().await;
2316
    let app = &h.app;
2317
    // Andy, the site's administrator, owns the acme organisation.
2318
    let res = oxygenhub::router(app.clone())
2319
        .oneshot(
2320
            Request::post("/register")
2321
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
2322
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
2323
                .unwrap(),
2324
        )
2325
        .await
2326
        .unwrap();
2327
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
2328
    let andy = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
2329
    db::accounts::create_org(&app.db, "acme", "Acme", andy.id).await.unwrap();
2330
    create(app, "acme", "app").await;
2331
    let page = |path: &str, form: Option<String>| {
2332
        let mut req =
2333
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2334
        if form.is_some() {
2335
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2336
        }
2337
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
2338
        let (app, cookie) = (app.clone(), cookie.clone());
2339
        async move {
2340
            let mut res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
2341
            // A repository settings form returns to its page (#278).
2342
            let back =
2343
                res.headers().get(header::LOCATION).and_then(|v| v.to_str().ok()).filter(|l| l.contains("/settings/")).map(String::from);
2344
            if let Some(to) = back {
2345
                let req = Request::get(to).header(header::COOKIE, cookie).body(Body::empty()).unwrap();
2346
                res = oxygenhub::router(app).oneshot(req).await.unwrap();
2347
            }
2348
            let status = res.status();
2349
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2350
            (status, body)
2351
        }
2352
    };
2353
    let csrf_of = |page: &str| {
2354
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2355
        page[i..].split('"').next().unwrap().to_string()
2356
    };
2357
2358
    // The site sets CC and LANG, the organisation its own CC, the
2359
    // repository RUST_LOG from its settings page.
2360
    variables::set(&app.db, Scope::Site, "CC", "gcc").await.unwrap();
2361
    variables::set(&app.db, Scope::Site, "LANG", "C").await.unwrap();
2362
    let org = db::accounts::org_by_name(&app.db, "acme").await.unwrap().unwrap();
2363
    variables::set(&app.db, Scope::Org(org.id), "CC", "clang").await.unwrap();
2364
    let (st, settings) = page("/acme/app/settings/variables", None).await;
2365
    assert_eq!(st, StatusCode::OK, "{settings}");
2366
    assert!(settings.contains("Inherited") && settings.contains("the acme organisation") && settings.contains("overridden"), "{settings}");
2367
    let csrf = csrf_of(&settings);
2368
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=RUST_LOG&value=debug"))).await;
2369
    assert!(body.contains("RUST_LOG set.") && body.contains("<code>debug</code>"), "{body}");
2370
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=FLOW_REPO&value=x"))).await;
2371
    assert!(body.contains("not FLOW_"), "{body}");
2372
    let repo = db::repos::get(&app.db, "acme", "app").await.unwrap().unwrap();
2373
    db::repos::set_flow(&app.db, repo.id, "on").await.unwrap();
2374
    let env = variables::env_for_repo(&app.db, &repo).await.unwrap();
2375
    assert_eq!(
2376
        env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect::<Vec<_>>(),
2377
        [("CC", "clang"), ("LANG", "C"), ("RUST_LOG", "debug")],
2378
        "the organisation's CC wins over the site's"
2379
    );
2380
2381
    // A claim carries them.
2382
    let url = format!("{}/acme/app", h.base);
2383
    let work = tempfile::tempdir().unwrap();
2384
    let c = client(&url, work.path());
2385
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2386
    write(work.path(), "test.sh", "echo ok\n");
2387
    c.snapshot("test").unwrap();
2388
    c.commit("Add a pipeline", &[]).unwrap();
2389
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2390
    let runs = runs_of(app, "acme", "app").await;
2391
    assert_eq!(runs.len(), 1, "{runs:?}");
2392
    let got = claim(app).await.unwrap_or_else(|| panic!("a job: {:?}", runs[0]));
2393
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "LANG": "C", "RUST_LOG": "debug" }), "{got}");
2394
2395
    // Removing a site variable from the admin page takes effect at the next claim.
2396
    let (_, admin) = page("/admin/variables", None).await;
2397
    assert!(admin.contains("Variables") && admin.contains("<code>gcc</code>"), "{admin}");
2398
    let (_, body) = page("/admin/variables", Some(format!("_csrf={}&action=delete&name=LANG", csrf_of(&admin)))).await;
2399
    assert!(body.contains("LANG removed."), "{body}");
2400
    let got = claim(app).await.expect("another job");
2401
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "RUST_LOG": "debug" }), "{got}");
2402
}
2403
2404
#[tokio::test(flavor = "multi_thread")]
2405
async fn secrets_a_job_declares_come_with_the_claim_and_never_reach_the_log() {
2406
    let h = hub().await;
2407
    let app = &h.app;
2408
    let res = oxygenhub::router(app.clone())
2409
        .oneshot(
2410
            Request::post("/register")
2411
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
2412
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
2413
                .unwrap(),
2414
        )
2415
        .await
2416
        .unwrap();
2417
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
2418
    let page = |path: &str, form: Option<String>| {
2419
        let mut req =
2420
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2421
        if form.is_some() {
2422
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2423
        }
2424
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
2425
        let (app, cookie) = (app.clone(), cookie.clone());
2426
        async move {
2427
            let mut res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
2428
            // A repository settings form returns to its page (#278).
2429
            let back =
2430
                res.headers().get(header::LOCATION).and_then(|v| v.to_str().ok()).filter(|l| l.contains("/settings/")).map(String::from);
2431
            if let Some(to) = back {
2432
                let req = Request::get(to).header(header::COOKIE, cookie).body(Body::empty()).unwrap();
2433
                res = oxygenhub::router(app).oneshot(req).await.unwrap();
2434
            }
2435
            let status = res.status();
2436
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2437
            (status, body)
2438
        }
2439
    };
2440
    let csrf_of = |page: &str| {
2441
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2442
        page[i..].split('"').next().unwrap().to_string()
2443
    };
2444
    create(app, "andy", "demo").await;
2445
    // The site sets deploy-token; the repository overrides it. Neither
2446
    // page shows a value, only that it is set.
2447
    let (_, admin) = page("/admin", None).await;
2448
    let csrf = csrf_of(&admin);
2449
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=deploy-token&value=site-level-value"))).await;
2450
    assert!(body.contains("deploy-token set.") && !body.contains("site-level-value"), "{body}");
2451
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=bad+name&value=x"))).await;
2452
    assert!(body.contains("name is 1 to 64 of"), "{body}");
2453
    let (_, settings) = page("/andy/demo/settings/secrets", None).await;
2454
    assert!(
2455
        settings.contains("Secrets") && settings.contains("<code>deploy-token</code>") && settings.contains("the site</td>"),
2456
        "{settings}"
2457
    );
2458
    let csrf_r = csrf_of(&settings);
2459
    let (_, body) =
2460
        page("/andy/demo/settings/secrets", Some(format!("_csrf={csrf_r}&action=set&name=deploy-token&value=hunter22-repo-value"))).await;
2461
    assert!(body.contains("deploy-token set.") && body.contains("overridden") && !body.contains("hunter22"), "{body}");
2462
    let repo = db::repos::get(&app.db, "andy", "demo").await.unwrap().unwrap();
2463
    assert!(
2464
        !String::from_utf8_lossy(&oxygenhub::secrets::list(&app.db, oxygenhub::levels::Scope::Repo(repo.id)).await.unwrap()[0].value)
2465
            .contains("hunter22"),
2466
        "sealed at rest"
2467
    );
2468
2469
    // A job that declares the secret, and one the levels do not hold.
2470
    let url = format!("{}/andy/demo", h.base);
2471
    let work = tempfile::tempdir().unwrap();
2472
    let c = client(&url, work.path());
2473
    write(
2474
        work.path(),
2475
        ".flow/pipeline.kdl",
2476
        &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"),
2477
    );
2478
    write(work.path(), "test.sh", "echo ok\n");
2479
    c.snapshot("test").unwrap();
2480
    c.commit("Add a pipeline", &[]).unwrap();
2481
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2482
    let runs = runs_of(app, "andy", "demo").await;
2483
    let jobs = match runs.first() {
2484
        Some(r) => db::flow::jobs(&app.db, r.id).await.unwrap().iter().map(|j| format!("{}:{}", j.name, j.status)).collect::<Vec<_>>(),
2485
        None => vec![],
2486
    };
2487
    let mut deploy = None;
2488
    for _ in 0..50 {
2489
        let Some(got) = claim(app).await else {
2490
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2491
            continue;
2492
        };
2493
        if got["job"]["name"] == "deploy" {
2494
            deploy = Some(got);
2495
            break;
2496
        }
2497
        assert_eq!(got["secrets"], serde_json::Value::Null, "{got}");
2498
    }
2499
    let got = deploy.unwrap_or_else(|| panic!("the deploy job: runs {runs:?} jobs {jobs:?}"));
2500
    assert_eq!(
2501
        got["secrets"],
2502
        serde_json::json!([{ "name": "deploy-token", "path": "/run/secrets/token", "value": "hunter22-repo-value" }]),
2503
        "the repository's value, the missing one left out: {got}"
2504
    );
2505
    let id = got["job_id"].as_i64().unwrap();
2506
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2507
    assert!(log.iter().any(|l| l.stream == "flow" && l.text.contains("secret \"missing\" is not set")), "{log:?}");
2508
2509
    // The value never reaches the stored log, plain or base64.
2510
    let records = serde_json::json!({ "records": [
2511
        { "t": 1, "stream": "out", "text": "token=hunter22-repo-value" },
2512
        { "t": 2, "stream": "err", "text": "b64 aHVudGVyMjItcmVwby12YWx1ZQ== end" },
2513
    ] });
2514
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2515
    assert_eq!(st, StatusCode::NO_CONTENT);
2516
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2517
    let texts: Vec<&str> = log.iter().map(|l| l.text.as_str()).collect();
2518
    assert!(texts.contains(&"token=***") && texts.contains(&"b64 *** end"), "{texts:?}");
2519
    assert!(!texts.iter().any(|t| t.contains("hunter22")), "{texts:?}");
2520
}
2521
2522
#[tokio::test(flavor = "multi_thread")]
2523
async fn a_job_s_identity_is_a_signed_token_the_discovery_document_lets_anyone_verify() {
2524
    let h = hub().await;
2525
    let app = &h.app;
2526
    let (st, disc) = call(app, "GET", "/.well-known/openid-configuration", None, None).await;
2527
    assert_eq!(st, StatusCode::OK, "{disc}");
2528
    let disc: serde_json::Value = serde_json::from_str(&disc).unwrap();
2529
    assert_eq!(disc["issuer"], h.base.as_str());
2530
    assert_eq!(disc["jwks_uri"], format!("{}/.well-known/jwks.json", h.base));
2531
    let (st, jwks) = call(app, "GET", "/.well-known/jwks.json", None, None).await;
2532
    assert_eq!(st, StatusCode::OK, "{jwks}");
2533
    let jwks: serde_json::Value = serde_json::from_str(&jwks).unwrap();
2534
    assert_eq!(jwks["keys"][0]["alg"], "RS256");
2535
    let kid = jwks["keys"][0]["kid"].as_str().unwrap().to_string();
2536
2537
    create(app, "andy", "demo").await;
2538
    let url = format!("{}/andy/demo", h.base);
2539
    let work = tempfile::tempdir().unwrap();
2540
    let c = client(&url, work.path());
2541
    write(
2542
        work.path(),
2543
        ".flow/pipeline.kdl",
2544
        &pipeline("job \"deploy\" {\n    sandbox \"alpine\"\n    identity \"sts.amazonaws.com\" {\n        mount-path \"/run/secrets/aws-token\"\n    }\n    exec \"deploy\"\n}\n"),
2545
    );
2546
    write(work.path(), "test.sh", "echo ok\n");
2547
    c.snapshot("test").unwrap();
2548
    c.commit("Add a pipeline", &[]).unwrap();
2549
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2550
    let mut deploy = None;
2551
    for _ in 0..50 {
2552
        let Some(got) = claim(app).await else {
2553
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2554
            continue;
2555
        };
2556
        if got["job"]["name"] == "deploy" {
2557
            deploy = Some(got);
2558
            break;
2559
        }
2560
    }
2561
    let got = deploy.expect("the deploy job");
2562
    let secrets = got["secrets"].as_array().expect("secrets");
2563
    assert_eq!(secrets.len(), 1);
2564
    assert_eq!(
2565
        (secrets[0]["name"].as_str(), secrets[0]["path"].as_str()),
2566
        (Some("identity:sts.amazonaws.com"), Some("/run/secrets/aws-token"))
2567
    );
2568
    let token = secrets[0]["value"].as_str().unwrap().to_string();
2569
    let issuer = app.oidc().await.unwrap();
2570
    assert_eq!(issuer.kid, kid, "the key the JWKS publishes signed it");
2571
    let claims = issuer.verify(&token, "sts.amazonaws.com", db::now_ms()).expect("verifies");
2572
    assert_eq!(claims["sub"], "repo:andy/demo:bookmark:main");
2573
    assert_eq!(claims["repository"], "andy/demo");
2574
    assert_eq!(claims["job"], "deploy");
2575
    assert_eq!(claims["run_number"], 1);
2576
    assert_eq!(claims["runner"], "test-1");
2577
    assert_eq!(claims["iss"], h.base.as_str());
2578
    assert!(claims["state"].as_str().unwrap().len() == 64);
2579
    // A job that prints its token leaves *** in the log.
2580
    let id = got["job_id"].as_i64().unwrap();
2581
    let records = serde_json::json!({ "records": [{ "t": 1, "stream": "out", "text": format!("TOKEN={token} end") }] });
2582
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2583
    assert_eq!(st, StatusCode::NO_CONTENT);
2584
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2585
    assert!(log.iter().any(|l| l.text == "TOKEN=*** end"), "{log:?}");
2586
}
2587
2588
#[tokio::test(flavor = "multi_thread")]
2589
async fn jobs_are_offered_only_to_runners_of_their_architecture() {
2590
    let h = hub().await;
2591
    let app = &h.app;
2592
    create(app, "andy", "demo").await;
2593
    let url = format!("{}/andy/demo", h.base);
2594
    let work = tempfile::tempdir().unwrap();
2595
    let c = client(&url, work.path());
2596
    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)));
2597
    write(work.path(), "test.sh", "echo ok\n");
2598
    c.snapshot("test").unwrap();
2599
    c.commit("Add a pipeline", &[]).unwrap();
2600
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2601
    let claim_as = |arch: &'static str, archs: serde_json::Value| {
2602
        let app = app.clone();
2603
        async move {
2604
            let body = serde_json::json!({
2605
                "runner": format!("{arch}-1"), "runtimes": ["microvm"],
2606
                "info": { "arch": arch, "os": "linux", "version": "t", "labels": [], "max_jobs": 1 },
2607
                "image_archs": archs,
2608
            });
2609
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
2610
            match st {
2611
                StatusCode::NO_CONTENT => None,
2612
                StatusCode::OK => {
2613
                    Some(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"].as_str().unwrap().to_string())
2614
                }
2615
                other => panic!("claim: {other} {body}"),
2616
            }
2617
        }
2618
    };
2619
    // An x86_64 runner that says the alpine image is x86_64: it takes the
2620
    // alpine jobs, never the one that asks for riscv64.
2621
    let rootfs = pipeline("").split("cas://blob/").nth(1).unwrap()[..64].to_string();
2622
    for _ in 0..50 {
2623
        if !runs_of(app, "andy", "demo").await.is_empty() {
2624
            break;
2625
        }
2626
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2627
    }
2628
    let runs = runs_of(app, "andy", "demo").await;
2629
    assert_eq!(runs.len(), 1, "{runs:?}");
2630
    let mut taken = vec![];
2631
    while let Some(j) = claim_as("x86_64", serde_json::json!({ rootfs.clone(): "x86_64" })).await {
2632
        taken.push(j);
2633
    }
2634
    assert_eq!(taken, ["build", "lint"], "test waits for build; flash is for riscv64");
2635
    // A riscv64 runner: the alpine image is known to be x86_64, so only flash.
2636
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await.as_deref(), Some("flash"));
2637
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await, None);
2638
    let (_, queue) = call(app, "GET", "/admin/runners", None, None).await;
2639
    let _ = queue;
2640
}
2641
2642
/// OxygenFlow spec §11.5: a runner hands back a job it cannot run. The
2643
/// job is queued again and not offered to that runner again, the decline
2644
/// shows on the run's page and is kept for the runner's, and once three
2645
/// runners have declined it the job ends as unplaceable with their reasons.
2646
#[tokio::test(flavor = "multi_thread")]
2647
async fn a_declined_job_goes_to_another_runner_or_ends_unplaceable() {
2648
    let h = hub().await;
2649
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2650
    create(&h.app, "andy", "declines").await;
2651
    let url = format!("{}/andy/declines", h.base);
2652
    let work = tempfile::tempdir().unwrap();
2653
    let c = client(&url, work.path());
2654
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2655
    write(work.path(), "test.sh", "echo ok\n");
2656
    c.commit("Add a pipeline", &[]).unwrap();
2657
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2658
    let run = runs_of(&h.app, "andy", "declines").await[0].clone();
2659
    let claim_as = |token: &'static str, name: &'static str| {
2660
        let app = h.app.clone();
2661
        async move {
2662
            let body = serde_json::json!({ "runner": name, "runtimes": ["microvm"] }).to_string();
2663
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(token), Some(body)).await;
2664
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap())
2665
        }
2666
    };
2667
    let decline = |token: &'static str, id: i64, reason: &'static str| {
2668
        let app = h.app.clone();
2669
        async move {
2670
            let body = serde_json::json!({ "reason": reason }).to_string();
2671
            call(&app, "POST", &format!("/api/v1/flow/jobs/{id}/decline"), Some(token), Some(body)).await.0
2672
        }
2673
    };
2674
    let job = claim_as("runner-secret", "earth-1").await.expect("a job");
2675
    // The other runners are known to the hub before they decline anything.
2676
    assert_eq!(decline("runner-two", job, "not mine").await, StatusCode::CONFLICT, "only the runner it runs on may decline it");
2677
    assert_eq!(decline("runner-secret", job, "the MicroVM tier needs /dev/kvm").await, StatusCode::NO_CONTENT);
2678
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2679
    assert_eq!((j.status.as_str(), j.runner.as_str()), ("queued", ""));
2680
    assert_eq!(j.waiting, "declined by earth-1: the MicroVM tier needs /dev/kvm; waiting for another runner");
2681
    // earth-1 is offered the other ready job, not this one, while it stays the same.
2682
    let next = claim_as("runner-secret", "earth-1").await.expect("the other ready job");
2683
    assert_ne!(next, job);
2684
    let page = call(&h.app, "GET", &format!("/andy/declines/flow/{}", run.number), None, None).await.1;
2685
    assert!(page.contains("Waiting: declined by earth-1: the MicroVM tier needs /dev/kvm"), "{page}");
2686
    assert_eq!(claim_as("runner-two", "plex-1").await, Some(job), "another runner takes it");
2687
    assert_eq!(decline("runner-two", job, "rootfs 36fc4e323804 is not on this runner").await, StatusCode::NO_CONTENT);
2688
    assert_eq!(claim_as("runner-three", "narvi").await, Some(job));
2689
    assert_eq!(decline("runner-three", job, "rootfs 36fc4e323804 is for x86_64; this runner is riscv64").await, StatusCode::NO_CONTENT);
2690
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2691
    assert_eq!(j.status, "error");
2692
    assert_eq!(
2693
        j.error,
2694
        "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"
2695
    );
2696
    let r = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex-1").unwrap();
2697
    let declined = db::flow::declines_of_runner(&h.app.db, r.id, 10).await.unwrap();
2698
    assert_eq!(declined.len(), 1);
2699
    assert_eq!((declined[0].job_id, declined[0].reason.as_str()), (job, "rootfs 36fc4e323804 is not on this runner"));
2700
    assert_eq!(r.tier_list(), vec!["microvm"]);
2701
}
2702
2703
/// oxygenflow#76, #312: a draining runner hands back a job it holds. It is
2704
/// queued again ahead of new work (even a job of lower priority), its log
2705
/// says why and goes on with the next attempt, and it is no decline. A
2706
/// runner the hub stops hearing from has its jobs handed back the same way.
2707
#[tokio::test(flavor = "multi_thread")]
2708
async fn a_drained_job_goes_back_ahead_of_new_work() {
2709
    let h = hub().await;
2710
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2711
    create(&h.app, "andy", "drains").await;
2712
    let url = format!("{}/andy/drains", h.base);
2713
    let work = tempfile::tempdir().unwrap();
2714
    let c = client(&url, work.path());
2715
    let bulk = "job \"bulk\" {\n    sandbox \"alpine\"\n    priority \"low\"\n    checkpoint \"/src/state\"\n    exec \"true\"\n}\n";
2716
    write(work.path(), ".flow/pipeline.kdl", &pipeline(bulk));
2717
    write(work.path(), "test.sh", "echo ok\n");
2718
    c.commit("Add a pipeline", &[]).unwrap();
2719
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2720
    runs_of(&h.app, "andy", "drains").await;
2721
    let claim_as = |token: &'static str, name: &'static str| {
2722
        let app = h.app.clone();
2723
        async move {
2724
            let body = serde_json::json!({ "runner": name, "runtimes": ["microvm"] }).to_string();
2725
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(token), Some(body)).await;
2726
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap())
2727
        }
2728
    };
2729
    let release = |token: &'static str, id: i64, reason: &'static str| {
2730
        let app = h.app.clone();
2731
        async move {
2732
            let body = serde_json::json!({ "reason": reason }).to_string();
2733
            call(&app, "POST", &format!("/api/v1/flow/jobs/{id}/release"), Some(token), Some(body)).await.0
2734
        }
2735
    };
2736
    let name_of = |id: i64| {
2737
        let app = h.app.clone();
2738
        async move { db::flow::job(&app.db, id).await.unwrap().unwrap().name }
2739
    };
2740
    let build = claim_as("runner-secret", "earth-1").await.unwrap();
2741
    let lint = claim_as("runner-two", "plex-1").await.unwrap();
2742
    let low = claim_as("runner-three", "phone").await.unwrap();
2743
    assert_eq!((name_of(build).await, name_of(lint).await, name_of(low).await), ("build".into(), "lint".into(), "bulk".into()));
2744
    // The low-priority job logs a line, then its runner leaves.
2745
    let line = serde_json::json!({ "records": [{ "t": 1200, "stream": "stdout", "text": "step 1 of 30" }] }).to_string();
2746
    call(&h.app, "POST", &format!("/api/v1/flow/jobs/{low}/log"), Some("runner-three"), Some(line)).await;
2747
    assert_eq!(finish(&h.app, build, serde_json::json!({ "exit_code": 0, "duration_ms": 700 })).await, StatusCode::NO_CONTENT);
2748
    // It keeps its checkpoint first (oxygenflow#77), a job's own only.
2749
    let (st, body) = call(&h.app, "POST", &format!("/api/v1/flow/jobs/{lint}/checkpoint"), Some("runner-two"), Some("x".into())).await;
2750
    assert_eq!(st, StatusCode::BAD_REQUEST, "lint declares no checkpoint: {body}");
2751
    let (st, body) =
2752
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{low}/checkpoint"), Some("runner-three"), Some("step 32".into())).await;
2753
    assert_eq!(st, StatusCode::OK, "{body}");
2754
    let saved = serde_json::from_str::<serde_json::Value>(&body).unwrap()["blob"].as_str().unwrap().to_string();
2755
    assert_eq!(release("runner-two", low, "off Wi-Fi").await, StatusCode::CONFLICT, "only the runner that holds it");
2756
    assert_eq!(release("runner-three", low, "off Wi-Fi").await, StatusCode::NO_CONTENT);
2757
    let j = db::flow::job(&h.app.db, low).await.unwrap().unwrap();
2758
    assert_eq!((j.status.as_str(), j.runner.as_str(), j.handbacks), ("queued", "", 1));
2759
    let log: Vec<String> = db::flow::log(&h.app.db, low, 0, 50).await.unwrap().into_iter().map(|l| l.text).collect();
2760
    assert_eq!(log, ["step 1 of 30", "── handed back by phone: off Wi-Fi; queued again ahead of new work"]);
2761
    assert!(db::flow::declines_of_job(&h.app.db, low).await.unwrap().is_empty(), "not a decline");
2762
    // `test` became ready when `build` passed, and is of higher priority:
2763
    // the handed-back job still goes first, to any runner, its own too.
2764
    let body = serde_json::json!({ "runner": "phone", "runtimes": ["microvm"] }).to_string();
2765
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-three"), Some(body)).await;
2766
    assert_eq!(st, StatusCode::OK, "{body}");
2767
    let again: serde_json::Value = serde_json::from_str(&body).unwrap();
2768
    assert_eq!((again["job_id"].as_i64(), again["checkpoint"].as_str()), (Some(low), Some(saved.as_str())), "it resumes: {again}");
2769
    let (st, bytes) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{low}/checkpoint"), Some("runner-three"), None).await;
2770
    assert_eq!((st, bytes.as_str()), (StatusCode::OK, "step 32"));
2771
    assert!(db::flow::artifacts(&h.app.db, low).await.unwrap().is_empty(), "a checkpoint is no artifact of the job");
2772
    assert_eq!(claim_as("runner-secret", "earth-1").await.map(|id| id != low), Some(true), "then new work");
2773
2774
    // The phone goes quiet: once its lease lapses the job is handed back.
2775
    let phone = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "phone").unwrap();
2776
    sqlx::query("UPDATE flow_runners SET last_seen_ms = $1 WHERE id = $2")
2777
        .bind(db::now_ms() - oxygenhub::flow::LEASE_MS - 1000)
2778
        .bind(phone.id)
2779
        .execute(&h.app.db)
2780
        .await
2781
        .unwrap();
2782
    assert_eq!(oxygenhub::flow::requeue_lapsed(&h.app).await.unwrap(), 1);
2783
    let j = db::flow::job(&h.app.db, low).await.unwrap().unwrap();
2784
    assert_eq!((j.status.as_str(), j.handbacks), ("queued", 2));
2785
    let log: Vec<String> = db::flow::log(&h.app.db, low, 0, 50).await.unwrap().into_iter().map(|l| l.text).collect();
2786
    assert_eq!(log.last().unwrap(), "── the runner phone has not been heard from for 3 minutes; queued again ahead of new work");
2787
    assert_eq!(claim_as("runner-two", "plex-1").await, Some(low), "another runner takes it");
2788
}
2789
2790
/// oxygenflow#76: a claim says how long the job is expected to take, once
2791
/// it has passed: the median of its recent passing runs in the repository,
2792
/// so a runner leaving with notice can tell whether to finish it.
2793
#[tokio::test(flavor = "multi_thread")]
2794
async fn a_claim_carries_the_job_s_expected_time() {
2795
    let h = hub().await;
2796
    create(&h.app, "andy", "eta").await;
2797
    let url = format!("{}/andy/eta", h.base);
2798
    let work = tempfile::tempdir().unwrap();
2799
    let c = client(&url, work.path());
2800
    let one = "schema-version 1\nsandbox \"alpine\" {\n    rootfs \"cas://blob/ROOTFS\"\n}\njob \"build\" {\n    sandbox \"alpine\"\n    exec \"make\"\n}\n".replace("ROOTFS", ROOTFS);
2801
    write(work.path(), ".flow/pipeline.kdl", &one);
2802
    c.commit("One job", &[]).unwrap();
2803
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2804
    runs_of(&h.app, "andy", "eta").await;
2805
    let first = claim(&h.app).await.expect("a job");
2806
    assert!(first.get("expected_ms").is_none(), "never passed: no estimate, {first}");
2807
    let id = first["job_id"].as_i64().unwrap();
2808
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700 })).await, StatusCode::NO_CONTENT);
2809
    // It took 42 s from its claim.
2810
    sqlx::query("UPDATE flow_jobs SET started_ms = finished_ms - 42000 WHERE id = $1").bind(id).execute(&h.app.db).await.unwrap();
2811
    write(work.path(), "README", "again\n");
2812
    c.commit("Again", &[]).unwrap();
2813
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2814
    let mut next = None;
2815
    for _ in 0..100 {
2816
        if let Some(j) = claim(&h.app).await {
2817
            next = Some(j);
2818
            break;
2819
        }
2820
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2821
    }
2822
    let next = next.expect("the second run's job");
2823
    assert_eq!(next["expected_ms"], 42_000, "{next}");
2824
}
2825
2826
/// oxygenhub#113: a job's artifact named `coverage` (LCOV) is read when
2827
/// it is uploaded. The job's log says what it found; the Coverage tab,
2828
/// the file view, the badge and the run page show it.
2829
#[tokio::test(flavor = "multi_thread")]
2830
async fn a_coverage_artifact_becomes_a_coverage_report() {
2831
    let h = hub().await;
2832
    create(&h.app, "andy", "cov").await;
2833
    let url = format!("{}/andy/cov", h.base);
2834
    let work = tempfile::tempdir().unwrap();
2835
    let c = client(&url, work.path());
2836
    write(
2837
        work.path(),
2838
        ".flow/pipeline.kdl",
2839
        &format!(
2840
            "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"
2841
        ),
2842
    );
2843
    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");
2844
    c.snapshot("test").unwrap();
2845
    c.commit("Code and coverage", &[]).unwrap();
2846
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2847
    let run = runs_of(&h.app, "andy", "cov").await.remove(0);
2848
    assert!(!call(&h.app, "GET", "/andy/cov", None, None).await.1.contains(">Reports</a>"), "no tab before a report");
2849
    let id = claim(&h.app).await.unwrap()["job_id"].as_i64().unwrap();
2850
2851
    let (st, text) = upload(&h.app, id, "coverage", b"this is not a report").await;
2852
    assert_eq!(st, StatusCode::OK, "a bad report never fails the upload: {text}");
2853
    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\
2854
SF:/src/src/gone.rs\nDA:1,1\nend_of_record\nSF:/usr/lib/rustlib/x.rs\nDA:1,1\nend_of_record\n";
2855
    let (st, text) = upload(&h.app, id, "coverage", lcov.as_bytes()).await;
2856
    assert_eq!(st, StatusCode::OK, "{text}");
2857
    let log: Vec<String> = db::flow::log(&h.app.db, id, 0, 50).await.unwrap().into_iter().map(|l| l.text).collect();
2858
    assert!(log.iter().any(|l| l.contains("coverage: this is not an LCOV report")), "{log:?}");
2859
    assert!(
2860
        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)"),
2861
        "{log:?}"
2862
    );
2863
2864
    let (st, page) = call(&h.app, "GET", "/andy/cov/coverage", None, None).await;
2865
    assert_eq!(st, StatusCode::OK);
2866
    assert!(
2867
        page.contains(">Reports</a>")
2868
            && page.contains("50.0%")
2869
            && page.contains("<strong>2</strong> of <strong>4</strong> relevant lines covered"),
2870
        "{page}"
2871
    );
2872
    assert!(page.contains("1 of 2") && page.contains("/andy/cov/coverage/") && page.contains("/file/src/lib.rs"), "{page}");
2873
    let report = crate_report(&h.app, run.id).await;
2874
    let (st, file) = call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/lib.rs"), None, None).await;
2875
    assert_eq!(st, StatusCode::OK, "{file}");
2876
    assert_eq!(file.matches("class=\"cov-hit\"").count(), 2, "{file}");
2877
    assert_eq!(file.matches("class=\"cov-miss\"").count(), 2, "{file}");
2878
    assert!(file.contains("3×"), "{file}");
2879
    assert_eq!(call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/gone.rs"), None, None).await.0, StatusCode::NOT_FOUND);
2880
    let (_, badge) = call(&h.app, "GET", "/andy/cov/coverage/badge.svg", None, None).await;
2881
    assert!(badge.contains("coverage: 50.0%"), "{badge}");
2882
    let (_, run_page) = call(&h.app, "GET", &format!("/andy/cov/flow/{}", run.number), None, None).await;
2883
    assert!(run_page.contains("coverage 50.0%"), "{run_page}");
2884
    // The API (#113).
2885
    let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/cov/coverage", None, None).await;
2886
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
2887
    assert_eq!((list[0]["percent"].as_f64(), list[0]["format"].as_str()), (Some(50.0), Some("lcov")), "{list}");
2888
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/cov/coverage/{report}"), None, None).await;
2889
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
2890
    assert_eq!((one["files"][0]["path"].as_str(), one["files"][0]["lines_hit"].as_i64()), (Some("src/lib.rs"), Some(2)), "{one}");
2891
2892
    // The `coverage` check on the run's state: it reports, and with a
2893
    // minimum the repository sets, it fails below it.
2894
    let row = db::repos::get(&h.app.db, "andy", "cov").await.unwrap().unwrap();
2895
    let check = |checks: Vec<db::hooks::Check>| checks.into_iter().find(|c| c.name == "coverage").expect("a coverage check");
2896
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
2897
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "50.0%"));
2898
    assert!(c.url.ends_with(&format!("/andy/cov/coverage?report={report}")), "{}", c.url);
2899
    oxygenhub::coverage::set_rules(&h.app.db, row.id, oxygenhub::coverage::Rules { min: Some(60.0), max_drop: None }).await.unwrap();
2900
    assert_eq!(upload(&h.app, id, "coverage", lcov.as_bytes()).await.0, StatusCode::OK);
2901
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
2902
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "50.0%: below the minimum of 60%"));
2903
}
2904
2905
async fn crate_report(app: &Shared, run_id: i64) -> i64 {
2906
    oxygenhub::coverage::for_run(&app.db, run_id).await.unwrap()[0].id
2907
}
2908
2909
/// The Tests tab (#114): three runs' JUnit reports on a bookmark; a test
2910
/// breaks in the second and is fixed in the third.
2911
#[tokio::test(flavor = "multi_thread")]
2912
async fn junit_reports_make_a_tests_tab() {
2913
    let h = hub().await;
2914
    create(&h.app, "andy", "t").await;
2915
    let url = format!("{}/andy/t", h.base);
2916
    let work = tempfile::tempdir().unwrap();
2917
    let c = client(&url, work.path());
2918
    write(
2919
        work.path(),
2920
        ".flow/pipeline.kdl",
2921
        &format!(
2922
            "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"
2923
        ),
2924
    );
2925
    assert!(!call(&h.app, "GET", "/andy/t", None, None).await.1.contains(">Reports</a>"));
2926
    let case = |name: &str, ok: bool, secs: &str| {
2927
        if ok {
2928
            format!(r#"<testcase classname="t.suite" name="{name}" time="{secs}"/>"#)
2929
        } else {
2930
            format!(
2931
                r#"<testcase classname="t.suite" name="{name}" time="{secs}"><failure message="{name} broke">AssertionError</failure></testcase>"#
2932
            )
2933
        }
2934
    };
2935
    let runs = [
2936
        vec![case("a", true, "0.1"), case("b", true, "2.5"), case("c", true, "0.2")],
2937
        vec![case("a", true, "0.1"), case("b", false, "2.6"), case("c", true, "0.2"), case("d", true, "0.3")],
2938
        vec![case("a", true, "0.1"), case("b", true, "2.4"), case("c", true, "0.2"), case("d", true, "0.3")],
2939
    ];
2940
    for (i, cases) in runs.iter().enumerate() {
2941
        write(work.path(), "n.txt", &i.to_string());
2942
        c.snapshot("test").unwrap();
2943
        c.commit(&format!("Run {i}"), &[]).unwrap();
2944
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2945
        // The run is made after the push answers.
2946
        let mut a = None;
2947
        for _ in 0..100 {
2948
            a = claim(&h.app).await;
2949
            if a.is_some() {
2950
                break;
2951
            }
2952
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2953
        }
2954
        let a = a.expect("a job to claim");
2955
        let id = a["job_id"].as_i64().unwrap();
2956
        let xml = format!("<testsuites><testsuite name=\"t\">{}</testsuite></testsuites>", cases.concat());
2957
        assert_eq!(upload(&h.app, id, "junit", xml.as_bytes()).await.0, StatusCode::OK);
2958
        let failed = cases.iter().any(|c| c.contains("<failure"));
2959
        let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), failed as u32);
2960
        if !failed {
2961
            r["outputs"] = serde_json::json!([oxy_core::repo::Repo::blob_ref(xml.as_bytes()).to_hex()]);
2962
        }
2963
        let code = failed as i32;
2964
        assert_eq!(
2965
            finish(&h.app, id, serde_json::json!({ "exit_code": code, "duration_ms": 700, "receipt": r })).await,
2966
            StatusCode::NO_CONTENT
2967
        );
2968
    }
2969
    let (st, page) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
2970
    assert_eq!(st, StatusCode::OK, "{page}");
2971
    if let Some(out) = std::env::var_os("OXYHUB_DUMP_TESTS_PAGE") {
2972
        std::fs::write(out, &page).unwrap();
2973
    }
2974
    assert!(page.contains(">Reports</a>"), "the tab");
2975
    assert!(page.contains("100%") && page.contains("of 4 tests passed"), "the latest run passes");
2976
    assert!(page.contains("1 fixed") && page.contains("t.suite::b"), "b fixed against the run before");
2977
    assert!(page.contains("1 ✕") && page.contains("2 ✓"), "b is flaky: {page}");
2978
    assert!(page.contains("<svg class=\"cov-chart\""), "charts");
2979
    // The slowest first.
2980
    let slow = page.find("Slowest tests").unwrap();
2981
    assert!(page[slow..].find("t.suite::b").unwrap() < page[slow..].find("t.suite::d").unwrap());
2982
    // The second run, picked: b newly failing, its failure listed.
2983
    let row = db::repos::get(&h.app.db, "andy", "t").await.unwrap().unwrap();
2984
    let second = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap()[1].id;
2985
    let (_, page) = call(&h.app, "GET", &format!("/andy/t/tests?report={second}"), None, None).await;
2986
    assert!(page.contains("1 failing") && page.contains("Newly failing") && page.contains("b broke"), "{page}");
2987
    assert!(page.contains("1 new tests"), "d is new");
2988
2989
    // The API (#114): the bookmark's reports newest first, and one with
2990
    // its failed cases.
2991
    let (st, list) = call(&h.app, "GET", "/api/v1/repos/andy/t/tests", None, None).await;
2992
    assert_eq!(st, StatusCode::OK, "{list}");
2993
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
2994
    assert_eq!(list.as_array().unwrap().len(), 3);
2995
    assert_eq!((list[0]["tests"].as_i64(), list[1]["failed"].as_i64()), (Some(4), Some(1)));
2996
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}?status=failed"), None, None).await;
2997
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
2998
    assert_eq!(one["cases"].as_array().unwrap().len(), 1);
2999
    assert_eq!((one["cases"][0]["name"].as_str(), one["cases"][0]["message"].as_str()), (Some("b"), Some("b broke")));
3000
    let (_, all) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}"), None, None).await;
3001
    assert_eq!(serde_json::from_str::<serde_json::Value>(&all).unwrap()["cases"].as_array().unwrap().len(), 4);
3002
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/t/tests/99999", None, None).await.0, StatusCode::NOT_FOUND);
3003
3004
    // The `tests` check names what broke against main.
3005
    let reports = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap();
3006
    let check = |state: String| {
3007
        let app = h.app.clone();
3008
        async move { db::hooks::checks_for_state(&app.db, row.id, &state).await.unwrap().into_iter().find(|c| c.name == "tests").unwrap() }
3009
    };
3010
    let c = check(reports[1].state.clone()).await;
3011
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "1 failing; 1 new against main: t.suite::b"));
3012
    let c = check(reports[0].state.clone()).await;
3013
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "4 passed"));
3014
3015
    // One test's history: b passed, failed, passed.
3016
    let (_, tab) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
3017
    assert!(
3018
        tab.contains("/andy/t/tests/case?classname=t.suite&amp;name=b") || tab.contains("/andy/t/tests/case?classname=t.suite&name=b"),
3019
        "linked"
3020
    );
3021
    let (st, hist) = call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=b", None, None).await;
3022
    assert_eq!(st, StatusCode::OK, "{hist}");
3023
    assert!(hist.contains("2 passed") && hist.contains("1 failed") && hist.contains("b broke"), "{hist}");
3024
    assert_eq!(call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=nope", None, None).await.0, StatusCode::NOT_FOUND);
3025
}
3026
3027
/// oxygenhub#28: a queued job no runner can take says why, in the API, on
3028
/// the run page (its panel open) and in its check.
3029
#[tokio::test(flavor = "multi_thread")]
3030
async fn a_job_no_runner_can_take_says_why() {
3031
    let h = hub().await;
3032
    create(&h.app, "andy", "demo").await;
3033
    let url = format!("{}/andy/demo", h.base);
3034
    let work = tempfile::tempdir().unwrap();
3035
    let c = client(&url, work.path());
3036
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3037
    write(work.path(), "test.sh", "echo ok\n");
3038
    c.commit("Add a pipeline", &[]).unwrap();
3039
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3040
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
3041
3042
    // One runner, online, holding another image only.
3043
    let r = db::runners::configured(&h.app.db, &blake3::hash(b"elsewhere").to_hex(), "earth-9").await.unwrap();
3044
    db::runners::seen(&h.app.db, r.id, None, None).await.unwrap();
3045
    let other = "ab".repeat(32);
3046
    db::runners::set_offer(&h.app.db, r.id, &["microvm".to_string()], Some(&[other]), false, "p").await.unwrap();
3047
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3048
3049
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
3050
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
3051
    let build = v["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "build").unwrap().clone();
3052
    let why = build["waiting"].as_str().unwrap_or_default().to_string();
3053
    assert!(why.contains("earth-9 does not hold image") && why.contains(&ROOTFS[..12]), "{body}");
3054
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/1", None, None).await;
3055
    assert!(page.contains("data-waiting") && page.contains("does not hold image"), "the run page says it");
3056
    // The check says it too. The hub's own placement pass runs beside this
3057
    // test's: if it lands a reading from before the runner's offer, the
3058
    // next pass puts it right.
3059
    let mut summary = String::new();
3060
    for _ in 0..40 {
3061
        let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
3062
        summary = checks.iter().find(|c| c.name == "flow/build").unwrap().summary.clone();
3063
        if summary.contains("does not hold image") {
3064
            break;
3065
        }
3066
        let build = db::flow::jobs(&h.app.db, run.id).await.unwrap().into_iter().find(|j| j.name == "build").unwrap();
3067
        db::flow::set_waiting(&h.app.db, build.id, "").await.unwrap();
3068
        oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3069
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3070
    }
3071
    assert!(summary.contains("does not hold image"), "{summary}");
3072
}
3073
3074
/// A job a runner could take but that still waits says why (#259): the
3075
/// runners that can take it are busy, or have a free slot without the room
3076
/// for it; and how many ready jobs come first.
3077
#[tokio::test(flavor = "multi_thread")]
3078
async fn a_job_waiting_for_a_busy_runner_says_so() {
3079
    let h = hub().await;
3080
    create(&h.app, "andy", "demo").await;
3081
    let url = format!("{}/andy/demo", h.base);
3082
    let work = tempfile::tempdir().unwrap();
3083
    let c = client(&url, work.path());
3084
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3085
    write(work.path(), "test.sh", "echo ok\n");
3086
    c.commit("Add a pipeline", &[]).unwrap();
3087
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3088
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
3089
    // One runner holding the image, its one slot taken by lint.
3090
    let r = db::runners::configured(&h.app.db, &blake3::hash(b"busy").to_hex(), "earth-9").await.unwrap();
3091
    db::runners::seen(&h.app.db, r.id, None, None).await.unwrap();
3092
    db::runners::set_offer(&h.app.db, r.id, &["microvm".to_string()], Some(&[ROOTFS.to_string()]), false, "p").await.unwrap();
3093
    sqlx::query(
3094
        "UPDATE flow_jobs SET status = 'running', runner_id = $1, runner = 'earth-9', started_ms = $2 WHERE run_id = $3 AND name = 'lint'",
3095
    )
3096
    .bind(r.id)
3097
    .bind(db::now_ms())
3098
    .bind(run.id)
3099
    .execute(&h.app.db)
3100
    .await
3101
    .unwrap();
3102
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3103
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
3104
    let build = jobs.iter().find(|j| j.name == "build").unwrap();
3105
    assert!(build.waiting.contains("the runners that can take it are busy: earth-9 busy (1 of 1)"), "{}", build.waiting);
3106
    // A second slot it hasn't used: free, but not the room for this job.
3107
    sqlx::query("UPDATE flow_runners SET max_jobs = 2 WHERE id = $1").bind(r.id).execute(&h.app.db).await.unwrap();
3108
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3109
    let build = db::flow::jobs(&h.app.db, run.id).await.unwrap().into_iter().find(|j| j.name == "build").unwrap();
3110
    assert!(build.waiting.contains("earth-9 has a free slot (1 of 2) but not the memory, CPUs or disk for it now"), "{}", build.waiting);
3111
}
3112
3113
/// #291: expediting a run places the queue again at once, and a job it
3114
/// moved down says which expedited run went before it.
3115
#[tokio::test(flavor = "multi_thread")]
3116
async fn an_expedited_run_moves_the_queue_at_once() {
3117
    let h = hub().await;
3118
    for name in ["first", "urgent"] {
3119
        create(&h.app, "andy", name).await;
3120
        let work = tempfile::tempdir().unwrap();
3121
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
3122
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3123
        write(work.path(), "test.sh", "echo ok\n");
3124
        c.commit("Add a pipeline", &[]).unwrap();
3125
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3126
        // In order: the second run is the newer.
3127
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
3128
    }
3129
    // One runner holding the image, busy with something else.
3130
    let r = db::runners::configured(&h.app.db, &blake3::hash(b"busy").to_hex(), "earth-9").await.unwrap();
3131
    db::runners::seen(&h.app.db, r.id, None, None).await.unwrap();
3132
    db::runners::set_offer(&h.app.db, r.id, &["microvm".to_string()], Some(&[ROOTFS.to_string()]), false, "p").await.unwrap();
3133
    let first = runs_of(&h.app, "andy", "first").await.remove(0);
3134
    sqlx::query(
3135
        "UPDATE flow_jobs SET status = 'running', runner_id = $1, runner = 'earth-9', started_ms = $2 WHERE run_id = $3 AND name = 'lint'",
3136
    )
3137
    .bind(r.id)
3138
    .bind(db::now_ms())
3139
    .bind(first.id)
3140
    .execute(&h.app.db)
3141
    .await
3142
    .unwrap();
3143
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3144
    let db = h.app.db.clone();
3145
    let build = |run: i64| {
3146
        let db = db.clone();
3147
        async move { db::flow::jobs(&db, run).await.unwrap().into_iter().find(|j| j.name == "build").unwrap() }
3148
    };
3149
    let urgent = runs_of(&h.app, "andy", "urgent").await.remove(0);
3150
    assert!(build(urgent.id).await.waiting.contains("1 ready job comes first"), "{}", build(urgent.id).await.waiting);
3151
3152
    // Expedited from its page: the places change before any pass runs.
3153
    let res = oxygenhub::router(h.app.clone())
3154
        .oneshot(
3155
            Request::post("/register")
3156
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
3157
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
3158
                .unwrap(),
3159
        )
3160
        .await
3161
        .unwrap();
3162
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
3163
    let page = oxygenhub::router(h.app.clone())
3164
        .oneshot(Request::get("/andy/urgent/flow/1").header(header::COOKIE, cookie.clone()).body(Body::empty()).unwrap())
3165
        .await
3166
        .unwrap();
3167
    let page = String::from_utf8_lossy(&page.into_body().collect().await.unwrap().to_bytes()).into_owned();
3168
    let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
3169
    let csrf = page[i..].split('"').next().unwrap().to_string();
3170
    let res = oxygenhub::router(h.app.clone())
3171
        .oneshot(
3172
            Request::post("/andy/urgent/flow/1/expedite")
3173
                .header(header::COOKIE, cookie.clone())
3174
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
3175
                .body(Body::from(format!("_csrf={csrf}&reason=incident")))
3176
                .unwrap(),
3177
        )
3178
        .await
3179
        .unwrap();
3180
    assert!(res.status().is_redirection(), "{}", res.status());
3181
    assert!(!build(urgent.id).await.waiting.contains("come"), "first now: {}", build(urgent.id).await.waiting);
3182
    let w = build(first.id).await.waiting;
3183
    assert!(w.contains("2 ready jobs come first (after expedited run andy/urgent #1)"), "{w}");
3184
3185
    // And over the API (oxygenhub-android#5): a reason is needed; then the
3186
    // first run is urgent too, within the cap of two.
3187
    let andy = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap();
3188
    let (token, hash) = oxygenhub::auth::new_token();
3189
    db::accounts::create_token(&h.app.db, andy.id, "phone", &hash, "repo:read,repo:write", "", None).await.unwrap();
3190
    let url = format!("/api/v1/repos/andy/first/flow/runs/{}/expedite", first.number);
3191
    let (st, body) = call(&h.app, "POST", &url, Some(&token), Some(r#"{"reason":"  "}"#.into())).await;
3192
    assert_eq!(st, StatusCode::CONFLICT, "{body}");
3193
    assert!(body.contains("Say why the run is urgent."), "{body}");
3194
    let (st, body) = call(&h.app, "POST", &url, Some(&token), Some(r#"{"reason":"the fix for the outage"}"#.into())).await;
3195
    assert_eq!(st, StatusCode::OK, "{body}");
3196
    let run = db::flow::run(&h.app.db, first.repo_id, first.number).await.unwrap().unwrap();
3197
    assert!(
3198
        run.priority == "urgent" && run.priority_note.contains("expedited by andy: the fix for the outage"),
3199
        "{} {}",
3200
        run.priority,
3201
        run.priority_note
3202
    );
3203
}
3204
3205
async fn put_bytes(app: &Shared, path: &str, bearer: &str, bytes: Vec<u8>) -> (StatusCode, String) {
3206
    let req = Request::put(path)
3207
        .header(header::AUTHORIZATION, format!("Bearer {bearer}"))
3208
        .header(header::CONTENT_TYPE, "application/octet-stream")
3209
        .body(Body::from(bytes))
3210
        .unwrap();
3211
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
3212
    let st = res.status();
3213
    (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
3214
}
3215
3216
/// oxygenflow#39: an image is sent as the chunks the hub lacks and then its
3217
/// manifest, checked against its hash; runners fetch it; and a job whose
3218
/// image only the hub holds is offered to a runner that fetches, not to one
3219
/// that does not.
3220
/// oxygenflow#94, #342: a runner sends the manifest of an image it holds
3221
/// that the hub lacks; the hub keeps it as held by runners only (no chunks,
3222
/// announce says it is no seed) until the image is pushed whole.
3223
#[tokio::test(flavor = "multi_thread")]
3224
async fn a_runner_offers_the_manifest_of_an_image_the_hub_lacks() {
3225
    let h = hub().await;
3226
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3227
    let image: Vec<u8> = (0..300_000u32).map(|i| (i % 241) as u8).collect();
3228
    let mut chunks = std::collections::HashMap::new();
3229
    let m = jet::images::scan(&image[..], Some("x86_64".into()), |c, b| {
3230
        chunks.insert(c.hash().to_string(), b.to_vec());
3231
        Ok(())
3232
    })
3233
    .unwrap();
3234
    let hash = m.hash.clone();
3235
    // Asked which of its images the hub lacks: this one.
3236
    let held = serde_json::json!({ "images": [hash.clone(), "not-a-hash"] }).to_string();
3237
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/images/held", Some("runner-secret"), Some(held.clone())).await;
3238
    assert_eq!(st, StatusCode::OK, "{body}");
3239
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["wanted"], serde_json::json!([hash.clone()]));
3240
    // Only runners may say so.
3241
    assert_ne!(call(&h.app, "POST", "/api/v1/flow/images/held", Some("site"), Some(held.clone())).await.0, StatusCode::OK);
3242
    // A manifest filed under another hash is refused; its own is kept as peer-held.
3243
    let manifest = serde_json::to_string(&m).unwrap();
3244
    let wrong = format!("/api/v1/flow/images/{}/held", "ab".repeat(32));
3245
    assert_eq!(call(&h.app, "PUT", &wrong, Some("runner-secret"), Some(manifest.clone())).await.0, StatusCode::BAD_REQUEST);
3246
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}/held"), Some("runner-secret"), Some(manifest.clone())).await;
3247
    assert_eq!(st, StatusCode::CREATED, "{body}");
3248
    let kept = oxygenhub::images::kept(&h.app.db).await.unwrap();
3249
    let row = kept.iter().find(|k| k.hash == hash).expect("recorded");
3250
    assert_eq!(row.source, "peer");
3251
    let (_, body) = call(&h.app, "POST", "/api/v1/flow/images/held", Some("runner-secret"), Some(held)).await;
3252
    assert!(body.contains("\"wanted\":[]"), "{body}");
3253
    // Runners fetch its manifest; the hub has none of its chunks.
3254
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), Some("runner-secret"), None).await;
3255
    assert_eq!(st, StatusCode::OK);
3256
    let first = m.needed()[0].to_string();
3257
    assert_ne!(call(&h.app, "GET", &format!("/api/v1/flow/images/chunks/{first}"), Some("runner-secret"), None).await.0, StatusCode::OK);
3258
    let reach = oxygenhub::images::reach(&h.app).await.unwrap();
3259
    assert!(reach.peer_only(&hash));
3260
    // Pushed whole, it becomes the hub's.
3261
    for c in m.needed() {
3262
        let (st, body) = put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
3263
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
3264
    }
3265
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest)).await;
3266
    assert_eq!(st, StatusCode::CREATED, "{body}");
3267
    let kept = oxygenhub::images::kept(&h.app.db).await.unwrap();
3268
    assert_eq!(kept.iter().find(|k| k.hash == hash).unwrap().source, "hub");
3269
    assert!(!oxygenhub::images::reach(&h.app).await.unwrap().peer_only(&hash));
3270
}
3271
3272
#[tokio::test(flavor = "multi_thread")]
3273
async fn images_are_sent_by_chunk_and_offered_to_runners_that_fetch() {
3274
    let h = hub().await;
3275
    // The site token acts as the first site administrator.
3276
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3277
    // An image: bytes, a run of zeros, more bytes.
3278
    let mut image: Vec<u8> = (0..400_000u32).map(|i| (i % 251) as u8).collect();
3279
    image.extend(std::iter::repeat_n(0u8, 2 << 20));
3280
    image.extend((0..100_000u32).map(|i| (i % 239) as u8));
3281
    let mut chunks = std::collections::HashMap::new();
3282
    let m = jet::images::scan(&image[..], Some("x86_64".into()), |c, b| {
3283
        chunks.insert(c.hash().to_string(), b.to_vec());
3284
        Ok(())
3285
    })
3286
    .unwrap();
3287
    let hash = m.hash.clone();
3288
3289
    // Which chunks the hub lacks: every one but zeros; a manifest before them is refused.
3290
    let ask = serde_json::json!({ "chunks": m.needed() }).to_string();
3291
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask.clone())).await;
3292
    assert_eq!(st, StatusCode::OK, "{body}");
3293
    let missing: Vec<String> = serde_json::from_str::<serde_json::Value>(&body).unwrap()["missing"]
3294
        .as_array()
3295
        .unwrap()
3296
        .iter()
3297
        .map(|v| v.as_str().unwrap().to_string())
3298
        .collect();
3299
    assert_eq!(missing.len(), m.needed().len());
3300
    let manifest = serde_json::to_string(&m).unwrap();
3301
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest.clone())).await;
3302
    assert!(st == StatusCode::CONFLICT && body.contains("was not sent"), "{st} {body}");
3303
    // A chunk is checked against its name; a runner token may not send.
3304
    let first = &missing[0];
3305
    assert_eq!(put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "site", vec![1, 2, 3]).await.0, StatusCode::BAD_REQUEST);
3306
    assert_ne!(
3307
        put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "runner-secret", chunks[first].clone()).await.0,
3308
        StatusCode::NO_CONTENT
3309
    );
3310
    for c in &missing {
3311
        let (st, body) = put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
3312
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
3313
    }
3314
    let (_, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask)).await;
3315
    assert!(body.contains("\"missing\":[]"), "{body}");
3316
    // A large image's question fits (#147): 60,000 names, ~4 MB of JSON.
3317
    let many: Vec<String> = (0..60_000u32).map(|i| blake3::hash(&i.to_le_bytes()).to_hex().to_string()).collect();
3318
    let (st, body) =
3319
        call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(serde_json::json!({ "chunks": many }).to_string())).await;
3320
    assert_eq!(st, StatusCode::OK, "{}", &body[..body.len().min(200)]);
3321
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["missing"].as_array().unwrap().len(), 60_000);
3322
    // A manifest naming another hash is refused; the right one is kept.
3323
    let mut wrong = m.clone();
3324
    wrong.hash = "ab".repeat(32);
3325
    let (st, _) =
3326
        call(&h.app, "PUT", &format!("/api/v1/flow/images/{}", wrong.hash), Some("site"), Some(serde_json::to_string(&wrong).unwrap()))
3327
            .await;
3328
    assert_eq!(st, StatusCode::CONFLICT, "chunks that make another image");
3329
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest.clone())).await;
3330
    assert_eq!(st, StatusCode::CREATED, "{body}");
3331
    // #341: a sender that gave up during the check left the manifest kept
3332
    // but no row; sending it again records it without reading the image
3333
    // again (a chunk gone from disk would fail a second check).
3334
    sqlx::query("DELETE FROM jet_images").execute(&h.app.db).await.unwrap();
3335
    let gone = h.app.config.data.join("images/chunks").join(&missing[0][..2]).join(&missing[0]);
3336
    let kept = std::fs::read(&gone).unwrap();
3337
    std::fs::remove_file(&gone).unwrap();
3338
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest)).await;
3339
    assert_eq!(st, StatusCode::CREATED, "{body}");
3340
    assert!(oxygenhub::images::held(&h.app.db).await.unwrap().contains(&hash));
3341
    std::fs::write(&gone, kept).unwrap();
3342
3343
    // A runner fetches the manifest and the chunks, and the image comes back whole.
3344
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), Some("runner-secret"), None).await;
3345
    assert_eq!(st, StatusCode::OK, "{body}");
3346
    let got: jet::images::Manifest = serde_json::from_str(&body).unwrap();
3347
    assert_eq!(got, m);
3348
    let dir = tempfile::tempdir().unwrap();
3349
    let out = dir.path().join("img.ext4");
3350
    let mut fetched = Vec::new();
3351
    for c in got.needed() {
3352
        let req = Request::get(format!("/api/v1/flow/images/chunks/{c}"))
3353
            .header(header::AUTHORIZATION, "Bearer runner-secret")
3354
            .body(Body::empty())
3355
            .unwrap();
3356
        let res = oxygenhub::router(h.app.clone()).oneshot(req).await.unwrap();
3357
        assert_eq!(res.status(), StatusCode::OK);
3358
        let bytes = res.into_body().collect().await.unwrap().to_bytes().to_vec();
3359
        fetched.push((c.to_string(), bytes));
3360
    }
3361
    jet::images::assemble(&got, &out, |c| Ok(fetched.iter().find(|(h, _)| h == c.hash()).unwrap().1.clone())).unwrap();
3362
    assert_eq!(std::fs::read(&out).unwrap(), image);
3363
    assert_eq!(
3364
        call(&h.app, "GET", &format!("/api/v1/flow/images/{}", "cd".repeat(32)), Some("runner-secret"), None).await.0,
3365
        StatusCode::NOT_FOUND
3366
    );
3367
    assert_ne!(call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), None, None).await.0, StatusCode::OK, "not anonymous");
3368
3369
    // A job on that image: a runner holding no images and not fetching
3370
    // is offered nothing; one that fetches is offered it.
3371
    create(&h.app, "andy", "demo").await;
3372
    let url = format!("{}/andy/demo", h.base);
3373
    let work = tempfile::tempdir().unwrap();
3374
    let c = client(&url, work.path());
3375
    write(
3376
        work.path(),
3377
        ".flow/pipeline.kdl",
3378
        &format!("schema-version 1\nsandbox \"img\" {{\n    rootfs \"cas://blob/{hash}\"\n}}\njob \"build\" {{\n    sandbox \"img\"\n    exec \"make\"\n}}\n"),
3379
    );
3380
    c.commit("Build on the image", &[]).unwrap();
3381
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3382
    runs_of(&h.app, "andy", "demo").await;
3383
    // #137: the run's images are held (by the hub), so no images check.
3384
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
3385
    let run1 = db::flow::run(&h.app.db, row.id, 1).await.unwrap().unwrap();
3386
    let checks = checks_when(&h.app, row.id, &run1.state, 1).await;
3387
    assert!(checks.iter().all(|c| c.name != "pipeline/images"), "{checks:?}");
3388
    let ask = |fetches: bool| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":[],"fetches_images":{fetches}}}"#);
3389
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(false))).await;
3390
    assert_eq!(st, StatusCode::NO_CONTENT, "it lacks the image and does not fetch");
3391
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3392
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
3393
    assert!(body.contains("does not hold image"), "{body}");
3394
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(true))).await;
3395
    assert_eq!(st, StatusCode::OK, "it fetches, and the hub holds the image: {body}");
3396
    // oxygenhub#135: once claimed, the old waiting reason is gone.
3397
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
3398
    assert!(!body.contains("waiting"), "a running job keeps no waiting reason: {body}");
3399
}
3400
3401
/// oxygenhub#136: coverage measured on a workstation is uploaded for a
3402
/// bookmark's state, kept as uploaded by its account, shown so, and sets
3403
/// no check.
3404
#[tokio::test(flavor = "multi_thread")]
3405
async fn coverage_uploaded_from_a_workstation_says_so() {
3406
    let h = hub().await;
3407
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3408
    create(&h.app, "andy", "vk").await;
3409
    let url = format!("{}/andy/vk", h.base);
3410
    let work = tempfile::tempdir().unwrap();
3411
    let c = client(&url, work.path());
3412
    write(work.path(), "src/game.c", "int a;\nint b;\nint c;\nint d;\n");
3413
    c.commit("Game", &[]).unwrap();
3414
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3415
3416
    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";
3417
    let body = serde_json::json!({ "bookmark": "main", "content": lcov }).to_string();
3418
    let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", Some("site"), Some(body)).await;
3419
    assert_eq!(st, StatusCode::CREATED, "{out}");
3420
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
3421
    assert_eq!((v["uploaded_by"].as_str(), v["lines_hit"].as_i64(), v["lines_found"].as_i64()), (Some("andy"), Some(3), Some(4)));
3422
    assert_eq!(v["dropped"], 1, "a file outside the state is left out");
3423
    assert_eq!(v["bookmark"], "main");
3424
3425
    let (_, page) = call(&h.app, "GET", "/andy/vk/coverage", None, None).await;
3426
    assert!(page.contains("uploaded by andy") && page.contains("75.0%"), "the Coverage page says where it came from");
3427
    let (_, page) = call(&h.app, "GET", "/andy/vk/reports", None, None).await;
3428
    assert!(page.contains("uploaded by andy"), "and the Reports card");
3429
    let row = db::repos::get(&h.app.db, "andy", "vk").await.unwrap().unwrap();
3430
    let state = v["state"].as_str().unwrap();
3431
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, state).await.unwrap();
3432
    assert!(checks.iter().all(|c| c.name != "coverage"), "an upload sets no check: {checks:?}");
3433
3434
    // Readers cannot upload; bad reports and bookmarks are refused.
3435
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", None, Some(r#"{"content":"x"}"#.into())).await;
3436
    assert_ne!(st, StatusCode::CREATED);
3437
    let (st, _) = call(
3438
        &h.app,
3439
        "POST",
3440
        "/api/v1/repos/andy/vk/coverage",
3441
        Some("site"),
3442
        Some(r#"{"bookmark":"nope","content":"SF:a\nend_of_record\n"}"#.into()),
3443
    )
3444
    .await;
3445
    assert_eq!(st, StatusCode::BAD_REQUEST);
3446
}
3447
3448
/// oxygenflow#40: what a runner measured at its claim is kept and shown.
3449
#[tokio::test(flavor = "multi_thread")]
3450
async fn a_runners_facts_are_kept_from_its_claim() {
3451
    let h = hub().await;
3452
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3453
    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"}}"#;
3454
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.into())).await;
3455
    assert_eq!(st, StatusCode::NO_CONTENT, "nothing to run, but the facts are kept");
3456
    let (st, out) = call(&h.app, "GET", "/api/v1/runners", Some("site"), None).await;
3457
    assert_eq!(st, StatusCode::OK, "{out}");
3458
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
3459
    let r = &v[0];
3460
    assert_eq!(
3461
        (r["speed"].as_i64(), r["speed_class"].as_i64(), r["free_disk_mib"].as_i64(), r["load_x100"].as_i64()),
3462
        (Some(100), Some(3), Some(42000), Some(112))
3463
    );
3464
    let row = db::runners::list(&h.app.db).await.unwrap().remove(0);
3465
    assert_eq!(row.facts_line(), "speed 100 (class 3) · load 1.12 · 41 GiB free");
3466
}
3467
3468
/// oxygenflow#41: a job's peaks set what its next run needs; a runner
3469
/// without that much free disk is not offered it, and the reason says so.
3470
#[tokio::test(flavor = "multi_thread")]
3471
async fn a_jobs_next_run_needs_the_disk_its_last_took() {
3472
    let h = hub().await;
3473
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3474
    create(&h.app, "andy", "demo").await;
3475
    let url = format!("{}/andy/demo", h.base);
3476
    let work = tempfile::tempdir().unwrap();
3477
    let c = client(&url, work.path());
3478
    write(
3479
        work.path(),
3480
        ".flow/pipeline.kdl",
3481
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
3482
    );
3483
    c.commit("Build", &[]).unwrap();
3484
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3485
    runs_of(&h.app, "andy", "demo").await;
3486
    let claim_with = |free: u64| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"facts":{{"free_disk_mib":{free}}}}}"#);
3487
3488
    // The first run has nothing to learn from: any runner takes it.
3489
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(500))).await;
3490
    assert_eq!(st, StatusCode::OK, "{body}");
3491
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
3492
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 10, "peak_disk_mib": 8000, "peak_memory_mib": 900 });
3493
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
3494
    let job = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
3495
    assert_eq!((job.peak_disk_mib, job.peak_memory_mib), (Some(8000), Some(900)));
3496
3497
    // The next run needs 8000 MiB and a quarter more.
3498
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
3499
    assert_eq!(st, StatusCode::CREATED);
3500
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
3501
    let run2 = db::flow::run(&h.app.db, repo.id, 2).await.unwrap().unwrap();
3502
    let next = db::flow::jobs(&h.app.db, run2.id).await.unwrap().remove(0);
3503
    assert_eq!(next.need_disk_mib, Some(8000 + 2000 + 64));
3504
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(9000))).await;
3505
    assert_eq!(st, StatusCode::NO_CONTENT, "9000 MiB free is not enough");
3506
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3507
    let waiting = db::flow::job(&h.app.db, next.id).await.unwrap().unwrap().waiting;
3508
    assert!(waiting.contains("8.8 GiB free; the job needs ~9.8 GiB"), "{waiting}");
3509
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(20_000))).await;
3510
    assert_eq!(st, StatusCode::OK, "a roomier runner takes it: {body}");
3511
}
3512
3513
/// oxygenflow#42: a job another free runner would do better (it holds the
3514
/// image) is held from a runner that would fetch it, the better runner
3515
/// takes it, and the job says why it ran there.
3516
#[tokio::test(flavor = "multi_thread")]
3517
async fn a_job_waits_briefly_for_a_runner_that_holds_its_image() {
3518
    let h = hub().await;
3519
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3520
    // A second runner, with a token of its own.
3521
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
3522
    let ask = |images: &str| {
3523
        format!(
3524
            r#"{{"runner":"r","runtimes":["microvm"],"images":[{images}],"fetches_images":true,"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
3525
        )
3526
    };
3527
    let holder = ask(&format!("\"{ROOTFS}\""));
3528
    // earth-9 holds the image and is polling; nothing is queued yet.
3529
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder.clone())).await;
3530
    assert_eq!(st, StatusCode::NO_CONTENT);
3531
    // The hub holds the image too, so test-1 could fetch it.
3532
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES ($1, 1, 'x86_64', 1, 'andy', 0)")
3533
        .bind(ROOTFS)
3534
        .execute(&h.app.db)
3535
        .await
3536
        .unwrap();
3537
3538
    create(&h.app, "andy", "demo").await;
3539
    let url = format!("{}/andy/demo", h.base);
3540
    let work = tempfile::tempdir().unwrap();
3541
    let c = client(&url, work.path());
3542
    write(
3543
        work.path(),
3544
        ".flow/pipeline.kdl",
3545
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
3546
    );
3547
    c.commit("Build", &[]).unwrap();
3548
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3549
    runs_of(&h.app, "andy", "demo").await;
3550
3551
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
3552
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner that holds the image");
3553
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
3554
    assert_eq!(st, StatusCode::OK, "{body}");
3555
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
3556
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
3557
    assert!(placed.starts_with("holds the image, idle, speed 100 (class 3)"), "{placed}");
3558
    assert!(placed.contains("held for a better runner"), "{placed}");
3559
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
3560
    assert!(body.contains("\"placed\":\"holds the image"), "{body}");
3561
}
3562
3563
/// oxygenflow#51: a job waits briefly for the runner holding its build
3564
/// cache, even when the other one holds its image too.
3565
#[tokio::test(flavor = "multi_thread")]
3566
async fn a_job_waits_briefly_for_the_runner_holding_its_build_cache() {
3567
    let h = hub().await;
3568
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3569
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
3570
    let slot = flow_core::api::cache_slot("andy/demo", "build");
3571
    let ask = |caches: &str| {
3572
        format!(
3573
            r#"{{"runner":"r","runtimes":["microvm"],"images":["{ROOTFS}"],"fetches_images":true,"caches":[{caches}],"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
3574
        )
3575
    };
3576
    let holder = ask(&format!("\"{slot}\""));
3577
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder.clone())).await;
3578
    assert_eq!(st, StatusCode::NO_CONTENT);
3579
3580
    create(&h.app, "andy", "demo").await;
3581
    let url = format!("{}/andy/demo", h.base);
3582
    let work = tempfile::tempdir().unwrap();
3583
    let c = client(&url, work.path());
3584
    write(
3585
        work.path(),
3586
        ".flow/pipeline.kdl",
3587
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
3588
    );
3589
    c.commit("Build", &[]).unwrap();
3590
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3591
    runs_of(&h.app, "andy", "demo").await;
3592
3593
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
3594
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner holding the build cache");
3595
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
3596
    assert_eq!(st, StatusCode::OK, "{body}");
3597
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
3598
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
3599
    assert!(placed.starts_with("holds its build cache, holds the image"), "{placed}");
3600
}
3601
3602
/// oxygenflow#54: when both runners hold a job's build cache, the job waits
3603
/// briefly for the one whose copy is fresher.
3604
#[tokio::test(flavor = "multi_thread")]
3605
async fn a_job_waits_briefly_for_the_fresher_build_cache() {
3606
    let h = hub().await;
3607
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3608
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
3609
    let slot = flow_core::api::cache_slot("andy/demo", "build");
3610
    let now = db::now_ms();
3611
    let ask = |kept: i64| {
3612
        format!(
3613
            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}}}}"#
3614
        )
3615
    };
3616
    // earth-9 kept its copy a minute ago; the other runner's is a day old.
3617
    let fresh = ask(now - 60_000);
3618
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(fresh.clone())).await;
3619
    assert_eq!(st, StatusCode::NO_CONTENT);
3620
3621
    create(&h.app, "andy", "demo").await;
3622
    let url = format!("{}/andy/demo", h.base);
3623
    let work = tempfile::tempdir().unwrap();
3624
    let c = client(&url, work.path());
3625
    write(
3626
        work.path(),
3627
        ".flow/pipeline.kdl",
3628
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
3629
    );
3630
    c.commit("Build", &[]).unwrap();
3631
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3632
    runs_of(&h.app, "andy", "demo").await;
3633
3634
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(now - 86_400_000))).await;
3635
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the fresher copy");
3636
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(fresh)).await;
3637
    assert_eq!(st, StatusCode::OK, "{body}");
3638
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
3639
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
3640
    assert!(placed.starts_with("holds its build cache (kept 1 min ago), holds the image"), "{placed}");
3641
}
3642
3643
/// oxygenhub#127 §3.3: report files expire beyond the newest 50 runs of a
3644
/// report on a bookmark other than the default; the default keeps all,
3645
/// and an expired report keeps its metrics.
3646
#[tokio::test(flavor = "multi_thread")]
3647
async fn report_files_expire_under_retention() {
3648
    let h = hub().await;
3649
    create(&h.app, "andy", "demo").await;
3650
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
3651
    let add = |bookmark: &'static str, at: i64| {
3652
        let db = h.app.db.clone();
3653
        async move {
3654
            let id: i64 = sqlx::query_scalar(
3655
                "INSERT INTO reports (repo_id, name, kind, title, summary, context, job, bookmark, state, files, bytes, created_ms) \
3656
                 VALUES ($1, 'perf', 'performance', 'Perf', '', '{}', 'perf', $2, 's', 1, 1, $3) RETURNING id",
3657
            )
3658
            .bind(repo.id)
3659
            .bind(bookmark)
3660
            .bind(at)
3661
            .fetch_one(&db)
3662
            .await
3663
            .unwrap();
3664
            sqlx::query("INSERT INTO report_files (report_id, path, blob, size) VALUES ($1, 'report.toml', $2, 1)")
3665
                .bind(id)
3666
                .bind(format!("{:064x}", id))
3667
                .execute(&db)
3668
                .await
3669
                .unwrap();
3670
            sqlx::query("INSERT INTO report_metrics (report_id, key, value, unit, better) VALUES ($1, 'ms', 1, '', '')")
3671
                .bind(id)
3672
                .execute(&db)
3673
                .await
3674
                .unwrap();
3675
            id
3676
        }
3677
    };
3678
    let main_old = add("main", 1).await;
3679
    add("main", 2).await;
3680
    let mut feature = Vec::new();
3681
    for at in 0..52 {
3682
        feature.push(add("feature", 10 + at).await);
3683
    }
3684
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 2, "the two oldest feature runs");
3685
    let files = |id: i64| {
3686
        let db = h.app.db.clone();
3687
        async move {
3688
            sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM report_files WHERE report_id = $1").bind(id).fetch_one(&db).await.unwrap()
3689
        }
3690
    };
3691
    assert_eq!((files(feature[0]).await, files(feature[1]).await, files(feature[2]).await), (0, 0, 1));
3692
    assert_eq!(files(main_old).await, 1, "the default bookmark keeps every run");
3693
    assert_eq!(oxygenhub::reports::metrics(&h.app.db, feature[0]).await.unwrap().len(), 1, "metrics are kept");
3694
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 0, "once");
3695
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/perf?id={}", feature[0]), None, None).await;
3696
    assert!(page.contains("files have expired"), "the page says so");
3697
}
3698
3699
/// #137: a run pinning an image neither the hub nor any runner holds sets a
3700
/// failing `pipeline/images` check saying how to send it; once it is held,
3701
/// a run of the same state turns the check to passed.
3702
#[tokio::test(flavor = "multi_thread")]
3703
async fn a_pipeline_pinning_an_image_nobody_holds_fails_a_check() {
3704
    let h = hub().await;
3705
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3706
    // The one runner reports holding no images.
3707
    let none = r#"{"runner":"test-1","runtimes":["microvm"],"images":[]}"#;
3708
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(none.into())).await;
3709
    assert_eq!(st, StatusCode::NO_CONTENT);
3710
    create(&h.app, "andy", "demo").await;
3711
    let url = format!("{}/andy/demo", h.base);
3712
    let work = tempfile::tempdir().unwrap();
3713
    let c = client(&url, work.path());
3714
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3715
    write(work.path(), "test.sh", "echo ok\n");
3716
    c.commit("Add a pipeline", &[]).unwrap();
3717
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3718
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
3719
    let checks = checks_when(&h.app, run.repo_id, &run.state, 4).await;
3720
    let check = checks.iter().find(|c| c.name == "pipeline/images").expect("an images check");
3721
    assert!(check.status == "failed" && check.summary.contains(&ROOTFS[..12]) && check.summary.contains("flow rootfs push"), "{check:?}");
3722
    // Once a runner holds it, a run of the state passes the check.
3723
    let holds = format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":["{ROOTFS}"]}}"#);
3724
    call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(holds)).await;
3725
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
3726
    assert_eq!(st, StatusCode::CREATED);
3727
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
3728
    let check = checks.iter().find(|c| c.name == "pipeline/images").unwrap();
3729
    assert_eq!(check.status, "passed", "{check:?}");
3730
}
3731
3732
/// The swarm's tracker (#144): a fetching runner is given the peers in its
3733
/// site that hold the image or are fetching it, and a ticket signed with
3734
/// the hub key; a runner not in a swarm is told how to join one.
3735
#[tokio::test(flavor = "multi_thread")]
3736
async fn the_tracker_names_peers_in_the_same_site_and_signs_a_ticket() {
3737
    let h = hub().await;
3738
    let app = &h.app;
3739
    let image = "ab".repeat(32);
3740
    let claim_as = |token: &'static str, name: &'static str, body: serde_json::Value| async move {
3741
        let mut b = serde_json::json!({ "runner": name, "runtimes": ["microvm"] });
3742
        b.as_object_mut().unwrap().extend(body.as_object().unwrap().clone());
3743
        let (st, out) = call(app, "POST", "/api/v1/flow/claim", Some(token), Some(b.to_string())).await;
3744
        assert_eq!(st, StatusCode::NO_CONTENT, "{out}");
3745
    };
3746
    let announce = |token: &'static str, state: &'static str| {
3747
        let body = serde_json::json!({ "image": image, "state": state }).to_string();
3748
        async move { call(app, "POST", "/api/v1/flow/swarm/announce", Some(token), Some(body)).await }
3749
    };
3750
    // A holds the image; B and C hold nothing; all three are in site "lab".
3751
    claim_as(
3752
        "runner-secret",
3753
        "a",
3754
        serde_json::json!({ "images": [image], "swarm": { "addr": "10.0.0.1:7401", "site": "lab", "cert": "11".repeat(32) } }),
3755
    )
3756
    .await;
3757
    claim_as(
3758
        "runner-two",
3759
        "b",
3760
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.2:7401", "site": "lab", "cert": "22".repeat(32) } }),
3761
    )
3762
    .await;
3763
    claim_as(
3764
        "runner-three",
3765
        "c",
3766
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.3:7401", "site": "lab", "cert": "33".repeat(32) } }),
3767
    )
3768
    .await;
3769
3770
    let (st, body) = announce("runner-two", "fetching").await;
3771
    assert_eq!(st, StatusCode::OK, "{body}");
3772
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3773
    let names: Vec<(&str, bool)> = a.peers.iter().map(|p| (p.addr.as_str(), p.complete)).collect();
3774
    assert_eq!(names, vec![("10.0.0.1:7401", true)], "only A holds it so far");
3775
    assert_eq!(a.peers[0].cert, "11".repeat(32), "with the fingerprint peers check it by");
3776
    let t = jet::swarm::Ticket::open(&a.ticket, &app.hub_key.identity, oxygenhub::db::now_ms() as u64).unwrap();
3777
    assert_eq!((t.name.as_str(), t.site.as_str()), ("b", "lab"));
3778
3779
    // C, fetching too, is told of A (whole) and B (fetching).
3780
    let (_, body) = announce("runner-three", "fetching").await;
3781
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3782
    let mut peers: Vec<(&str, bool)> = a.peers.iter().map(|p| (p.addr.as_str(), p.complete)).collect();
3783
    peers.sort();
3784
    assert_eq!(peers, vec![("10.0.0.1:7401", true), ("10.0.0.2:7401", false)]);
3785
3786
    // B is done: no longer offered as fetching. C moves site: no peers.
3787
    announce("runner-two", "done").await;
3788
    claim_as(
3789
        "runner-three",
3790
        "c",
3791
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.3:7401", "site": "elsewhere", "cert": "33".repeat(32) } }),
3792
    )
3793
    .await;
3794
    let (_, body) = announce("runner-three", "fetching").await;
3795
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3796
    assert!(a.peers.is_empty(), "{:?}", a.peers);
3797
3798
    // A runner without a certificate (an older flow) is not in the swarm.
3799
    claim_as("runner-secret", "a", serde_json::json!({ "images": [image], "swarm": { "addr": "10.0.0.1:7401", "site": "elsewhere" } }))
3800
        .await;
3801
    let (st, _) = announce("runner-secret", "fetching").await;
3802
    assert_eq!(st, StatusCode::CONFLICT);
3803
3804
    // A runner that left the swarm is told how to join; nonsense is refused.
3805
    claim_as("runner-two", "b", serde_json::json!({ "images": [] })).await;
3806
    let (st, body) = announce("runner-two", "fetching").await;
3807
    assert_eq!(st, StatusCode::CONFLICT);
3808
    assert!(body.contains("[runner.swarm]"), "{body}");
3809
    let (st, _) =
3810
        call(app, "POST", "/api/v1/flow/swarm/announce", Some("runner-secret"), Some(r#"{"image":"nope","state":"fetching"}"#.into()))
3811
            .await;
3812
    assert_eq!(st, StatusCode::BAD_REQUEST);
3813
    let (st, _) = call(
3814
        app,
3815
        "POST",
3816
        "/api/v1/flow/swarm/announce",
3817
        None,
3818
        Some(serde_json::json!({ "image": image, "state": "fetching" }).to_string()),
3819
    )
3820
    .await;
3821
    assert_eq!(st, StatusCode::UNAUTHORIZED);
3822
}
3823
3824
/// Admin › Runners › Images (C0): each image, where it is and what uses it.
3825
#[tokio::test(flavor = "multi_thread")]
3826
async fn the_images_page_says_where_each_image_is_and_what_uses_it() {
3827
    let h = hub().await;
3828
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3829
    create(&h.app, "andy", "demo").await;
3830
    let work = tempfile::tempdir().unwrap();
3831
    let c = client(&format!("{}/andy/demo", h.base), work.path());
3832
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3833
    write(work.path(), "test.sh", "echo ok\n");
3834
    c.commit("Add a pipeline", &[]).unwrap();
3835
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3836
    // A runner holds another image and shares it; the hub keeps a third.
3837
    let held = "cd".repeat(32);
3838
    let kept = "ef".repeat(32);
3839
    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) } });
3840
    let (st, out) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
3841
    assert!(st == StatusCode::NO_CONTENT || st == StatusCode::OK, "{st} {out}");
3842
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES ($1, 1048576, 'x86_64', 9, 'andy', 1)")
3843
        .bind(&kept)
3844
        .execute(&h.app.db)
3845
        .await
3846
        .unwrap();
3847
3848
    let res = oxygenhub::router(h.app.clone())
3849
        .oneshot(
3850
            Request::post("/register")
3851
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
3852
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
3853
                .unwrap(),
3854
        )
3855
        .await
3856
        .unwrap();
3857
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
3858
    let carol = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
3859
    db::accounts::set_admin(&h.app.db, carol.id, true).await.unwrap();
3860
    // An image only runners held (oxygenflow#94), and none holds it now.
3861
    let lost = jet::images::scan(&[7u8; 4096][..], Some("x86_64".into()), |_, _| Ok(())).unwrap();
3862
    oxygenhub::images::record_peer(&h.app.db, &lost, "mars-1").await.unwrap();
3863
    let res = oxygenhub::router(h.app.clone())
3864
        .oneshot(Request::get("/admin/runners/images").header(header::COOKIE, cookie).body(Body::empty()).unwrap())
3865
        .await
3866
        .unwrap();
3867
    assert_eq!(res.status(), StatusCode::OK);
3868
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
3869
    let row = |hash: &str| {
3870
        let at = page.find(&format!("title=\"{hash}\"")).unwrap_or_else(|| panic!("{hash} is not on the page"));
3871
        let end = page[at..].find("</tr>").unwrap();
3872
        page[at..at + end].to_string()
3873
    };
3874
    let pinned = row(ROOTFS);
3875
    assert!(pinned.contains("nowhere") && pinned.contains("andy/demo") && pinned.contains("3 jobs"), "{pinned}");
3876
    let on_runner = row(&held);
3877
    assert!(on_runner.contains("img-holds") && on_runner.contains("earth-1") && !on_runner.contains("nowhere"), "{on_runner}");
3878
    let on_hub = row(&kept);
3879
    assert!(on_hub.contains("img-hub") && on_hub.contains("1.0 MiB") && on_hub.contains("x86_64"), "{on_hub}");
3880
    let peer_only = row(&lost.hash);
3881
    assert!(peer_only.contains("img-peer") && peer_only.contains("sent by mars-1") && peer_only.contains("nowhere"), "{peer_only}");
3882
    assert!(page.contains("earth-1 (home)"), "the swarm is named");
3883
    // The swarm backdrop (docs/backgrounds.md §2): the hub and the runners.
3884
    assert!(page.contains(r#"{"images":"#) && page.contains(r#""scene":"swarm""#) && page.contains(r#""earth-1""#), "the swarm's data");
3885
    assert_eq!(call(&h.app, "GET", "/admin/runners/images", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
3886
}
3887
3888
/// Diffusion D1 (#148): the reverse pin index. A repository that pins
3889
/// another as a subrepo is a consumer of it; the upstream's API and page
3890
/// say who, at which state, and how far behind its default bookmark.
3891
#[tokio::test(flavor = "multi_thread")]
3892
async fn consumers_of_a_subrepo_are_indexed_with_how_far_behind_they_are() {
3893
    let h = hub().await;
3894
    // The site token acts as the first site administrator.
3895
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3896
    create(&h.app, "andy", "api").await;
3897
    create(&h.app, "andy", "game").await;
3898
    let api_work = tempfile::tempdir().unwrap();
3899
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
3900
    write(api_work.path(), "api.h", "v1\n");
3901
    api.snapshot("t").unwrap();
3902
    api.commit("api v1", &[]).unwrap();
3903
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3904
3905
    let game_work = tempfile::tempdir().unwrap();
3906
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
3907
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3908
    write(game_work.path(), "game.c", "int main;\n");
3909
    game.snapshot("t").unwrap();
3910
    game.commit("game on api v1", &[]).unwrap();
3911
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3912
3913
    let consumers = || async {
3914
        let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
3915
        assert_eq!(st, StatusCode::OK, "{body}");
3916
        serde_json::from_str::<Vec<serde_json::Value>>(&body).unwrap()
3917
    };
3918
    // The index is written by the push's after-work, a moment after the
3919
    // client hears the push succeeded.
3920
    let settle = |want: &'static (dyn Fn(&[serde_json::Value]) -> bool + Sync)| {
3921
        let consumers = &consumers;
3922
        async move {
3923
            for _ in 0..100 {
3924
                let list = consumers().await;
3925
                if want(&list) {
3926
                    return list;
3927
                }
3928
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3929
            }
3930
            consumers().await
3931
        }
3932
    };
3933
    let list = settle(&|l| !l.is_empty()).await;
3934
    assert_eq!(list.len(), 1, "{list:?}");
3935
    assert_eq!(
3936
        (list[0]["name"].as_str(), list[0]["path"].as_str(), list[0]["bookmark"].as_str()),
3937
        (Some("game"), Some("deps/api"), Some("main"))
3938
    );
3939
    assert_eq!(list[0]["behind"], 0);
3940
3941
    // The upstream moves on: the consumer is one change behind.
3942
    write(api_work.path(), "api.c", "v2\n");
3943
    api.snapshot("t").unwrap();
3944
    api.commit("api v2", &[]).unwrap();
3945
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3946
    assert_eq!(settle(&|l| l.first().is_some_and(|c| c["behind"] == 1)).await[0]["behind"], 1);
3947
    let (_, page) = call(&h.app, "GET", "/andy/api", None, None).await;
3948
    assert!(page.contains("Diffuses to") && page.contains("andy/game") && page.contains("1 behind"), "the page shows it");
3949
3950
    // A private consumer is not shown to someone who cannot read it.
3951
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'game'").execute(&h.app.db).await.unwrap();
3952
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", None, None).await;
3953
    assert_eq!(body.trim(), "[]");
3954
    let (_, page) = call(&h.app, "GET", "/andy/api", None, None).await;
3955
    assert!(!page.contains("andy/game"));
3956
    sqlx::query("UPDATE repositories SET visibility = 'public' WHERE name = 'game'").execute(&h.app.db).await.unwrap();
3957
3958
    // A bump (DF3): one signed change on the target moving only the pin, on
3959
    // `diffusion/deps/api`; again with the same state, nothing new.
3960
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3961
    let api_row = db::repos::get(&h.app.db, "andy", "api").await.unwrap().unwrap();
3962
    let api_heads = api.bookmark_heads().unwrap();
3963
    let bumped = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, api_heads.clone()).await.unwrap();
3964
    let oxygenhub::diffusion::Bumped::Moved { bookmark, heads, .. } = bumped else { panic!("{bumped:?}") };
3965
    assert_eq!(bookmark, "diffusion/deps/api");
3966
    game.fetch("origin").unwrap();
3967
    let bump_state = game.load_state(&heads).unwrap().materialize();
3968
    let pin = match &bump_state.files["deps/api"].content {
3969
        oxy_core::state::FileContent::Opaque { blobs } => oxy_core::subrepo::Pin::decode(&game.read_blob(&blobs[0]).unwrap()).unwrap(),
3970
        other => panic!("{other:?}"),
3971
    };
3972
    assert!(
3973
        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 }),
3974
        "{pin:?}"
3975
    );
3976
    assert!(bump_state.files.contains_key("game.c"), "the rest of the game is as it was");
3977
    assert!(matches!(
3978
        oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, api_heads.clone()).await.unwrap(),
3979
        oxygenhub::diffusion::Bumped::Already { .. }
3980
    ));
3981
    // A state lacking changes the pin has (as when the consumer pinned an
3982
    // upstream proposal not landed yet) is combined with the pin, never
3983
    // dropping what it relies on.
3984
    write(api_work.path(), "other.c", "v3\n");
3985
    api.snapshot("t").unwrap();
3986
    let v3 = api.commit("api v3, on its own", &[]).unwrap();
3987
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3988
    let only_v3 = api.load_state(&[v3]).unwrap().heads().to_vec();
3989
    let combined = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, only_v3).await.unwrap();
3990
    let oxygenhub::diffusion::Bumped::Moved { heads: ch, .. } = combined else { panic!("{combined:?}") };
3991
    game.fetch("origin").unwrap();
3992
    let st = game.load_state(&ch).unwrap().materialize();
3993
    let pin = match &st.files["deps/api"].content {
3994
        oxy_core::state::FileContent::Opaque { blobs } => oxy_core::subrepo::Pin::decode(&game.read_blob(&blobs[0]).unwrap()).unwrap(),
3995
        other => panic!("{other:?}"),
3996
    };
3997
    let oxy_core::subrepo::Pin::Oxy { heads: pinned, .. } = pin else { panic!() };
3998
    let all = api.load_state(&pinned).unwrap();
3999
    // The game's main still pins v1 alone; combined with v3, it is both.
4000
    assert!(all.contains(&v3) && all.len() == 2, "v1 and v3, {} changes", all.len());
4001
    // The upstream moves again: the same bookmark moves.
4002
    let newer = api.bookmark_heads().unwrap();
4003
    let again = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, newer).await.unwrap();
4004
    assert!(matches!(again, oxygenhub::diffusion::Bumped::Moved { ref bookmark, .. } if bookmark == "diffusion/deps/api"), "{again:?}");
4005
4006
    // Following is off by default; owners turn it on (DF2).
4007
    let put =
4008
        |body: &'static str, who: Option<&'static str>| call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", who, Some(body.into()));
4009
    let (st, body) = put(r#"{"follow":"green"}"#, Some("site")).await;
4010
    assert_eq!(st, StatusCode::OK, "{body}");
4011
    assert!(body.contains("\"follow\":\"green\"") && body.contains("\"from\":\"setting\""), "{body}");
4012
    assert_eq!(put(r#"{"follow":"sometimes"}"#, Some("site")).await.0, StatusCode::BAD_REQUEST);
4013
    assert_ne!(put(r#"{"follow":"any"}"#, None).await.0, StatusCode::OK, "not without a token");
4014
    let (_, body) = put(r#"{"follow":"default"}"#, Some("site")).await;
4015
    assert!(body.contains("\"follow\":\"off\"") && body.contains("\"from\":\"site\""), "{body}");
4016
4017
    // Dropping the subrepo drops the consumer.
4018
    game.submodule_remove("deps/api").unwrap();
4019
    std::fs::remove_dir_all(game_work.path().join("deps/api")).unwrap();
4020
    game.snapshot("t").unwrap();
4021
    game.commit("game without api", &[]).unwrap();
4022
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
4023
    let left = settle(&|l| l.is_empty()).await;
4024
    assert!(left.is_empty(), "{left:?}");
4025
}
4026
4027
/// Diffusion D1 end to end (#148): a consumer that follows every move gets
4028
/// a bump proposal on a push; one that follows green gets it when the
4029
/// upstream's run passes. One proposal, kept up to date.
4030
#[tokio::test(flavor = "multi_thread")]
4031
async fn diffusion_proposes_a_bump_when_the_upstream_moves() {
4032
    let h = hub().await;
4033
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4034
    create(&h.app, "andy", "api").await;
4035
    create(&h.app, "andy", "game").await;
4036
    // Run every job of the upstream's newest run to a pass, keeping each claim.
4037
    let seen: std::sync::Mutex<Vec<serde_json::Value>> = std::sync::Mutex::new(Vec::new());
4038
    let seen = &seen;
4039
    let hub_app = &h.app;
4040
    let pass_all = move || async move {
4041
        let h_app = hub_app;
4042
        for _ in 0..20 {
4043
            let Some(a) = claim(h_app).await else {
4044
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4045
                if !jobs_left(h_app).await {
4046
                    break;
4047
                }
4048
                continue;
4049
            };
4050
            seen.lock().unwrap().push(a.clone());
4051
            let id = a["job_id"].as_i64().unwrap();
4052
            let (name, ph) = (a["job"]["name"].as_str().unwrap().to_string(), a["pipeline_hash"].as_str().unwrap().to_string());
4053
            let st = finish(h_app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt(&name, &ph, 0) })).await;
4054
            // A run started in the background (a bump, a landing's run, #197)
4055
            // may supersede the one this job belongs to between its claim and
4056
            // its finish; then, and only then, the hub refuses the finish.
4057
            if st == StatusCode::CONFLICT {
4058
                let job = db::flow::job(&h_app.db, id).await.unwrap().unwrap();
4059
                assert_eq!(job.status, "cancelled", "refused only because a newer run cancelled it");
4060
                continue;
4061
            }
4062
            assert_eq!(st, StatusCode::NO_CONTENT);
4063
        }
4064
    };
4065
    let api_work = tempfile::tempdir().unwrap();
4066
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
4067
    write(api_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4068
    write(api_work.path(), "test.sh", "echo ok\n");
4069
    write(api_work.path(), "api.h", "v1\n");
4070
    api.snapshot("t").unwrap();
4071
    api.commit("api v1", &[]).unwrap();
4072
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4073
    pass_all().await;
4074
4075
    let game_work = tempfile::tempdir().unwrap();
4076
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
4077
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
4078
    write(game_work.path(), "game.c", "int main;\n");
4079
    write(game_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4080
    write(game_work.path(), "test.sh", "echo ok\n");
4081
    game.snapshot("t").unwrap();
4082
    game.commit("game on api v1", &[]).unwrap();
4083
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
4084
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
4085
    let bump = || async {
4086
        for _ in 0..100 {
4087
            let open = db::proposals::list(&h.app.db, game_row.id, &["open"]).await.unwrap();
4088
            if let Some(p) = open.into_iter().find(|p| p.source_bookmark == "diffusion/deps/api") {
4089
                return Some(p);
4090
            }
4091
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4092
        }
4093
        None
4094
    };
4095
4096
    // Off by default: an upstream move proposes nothing.
4097
    write(api_work.path(), "a2.c", "v2\n");
4098
    api.snapshot("t").unwrap();
4099
    api.commit("api v2: faster sprites", &[]).unwrap();
4100
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4101
    pass_all().await;
4102
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
4103
    assert!(db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap().is_empty(), "off proposes nothing");
4104
4105
    // Turned on to follow every move: bumped at once to where the upstream
4106
    // is (v2), by the diffusion account; the next push updates it.
4107
    let put = |body: &'static str| call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(body.into()));
4108
    assert_eq!(put(r#"{"follow":"any"}"#).await.0, StatusCode::OK);
4109
    let first = bump().await.expect("caught up when turned on");
4110
    assert!(first.title.contains("1 change") && first.body.contains("api v2: faster sprites"), "{:?}", first.title);
4111
    // The bump's pipeline runs, as a push of it would, so the proposal is tested.
4112
    let mut ran = false;
4113
    for _ in 0..100 {
4114
        if runs_of(&h.app, "andy", "game").await.iter().any(|r| r.bookmark == "diffusion/deps/api") {
4115
            ran = true;
4116
            break;
4117
        }
4118
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4119
    }
4120
    assert!(ran, "a run of the bump");
4121
    pass_all().await;
4122
    write(api_work.path(), "a3.c", "v3\n");
4123
    api.snapshot("t").unwrap();
4124
    api.commit("api v3: save slots past ten", &[]).unwrap();
4125
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4126
    let mut p = first.clone();
4127
    for _ in 0..100 {
4128
        p = bump().await.unwrap();
4129
        if p.body.contains("api v3") {
4130
            break;
4131
        }
4132
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4133
    }
4134
    assert_eq!(p.number, first.number, "the same proposal");
4135
    assert_eq!((p.author.as_str(), p.target.as_str()), ("diffusion", "main"));
4136
    assert!(p.title.contains("deps/api") && p.title.contains("andy/api") && p.title.contains("2 changes"), "{}", p.title);
4137
    assert!(p.body.contains("api v2: faster sprites") && p.body.contains("api v3: save slots past ten"), "{}", p.body);
4138
    let labels = db::issues::proposal_labels(&h.app.db, p.id).await.unwrap();
4139
    assert!(labels.iter().any(|l| l.name == "dependencies"));
4140
    pass_all().await;
4141
4142
    // Following green: a push alone does not move it; the passing run does,
4143
    // and the same proposal is brought up to date.
4144
    assert_eq!(put(r#"{"follow":"green"}"#).await.0, StatusCode::OK);
4145
    write(api_work.path(), "a4.c", "v4\n");
4146
    api.snapshot("t").unwrap();
4147
    api.commit("api v4: rsm_set cheaper", &[]).unwrap();
4148
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4149
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
4150
    assert!(!bump().await.unwrap().body.contains("api v4"), "not before its run passes");
4151
    pass_all().await;
4152
    let mut updated = None;
4153
    // Up to 30 s: under the whole Postgres suite 5 s was not always enough.
4154
    for _ in 0..600 {
4155
        let p2 = bump().await.unwrap();
4156
        if p2.body.contains("api v4") {
4157
            updated = Some(p2);
4158
            break;
4159
        }
4160
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4161
    }
4162
    let p2 = updated.expect("brought up to date once the run passed");
4163
    assert_eq!(p2.number, p.number, "the same proposal");
4164
    assert!(p2.title.contains("3 changes"), "{}", p2.title);
4165
    assert_eq!(db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap().len(), 1, "never a pile of bumps");
4166
4167
    // The views (#150): the upstream's Diffusion tab lists the game with its
4168
    // status; the game's tab and overview say what it follows.
4169
    pass_all().await;
4170
    let (st, page) = call(&h.app, "GET", "/andy/api/diffusion", None, None).await;
4171
    assert_eq!(st, StatusCode::OK);
4172
    assert!(page.contains("Diffuses to") && page.contains("andy/game") && page.contains(&format!("#{}", p2.number)), "the bump is listed");
4173
    assert!(page.contains("df-green"), "a passing run of a checked upstream is green");
4174
    // The ripples backdrop: the page's own repositories and tones.
4175
    assert!(
4176
        page.contains(r#""scene":"ripples""#) && page.contains(r#"["andy/game","#) && page.contains(r#""repo":"andy/api""#),
4177
        "the ripples' data"
4178
    );
4179
    let (_, page) = call(&h.app, "GET", "/andy/game/diffusion", None, None).await;
4180
    assert!(page.contains("Takes from") && page.contains("andy/api"));
4181
    let (_, overview) = call(&h.app, "GET", "/andy/game", None, None).await;
4182
    assert!(overview.contains("Takes from") && overview.contains(">Diffusion</a>"), "the tab and the panel");
4183
    // Both directions through the API (#153), as the extension reads them.
4184
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/game/diffusion", Some("site"), None).await;
4185
    assert_eq!(st, StatusCode::OK, "{body}");
4186
    let d: hub_api::Diffusion = serde_json::from_str(&body).unwrap();
4187
    assert!(d.diffuses_to.is_empty(), "nothing pins the game");
4188
    let pin = d.takes_from.first().expect("the game takes from the api");
4189
    assert_eq!((pin.upstream.as_str(), pin.consumer.as_str()), ("andy/api", "andy/game"));
4190
    assert_eq!(pin.bump, Some(p2.number));
4191
    assert_eq!(pin.upstream_state.tone, "green", "{body}");
4192
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/diffusion", Some("site"), None).await;
4193
    let d: hub_api::Diffusion = serde_json::from_str(&body).unwrap();
4194
    assert!(d.takes_from.is_empty() && d.diffuses_to.iter().any(|p| p.consumer == "andy/game"), "{body}");
4195
    let (st, _) = call(&h.app, "GET", "/admin/diffusion", None, None).await;
4196
    assert_eq!(st, StatusCode::NOT_FOUND, "administrators only");
4197
4198
    // Landing the bump on the hub moves the game's pin as a push would:
4199
    // the index follows, so it is no longer behind; even when the first
4200
    // write fails, as a busy database's would (#210: it is tried again).
4201
    let game = oxygenhub::db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
4202
    oxygenhub::diffusion::fail_next_records(&h.app, game.id, 1);
4203
    let (st, body) =
4204
        call(&h.app, "POST", &format!("/api/v1/repos/andy/game/proposals/{}/land", p2.number), Some("site"), Some("{}".into())).await;
4205
    assert_eq!(st, StatusCode::OK, "{body}");
4206
    let mut behind = serde_json::Value::Null;
4207
    for _ in 0..100 {
4208
        let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
4209
        let list: Vec<serde_json::Value> = serde_json::from_str(&list).unwrap();
4210
        behind = list.iter().find(|c| c["name"] == "game").map(|c| c["behind"].clone()).unwrap_or_default();
4211
        if behind == 0 {
4212
            break;
4213
        }
4214
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4215
    }
4216
    assert_eq!(behind, 0, "the index followed the landing");
4217
    assert_eq!(oxygenhub::diffusion::forced_left(&h.app, game.id), 0, "the first write did fail");
4218
    // The reconciler (#210): an index left behind its bookmark (as when
4219
    // both writes failed) is mended from the bookmark itself, and a pass
4220
    // with nothing to mend changes nothing.
4221
    let pins_of = || async {
4222
        sqlx::query_scalar::<_, String>("SELECT heads FROM diffusion_pins WHERE consumer_id = $1")
4223
            .bind(game.id)
4224
            .fetch_one(&h.app.db)
4225
            .await
4226
            .unwrap()
4227
    };
4228
    let right = pins_of().await;
4229
    sqlx::query("UPDATE diffusion_pins SET heads = 'stale' WHERE consumer_id = $1").bind(game.id).execute(&h.app.db).await.unwrap();
4230
    sqlx::query("DELETE FROM diffusion_indexed WHERE consumer_id = $1").bind(game.id).execute(&h.app.db).await.unwrap();
4231
    let r = oxygenhub::diffusion::reconcile(&h.app).await;
4232
    assert!(r.reindexed >= 1, "{r:?}");
4233
    assert_eq!(pins_of().await, right, "the pin read again from the game's bookmark");
4234
    assert_eq!(oxygenhub::diffusion::reconcile(&h.app).await.reindexed, 0, "nothing left to mend");
4235
4236
    // A private upstream: the bump's run (started by the diffusion account,
4237
    // which cannot read it) still gets the subrepo it bumps.
4238
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'api'").execute(&h.app.db).await.unwrap();
4239
    seen.lock().unwrap().clear();
4240
    write(api_work.path(), "a6.c", "v6\n");
4241
    api.snapshot("t").unwrap();
4242
    api.commit("api v6", &[]).unwrap();
4243
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4244
    // The bump's run starts in the background: wait for its job, under a
4245
    // loaded test run as well as alone.
4246
    let mut bump_job = None;
4247
    for _ in 0..100 {
4248
        pass_all().await;
4249
        bump_job = seen.lock().unwrap().iter().find(|c| c["repo"] == "andy/game" && c["bookmark"] == "diffusion/deps/api").cloned();
4250
        if bump_job.is_some() {
4251
            break;
4252
        }
4253
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
4254
    }
4255
    let bump_job = bump_job.expect("the bump's job ran");
4256
    let subs: Vec<&str> = bump_job["subrepos"].as_array().unwrap().iter().filter_map(|s| s["path"].as_str()).collect();
4257
    assert_eq!(subs, vec!["deps/api"], "{bump_job}");
4258
4259
    // A consumer turning Diffusion on is bumped at once to the upstream's
4260
    // newest passing state, without waiting for it to move again.
4261
    create(&h.app, "andy", "game2").await;
4262
    let g2_work = tempfile::tempdir().unwrap();
4263
    let g2 = client(&format!("{}/andy/game2", h.base), g2_work.path());
4264
    g2.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
4265
    g2.snapshot("t").unwrap();
4266
    g2.commit("game2 on api", &[]).unwrap();
4267
    assert!(g2.push("origin", false).unwrap().iter().all(|r| r.ok));
4268
    // Its pin is api's newest state already: move api on, pass the run.
4269
    write(api_work.path(), "a5.c", "v5\n");
4270
    api.snapshot("t").unwrap();
4271
    api.commit("api v5", &[]).unwrap();
4272
    let api_row = db::repos::get(&h.app.db, "andy", "api").await.unwrap().unwrap();
4273
    let runs_before = db::flow::runs(&h.app.db, api_row.id, 100, None).await.unwrap().len();
4274
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4275
    // The push's run is made in the background: wait for it, or pass_all
4276
    // can finish before it exists and v5 never passes (a flake under load).
4277
    for _ in 0..300 {
4278
        if db::flow::runs(&h.app.db, api_row.id, 100, None).await.unwrap().len() > runs_before {
4279
            break;
4280
        }
4281
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
4282
    }
4283
    pass_all().await;
4284
    let g2_row = db::repos::get(&h.app.db, "andy", "game2").await.unwrap().unwrap();
4285
    for _ in 0..100 {
4286
        if sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
4287
            .bind(g2_row.id)
4288
            .fetch_one(&h.app.db)
4289
            .await
4290
            .unwrap()
4291
            > 0
4292
        {
4293
            break;
4294
        }
4295
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4296
    }
4297
    assert!(db::proposals::list(&h.app.db, g2_row.id, &[]).await.unwrap().is_empty(), "off until turned on");
4298
    let (st, _) = call(&h.app, "PUT", "/api/v1/repos/andy/game2/diffusion", Some("site"), Some(r#"{"follow":"green"}"#.into())).await;
4299
    assert_eq!(st, StatusCode::OK);
4300
    let mut caught = None;
4301
    // Up to 15 s: under a full parallel test run the bump can take a while.
4302
    for _ in 0..300 {
4303
        if let Some(p) = db::proposals::list(&h.app.db, g2_row.id, &["open"]).await.unwrap().into_iter().next() {
4304
            caught = Some(p);
4305
            break;
4306
        }
4307
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4308
    }
4309
    let caught = caught.expect("bumped as soon as it was turned on");
4310
    assert!(caught.body.contains("api v5") && caught.title.contains("1 change"), "{:?} {:?}", caught.title, caught.body);
4311
    // A bump someone closed is a "no": the reconciler does not open it again.
4312
    sqlx::query("UPDATE proposals SET state = 'closed' WHERE id = $1").bind(caught.id).execute(&h.app.db).await.unwrap();
4313
    // (The bump's own runs finishing may still propose again, as Diffusion
4314
    // does on an upstream's moves; the reconciler itself opens nothing.)
4315
    let r = oxygenhub::diffusion::reconcile(&h.app).await;
4316
    assert_eq!(r.caught_up, 0, "the reconciler respects the closed bump: {r:?}");
4317
}
4318
4319
/// Whether any job is queued or running.
4320
async fn jobs_left(app: &Shared) -> bool {
4321
    sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM flow_jobs WHERE status IN ('queued', 'running')")
4322
        .fetch_one(&app.db)
4323
        .await
4324
        .unwrap_or(0)
4325
        > 0
4326
}
4327
4328
/// An upstream with no checks never turns green: a consumer following green
4329
/// still gets its bumps, marked amber, `upstream unverified` (#148).
4330
#[tokio::test(flavor = "multi_thread")]
4331
async fn bumps_from_an_upstream_without_checks_are_marked_unverified() {
4332
    let h = hub().await;
4333
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4334
    create(&h.app, "andy", "lib").await;
4335
    create(&h.app, "andy", "app").await;
4336
    let lib_work = tempfile::tempdir().unwrap();
4337
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
4338
    write(lib_work.path(), "lib.h", "v1\n");
4339
    lib.snapshot("t").unwrap();
4340
    lib.commit("lib v1", &[]).unwrap();
4341
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4342
    let app_work = tempfile::tempdir().unwrap();
4343
    let app = client(&format!("{}/andy/app", h.base), app_work.path());
4344
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
4345
    // It watches lib.c: upstream changes touching it are flagged.
4346
    let modules = std::fs::read_to_string(app_work.path().join(".oxymodules")).unwrap();
4347
    write(app_work.path(), ".oxymodules", &format!("{modules}watch = lib.c\n"));
4348
    app.snapshot("t").unwrap();
4349
    app.commit("app on lib", &[]).unwrap();
4350
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
4351
    let app_row = db::repos::get(&h.app.db, "andy", "app").await.unwrap().unwrap();
4352
    for _ in 0..100 {
4353
        if sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
4354
            .bind(app_row.id)
4355
            .fetch_one(&h.app.db)
4356
            .await
4357
            .unwrap()
4358
            > 0
4359
        {
4360
            break;
4361
        }
4362
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4363
    }
4364
    let (st, _) = call(&h.app, "PUT", "/api/v1/repos/andy/app/diffusion", Some("site"), Some(r#"{"follow":"green"}"#.into())).await;
4365
    assert_eq!(st, StatusCode::OK);
4366
    write(lib_work.path(), "lib.c", "v2\n");
4367
    lib.snapshot("t").unwrap();
4368
    lib.commit("lib v2", &[]).unwrap();
4369
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4370
    let mut found = None;
4371
    for _ in 0..100 {
4372
        if let Some(p) = db::proposals::list(&h.app.db, app_row.id, &["open"]).await.unwrap().into_iter().next() {
4373
            found = Some(p);
4374
            break;
4375
        }
4376
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4377
    }
4378
    let p = found.expect("a bump although the upstream never goes green");
4379
    assert!(p.body.contains("Upstream unverified"), "{}", p.body);
4380
    assert!(p.body.contains("Touches what you watch") && p.body.contains("touches `lib.c`") && p.body.contains("⚑"), "{}", p.body);
4381
    let mut labels = Vec::new();
4382
    for _ in 0..100 {
4383
        labels = db::issues::proposal_labels(&h.app.db, p.id).await.unwrap().into_iter().map(|l| l.name).collect::<Vec<String>>();
4384
        if labels.len() == 2 {
4385
            break;
4386
        }
4387
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4388
    }
4389
    assert!(labels.contains(&"upstream unverified".to_string()) && labels.contains(&"dependencies".to_string()), "{labels:?}");
4390
}
4391
4392
/// #134: when a proposal's target moves, its projected state is new; the
4393
/// hub runs the pipeline on it, so its checks are never for an older one.
4394
#[tokio::test(flavor = "multi_thread")]
4395
async fn a_moved_target_runs_its_open_proposals_again() {
4396
    let h = hub().await;
4397
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4398
    create(&h.app, "andy", "demo").await;
4399
    let work = tempfile::tempdir().unwrap();
4400
    let mut c = client(&format!("{}/andy/demo", h.base), work.path());
4401
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4402
    write(work.path(), "test.sh", "echo ok\n");
4403
    c.snapshot("t").unwrap();
4404
    let base = c.commit("base", &[]).unwrap();
4405
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4406
    // Two proposals, each main plus one change.
4407
    for (b, file) in [("fix-a", "a.txt"), ("fix-b", "b.txt")] {
4408
        c.bookmark_create(b, Some(&[base])).unwrap();
4409
        c.bookmark_switch(b, true).unwrap();
4410
        write(work.path(), file, "x\n");
4411
        c.snapshot("t").unwrap();
4412
        c.commit(&format!("add {file}"), &[]).unwrap();
4413
        assert!(c.push_bookmark("origin", b, false).unwrap().iter().all(|r| r.ok));
4414
        let body = serde_json::json!({ "title": b, "target": "main", "source": b }).to_string();
4415
        let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/demo/proposals", Some("site"), Some(body)).await;
4416
        assert_eq!(st, StatusCode::CREATED, "{out}");
4417
    }
4418
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
4419
    let props = db::proposals::list(&h.app.db, row.id, &["open"]).await.unwrap();
4420
    let a = props.iter().find(|p| p.source_bookmark == "fix-a").unwrap().number;
4421
    let b = props.iter().find(|p| p.source_bookmark == "fix-b").unwrap().number;
4422
    // Landing fix-a moves main: fix-b's projected state gets a run.
4423
    let (st, out) = call(&h.app, "POST", &format!("/api/v1/repos/andy/demo/proposals/{a}/land"), Some("site"), Some("{}".into())).await;
4424
    assert_eq!(st, StatusCode::OK, "{out}");
4425
    let label = format!("proposal/{b}");
4426
    let mut found = None;
4427
    for _ in 0..100 {
4428
        if let Some(r) = runs_of(&h.app, "andy", "demo").await.into_iter().find(|r| r.bookmark == label) {
4429
            found = Some(r);
4430
            break;
4431
        }
4432
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4433
    }
4434
    let run = found.expect("a run of fix-b's new projected state");
4435
    let projected = db::proposals::get(&h.app.db, row.id, b).await.unwrap().unwrap();
4436
    assert_eq!((run.trigger.as_str(), run.state.as_str()), ("proposal", projected.projected_state.as_str()), "on its projected state");
4437
    // Moving main again by a push does it once more; the same state is not run twice.
4438
    let before = runs_of(&h.app, "andy", "demo").await.len();
4439
    oxygenhub::web::proposals::settle_after_push(&h.app, &row, "main", "andy").await;
4440
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), before, "not again for the same state");
4441
}
4442
4443
/// Send image bytes to the hub as their chunks and then a manifest that
4444
/// names no architecture; the manifest as the hub answers it.
4445
async fn send_image(app: &Shared, image: &[u8]) -> (String, serde_json::Value) {
4446
    let mut chunks = std::collections::HashMap::new();
4447
    let m = jet::images::scan(image, None, |c, b| {
4448
        chunks.insert(c.hash().to_string(), b.to_vec());
4449
        Ok(())
4450
    })
4451
    .unwrap();
4452
    for c in m.needed() {
4453
        let (st, body) = put_bytes(app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
4454
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
4455
    }
4456
    let (st, body) =
4457
        call(app, "PUT", &format!("/api/v1/flow/images/{}", m.hash), Some("site"), Some(serde_json::to_string(&m).unwrap())).await;
4458
    assert_eq!(st, StatusCode::CREATED, "{body}");
4459
    (m.hash.clone(), serde_json::from_str(&body).unwrap())
4460
}
4461
4462
/// oxygenhub#173 (OxygenFlow spec §11.2, Andy's "detect and learn"): an
4463
/// image sent with no architecture is read from its own files, so a
4464
/// riscv64 runner is never offered an x86_64 image's jobs; an image
4465
/// nobody can read takes the architecture its first pass ran on.
4466
#[tokio::test(flavor = "multi_thread")]
4467
async fn an_image_names_its_own_architecture_and_a_pass_teaches_the_rest() {
4468
    use oxy_core::identity::SecretKey;
4469
    let h = hub().await;
4470
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4471
    // An ext4 image whose shell is x86_64, as `flow rootfs import` makes one.
4472
    let dir = tempfile::tempdir().unwrap();
4473
    let tree = dir.path().join("tree");
4474
    std::fs::create_dir_all(tree.join("bin")).unwrap();
4475
    let mut elf = vec![0u8; 64];
4476
    elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
4477
    elf[18..20].copy_from_slice(&0x3Eu16.to_le_bytes());
4478
    std::fs::write(tree.join("bin/sh"), &elf).unwrap();
4479
    let img = dir.path().join("rootfs.ext4");
4480
    let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
4481
    if !made.is_ok_and(|s| s.success()) {
4482
        eprintln!("mkfs.ext4 not found: skipped");
4483
        return;
4484
    }
4485
    let (x86, answer) = send_image(&h.app, &std::fs::read(&img).unwrap()).await;
4486
    assert_eq!(answer["arch"], "x86_64", "read from its shell: {answer}");
4487
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{x86}"), Some("runner-secret"), None).await;
4488
    assert_eq!(serde_json::from_str::<jet::images::Manifest>(&body).unwrap().arch.as_deref(), Some("x86_64"), "runners fetch it named");
4489
    // One nobody can read: no ext4, no shell.
4490
    let blob: Vec<u8> = (0..300_000u32).map(|i| (i % 241) as u8).collect();
4491
    let (unread, answer) = send_image(&h.app, &blob).await;
4492
    assert!(answer["arch"].is_null(), "{answer}");
4493
    let archs = db::flow::image_archs(&h.app.db).await.unwrap();
4494
    assert_eq!((archs.get(&x86).map(String::as_str), archs.get(&unread)), (Some("x86_64"), None));
4495
    // Kept images with none are read once at start.
4496
    sqlx::query("UPDATE jet_images SET arch = ''").execute(&h.app.db).await.unwrap();
4497
    sqlx::query("DELETE FROM flow_images").execute(&h.app.db).await.unwrap();
4498
    assert_eq!(oxygenhub::images::learn_archs(&h.app).await.unwrap(), 1);
4499
    assert_eq!(db::flow::image_archs(&h.app.db).await.unwrap().get(&x86).map(String::as_str), Some("x86_64"));
4500
4501
    // A job on each image.
4502
    create(&h.app, "andy", "arch").await;
4503
    let work = tempfile::tempdir().unwrap();
4504
    let c = client(&format!("{}/andy/arch", h.base), work.path());
4505
    let kdl = format!(
4506
        "schema-version 1\nsandbox \"unread\" {{\n    rootfs \"cas://blob/{unread}\"\n}}\nsandbox \"x86\" {{\n    rootfs \"cas://blob/{x86}\"\n}}\n\
4507
         job \"first\" {{\n    sandbox \"unread\"\n    exec \"make\"\n}}\njob \"second\" {{\n    sandbox \"x86\"\n    exec \"make\"\n    depends-on \"first\"\n}}\n\
4508
         job \"third\" {{\n    sandbox \"unread\"\n    exec \"make\"\n    depends-on \"first\"\n}}\n"
4509
    );
4510
    write(work.path(), ".flow/pipeline.kdl", &kdl);
4511
    c.commit("Jobs on two images", &[]).unwrap();
4512
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4513
    runs_of(&h.app, "andy", "arch").await;
4514
4515
    // The x86_64 runner passes the first job: its image is x86_64 now.
4516
    let x86_info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
4517
    let x86_claim =
4518
        serde_json::json!({ "runner": "earth", "runtimes": ["microvm"], "images": [], "fetches_images": true, "info": x86_info });
4519
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(x86_claim.to_string())).await;
4520
    assert_eq!(st, StatusCode::OK, "{body}");
4521
    let first: serde_json::Value = serde_json::from_str(&body).unwrap();
4522
    assert_eq!(first["job"]["name"], "first");
4523
    let ph = first["pipeline_hash"].as_str().unwrap();
4524
    let id = first["job_id"].as_i64().unwrap();
4525
    assert_eq!(
4526
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("first", ph, 0) })).await,
4527
        StatusCode::NO_CONTENT
4528
    );
4529
    assert_eq!(db::flow::image_archs(&h.app.db).await.unwrap().get(&unread).map(String::as_str), Some("x86_64"), "learned");
4530
4531
    // A riscv64 runner is offered neither: one read, one learned.
4532
    let token = "flowreg_narvi";
4533
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
4534
    let identity = SecretKey::generate().identity("narvi", "", 1);
4535
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
4536
    let reg = serde_json::json!({ "token": token, "name": "narvi", "identity": hex::encode(identity.encode()), "info": info });
4537
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
4538
    assert_eq!(st, StatusCode::OK, "{body}");
4539
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
4540
    let narvi =
4541
        serde_json::json!({ "runner": "narvi", "runtimes": ["microvm"], "images": [], "fetches_images": true, "info": info }).to_string();
4542
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(narvi)).await;
4543
    assert_eq!(st, StatusCode::NO_CONTENT, "the second job's image is x86_64 and the third's learned so: {body}");
4544
    for _ in 0..2 {
4545
        let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(x86_claim.to_string())).await;
4546
        assert_eq!(st, StatusCode::OK, "both go to x86_64: {body}");
4547
    }
4548
}
4549
4550
/// Diffusion auto-land (docs/diffusion.md §4.2; Andy chose "opt-in, per
4551
/// repository", 2026-10-13): a consumer that chose `land = auto` has a bump
4552
/// landed by itself, as the diffusion account, once both halves are green;
4553
/// a bump from an upstream with no checks (amber) always waits.
4554
#[tokio::test(flavor = "multi_thread")]
4555
async fn a_consumer_that_chose_auto_lands_green_bumps_itself() {
4556
    let h = hub().await;
4557
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4558
    create(&h.app, "andy", "api").await;
4559
    create(&h.app, "andy", "game").await;
4560
    let hub_app = &h.app;
4561
    // Run every queued job to a pass.
4562
    let pass_all = move || async move {
4563
        for _ in 0..20 {
4564
            let Some(a) = claim(hub_app).await else {
4565
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4566
                if !jobs_left(hub_app).await {
4567
                    break;
4568
                }
4569
                continue;
4570
            };
4571
            let id = a["job_id"].as_i64().unwrap();
4572
            let (name, ph) = (a["job"]["name"].as_str().unwrap().to_string(), a["pipeline_hash"].as_str().unwrap().to_string());
4573
            assert_eq!(
4574
                finish(hub_app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt(&name, &ph, 0) })).await,
4575
                StatusCode::NO_CONTENT
4576
            );
4577
        }
4578
    };
4579
    let api_work = tempfile::tempdir().unwrap();
4580
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
4581
    write(api_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4582
    write(api_work.path(), "test.sh", "echo ok\n");
4583
    api.snapshot("t").unwrap();
4584
    api.commit("api v1", &[]).unwrap();
4585
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4586
    pass_all().await;
4587
    let game_work = tempfile::tempdir().unwrap();
4588
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
4589
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
4590
    write(game_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4591
    write(game_work.path(), "test.sh", "echo ok\n");
4592
    game.snapshot("t").unwrap();
4593
    game.commit("game on api v1", &[]).unwrap();
4594
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
4595
    pass_all().await;
4596
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
4597
    for _ in 0..100 {
4598
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
4599
            .bind(game_row.id)
4600
            .fetch_one(&h.app.db)
4601
            .await
4602
            .unwrap();
4603
        if n > 0 {
4604
            break;
4605
        }
4606
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4607
    }
4608
    let (st, body) =
4609
        call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(r#"{"follow":"green","land":"auto"}"#.into())).await;
4610
    assert_eq!(st, StatusCode::OK, "{body}");
4611
    assert!(body.contains(r#""land":"auto""#), "{body}");
4612
    let (st, _) =
4613
        call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(r#"{"follow":"green","land":"soon"}"#.into())).await;
4614
    assert_eq!(st, StatusCode::BAD_REQUEST);
4615
4616
    // The upstream moves and passes: the bump is proposed, its run passes,
4617
    // and it lands by itself.
4618
    write(api_work.path(), "a2.c", "v2\n");
4619
    api.snapshot("t").unwrap();
4620
    api.commit("api v2: faster sprites", &[]).unwrap();
4621
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4622
    let mut landed = None;
4623
    for _ in 0..100 {
4624
        pass_all().await;
4625
        let all = db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap();
4626
        if let Some(p) = all.into_iter().find(|p| p.source_bookmark == "diffusion/deps/api" && p.state == "landed") {
4627
            landed = Some(p);
4628
            break;
4629
        }
4630
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4631
    }
4632
    let p = landed.expect("landed by itself once both halves were green");
4633
    assert!(p.body.contains("lands its bumps itself"), "{}", p.body);
4634
    let events = db::proposals::events(&h.app.db, p.id).await.unwrap();
4635
    let landing = events.iter().find(|e| e.event == "landed").expect("a landing on the timeline");
4636
    assert_eq!(landing.actor, "diffusion");
4637
    assert!(landing.detail.contains("Diffusion, both halves green"), "{}", landing.detail);
4638
    // The game's main now pins api v2.
4639
    let mut behind = serde_json::Value::Null;
4640
    for _ in 0..100 {
4641
        let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
4642
        let list: Vec<serde_json::Value> = serde_json::from_str(&list).unwrap();
4643
        behind = list.iter().find(|c| c["name"] == "game").map(|c| c["behind"].clone()).unwrap_or_default();
4644
        if behind == 0 {
4645
            break;
4646
        }
4647
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4648
    }
4649
    assert_eq!(behind, 0, "main moved to the bump");
4650
4651
    // An upstream with no checks: its bump passes in the consumer, but
4652
    // amber never lands by itself, whatever the setting.
4653
    create(&h.app, "andy", "lib").await;
4654
    create(&h.app, "andy", "app").await;
4655
    let lib_work = tempfile::tempdir().unwrap();
4656
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
4657
    write(lib_work.path(), "lib.h", "v1\n");
4658
    lib.snapshot("t").unwrap();
4659
    lib.commit("lib v1", &[]).unwrap();
4660
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4661
    let app_work = tempfile::tempdir().unwrap();
4662
    let app = client(&format!("{}/andy/app", h.base), app_work.path());
4663
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
4664
    let modules = std::fs::read_to_string(app_work.path().join(".oxymodules")).unwrap();
4665
    write(app_work.path(), ".oxymodules", &format!("{modules}follow = green\nland = auto\n"));
4666
    write(app_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4667
    write(app_work.path(), "test.sh", "echo ok\n");
4668
    app.snapshot("t").unwrap();
4669
    app.commit("app on lib", &[]).unwrap();
4670
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
4671
    pass_all().await;
4672
    let app_row = db::repos::get(&h.app.db, "andy", "app").await.unwrap().unwrap();
4673
    for _ in 0..100 {
4674
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
4675
            .bind(app_row.id)
4676
            .fetch_one(&h.app.db)
4677
            .await
4678
            .unwrap();
4679
        if n > 0 {
4680
            break;
4681
        }
4682
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4683
    }
4684
    write(lib_work.path(), "lib.c", "v2\n");
4685
    lib.snapshot("t").unwrap();
4686
    lib.commit("lib v2", &[]).unwrap();
4687
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4688
    let mut passed = false;
4689
    for _ in 0..100 {
4690
        pass_all().await;
4691
        let s: Option<String> = sqlx::query_scalar(
4692
            "SELECT status FROM flow_runs WHERE repo_id = $1 AND bookmark = 'diffusion/deps/lib' ORDER BY id DESC LIMIT 1",
4693
        )
4694
        .bind(app_row.id)
4695
        .fetch_optional(&h.app.db)
4696
        .await
4697
        .unwrap();
4698
        if s.as_deref() == Some("passed") {
4699
            passed = true;
4700
            break;
4701
        }
4702
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4703
    }
4704
    assert!(passed, "the app's run on the bump passed");
4705
    assert_eq!(oxygenhub::diffusion::auto_land(&h.app, &app_row, "deps/lib").await, Err(oxygenhub::diffusion::Held::Unverified));
4706
    let open = db::proposals::list(&h.app.db, app_row.id, &["open"]).await.unwrap();
4707
    assert!(open.iter().any(|p| p.source_bookmark == "diffusion/deps/lib"), "amber waits for a person");
4708
}
4709
4710
/// oxygenflow#31: one finished job runs again in the same run, with the
4711
/// jobs that depend on it; what it depends on keeps its result, so a flaky
4712
/// test reruns without its build. Not while the run is live, and only a
4713
/// job the run has.
4714
#[tokio::test(flavor = "multi_thread")]
4715
async fn one_job_reruns_with_what_depends_on_it() {
4716
    let h = hub().await;
4717
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4718
    create(&h.app, "andy", "flaky").await;
4719
    let work = tempfile::tempdir().unwrap();
4720
    let c = client(&format!("{}/andy/flaky", h.base), work.path());
4721
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4722
    write(work.path(), "test.sh", "echo ok\n");
4723
    c.commit("Add a pipeline", &[]).unwrap();
4724
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4725
    let run = runs_of(&h.app, "andy", "flaky").await[0].clone();
4726
    // build and lint pass; test fails, as a flaky one does.
4727
    let (st, _) =
4728
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/test/rerun", run.number), Some("site"), None).await;
4729
    assert_eq!(st, StatusCode::CONFLICT, "not while the run is live");
4730
    while let Some(j) = claim(&h.app).await {
4731
        let id = j["job_id"].as_i64().unwrap();
4732
        let (name, ph) = (j["job"]["name"].as_str().unwrap().to_string(), j["pipeline_hash"].as_str().unwrap().to_string());
4733
        let exit = if name == "test" { 1 } else { 0 };
4734
        let log = serde_json::json!({ "records": [{ "t": 1, "stream": "out", "text": format!("{name} ran") }] });
4735
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(log.to_string())).await;
4736
        assert_eq!(
4737
            finish(&h.app, id, serde_json::json!({ "exit_code": exit, "duration_ms": 10, "receipt": receipt(&name, &ph, exit as u32) }))
4738
                .await,
4739
            StatusCode::NO_CONTENT
4740
        );
4741
    }
4742
    let status = |n: &'static str| {
4743
        let (app, run_id) = (h.app.clone(), run.id);
4744
        async move { db::flow::jobs(&app.db, run_id).await.unwrap().into_iter().find(|j| j.name == n).unwrap() }
4745
    };
4746
    assert_eq!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().status, "failed");
4747
    let failed_test = status("test").await;
4748
4749
    // The test again: build and lint keep their results.
4750
    let (st, body) =
4751
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/test/rerun", run.number), Some("site"), None).await;
4752
    assert_eq!(st, StatusCode::OK, "{body}");
4753
    assert!(body.contains(r#""queued":1"#), "{body}");
4754
    assert_eq!(
4755
        (status("build").await.status, status("lint").await.status, status("test").await.status),
4756
        ("passed".into(), "passed".into(), "queued".into())
4757
    );
4758
    assert!(db::flow::log(&h.app.db, failed_test.id, 0, 100).await.unwrap().is_empty(), "its old log is gone");
4759
    assert!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().live());
4760
    let checks = checks_when(&h.app, run.repo_id, &run.state, 3).await;
4761
    assert_eq!(checks.iter().find(|c| c.name == "flow/test").map(|c| c.status.as_str()), Some("queued"));
4762
    let j = claim(&h.app).await.expect("the test, queued again");
4763
    assert_eq!(j["job"]["name"], "test");
4764
    let ph = j["pipeline_hash"].as_str().unwrap().to_string();
4765
    let id = j["job_id"].as_i64().unwrap();
4766
    assert_eq!(
4767
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("test", &ph, 0) })).await,
4768
        StatusCode::NO_CONTENT
4769
    );
4770
    assert_eq!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().status, "passed", "the run is whole again");
4771
    // Andy owns it: told it failed, then that it is fixed (#183).
4772
    let andy_id = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap().id;
4773
    let kinds: Vec<String> = db::notify::inbox(&h.app.db, andy_id, 20).await.unwrap().into_iter().map(|n| n.kind).collect();
4774
    assert!(kinds.contains(&"flow.failed".to_string()) && kinds.contains(&"flow.fixed".to_string()), "{kinds:?}");
4775
4776
    // The build again brings the test that depends on it; lint stays.
4777
    let (_, body) =
4778
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/build/rerun", run.number), Some("site"), None).await;
4779
    assert!(body.contains(r#""queued":2"#), "{body}");
4780
    assert_eq!(
4781
        (status("build").await.status, status("lint").await.status, status("test").await.status),
4782
        ("queued".into(), "passed".into(), "queued".into())
4783
    );
4784
    let (st, _) =
4785
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/deploy/rerun", run.number), Some("site"), None).await;
4786
    assert_eq!(st, StatusCode::CONFLICT, "live again, and no such job either way");
4787
}
4788
4789
/// oxygenflow#30: a failed run tells its pusher and the repository's
4790
/// watchers; a runner whose last five jobs ended in infrastructure errors
4791
/// is drained and the administrators told, counting only since an
4792
/// administrator last made it active.
4793
#[tokio::test(flavor = "multi_thread")]
4794
async fn failed_runs_are_told_and_an_erroring_runner_is_drained() {
4795
    let h = hub().await;
4796
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4797
    let bob = db::accounts::create_account(&h.app.db, "bob", "[email protected]", "x", "salt", false).await.unwrap();
4798
    create(&h.app, "andy", "alerts").await;
4799
    let row = db::repos::get(&h.app.db, "andy", "alerts").await.unwrap().unwrap();
4800
    db::notify::set_watch(&h.app.db, bob.id, row.id, true).await.unwrap();
4801
    let work = tempfile::tempdir().unwrap();
4802
    let c = client(&format!("{}/andy/alerts", h.base), work.path());
4803
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4804
    write(work.path(), "test.sh", "exit 1\n");
4805
    c.commit("Add a pipeline", &[]).unwrap();
4806
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4807
    let run = runs_of(&h.app, "andy", "alerts").await[0].clone();
4808
    sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&h.app.db).await.unwrap();
4809
    while let Some(j) = claim(&h.app).await {
4810
        let id = j["job_id"].as_i64().unwrap();
4811
        let (name, ph) = (j["job"]["name"].as_str().unwrap().to_string(), j["pipeline_hash"].as_str().unwrap().to_string());
4812
        let exit = if name == "test" { 1 } else { 0 };
4813
        finish(&h.app, id, serde_json::json!({ "exit_code": exit, "duration_ms": 10, "receipt": receipt(&name, &ph, exit as u32) })).await;
4814
    }
4815
    let told = |id: i64| {
4816
        let db = h.app.db.clone();
4817
        async move { db::notify::inbox(&db, id, 20).await.unwrap().into_iter().filter(|n| n.kind == "flow.failed").collect::<Vec<_>>() }
4818
    };
4819
    let (for_andy, for_bob) = (told(andy.id).await, told(bob.id).await);
4820
    assert_eq!((for_andy.len(), for_bob.len()), (1, 1), "the pusher and a watcher");
4821
    assert!(for_andy[0].title.contains(&format!("run #{} on main failed (test)", run.number)), "{}", for_andy[0].title);
4822
    assert_eq!(for_andy[0].url, format!("/andy/alerts/flow/{}", run.number));
4823
4824
    // Five infrastructure errors in a row drain the runner.
4825
    let runner_id = || {
4826
        let db = h.app.db.clone();
4827
        async move { sqlx::query_scalar::<_, i64>("SELECT id FROM flow_runners WHERE name = 'test-1'").fetch_one(&db).await.unwrap() }
4828
    };
4829
    let mut errors = 0;
4830
    while errors < 5 {
4831
        let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/alerts/flow/runs", Some("site"), Some("{}".into())).await;
4832
        assert_eq!(st, StatusCode::CREATED);
4833
        while let Some(j) = claim(&h.app).await {
4834
            let id = j["job_id"].as_i64().unwrap();
4835
            let st = finish(
4836
                &h.app,
4837
                id,
4838
                serde_json::json!({ "exit_code": null, "duration_ms": 10, "error": "the microVM did not start: /dev/kvm busy" }),
4839
            )
4840
            .await;
4841
            assert_eq!(st, StatusCode::NO_CONTENT);
4842
            errors += 1;
4843
            if errors == 5 {
4844
                break;
4845
            }
4846
        }
4847
    }
4848
    let state = |id: i64| {
4849
        let db = h.app.db.clone();
4850
        async move { db::runners::get(&db, id).await.unwrap().unwrap().state }
4851
    };
4852
    let id = runner_id().await;
4853
    assert_eq!(state(id).await, "draining");
4854
    let drained: Vec<_> =
4855
        db::notify::inbox(&h.app.db, andy.id, 50).await.unwrap().into_iter().filter(|n| n.kind == "flow.runner_drained").collect();
4856
    assert_eq!(drained.len(), 1, "the administrator is told");
4857
    assert!(drained[0].title.contains("/dev/kvm busy"), "{}", drained[0].title);
4858
    assert!(
4859
        !told(bob.id).await.is_empty()
4860
            && db::notify::inbox(&h.app.db, bob.id, 50).await.unwrap().iter().all(|n| n.kind != "flow.runner_drained")
4861
    );
4862
    // Made active again, past errors no longer count.
4863
    db::runners::set_state(&h.app.db, id, "active").await.unwrap();
4864
    assert_eq!(db::runners::erroring(&h.app.db, id, 5).await.unwrap(), None);
4865
}
4866
4867
/// #197: landing a proposal moves its target as a push does, so the
4868
/// target's pipeline runs on the landed state.
4869
#[tokio::test(flavor = "multi_thread")]
4870
async fn a_landed_proposal_runs_its_targets_pipeline() {
4871
    let h = hub().await;
4872
    create(&h.app, "andy", "demo").await;
4873
    let url = format!("{}/andy/demo", h.base);
4874
    let work = tempfile::tempdir().unwrap();
4875
    let mut c = client(&url, work.path());
4876
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4877
    write(work.path(), "test.sh", "echo ok\n");
4878
    c.snapshot("test").unwrap();
4879
    c.commit("Add a pipeline", &[]).unwrap();
4880
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4881
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
4882
    c.bookmark_create("feature", None).unwrap();
4883
    c.bookmark_switch("feature", false).unwrap();
4884
    write(work.path(), "b.txt", "more\n");
4885
    c.snapshot("test").unwrap();
4886
    c.commit("More", &[]).unwrap();
4887
    assert!(c.push_bookmark("origin", "feature", false).unwrap().iter().all(|r| r.ok));
4888
    let runs_before =
4889
        db::flow::runs(&h.app.db, db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap().id, 10, None).await.unwrap().len();
4890
4891
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4892
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
4893
    db::proposals::create(
4894
        &h.app.db,
4895
        db::proposals::NewProposal {
4896
            repo_id: row.id,
4897
            title: "More",
4898
            body: "",
4899
            author_id: Some(andy.id),
4900
            author: "andy",
4901
            draft: false,
4902
            target: "main",
4903
            source_kind: "bookmark",
4904
            source_repo_id: Some(row.id),
4905
            source_bookmark: "feature",
4906
            source_changes: "",
4907
        },
4908
    )
4909
    .await
4910
    .unwrap();
4911
    let repo = RepoName::parse("andy/demo").unwrap();
4912
    let state = oxygenhub::web::proposals::land_as(&h.app, &repo, &row, &andy, 1, "web", false, None).await.ok().expect("landed");
4913
    let mut runs = vec![];
4914
    for _ in 0..100 {
4915
        runs = db::flow::runs(&h.app.db, row.id, 10, None).await.unwrap();
4916
        if runs.len() > runs_before {
4917
            break;
4918
        }
4919
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4920
    }
4921
    let landed = runs.iter().find(|r| r.bookmark == "main" && r.state == state).expect("a run of the landed state on main");
4922
    assert_eq!((landed.trigger.as_str(), landed.actor.as_str()), ("push", "andy"));
4923
}
4924
4925
/// #225: an ordinary user turns Flow on for their repository on their own
4926
/// runner, and the site's runners never take its jobs.
4927
#[tokio::test(flavor = "multi_thread")]
4928
async fn owners_run_flow_on_their_own_runners_only() {
4929
    use oxy_core::identity::SecretKey;
4930
    let h = hub().await;
4931
    let register = |name: &'static str| {
4932
        let app = h.app.clone();
4933
        async move {
4934
            let body = format!("username={name}&email={name}%40example.com&password=correct-horse-battery&setup=test-setup");
4935
            let res = oxygenhub::router(app)
4936
                .oneshot(
4937
                    Request::post("/register")
4938
                        .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
4939
                        .body(Body::from(body))
4940
                        .unwrap(),
4941
                )
4942
                .await
4943
                .unwrap();
4944
            res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string()
4945
        }
4946
    };
4947
    register("andy").await; // the first account: the site's administrator
4948
    let bob = register("bob").await;
4949
    create(&h.app, "bob", "game").await;
4950
    let web = |method: &'static str, path: &str, body: Option<String>| {
4951
        let (app, cookie, path) = (h.app.clone(), bob.clone(), path.to_string());
4952
        async move {
4953
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie.clone());
4954
            if body.is_some() {
4955
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
4956
            }
4957
            let req = req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap();
4958
            let mut res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
4959
            // A repository settings form returns to its page (#278).
4960
            let back =
4961
                res.headers().get(header::LOCATION).and_then(|v| v.to_str().ok()).filter(|l| l.contains("/settings/")).map(String::from);
4962
            if let Some(to) = back {
4963
                let req = Request::get(to).header(header::COOKIE, cookie).body(Body::empty()).unwrap();
4964
                res = oxygenhub::router(app).oneshot(req).await.unwrap();
4965
            }
4966
            String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned()
4967
        }
4968
    };
4969
    let csrf_of = |page: &str| {
4970
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
4971
        page[i..].split('"').next().unwrap().to_string()
4972
    };
4973
    // No runner of his own yet: he is told how, and cannot switch it on.
4974
    let page = web("GET", "/bob/game/settings/flow", None).await;
4975
    assert!(page.contains("register a runner for this repository") && !page.contains("value=\"own\""), "{page}");
4976
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=own", csrf_of(&page)))).await;
4977
    assert!(page.contains("Register a runner for this repository"), "{page}");
4978
    // He registers one.
4979
    let page = web("GET", "/bob/game/settings", None).await;
4980
    let page = web("POST", "/bob/game/settings/runners/token", Some(format!("_csrf={}", csrf_of(&page)))).await;
4981
    let i = page.find("--token ").unwrap() + "--token ".len();
4982
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
4983
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
4984
    let identity = SecretKey::generate().identity("bobs", "", 1);
4985
    let reg = serde_json::json!({ "token": token, "name": "bobs", "identity": hex::encode(identity.encode()), "info": info });
4986
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
4987
    assert_eq!(st, StatusCode::OK, "{body}");
4988
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
4989
    // The site's runners stay a site administrator's to grant; his own he may choose.
4990
    let page = web("GET", "/bob/game/settings/flow", None).await;
4991
    assert!(page.contains("value=\"own\"") && !page.contains("value=\"on\""), "{page}");
4992
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=on", csrf_of(&page)))).await;
4993
    assert!(page.contains("Only site administrators let the site's runners"), "{page}");
4994
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=own", csrf_of(&page)))).await;
4995
    assert!(page.contains("value=\"own\" checked") && page.contains("start runs"), "{page}");
4996
    assert_eq!(db::repos::get(&h.app.db, "bob", "game").await.unwrap().unwrap().flow, "own");
4997
    // A push starts a run; the site's runner is not offered it, his is.
4998
    let work = tempfile::tempdir().unwrap();
4999
    let c = client(&format!("{}/bob/game", h.base), work.path());
5000
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5001
    write(work.path(), "test.sh", "echo ok\n");
5002
    c.snapshot("t").unwrap();
5003
    c.commit("A pipeline", &[]).unwrap();
5004
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5005
    assert_eq!(runs_of(&h.app, "bob", "game").await.len(), 1, "a run started");
5006
    assert!(claim(&h.app).await.is_none(), "the site's runner is not offered it");
5007
    let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
5008
    let (st, job) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(body)).await;
5009
    assert_eq!(st, StatusCode::OK, "{job}");
5010
    assert_eq!(serde_json::from_str::<serde_json::Value>(&job).unwrap()["repo"], "bob/game");
5011
}
5012
5013
#[tokio::test(flavor = "multi_thread")]
5014
async fn a_job_takes_the_artifact_its_producer_kept() {
5015
    let h = hub().await;
5016
    create(&h.app, "andy", "demo").await;
5017
    let url = format!("{}/andy/demo", h.base);
5018
    let work = tempfile::tempdir().unwrap();
5019
    let c = client(&url, work.path());
5020
    write(
5021
        work.path(),
5022
        ".flow/pipeline.kdl",
5023
        &format!(
5024
            "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"
5025
        ),
5026
    );
5027
    c.snapshot("test").unwrap();
5028
    c.commit("Plan, then apply that plan", &[]).unwrap();
5029
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5030
5031
    // The plan job runs and keeps its plan, named by its receipt.
5032
    let runs = runs_of(&h.app, "andy", "demo").await;
5033
    assert_eq!(runs.len(), 1, "a run");
5034
    let jobs = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap();
5035
    assert!(!jobs.is_empty(), "jobs: {:?}", runs[0]);
5036
    let p = claim(&h.app)
5037
        .await
5038
        .unwrap_or_else(|| panic!("nothing to claim: {:?}", jobs.iter().map(|j| (&j.name, &j.status, &j.error)).collect::<Vec<_>>()));
5039
    assert_eq!(p["job"]["name"], "plan");
5040
    let plan_id = p["job_id"].as_i64().unwrap();
5041
    let plan = b"the reviewed plan".to_vec();
5042
    let (st, text) = upload(&h.app, plan_id, "tfplan", &plan).await;
5043
    assert_eq!(st, StatusCode::OK, "{text}");
5044
    let blob = oxy_core::repo::Repo::blob_ref(&plan).to_hex();
5045
    let mut r = receipt("plan", p["pipeline_hash"].as_str().unwrap(), 0);
5046
    r["outputs"] = serde_json::json!([blob]);
5047
    assert_eq!(
5048
        finish(&h.app, plan_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r })).await,
5049
        StatusCode::NO_CONTENT
5050
    );
5051
5052
    // The apply job is told what to take and the blob to expect, and the
5053
    // runner fetches exactly those bytes.
5054
    let a = claim(&h.app).await.unwrap();
5055
    assert_eq!(a["job"]["name"], "apply");
5056
    let apply_id = a["job_id"].as_i64().unwrap();
5057
    assert_eq!(
5058
        a["inputs"],
5059
        serde_json::json!([{ "artifact": "tfplan", "from": "plan", "path": "/src/tfplan", "blob": blob }]),
5060
        "the claim names the producer's blob"
5061
    );
5062
    let req = Request::get(format!("/api/v1/flow/jobs/{apply_id}/inputs/0")).header(header::AUTHORIZATION, "Bearer runner-secret");
5063
    let res = oxygenhub::router(h.app.clone()).oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
5064
    assert_eq!(res.status(), StatusCode::OK);
5065
    assert_eq!(res.into_body().collect().await.unwrap().to_bytes().to_vec(), plan);
5066
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{apply_id}/inputs/1"), Some("runner-secret"), None).await;
5067
    assert_eq!(st, StatusCode::NOT_FOUND, "no second input");
5068
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{apply_id}/inputs/0"), None, None).await;
5069
    assert_eq!(st, StatusCode::UNAUTHORIZED, "runners only");
5070
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{plan_id}/inputs/0"), Some("runner-secret"), None).await;
5071
    assert_eq!(st, StatusCode::CONFLICT, "only a running job's");
5072
}
5073
5074
#[tokio::test(flavor = "multi_thread")]
5075
async fn a_job_waits_for_approval_and_is_approved_rejected_or_expires() {
5076
    let h = hub().await;
5077
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
5078
    let bob = db::accounts::create_account(&h.app.db, "bob", "[email protected]", "x", "salt", false).await.unwrap();
5079
    let carol = db::accounts::create_account(&h.app.db, "carol", "[email protected]", "x", "salt", true).await.unwrap();
5080
    create(&h.app, "andy", "gated").await;
5081
    let row = db::repos::get(&h.app.db, "andy", "gated").await.unwrap().unwrap();
5082
    let work = tempfile::tempdir().unwrap();
5083
    let c = client(&format!("{}/andy/gated", h.base), work.path());
5084
    write(
5085
        work.path(),
5086
        ".flow/pipeline.kdl",
5087
        &format!(
5088
            "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"
5089
        ),
5090
    );
5091
    let mut n = 0;
5092
    let mut push = || {
5093
        n += 1;
5094
        write(work.path(), "n.txt", &format!("{n}\n"));
5095
        c.snapshot("test").unwrap();
5096
        c.commit(&format!("Push {n}"), &[]).unwrap();
5097
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5098
    };
5099
    // Runs `plan` to a pass; returns the run, its actor set to andy.
5100
    let plan_passes = |number: i64| {
5101
        let app = h.app.clone();
5102
        let row = row.clone();
5103
        async move {
5104
            let mut run = None;
5105
            for _ in 0..100 {
5106
                if let Some(r) = db::flow::run(&app.db, row.id, number).await.unwrap() {
5107
                    run = Some(r);
5108
                    break;
5109
                }
5110
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
5111
            }
5112
            let run = run.expect("the run");
5113
            sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&app.db).await.unwrap();
5114
            let j = claim(&app).await.expect("plan is claimed");
5115
            assert_eq!(j["job"]["name"], "plan");
5116
            let (id, ph) = (j["job_id"].as_i64().unwrap(), j["pipeline_hash"].as_str().unwrap().to_string());
5117
            finish(&app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("plan", &ph, 0) })).await;
5118
            db::flow::run(&app.db, row.id, number).await.unwrap().unwrap()
5119
        }
5120
    };
5121
5122
    // Run 1: apply waits; only someone with the role, other than the pusher, approves it.
5123
    push();
5124
    let run = runs_of(&h.app, "andy", "gated").await[0].clone();
5125
    // Live pages hear of the push (oxygenhub#203).
5126
    let heard = |topic: String| match h.app.bus.live.since(0, &[topic]) {
5127
        oxygenhub::events::Replay::Events(e) => e.into_iter().map(|e| e.kind).collect::<Vec<_>>(),
5128
        oxygenhub::events::Replay::Reload => vec!["reload".into()],
5129
    };
5130
    assert!(heard(oxygenhub::events::topic::repo(row.id)).contains(&"push".to_string()), "the push is on the repository's topic");
5131
    sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&h.app.db).await.unwrap();
5132
    let early = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true, None).await.unwrap_err();
5133
    assert!(early.contains("waits for plan first"), "{early}");
5134
    let run = plan_passes(run.number).await;
5135
    assert!(claim(&h.app).await.is_none(), "apply waits for a person, so no runner gets it");
5136
    assert!(heard(oxygenhub::events::topic::run(run.id)).contains(&"jobs".to_string()), "the run's topic hears its jobs");
5137
    // Those who may approve are told, once; the pusher (others-only) and
5138
    // someone without the role are not.
5139
    let told = |id: i64| {
5140
        let db = h.app.db.clone();
5141
        async move { db::notify::inbox(&db, id, 20).await.unwrap().into_iter().filter(|n| n.kind == "flow.approval").count() }
5142
    };
5143
    assert_eq!((told(carol.id).await, told(andy.id).await, told(bob.id).await), (1, 0, 0));
5144
    let (_, page) = call(&h.app, "GET", &format!("/andy/gated/flow/{}", run.number), None, None).await;
5145
    assert!(page.contains("waits for approval by someone with the <em>maintain</em> role, other than andy"), "the run page says so");
5146
    // The API says which job waits for a person (oxygenhub-android#5).
5147
    let (_, v) = call(&h.app, "GET", &format!("/api/v1/repos/andy/gated/flow/runs/{}", run.number), None, None).await;
5148
    let v: serde_json::Value = serde_json::from_str(&v).unwrap();
5149
    let apply = v["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "apply").unwrap().clone();
5150
    assert_eq!(apply["approval"], "waiting", "{v}");
5151
    assert!(v["jobs"].as_array().unwrap().iter().filter(|j| j["name"] != "apply").all(|j| j.get("approval").is_none()), "{v}");
5152
    let own = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &andy, true, None).await.unwrap_err();
5153
    assert!(own.contains("someone other than andy"), "{own}");
5154
    let no_role = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &bob, true, None).await.unwrap_err();
5155
    assert!(no_role.contains("takes the maintain role"), "{no_role}");
5156
    assert_eq!(oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true, None).await.unwrap(), "apply: approved by carol");
5157
    assert_eq!(told(carol.id).await, 1, "told once");
5158
    let j = claim(&h.app).await.expect("approved, it runs");
5159
    assert_eq!(j["job"]["name"], "apply");
5160
    // Approved, its identity token names the environment (oxygenflow#59).
5161
    let token =
5162
        j["secrets"].as_array().unwrap().iter().find(|s| s["path"] == "/run/secrets/cloud").unwrap()["value"].as_str().unwrap().to_string();
5163
    let claims = h.app.oidc().await.unwrap().verify(&token, "https://sts.example", db::now_ms()).expect("a valid token");
5164
    assert_eq!(claims["environment"], "prod");
5165
    let (id, ph) = (j["job_id"].as_i64().unwrap(), j["pipeline_hash"].as_str().unwrap().to_string());
5166
    finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("apply", &ph, 0) })).await;
5167
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
5168
    assert!(audit.iter().any(|r| r.action == "flow.approved" && r.actor == "carol" && r.target.ends_with("#1 apply")), "audited");
5169
    let (_, page) = call(&h.app, "GET", &format!("/andy/gated/flow/{}", run.number), None, None).await;
5170
    assert!(page.contains("approved by carol"), "the run says who");
5171
    let (_, page) = call(&h.app, "GET", "/andy/gated/deployments", None, None).await;
5172
    assert!(page.contains("<strong>prod</strong>") && page.contains(">#1</a>") && page.contains("<td>carol</td>"), "the Deployments page");
5173
    let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/gated/deployments", Some("site"), None).await;
5174
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
5175
    assert_eq!((list[0]["environment"].as_str(), list[0]["approved_by"].as_str()), (Some("prod"), Some("carol")));
5176
5177
    // Run 2: rejected through the API with carol's agent token: the job
5178
    // ends cancelled, the run ends, and it says the agent did it
5179
    // (oxygenhub#229).
5180
    push();
5181
    let run = plan_passes(2).await;
5182
    let (secret, hash) = oxygenhub::auth::new_token();
5183
    let tok = db::accounts::create_token(&h.app.db, carol.id, "claude-code", &hash, "repo:write", "", None).await.unwrap();
5184
    db::accounts::set_token_agent(&h.app.db, carol.id, tok.id, true).await.unwrap();
5185
    // An agent's token decides a gate only where the repository allows it
5186
    // (#258).
5187
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/gated/flow/runs/2/jobs/apply/reject", Some(&secret), Some("{}".into())).await;
5188
    assert_eq!(st, StatusCode::CONFLICT, "{body}");
5189
    assert!(body.contains("decided by a person here") && body.contains("Settings › OxygenFlow"), "{body}");
5190
    let gated = db::repos::get(&h.app.db, "andy", "gated").await.unwrap().unwrap();
5191
    db::repos::set_agents_decide_gates(&h.app.db, gated.id, true).await.unwrap();
5192
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/gated/flow/runs/2/jobs/apply/reject", Some(&secret), Some("{}".into())).await;
5193
    assert_eq!(st, StatusCode::OK, "{body}");
5194
    assert!(body.contains("rejected by carol via claude-code"), "{body}");
5195
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
5196
    let apply = jobs.iter().find(|j| j.name == "apply").unwrap();
5197
    assert_eq!((apply.status.as_str(), apply.error.as_str()), ("cancelled", "rejected by carol via claude-code"));
5198
    assert_eq!((apply.approved_by.as_str(), apply.approved_via.as_str()), ("carol", "claude-code"));
5199
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
5200
    assert!(
5201
        audit.iter().any(|r| r.action == "flow.rejected" && r.actor == "carol" && r.detail.contains("via claude-code")),
5202
        "audited with the agent"
5203
    );
5204
    assert!(claim(&h.app).await.is_none());
5205
5206
    // Run 3: nobody decides in time.
5207
    push();
5208
    let run = plan_passes(3).await;
5209
    assert_eq!(oxygenhub::flow::expire_approvals(&h.app, db::now_ms() + 3_600_000).await.unwrap(), 0, "not yet");
5210
    assert_eq!(oxygenhub::flow::expire_approvals(&h.app, db::now_ms() + 25 * 3_600_000).await.unwrap(), 1);
5211
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
5212
    let apply = jobs.iter().find(|j| j.name == "apply").unwrap();
5213
    assert_eq!((apply.status.as_str(), apply.error.as_str()), ("cancelled", "no approval within 24h"));
5214
}
5215
5216
#[tokio::test(flavor = "multi_thread")]
5217
async fn live_streams_only_topics_the_viewer_may_hear_and_replays() {
5218
    let h = hub().await;
5219
    create(&h.app, "andy", "open").await;
5220
    h.app.repos.create(&RepoName::parse("andy/shut").unwrap(), None).unwrap();
5221
    db::repos::create(&h.app.db, "andy", "shut", "", hub_api::Visibility::Private).await.unwrap();
5222
    let open = db::repos::get(&h.app.db, "andy", "open").await.unwrap().unwrap();
5223
    let shut = db::repos::get(&h.app.db, "andy", "shut").await.unwrap().unwrap();
5224
    let live = &h.app.bus.live;
5225
    let first = live.publish(&oxygenhub::events::topic::repo(open.id), "push");
5226
    live.publish(&oxygenhub::events::topic::repo(shut.id), "push");
5227
    live.publish(&oxygenhub::events::topic::proposal(open.id, 3), "review");
5228
5229
    // The first bytes of a stream, within a moment.
5230
    let read = |path: String, last: Option<u64>| {
5231
        let app = h.app.clone();
5232
        async move {
5233
            let mut req = Request::get(&path);
5234
            if let Some(l) = last {
5235
                req = req.header("last-event-id", l.to_string());
5236
            }
5237
            let res = oxygenhub::router(app).oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
5238
            let status = res.status();
5239
            let mut body = res.into_body();
5240
            let mut text = String::new();
5241
            while let Ok(Some(Ok(frame))) = tokio::time::timeout(std::time::Duration::from_millis(300), body.frame()).await {
5242
                if let Some(d) = frame.data_ref() {
5243
                    text.push_str(&String::from_utf8_lossy(d));
5244
                }
5245
            }
5246
            (status, text)
5247
        }
5248
    };
5249
    let topics = format!("/live?topics=repo:{},repo:{}/proposal:3", open.id, open.id);
5250
    // From the first event on: what came after it on these topics only.
5251
    let (st, text) = read(topics.clone(), Some(first.id)).await;
5252
    assert_eq!(st, StatusCode::OK);
5253
    assert!(text.contains("event: change") && text.contains(&format!("\"topic\":\"repo:{}/proposal:3\"", open.id)), "{text}");
5254
    assert!(!text.contains(&format!("\"topic\":\"repo:{}\"", shut.id)), "never another topic: {text}");
5255
    assert!(!text.contains(&format!("id: {}\n", first.id)), "not what was already seen: {text}");
5256
    // A private repository's topic, or someone else's, is refused whole.
5257
    let (st, _) = read(format!("/live?topics=repo:{},repo:{}", open.id, shut.id), None).await;
5258
    assert_eq!(st, StatusCode::FORBIDDEN);
5259
    assert_eq!(read("/live?topics=user:1".into(), None).await.0, StatusCode::FORBIDDEN);
5260
    assert_eq!(read("/live?topics=nonsense".into(), None).await.0, StatusCode::BAD_REQUEST);
5261
    assert_eq!(read("/live?topics=".into(), None).await.0, StatusCode::BAD_REQUEST);
5262
    // Too far behind: told to reload.
5263
    for _ in 0..oxygenhub::events::REPLAY {
5264
        live.publish("repo:999999", "push");
5265
    }
5266
    let (_, text) = read(topics, Some(first.id)).await;
5267
    assert!(text.contains("event: reload"), "{text}");
5268
}
5269
5270
#[tokio::test(flavor = "multi_thread")]
5271
async fn a_sealed_approval_releases_exactly_the_reviewed_plan() {
5272
    use oxy_core::approval::{SignedApproval, Statement};
5273
    use oxy_core::hash::ObjectRef;
5274
    use oxy_core::identity::SecretKey;
5275
    let h = hub().await;
5276
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
5277
    let carol = db::accounts::create_account(&h.app.db, "carol", "[email protected]", "x", "salt", true).await.unwrap();
5278
    let sk = SecretKey::generate();
5279
    let carol_id = sk.identity("Carol", "[email protected]", 1);
5280
    db::accounts::link_identity(&h.app.db, carol.id, &carol_id.hash().to_hex(), "Carol", "[email protected]", &carol_id.encode())
5281
        .await
5282
        .unwrap();
5283
    create(&h.app, "andy", "infra").await;
5284
    let row = db::repos::get(&h.app.db, "andy", "infra").await.unwrap().unwrap();
5285
    let work = tempfile::tempdir().unwrap();
5286
    let c = client(&format!("{}/andy/infra", h.base), work.path());
5287
    write(
5288
        work.path(),
5289
        ".flow/pipeline.kdl",
5290
        &format!(
5291
            "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"
5292
        ),
5293
    );
5294
    c.snapshot("test").unwrap();
5295
    c.commit("Plan, then apply", &[]).unwrap();
5296
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5297
    let run = runs_of(&h.app, "andy", "infra").await[0].clone();
5298
    let p = claim(&h.app).await.unwrap();
5299
    let plan_id = p["job_id"].as_i64().unwrap();
5300
    let plan = b"the reviewed plan".to_vec();
5301
    upload(&h.app, plan_id, "tfplan", &plan).await;
5302
    let mut r = receipt("plan", p["pipeline_hash"].as_str().unwrap(), 0);
5303
    r["outputs"] = serde_json::json!([oxy_core::repo::Repo::blob_ref(&plan).to_hex()]);
5304
    finish(&h.app, plan_id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": r })).await;
5305
    let run = db::flow::run(&h.app.db, row.id, run.number).await.unwrap().unwrap();
5306
5307
    // An environment's gate takes a sealed approval: pressing Approve is not enough.
5308
    let plain = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true, None).await.unwrap_err();
5309
    assert!(plain.contains(&format!("oxy seal --flow {}/andy/infra/flow/{} --job apply", h.base, run.number)), "{plain}");
5310
    // What there is to sign.
5311
    let (st, body) =
5312
        call(&h.app, "GET", &format!("/api/v1/repos/andy/infra/flow/runs/{}/jobs/apply/approval", run.number), Some("site"), None).await;
5313
    assert_eq!(st, StatusCode::OK, "{body}");
5314
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
5315
    assert_eq!(v["environment"], "prod");
5316
    assert_eq!(v["inputs"], serde_json::json!([oxy_core::repo::Repo::blob_ref(&plan).to_hex()]), "the reviewed plan");
5317
    let mut repo = [0u8; 16];
5318
    repo.copy_from_slice(&hex::decode(v["repo"].as_str().unwrap()).unwrap());
5319
    let oref = |k: &str| ObjectRef::from_hex(v[k].as_str().unwrap()).unwrap();
5320
    let statement = Statement {
5321
        repo,
5322
        run: v["run"].as_str().unwrap().into(),
5323
        job: "apply".into(),
5324
        job_hash: oref("job_hash"),
5325
        state: oref("state"),
5326
        inputs: v["inputs"].as_array().unwrap().iter().map(|i| ObjectRef::from_hex(i.as_str().unwrap()).unwrap()).collect(),
5327
        environment: "prod".into(),
5328
        approve: true,
5329
    };
5330
    let seal = |s: &Statement, key: &SecretKey, id: &oxy_core::identity::Identity| {
5331
        let body = serde_json::json!({ "signed": hex::encode(SignedApproval::sign(s, id, key).encode()) }).to_string();
5332
        let app = h.app.clone();
5333
        let path = format!("/api/v1/repos/andy/infra/flow/runs/{}/jobs/apply/seal", run.number);
5334
        async move { call(&app, "POST", &path, Some("site"), Some(body)).await }
5335
    };
5336
    // Another plan, or a key linked to nobody (an agent's), is refused.
5337
    let other_plan = Statement { inputs: vec![ObjectRef([9; 32])], ..statement.clone() };
5338
    let (st, body) = seal(&other_plan, &sk, &carol_id).await;
5339
    assert!(st == StatusCode::CONFLICT && body.contains("approves something else"), "{st} {body}");
5340
    let agent = SecretKey::generate();
5341
    let agent_id = agent.identity("Claude Code", "[email protected]", 1);
5342
    let (st, body) = seal(&statement, &agent, &agent_id).await;
5343
    assert!(st == StatusCode::CONFLICT && body.contains("not linked to an account"), "{st} {body}");
5344
    assert!(claim(&h.app).await.is_none(), "still waiting");
5345
5346
    // Carol's seal releases it; it is kept in the repository; the token names her and it.
5347
    let (st, body) = seal(&statement, &sk, &carol_id).await;
5348
    assert_eq!(st, StatusCode::OK, "{body}");
5349
    assert!(body.contains("approved by carol, sealed"), "{body}");
5350
    let name = oxygenhub::repos::RepoName::parse("andy/infra").unwrap();
5351
    let state = statement.state;
5352
    let kept = h.app.repos.read(&name, move |r, _| Ok(r.store().approvals_for(&state)?)).await.unwrap();
5353
    assert_eq!(kept.len(), 1, "the approval is in the repository");
5354
    let j = claim(&h.app).await.expect("released");
5355
    assert_eq!(j["job"]["name"], "apply");
5356
    let token =
5357
        j["secrets"].as_array().unwrap().iter().find(|s| s["path"] == "/run/secrets/cloud").unwrap()["value"].as_str().unwrap().to_string();
5358
    let claims = h.app.oidc().await.unwrap().verify(&token, "https://sts.example", db::now_ms()).unwrap();
5359
    assert_eq!((claims["environment"].as_str(), claims["approved_by"].as_str()), (Some("prod"), Some("carol")));
5360
    assert_eq!(claims["approval"].as_str(), Some(kept[0].to_hex().as_str()));
5361
    let (_, page) = call(&h.app, "GET", &format!("/andy/infra/flow/{}", run.number), None, None).await;
5362
    assert!(page.contains("sealed with their key"), "the run page says so");
5363
}
5364
5365
/// Repositories take turns (oxygenhub#244): a repository with a job running
5366
/// waits behind one with none, so a burst can't hold up the rest.
5367
#[tokio::test(flavor = "multi_thread")]
5368
async fn repositories_take_turns_on_the_runners() {
5369
    let h = hub().await;
5370
    for name in ["busy", "quiet"] {
5371
        create(&h.app, "andy", name).await;
5372
        let work = tempfile::tempdir().unwrap();
5373
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
5374
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5375
        write(work.path(), "test.sh", "echo ok\n");
5376
        c.snapshot("test").unwrap();
5377
        c.commit("Add a pipeline", &[]).unwrap();
5378
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5379
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
5380
    }
5381
    // busy pushed first: its first job goes first; then quiet's turn, though
5382
    // busy's other independent job is older; then busy's again.
5383
    let order: Vec<String> = {
5384
        let mut out = Vec::new();
5385
        for _ in 0..3 {
5386
            let c = claim(&h.app).await.expect("a job to claim");
5387
            out.push(c["repo"].as_str().unwrap().to_string());
5388
        }
5389
        out
5390
    };
5391
    assert_eq!(order, ["andy/busy", "andy/quiet", "andy/busy"]);
5392
}
5393
5394
/// A pipeline lowers its jobs, never raises them (oxygenhub#244): a
5395
/// repository whose pipeline says `priority "low"` waits for another's
5396
/// everyday jobs, even set high itself; the queue says why; an expedited
5397
/// run is still urgent.
5398
#[tokio::test(flavor = "multi_thread")]
5399
async fn a_pipeline_lowers_its_jobs_and_expediting_still_wins() {
5400
    let h = hub().await;
5401
    for (name, extra) in [("nightly", "priority \"low\"\n"), ("everyday", "")] {
5402
        create(&h.app, "andy", name).await;
5403
        let work = tempfile::tempdir().unwrap();
5404
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
5405
        write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
5406
        write(work.path(), "test.sh", "echo ok\n");
5407
        c.snapshot("test").unwrap();
5408
        c.commit("Add a pipeline", &[]).unwrap();
5409
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5410
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
5411
    }
5412
    let nightly = db::repos::get(&h.app.db, "andy", "nightly").await.unwrap().unwrap();
5413
    db::repos::set_flow_priority(&h.app.db, nightly.id, "high").await.unwrap();
5414
    let q = db::flow::queue(&h.app.db).await.unwrap();
5415
    assert!(
5416
        q.iter().filter(|e| e.name == "nightly").all(|e| e.priority() == "low" && e.priority_note == "pipeline: low"),
5417
        "{:?}",
5418
        q.iter().map(|e| (&e.name, e.priority(), &e.priority_note)).collect::<Vec<_>>()
5419
    );
5420
    let repo_of = |c: serde_json::Value| c["repo"].as_str().unwrap().to_string();
5421
    // nightly pushed first and its repository is high, but its pipeline
5422
    // says low: everyday's jobs go first.
5423
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/everyday");
5424
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/everyday");
5425
    let run = &runs_of(&h.app, "andy", "nightly").await[0];
5426
    assert!(db::flow::expedite(&h.app.db, run.id, "expedited by andy: needed now").await.unwrap());
5427
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/nightly", "an expedited run is urgent whatever its jobs say");
5428
}
5429
5430
/// Priority comes before taking turns (oxygenhub#244): a low repository's
5431
/// jobs wait for a normal one's, and an expedited run goes first of all.
5432
#[tokio::test(flavor = "multi_thread")]
5433
async fn priority_then_turns_and_an_expedited_run_first() {
5434
    let h = hub().await;
5435
    for name in ["early", "later"] {
5436
        create(&h.app, "andy", name).await;
5437
        let work = tempfile::tempdir().unwrap();
5438
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
5439
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5440
        write(work.path(), "test.sh", "echo ok\n");
5441
        c.snapshot("test").unwrap();
5442
        c.commit("Add a pipeline", &[]).unwrap();
5443
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5444
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
5445
    }
5446
    let early = db::repos::get(&h.app.db, "andy", "early").await.unwrap().unwrap();
5447
    db::repos::set_flow_priority(&h.app.db, early.id, "low").await.unwrap();
5448
    // early pushed first, but it is low: later's jobs go first.
5449
    let repo_of = |c: serde_json::Value| c["repo"].as_str().unwrap().to_string();
5450
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/later");
5451
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/later");
5452
    // Expedited, early's run goes before anything else.
5453
    let run = &runs_of(&h.app, "andy", "early").await[0];
5454
    assert!(db::flow::expedite(&h.app.db, run.id, "expedited by andy: an incident").await.unwrap());
5455
    // What the cap on expedited runs counts: andy's live urgent runs.
5456
    assert_eq!(db::flow::expedited_live(&h.app.db, "andy").await.unwrap(), 1);
5457
    assert_eq!(db::flow::expedited_live(&h.app.db, "someone-else").await.unwrap(), 0);
5458
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/early");
5459
    let q = db::flow::queue(&h.app.db).await.unwrap();
5460
    assert!(
5461
        q.iter().any(|e| e.name == "early" && e.priority() == "urgent" && e.priority_note.contains("an incident")),
5462
        "{:?}",
5463
        q.iter().map(|e| (&e.name, e.priority())).collect::<Vec<_>>()
5464
    );
5465
    // The site's level is the default for everyone else.
5466
    db::accounts::set_setting(&h.app.db, "flow_priority", "high").await.unwrap();
5467
    let q = db::flow::queue(&h.app.db).await.unwrap();
5468
    assert!(q.iter().filter(|e| e.name == "later").all(|e| e.priority() == "high"));
5469
}
5470
5471
/// Keyless (oxygenhub#241): a running job's token gets a ten-minute
5472
/// certificate for a fresh key from the hub, signed with the hub's key and
5473
/// naming the job's repository and bookmark; a proof made for another
5474
/// credential, an OIDC token for another audience, and a finished job's
5475
/// token get nothing.
5476
#[tokio::test(flavor = "multi_thread")]
5477
async fn a_running_job_gets_a_short_certificate_for_a_fresh_key() {
5478
    use oxy_core::cert::{certify_challenge, SignedCertificate};
5479
    use oxy_core::identity::{Scope, SecretKey};
5480
    let h = hub().await;
5481
    create(&h.app, "andy", "demo").await;
5482
    let work = tempfile::tempdir().unwrap();
5483
    let c = client(&format!("{}/andy/demo", h.base), work.path());
5484
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5485
    write(work.path(), "test.sh", "echo ok\n");
5486
    c.snapshot("test").unwrap();
5487
    c.commit("Add a pipeline", &[]).unwrap();
5488
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5489
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
5490
    let job = claim(&h.app).await.expect("a job");
5491
    let token = job["token"].as_str().unwrap().to_string();
5492
    let job_id = job["job_id"].as_i64().unwrap();
5493
5494
    let sk = SecretKey::generate();
5495
    let id = sk.identity("job", "[email protected]", 1);
5496
    let ask = |credential: &str, signed_for: &str| {
5497
        let proof = sk.sign_challenge(&id.hash(), &certify_challenge(signed_for)).unwrap();
5498
        let body = serde_json::json!({
5499
            "identity": oxy_core::dsse::base64(&id.encode()),
5500
            "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
5501
            "scope": "changes,refs",
5502
        });
5503
        let (credential, app) = (credential.to_string(), h.app.clone());
5504
        async move { call(&app, "POST", "/api/v1/keyless/certify", Some(&credential), Some(body.to_string())).await }
5505
    };
5506
    let (st, body) = ask(&token, &token).await;
5507
    assert_eq!(st, StatusCode::OK, "{body}");
5508
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
5509
    let sc = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
5510
    assert!(sc.verify(&h.app.hub_key.identity).is_ok(), "signed with the hub's key");
5511
    assert_eq!(sc.cert.key_id(), id.hash());
5512
    assert_eq!(sc.cert.subject, "repo:andy/demo:bookmark:main");
5513
    assert_eq!(sc.cert.claim("repository"), Some("andy/demo"));
5514
    assert!(sc.cert.claim("job").is_some() && sc.cert.claim("run") == Some("1"));
5515
    assert_eq!(sc.cert.scope, Scope::CHANGES | Scope::REFS);
5516
    assert!(sc.cert.expires - sc.cert.not_before <= 10 * 60_000 + 30_000, "ten minutes");
5517
5518
    // A proof made for another credential is not this one's.
5519
    let (st, body) = ask(&token, "flowjob_someone_else").await;
5520
    assert_eq!(st, StatusCode::UNAUTHORIZED, "{body}");
5521
    assert!(body.contains("the proof does not show"), "{body}");
5522
5523
    // The hub's own OIDC token, for the keyless audience, works too; for
5524
    // another audience it does not.
5525
    let issuer = h.app.oidc().await.unwrap();
5526
    let now = oxygenhub::db::now_ms();
5527
    let aud = oxygenhub::keyless::audience(h.app.config.base_url());
5528
    let good = issuer.mint_for(h.app.config.base_url(), "agent:claude@andy", &aud, now, 600);
5529
    let (st, body) = ask(&good, &good).await;
5530
    assert_eq!(st, StatusCode::OK, "{body}");
5531
    assert!(body.contains("\"subject\":\"agent:claude@andy\""), "{body}");
5532
    let other = issuer.mint_for(h.app.config.base_url(), "agent:claude@andy", "sts.amazonaws.com", now, 600);
5533
    let (st, _) = ask(&other, &other).await;
5534
    assert_eq!(st, StatusCode::UNAUTHORIZED);
5535
5536
    // A job that has finished asks with a token that no longer counts.
5537
    sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE id = $1").bind(job_id).execute(&h.app.db).await.unwrap();
5538
    let (st, body) = ask(&token, &token).await;
5539
    assert_eq!(st, StatusCode::UNAUTHORIZED, "{body}");
5540
}
5541
5542
/// Keyless step 3 (oxygenhub#241): a job signs its receipt with a fresh
5543
/// key the hub certified for it, and the hub keeps the receipt without
5544
/// binding any runner key; a certificate for another job, or from another
5545
/// issuer, is not this job's.
5546
#[tokio::test(flavor = "multi_thread")]
5547
async fn a_receipt_signed_by_a_certified_key_is_kept() {
5548
    use oxy_core::cert::{certify_challenge, SignedCertificate};
5549
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
5550
    use oxy_core::identity::SecretKey;
5551
    use oxy_core::objects::StateObject;
5552
    use oxy_core::receipt::SignedReceipt;
5553
    let h = hub().await;
5554
    create(&h.app, "andy", "demo").await;
5555
    let url = format!("{}/andy/demo", h.base);
5556
    let work = tempfile::tempdir().unwrap();
5557
    let c = client(&url, work.path());
5558
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5559
    c.snapshot("test").unwrap();
5560
    c.commit("Add a pipeline", &[]).unwrap();
5561
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5562
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
5563
    let heads: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
5564
    let state = hash_object(ObjectType::State, &StateObject::new(heads.clone()).encode());
5565
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
5566
5567
    // Certify a fresh key with a job's token, as a runner does just before
5568
    // it signs the receipt.
5569
    let certify = |token: String| {
5570
        let app = h.app.clone();
5571
        async move {
5572
            let sk = SecretKey::generate();
5573
            let id = sk.identity("test-1 job", "", 1);
5574
            let proof = sk.sign_challenge(&id.hash(), &certify_challenge(&token)).unwrap();
5575
            let body = serde_json::json!({
5576
                "identity": oxy_core::dsse::base64(&id.encode()),
5577
                "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
5578
                "scope": "seal",
5579
            });
5580
            let (st, body) = call(&app, "POST", "/api/v1/keyless/certify", Some(&token), Some(body.to_string())).await;
5581
            assert_eq!(st, StatusCode::OK, "{body}");
5582
            let v: serde_json::Value = serde_json::from_str(&body).unwrap();
5583
            let cert = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
5584
            (sk, id, cert)
5585
        }
5586
    };
5587
    let sign = |r: &serde_json::Value,
5588
                sk: &SecretKey,
5589
                id: &oxy_core::identity::Identity,
5590
                cert: SignedCertificate,
5591
                issuer: oxy_core::identity::Identity| {
5592
        let r: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
5593
        let run_url = format!("{url}/flow/{}", run.number);
5594
        hex::encode(SignedReceipt::sign(r.to_oxy(), repo_id, state, &run_url, id, sk).with_certificate(cert, issuer).encode())
5595
    };
5596
    let hub_id = h.app.hub_key.identity.clone();
5597
5598
    let a = claim(&h.app).await.unwrap();
5599
    let b = claim(&h.app).await.unwrap();
5600
    let ph = a["pipeline_hash"].as_str().unwrap().to_string();
5601
    let (a_name, b_name) = (a["job"]["name"].as_str().unwrap().to_string(), b["job"]["name"].as_str().unwrap().to_string());
5602
    let (a_id, b_id) = (a["job_id"].as_i64().unwrap(), b["job_id"].as_i64().unwrap());
5603
    let (sk_a, id_a, cert_a) = certify(a["token"].as_str().unwrap().to_string()).await;
5604
5605
    // Job b's receipt signed with job a's certified key: another job's.
5606
    let rb = receipt(&b_name, &ph, 0);
5607
    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()) });
5608
    assert_eq!(finish(&h.app, b_id, body).await, StatusCode::NO_CONTENT);
5609
    // Job a's, with its own certificate: kept.
5610
    let ra = receipt(&a_name, &ph, 0);
5611
    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()) });
5612
    assert_eq!(finish(&h.app, a_id, body).await, StatusCode::NO_CONTENT);
5613
5614
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
5615
    let job = |n: &str| jobs.iter().find(|j| j.name == n).unwrap().clone();
5616
    assert_eq!(job(&a_name).receipt_attest.len(), 64, "{}", job(&a_name).receipt_note);
5617
    assert!(job(&a_name).receipt_signer.ends_with("(short-lived key)"), "{}", job(&a_name).receipt_signer);
5618
    assert!(job(&b_name).receipt_attest.is_empty());
5619
    assert!(job(&b_name).receipt_note.contains("another run or job"), "{}", job(&b_name).receipt_note);
5620
    // The kept receipt carries its certificate, and verifies on its own.
5621
    let kept = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().receipts(&heads).unwrap();
5622
    assert_eq!(kept.len(), 1);
5623
    assert!(kept[0].problem.is_none() && kept[0].signed.certificate.is_some());
5624
5625
    // A certificate from another issuer, for the third job: not this hub's.
5626
    let t = claim(&h.app).await.unwrap();
5627
    let t_name = t["job"]["name"].as_str().unwrap().to_string();
5628
    let fake_sk = SecretKey::generate();
5629
    let fake = fake_sk.identity("not the hub", "", 1);
5630
    let (sk_t, id_t, mut cert_t) = certify(t["token"].as_str().unwrap().to_string()).await;
5631
    cert_t.cert.issuer = fake.hash();
5632
    let cert_t = SignedCertificate::sign(cert_t.cert, &fake, &fake_sk);
5633
    let rt = receipt(&t_name, &ph, 0);
5634
    let body =
5635
        serde_json::json!({ "exit_code": 0, "duration_ms": 500, "receipt": rt, "signed_receipt": sign(&rt, &sk_t, &id_t, cert_t, fake) });
5636
    assert_eq!(finish(&h.app, t["job_id"].as_i64().unwrap(), body).await, StatusCode::NO_CONTENT);
5637
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
5638
    let t_job = jobs.iter().find(|j| j.name == t_name).unwrap();
5639
    assert!(t_job.receipt_note.contains("not issued by this hub"), "{}", t_job.receipt_note);
5640
}
5641
5642
/// oxygenhub#241: a release asset whose receipt a short-lived key signed,
5643
/// certified by this hub for the job, is an attested build of a known
5644
/// signer on the release's trust report (it was "not one this hub's
5645
/// runners use" with 0.4.5).
5646
#[tokio::test(flavor = "multi_thread")]
5647
async fn a_release_built_by_a_certified_key_is_attested() {
5648
    use oxy_core::cert::{certify_challenge, SignedCertificate};
5649
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
5650
    use oxy_core::identity::SecretKey;
5651
    use oxy_core::objects::StateObject;
5652
    use oxy_core::receipt::SignedReceipt;
5653
    let h = hub().await;
5654
    create(&h.app, "andy", "demo").await;
5655
    let url = format!("{}/andy/demo", h.base);
5656
    let work = tempfile::tempdir().unwrap();
5657
    let mut c = client(&url, work.path());
5658
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5659
    write(
5660
        work.path(),
5661
        ".flow/pipeline.kdl",
5662
        &format!(
5663
            "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"
5664
        ),
5665
    );
5666
    c.snapshot("test").unwrap();
5667
    c.commit("Build a tool", &[]).unwrap();
5668
    let heads = c.bookmark_heads().unwrap();
5669
    c.tag_create("v1", &heads, "first").unwrap();
5670
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5671
5672
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
5673
    let a = claim(&h.app).await.unwrap();
5674
    let id = a["job_id"].as_i64().unwrap();
5675
    let token = a["token"].as_str().unwrap().to_string();
5676
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
5677
    let (_, text) = upload(&h.app, id, "tool", &body).await;
5678
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
5679
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
5680
    r["outputs"] = serde_json::json!([blob]);
5681
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
5682
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
5683
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
5684
    // The job's fresh key, certified with its token.
5685
    let sk = SecretKey::generate();
5686
    let key = sk.identity("test-1 job", "", 1);
5687
    let proof = sk.sign_challenge(&key.hash(), &certify_challenge(&token)).unwrap();
5688
    let ask = serde_json::json!({
5689
        "identity": oxy_core::dsse::base64(&key.encode()),
5690
        "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
5691
        "scope": "seal",
5692
    });
5693
    let (st, answer) = call(&h.app, "POST", "/api/v1/keyless/certify", Some(&token), Some(ask.to_string())).await;
5694
    assert_eq!(st, StatusCode::OK, "{answer}");
5695
    let v: serde_json::Value = serde_json::from_str(&answer).unwrap();
5696
    let cert = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
5697
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
5698
    let signed = hex::encode(
5699
        SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/{}", run.number), &key, &sk)
5700
            .with_certificate(cert, h.app.hub_key.identity.clone())
5701
            .encode(),
5702
    );
5703
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
5704
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
5705
5706
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
5707
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
5708
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
5709
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
5710
    assert_eq!(st, StatusCode::OK);
5711
    for want in [
5712
        "tool: signed receipt from run #1 build",
5713
        "a short-lived key this hub certified for repo:andy/demo:bookmark:main",
5714
        "1 of 1 assets built and attested by OxygenFlow",
5715
    ] {
5716
        assert!(page.contains(want), "missing {want:?}");
5717
    }
5718
    assert!(!page.contains("not one this hub"), "not an unknown key");
5719
}
5720
5721
/// The transparency log (oxygenhub#238): a push's reference attestation,
5722
/// seal and policy become entries; the checkpoint is signed by the hub's
5723
/// key; the tiles and entry bundles served rebuild the checkpoint's root;
5724
/// and the `/log` page lists them.
5725
#[tokio::test(flavor = "multi_thread")]
5726
async fn a_push_is_logged_and_the_log_checks_out() {
5727
    use oxy_core::tlog::{self, Checkpoint, Entry, Hash, Note, Tile};
5728
    let h = hub().await;
5729
    create(&h.app, "andy", "demo").await;
5730
    let url = format!("{}/andy/demo", h.base);
5731
    let work = tempfile::tempdir().unwrap();
5732
    let mut c = client(&url, work.path());
5733
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5734
    write(work.path(), "a.txt", "a\n");
5735
    c.commit("a", &[]).unwrap();
5736
    c.policy_init().unwrap();
5737
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5738
    let host = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
5739
    let (attest, _) = host.latest_ref_attest("main").unwrap().unwrap();
5740
5741
    // Sign a checkpoint now rather than wait for the next tick.
5742
    let (_, sk) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
5743
    h.app.tlog.refresh_checkpoint(&h.app.hub_key.identity, &sk).unwrap();
5744
    let (st, note) = call(&h.app, "GET", "/log/checkpoint", None, None).await;
5745
    assert_eq!(st, StatusCode::OK, "{note}");
5746
    let origin = oxygenhub::tlog::origin_of(h.app.config.base_url());
5747
    let cp = Checkpoint::verify(&Note::parse(&note).unwrap(), &origin, &h.app.hub_key.identity).unwrap();
5748
    assert!(cp.size >= 3, "ref, seal and policy: {}", cp.size);
5749
5750
    // The entries, from the bundle beside the partial level-0 tile.
5751
    let bundle_path = Tile { level: 0, n: 0, width: cp.size as u32 }.entries_path();
5752
    let (st, _) = call(&h.app, "GET", &format!("/log/{bundle_path}"), None, None).await;
5753
    assert_eq!(st, StatusCode::OK);
5754
    let res =
5755
        oxygenhub::router(h.app.clone()).oneshot(Request::get(format!("/log/{bundle_path}")).body(Body::empty()).unwrap()).await.unwrap();
5756
    assert_eq!(res.headers()[header::CACHE_CONTROL], "public, max-age=5", "a partial tile changes");
5757
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
5758
    let entries: Vec<Entry> = tlog::decode_bundle(&bytes).unwrap().iter().map(|b| Entry::decode(b).unwrap()).collect();
5759
    let kinds: Vec<&str> = entries.iter().map(|e| e.kind.as_str()).collect();
5760
    assert!(kinds.contains(&"ref") && kinds.contains(&"seal") && kinds.contains(&"policy"), "{kinds:?}");
5761
    let r = entries.iter().find(|e| e.kind == "ref").unwrap();
5762
    assert_eq!(r.object, attest);
5763
    assert_eq!(r.repo, c.id().unwrap());
5764
5765
    // The leaves rebuild the checkpoint's root, and the hash tile served
5766
    // is what they make.
5767
    let mut stored: Vec<Hash> = Vec::new();
5768
    for (n, e) in entries.iter().enumerate() {
5769
        stored.extend(tlog::stored_hashes_for_leaf(n as u64, e.leaf_hash(), &stored).unwrap());
5770
    }
5771
    assert_eq!(tlog::tree_hash(cp.size, &stored).unwrap(), cp.root);
5772
    let t = Tile { level: 0, n: 0, width: cp.size as u32 };
5773
    let res =
5774
        oxygenhub::router(h.app.clone()).oneshot(Request::get(format!("/log/{}", t.path())).body(Body::empty()).unwrap()).await.unwrap();
5775
    assert_eq!(res.status(), StatusCode::OK);
5776
    let data = res.into_body().collect().await.unwrap().to_bytes();
5777
    assert_eq!(data.to_vec(), t.read_data(&stored).unwrap());
5778
    let (st, _) = call(&h.app, "GET", "/log/tile/0/000.p/200", None, None).await;
5779
    assert_eq!(st, StatusCode::NOT_FOUND, "not held yet");
5780
5781
    // Pushing the same again logs nothing new.
5782
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5783
    assert_eq!(h.app.tlog.size(), cp.size);
5784
    let (st, page) = call(&h.app, "GET", "/log", None, None).await;
5785
    assert_eq!(st, StatusCode::OK);
5786
    assert!(page.contains("Transparency log") && page.contains("andy/demo") && page.contains(&origin), "{page}");
5787
}
5788
5789
/// Fetching checks the hub's log (oxygenhub#238, step A3): the checkpoint
5790
/// comes with the refs, each attestation with its entry and inclusion
5791
/// proof; a later checkpoint is proved to extend the one seen before, from
5792
/// the hub's tiles; an attestation not in a checkpoint yet is a note; and a
5793
/// log that does not extend what this user saw fails the fetch.
5794
#[tokio::test(flavor = "multi_thread")]
5795
async fn a_fetch_checks_the_hub_s_log_and_refuses_a_fork() {
5796
    use oxy_core::tlog::{Checkpoint, Note};
5797
    let h = hub().await;
5798
    create(&h.app, "andy", "demo").await;
5799
    let url = format!("{}/andy/demo", h.base);
5800
    let work = tempfile::tempdir().unwrap();
5801
    let mut a = client(&url, &work.path().join("a"));
5802
    a.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5803
    let (_, sk) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
5804
    let hub_id = h.app.hub_key.identity.clone();
5805
    let checkpoint = || h.app.tlog.refresh_checkpoint(&hub_id, &sk).unwrap();
5806
    let mut n = 0;
5807
    let mut push = |a: &Repo| {
5808
        n += 1;
5809
        write(&work.path().join("a"), "a.txt", &format!("{n}\n"));
5810
        a.commit(&format!("change {n}"), &[]).unwrap();
5811
        assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
5812
    };
5813
    push(&a);
5814
    checkpoint();
5815
5816
    let home = work.path().join("home-b");
5817
    let b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(home.clone());
5818
    let report = b.fetch("origin").unwrap();
5819
    assert!(report.log_notes.is_empty(), "{:?}", report.log_notes);
5820
    let pin = std::fs::read_dir(home.join("tlog")).unwrap().next().unwrap().unwrap().path();
5821
    let seen = |p: &std::path::Path| {
5822
        let t = std::fs::read_to_string(p).unwrap();
5823
        Checkpoint::parse(&Note::parse(t.split_once('\n').unwrap().1).unwrap().text).unwrap()
5824
    };
5825
    let first = seen(&pin);
5826
5827
    // A later checkpoint: proved to extend the first from the tiles.
5828
    push(&a);
5829
    checkpoint();
5830
    let report = b.fetch("origin").unwrap();
5831
    assert!(report.log_notes.is_empty(), "{:?}", report.log_notes);
5832
    assert!(seen(&pin).size > first.size);
5833
5834
    // Pushed after the last checkpoint: not provable yet, only a note.
5835
    push(&a);
5836
    let report = b.fetch("origin").unwrap();
5837
    assert!(report.log_notes.iter().any(|n| n.contains("not in its transparency log yet")), "{:?}", report.log_notes);
5838
5839
    // A log key other than the one pinned (a hub given a new key, or a
5840
    // port reused by another hub): a note, and the new key pinned.
5841
    let text = std::fs::read_to_string(&pin).unwrap();
5842
    let other_sk = oxy_core::identity::SecretKey::generate();
5843
    let other = other_sk.identity("another hub", "[email protected]", 1);
5844
    let note = text.split_once('\n').unwrap().1;
5845
    std::fs::write(&pin, format!("{}\n{note}", oxy_core::dsse::base64(&other.encode()))).unwrap();
5846
    let report = b.fetch("origin").unwrap();
5847
    assert!(report.log_notes.iter().any(|n| n.contains("signed by another key")), "{:?}", report.log_notes);
5848
    let report = b.fetch("origin").unwrap();
5849
    assert!(!report.log_notes.iter().any(|n| n.contains("another key")), "pinned now: {:?}", report.log_notes);
5850
5851
    // What this user saw replaced by another log of the same size, signed
5852
    // by the hub's own key: the hub's real log does not extend it.
5853
    let size = seen(&pin).size;
5854
    let forged = Checkpoint { origin: oxygenhub::tlog::origin_of(h.app.config.base_url()), size, root: [7; 32], extensions: vec![] };
5855
    let text = std::fs::read_to_string(&pin).unwrap();
5856
    let key = text.split_once('\n').unwrap().0;
5857
    std::fs::write(&pin, format!("{key}\n{}", forged.sign(&hub_id, &sk).unwrap().encode())).unwrap();
5858
    checkpoint();
5859
    let err = b.fetch("origin").unwrap_err().to_string();
5860
    assert!(err.contains("showed two histories") && err.contains("does not extend"), "{err}");
5861
}
5862
5863
/// Witnesses (oxygenhub#238, step A5): one hub cosigns another's
5864
/// checkpoints when each extends the last it cosigned, and the log serves
5865
/// the cosignatures with its checkpoint; the witness refuses a fork (422),
5866
/// tells a log that guessed its size wrong (409), and knows only the logs
5867
/// it was told to witness (404).
5868
#[tokio::test(flavor = "multi_thread")]
5869
async fn a_hub_witnesses_another_hub_s_log() {
5870
    use oxy_core::tlog::{AddCheckpoint, Checkpoint, Note};
5871
    let log = hub().await;
5872
    let witness = hub().await;
5873
    let origin = oxygenhub::tlog::origin_of(log.app.config.base_url());
5874
    witness.app.tlog.add_witness_for(&origin, log.app.hub_key.identity.clone());
5875
    let name = witness.app.tlog.witness_name().to_string();
5876
    log.app.tlog.set_witnesses(vec![oxygenhub::tlog::Peer {
5877
        name: name.clone(),
5878
        url: format!("{}/log/witness/add-checkpoint", witness.base),
5879
        identity: witness.app.hub_key.identity.clone(),
5880
    }]);
5881
    create(&log.app, "andy", "demo").await;
5882
    let work = tempfile::tempdir().unwrap();
5883
    let mut c = client(&format!("{}/andy/demo", log.base), work.path());
5884
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5885
    let (_, sk) = oxygenhub::keys::load_secret(&log.app.config.keys_dir()).unwrap();
5886
    let log_id = log.app.hub_key.identity.clone();
5887
    let wid = witness.app.hub_key.identity.clone();
5888
    for n in 0..2 {
5889
        write(work.path(), "a.txt", &format!("{n}\n"));
5890
        c.commit(&format!("change {n}"), &[]).unwrap();
5891
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5892
        log.app.tlog.refresh_checkpoint(&log_id, &sk).unwrap();
5893
        oxygenhub::tlog::collect(&log.app).await;
5894
        let note = Note::parse(&log.app.tlog.checkpoint().unwrap()).unwrap();
5895
        assert!(note.cosigned_by(&name, &wid).is_ok(), "round {n}: {}", note.encode());
5896
        // Served as such.
5897
        let (_, served) = call(&log.app, "GET", "/log/checkpoint", None, None).await;
5898
        assert!(Note::parse(&served).unwrap().cosigned_by(&name, &wid).is_ok());
5899
    }
5900
    let cp = Checkpoint::parse(&Note::parse(&log.app.tlog.checkpoint().unwrap()).unwrap().text).unwrap();
5901
5902
    // Trusted time (#240): the log lists its witnesses, and a fetch's refs
5903
    // carry, for a logged bookmark, the cosigned checkpoints that first held
5904
    // its entry, from which the client takes the integrated time.
5905
    let (_, listed) = call(&log.app, "GET", "/log/witnesses", None, None).await;
5906
    assert!(listed.starts_with(&format!("{name} ")), "{listed}");
5907
    let url = format!("{}/andy/demo", log.base);
5908
    let refs = tokio::task::spawn_blocking(move || {
5909
        let opts = RemoteOptions { token: Some("site".into()), ..Default::default() };
5910
        open_remote(&url, &opts).unwrap().refs().unwrap()
5911
    })
5912
    .await
5913
    .unwrap();
5914
    assert_eq!(refs.witnesses.len(), 1);
5915
    assert_eq!(refs.witnesses[0].0, name);
5916
    let main = refs.refs.iter().find(|r| r.name == "main").expect("main");
5917
    let logged = main.logged.as_ref().expect("logged");
5918
    assert!(!main.integration.is_empty(), "a witnessed checkpoint holds it");
5919
    let cosigned: Vec<(&str, &[[u8; 32]])> = main.integration.iter().map(|i| (i.note.as_str(), i.proof.as_slice())).collect();
5920
    let at = oxy_core::tlog::integrated_time(&logged.entry, logged.index, &cosigned, &origin, &log_id, &[(name.clone(), wid.clone())])
5921
        .expect("an integrated time");
5922
    assert_eq!(at.witness, name);
5923
    assert!(at.size > logged.index);
5924
5925
    let ask = |req: AddCheckpoint| {
5926
        let app = witness.app.clone();
5927
        async move { call(&app, "POST", "/log/witness/add-checkpoint", None, Some(req.encode())).await }
5928
    };
5929
    // Another log of the same size, signed by the log's own key: a fork.
5930
    let forked = Checkpoint { root: [7; 32], ..cp.clone() }.sign(&log_id, &sk).unwrap().encode();
5931
    let (st, body) = ask(AddCheckpoint { old_size: cp.size, proof: vec![], note: forked.clone() }).await;
5932
    assert_eq!(st, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
5933
    // A wrong idea of what the witness saw: its size, to try again from.
5934
    let (st, body) = ask(AddCheckpoint { old_size: 1, proof: vec![], note: forked }).await;
5935
    assert_eq!((st, body.trim()), (StatusCode::CONFLICT, cp.size.to_string().as_str()));
5936
    // A log it was not told to witness.
5937
    let stranger = oxy_core::identity::SecretKey::generate();
5938
    let sid = stranger.identity("elsewhere", "[email protected]", 1);
5939
    let other = Checkpoint { origin: "elsewhere.example/log".into(), ..cp.clone() }.sign(&sid, &stranger).unwrap().encode();
5940
    let (st, _) = ask(AddCheckpoint { old_size: 0, proof: vec![], note: other }).await;
5941
    assert_eq!(st, StatusCode::NOT_FOUND);
5942
}
5943
5944
/// Terraform state (oxygenhub#252): the HTTP backend's calls as
5945
/// Terraform and OpenTofu make them, with a running job's token as the
5946
/// Basic-auth password; the lock is honoured, versions are kept, the state
5947
/// is sealed at rest, and another repository's job is refused.
5948
#[tokio::test(flavor = "multi_thread")]
5949
async fn a_job_keeps_its_terraform_state_on_the_hub() {
5950
    let h = hub().await;
5951
    create(&h.app, "andy", "infra").await;
5952
    create(&h.app, "andy", "other").await;
5953
    let work = tempfile::tempdir().unwrap();
5954
    let c = client(&format!("{}/andy/infra", h.base), work.path());
5955
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5956
    write(work.path(), "test.sh", "echo ok\n");
5957
    c.snapshot("test").unwrap();
5958
    c.commit("Add a pipeline", &[]).unwrap();
5959
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5960
    assert_eq!(runs_of(&h.app, "andy", "infra").await.len(), 1);
5961
    let job = claim(&h.app).await.expect("a job");
5962
    let token = job["token"].as_str().unwrap().to_string();
5963
    let basic = format!("Basic {}", oxy_core::dsse::base64(format!("flow:{token}").as_bytes()));
5964
    let path = "/api/v1/repos/andy/infra/terraform/state/prod";
5965
    let send = |method: &str, uri: String, auth: Option<String>, body: &str| {
5966
        let mut req = Request::builder().method(method).uri(uri);
5967
        if let Some(a) = auth {
5968
            req = req.header(header::AUTHORIZATION, a);
5969
        }
5970
        let req = req.body(Body::from(body.to_string())).unwrap();
5971
        let app = h.app.clone();
5972
        async move {
5973
            let res = oxygenhub::router(app).oneshot(req).await.unwrap();
5974
            let st = res.status();
5975
            let b = res.into_body().collect().await.unwrap().to_bytes();
5976
            (st, String::from_utf8_lossy(&b).into_owned())
5977
        }
5978
    };
5979
    let lock = r#"{"ID":"lock-1","Operation":"OperationTypeApply","Who":"flow@runner","Version":"1.8.0"}"#;
5980
    // No state yet; no token, nothing.
5981
    assert_eq!(send("GET", path.into(), None, "").await.0, StatusCode::UNAUTHORIZED);
5982
    assert_eq!(send("GET", path.into(), Some(basic.clone()), "").await.0, StatusCode::NO_CONTENT);
5983
    // Lock, write under the lock, unlock.
5984
    let (st, body) = send("LOCK", path.into(), Some(basic.clone()), lock).await;
5985
    assert_eq!(st, StatusCode::OK, "{body}");
5986
    let other_lock = r#"{"ID":"lock-2","Operation":"OperationTypePlan"}"#;
5987
    let (st, held) = send("LOCK", path.into(), Some(basic.clone()), other_lock).await;
5988
    assert_eq!(st, StatusCode::LOCKED);
5989
    assert!(held.contains("lock-1"), "the holder's lock info: {held}");
5990
    let state1 = r#"{"version":4,"serial":1,"lineage":"l","resources":[{"secret":"hunter2"}]}"#;
5991
    assert_eq!(send("POST", path.into(), Some(basic.clone()), state1).await.0, StatusCode::LOCKED, "not under its lock");
5992
    assert_eq!(send("POST", format!("{path}?ID=lock-1"), Some(basic.clone()), state1).await.0, StatusCode::OK);
5993
    assert_eq!(send("UNLOCK", path.into(), Some(basic.clone()), other_lock).await.0, StatusCode::CONFLICT, "not its lock");
5994
    assert_eq!(send("UNLOCK", path.into(), Some(basic.clone()), lock).await.0, StatusCode::OK);
5995
    let (st, got) = send("GET", path.into(), Some(basic.clone()), "").await;
5996
    assert_eq!((st, got.as_str()), (StatusCode::OK, state1));
5997
    // A second write keeps the first as a version; the body is sealed.
5998
    let state2 = state1.replace("\"serial\":1", "\"serial\":2");
5999
    assert_eq!(send("POST", path.into(), Some(basic.clone()), &state2).await.0, StatusCode::OK);
6000
    let row = db::repos::get(&h.app.db, "andy", "infra").await.unwrap().unwrap();
6001
    assert_eq!(db::terraform::versions(&h.app.db, row.id, "prod").await.unwrap(), 1);
6002
    let kept = db::terraform::get(&h.app.db, row.id, "prod").await.unwrap().unwrap();
6003
    assert_eq!(kept.serial, 2);
6004
    assert!(!String::from_utf8_lossy(&kept.body).contains("hunter2"), "sealed at rest");
6005
    // Another repository's state is not this job's; a bad name is refused.
6006
    let (st, _) = send("GET", "/api/v1/repos/andy/other/terraform/state/prod".into(), Some(basic.clone()), "").await;
6007
    assert_eq!(st, StatusCode::FORBIDDEN);
6008
    assert_eq!(
6009
        send("GET", "/api/v1/repos/andy/infra/terraform/state/..x".into(), Some(basic.clone()), "").await.0,
6010
        StatusCode::BAD_REQUEST
6011
    );
6012
    // A stranger reads a public repository, but not its state: states hold
6013
    // secrets (#256), so reading one needs the write role, whatever the token.
6014
    let mallory = db::accounts::create_account(&h.app.db, "mallory", "[email protected]", "x", "salt", false).await.unwrap();
6015
    let (secret, hash) = oxygenhub::auth::new_token();
6016
    db::accounts::create_token(&h.app.db, mallory.id, "cli", &hash, "repo:write", "", None).await.unwrap();
6017
    let (st, got) = send("GET", path.into(), Some(format!("Bearer {secret}")), "").await;
6018
    assert_eq!(st, StatusCode::FORBIDDEN, "{got}");
6019
    assert!(!got.contains("hunter2"));
6020
    let (_, page) = call(&h.app, "GET", "/andy/infra/terraform", Some(&secret), None).await;
6021
    assert!(!page.contains("<strong>prod</strong>") && page.contains("shown to people who can write"), "{page}");
6022
    // The site token is no person's: refused.
6023
    let (st, _) = send("GET", path.into(), Some("Bearer site".into()), "").await;
6024
    assert_eq!(st, StatusCode::UNAUTHORIZED, "the site token is not a person's token");
6025
    // A job's identity token for the Terraform audience, as its pipeline's
6026
    // identity block mounts it: its own repository only, that audience only.
6027
    let issuer = h.app.oidc().await.unwrap();
6028
    let now = db::now_ms();
6029
    let aud = oxygenhub::terraform::audience(h.app.config.base_url());
6030
    let own = issuer.mint_for(h.app.config.base_url(), "repo:andy/infra:bookmark:main", &aud, now, 600);
6031
    let (st, got) = send("GET", path.into(), Some(format!("Bearer {own}")), "").await;
6032
    assert_eq!((st, got.contains("\"serial\":2")), (StatusCode::OK, true));
6033
    let other = issuer.mint_for(h.app.config.base_url(), "repo:andy/other:bookmark:main", &aud, now, 600);
6034
    assert_eq!(send("GET", path.into(), Some(format!("Bearer {other}")), "").await.0, StatusCode::FORBIDDEN);
6035
    let elsewhere = issuer.mint_for(h.app.config.base_url(), "repo:andy/infra:bookmark:main", "sts.amazonaws.com", now, 600);
6036
    assert_eq!(send("GET", path.into(), Some(format!("Bearer {elsewhere}")), "").await.0, StatusCode::UNAUTHORIZED);
6037
    // Its page under Artifacts (#254) lists the state and the backend block.
6038
    // Its owner, signed in, sees the states.
6039
    let res = oxygenhub::router(h.app.clone())
6040
        .oneshot(
6041
            Request::post("/register")
6042
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
6043
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
6044
                .unwrap(),
6045
        )
6046
        .await
6047
        .unwrap();
6048
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
6049
    let res = oxygenhub::router(h.app.clone())
6050
        .oneshot(Request::get("/andy/infra/terraform").header(header::COOKIE, cookie.clone()).body(Body::empty()).unwrap())
6051
        .await
6052
        .unwrap();
6053
    let st = res.status();
6054
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
6055
    assert_eq!(st, StatusCode::OK, "{page}");
6056
    assert!(page.contains("<strong>prod</strong>") && page.contains("/api/v1/repos/andy/infra/terraform/state/NAME"), "{page}");
6057
    assert!(page.contains("allow &quot;") || page.contains("allow \""), "the egress line names the hub");
6058
    assert!(page.contains("1 kept version") && page.contains(">restore</button>"), "its versions, restorable by its owner: {page}");
6059
6060
    // Versions (#255) through the API: listed and read with the write role,
6061
    // restored with the maintain role (never by a job, never under a lock),
6062
    // as a new serial, so nothing is lost and going forward again works.
6063
    let andy = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap();
6064
    let (pat, hash) = oxygenhub::auth::new_token();
6065
    db::accounts::create_token(&h.app.db, andy.id, "cli", &hash, "repo:write", "", None).await.unwrap();
6066
    let bearer = format!("Bearer {pat}");
6067
    let (st, list) = send("GET", format!("{path}/versions"), Some(bearer.clone()), "").await;
6068
    assert_eq!(st, StatusCode::OK, "{list}");
6069
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
6070
    assert_eq!((list.as_array().unwrap().len(), list[0]["serial"].as_i64()), (1, Some(1)), "{list}");
6071
    let first = list[0]["id"].as_i64().unwrap();
6072
    let (st, got) = send("GET", format!("{path}/versions/{first}"), Some(bearer.clone()), "").await;
6073
    assert_eq!((st, got.as_str()), (StatusCode::OK, state1));
6074
    assert_eq!(send("GET", format!("{path}/versions"), Some(format!("Bearer {secret}")), "").await.0, StatusCode::FORBIDDEN, "a stranger");
6075
    let restore = |id: i64, auth: String| send("POST", format!("{path}/versions/{id}/restore"), Some(auth), "");
6076
    assert_eq!(restore(first, basic.clone()).await.0, StatusCode::FORBIDDEN, "a job does not restore");
6077
    assert_eq!(restore(first, format!("Bearer {secret}")).await.0, StatusCode::FORBIDDEN, "nor a stranger");
6078
    assert_eq!(restore(9999, bearer.clone()).await.0, StatusCode::NOT_FOUND);
6079
    assert_eq!(send("LOCK", path.into(), Some(basic.clone()), lock).await.0, StatusCode::OK);
6080
    assert_eq!(restore(first, bearer.clone()).await.0, StatusCode::LOCKED, "not under someone's lock");
6081
    assert_eq!(send("UNLOCK", path.into(), Some(basic.clone()), lock).await.0, StatusCode::OK);
6082
    let (st, got) = restore(first, bearer.clone()).await;
6083
    assert_eq!((st, got.contains("\"serial\":3")), (StatusCode::OK, true), "{got}");
6084
    let (_, now) = send("GET", path.into(), Some(bearer.clone()), "").await;
6085
    let now: serde_json::Value = serde_json::from_str(&now).unwrap();
6086
    assert_eq!(
6087
        (now["serial"].as_i64(), now["lineage"].as_str(), now["resources"][0]["secret"].as_str()),
6088
        (Some(3), Some("l"), Some("hunter2"))
6089
    );
6090
    // Forward again: serial 2 is a kept version now.
6091
    let (_, list) = send("GET", format!("{path}/versions"), Some(bearer.clone()), "").await;
6092
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
6093
    let serials: Vec<i64> = list.as_array().unwrap().iter().map(|v| v["serial"].as_i64().unwrap()).collect();
6094
    assert_eq!(serials, vec![2, 1], "{list}");
6095
    let (st, got) = restore(list[0]["id"].as_i64().unwrap(), bearer.clone()).await;
6096
    assert_eq!((st, got.contains("\"serial\":4")), (StatusCode::OK, true), "{got}");
6097
6098
    // And from the page: download a version, restore one with the form.
6099
    let page_with = |req: axum::http::request::Builder, body: Body| {
6100
        let (app, cookie) = (h.app.clone(), cookie.clone());
6101
        async move {
6102
            let res = oxygenhub::router(app).oneshot(req.header(header::COOKIE, cookie).body(body).unwrap()).await.unwrap();
6103
            let st = res.status();
6104
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
6105
        }
6106
    };
6107
    let (st, file) = page_with(Request::get(format!("/andy/infra/terraform/prod/download?version={first}")), Body::empty()).await;
6108
    assert_eq!((st, file.as_str()), (StatusCode::OK, state1));
6109
    let (_, page) = page_with(Request::get("/andy/infra/terraform"), Body::empty()).await;
6110
    let csrf = page.split("name=\"_csrf\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
6111
    let (st, page) = page_with(
6112
        Request::post("/andy/infra/terraform/prod/restore").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"),
6113
        Body::from(format!("_csrf={csrf}&version={first}")),
6114
    )
6115
    .await;
6116
    assert_eq!(st, StatusCode::OK, "{page}");
6117
    assert!(page.contains("Restored prod: it is now serial 5."), "{page}");
6118
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
6119
    assert_eq!(audit.iter().filter(|r| r.action == "terraform.restored").count(), 3, "every restore audited");
6120
}
6121
6122
/// The real OpenTofu against the backend (oxygenhub#252): init, apply,
6123
/// a second apply that changes nothing, all through the hub's state with a
6124
/// job's token. Needs Docker and the `oxygenflow-tofu` image; run with
6125
/// `cargo test -p oxygenhub --test flow -- --ignored tofu_keeps`.
6126
#[tokio::test(flavor = "multi_thread")]
6127
#[ignore]
6128
async fn tofu_keeps_its_state_on_the_hub() {
6129
    let h = hub().await;
6130
    create(&h.app, "andy", "infra").await;
6131
    let work = tempfile::tempdir().unwrap();
6132
    let c = client(&format!("{}/andy/infra", h.base), work.path());
6133
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
6134
    write(work.path(), "test.sh", "echo ok\n");
6135
    c.snapshot("test").unwrap();
6136
    c.commit("Add a pipeline", &[]).unwrap();
6137
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6138
    assert_eq!(runs_of(&h.app, "andy", "infra").await.len(), 1);
6139
    let job = claim(&h.app).await.expect("a job");
6140
    let token = job["token"].as_str().unwrap().to_string();
6141
    let tf = tempfile::tempdir().unwrap();
6142
    let address = format!("{}/api/v1/repos/andy/infra/terraform/state/prod", h.base);
6143
    std::fs::write(
6144
        tf.path().join("main.tf"),
6145
        format!(
6146
            "terraform {{\n  backend \"http\" {{\n    address = \"{address}\"\n    lock_address = \"{address}\"\n    unlock_address = \"{address}\"\n    username = \"flow\"\n  }}\n}}\nresource \"terraform_data\" \"x\" {{\n  input = \"hello\"\n}}\n"
6147
        ),
6148
    )
6149
    .unwrap();
6150
    let tofu = |args: &[&str]| {
6151
        let out = std::process::Command::new("docker")
6152
            .args(["run", "--rm", "--network", "host", "-v"])
6153
            .arg(format!("{}:/w", tf.path().display()))
6154
            .args(["-w", "/w", "-e"])
6155
            .arg(format!("TF_HTTP_PASSWORD={token}"))
6156
            .args(["--entrypoint", "tofu", "oxygenflow-tofu:latest"])
6157
            .args(args)
6158
            .output()
6159
            .expect("docker");
6160
        let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
6161
        assert!(out.status.success(), "tofu {args:?}: {text}");
6162
        text
6163
    };
6164
    tofu(&["init", "-input=false", "-no-color"]);
6165
    let applied = tofu(&["apply", "-auto-approve", "-input=false", "-no-color"]);
6166
    assert!(applied.contains("1 added"), "{applied}");
6167
    let again = tofu(&["apply", "-auto-approve", "-input=false", "-no-color"]);
6168
    assert!(again.contains("No changes"), "the state was kept: {again}");
6169
    let row = db::repos::get(&h.app.db, "andy", "infra").await.unwrap().unwrap();
6170
    let kept = db::terraform::get(&h.app.db, row.id, "prod").await.unwrap().unwrap();
6171
    assert!(kept.lock_id.is_empty(), "unlocked after each run");
6172
    assert!(kept.serial >= 1);
6173
}
6174
6175
/// `/metrics` (oxygenhub#212): off until a token is set, then served only
6176
/// to its bearer, in the Prometheus text format, with Flow's jobs counted.
6177
#[tokio::test(flavor = "multi_thread")]
6178
async fn metrics_are_private_and_count_flow_jobs() {
6179
    let h = hub().await;
6180
    let (st, _) = call(&h.app, "GET", "/metrics", None, None).await;
6181
    assert_eq!(st, StatusCode::NOT_FOUND, "off by default");
6182
    let text = oxygenhub::metrics::render(&h.app).await;
6183
    for want in [
6184
        "# TYPE oxyhub_uptime_seconds gauge",
6185
        "oxyhub_flow_jobs{state=\"queued\"} 0",
6186
        "oxyhub_bucket_requests_total{kind=\"list\"}",
6187
        "oxyhub_tlog_entries",
6188
        "oxyhub_db_connections{idle=\"true\"}",
6189
        "oxyhub_pushes_last_day{result=\"refused\"} 0",
6190
        "# TYPE oxyhub_backup_last_run_ok gauge",
6191
        "# TYPE oxyhub_flow_runner_last_seen_seconds gauge",
6192
        "oxyhub_flow_runs_last_day{result=\"failed\"} 0",
6193
        "oxyhub_mail_total{result=\"sent\"}",
6194
    ] {
6195
        assert!(text.contains(want), "missing {want}:\n{text}");
6196
    }
6197
    create(&h.app, "andy", "demo").await;
6198
    let work = tempfile::tempdir().unwrap();
6199
    let c = client(&format!("{}/andy/demo", h.base), work.path());
6200
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
6201
    write(work.path(), "test.sh", "echo ok\n");
6202
    c.snapshot("test").unwrap();
6203
    c.commit("Add a pipeline", &[]).unwrap();
6204
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6205
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
6206
    let text = oxygenhub::metrics::render(&h.app).await;
6207
    assert!(!text.contains("oxyhub_flow_jobs{state=\"queued\"} 0"), "the run's jobs are queued:\n{text}");
6208
    assert!(text.contains("oxyhub_pushes_last_day{result=\"accepted\"}"), "{text}");
6209
    // The push's bytes are counted (other tests share the counters, so
6210
    // only that they are there and not nothing).
6211
    let pushed = text
6212
        .lines()
6213
        .find_map(|l| l.strip_prefix("oxyhub_protocol_bytes_total{endpoint=\"push\",direction=\"received\"} "))
6214
        .and_then(|v| v.parse::<f64>().ok())
6215
        .unwrap_or(0.0);
6216
    assert!(pushed > 0.0, "{text}");
6217
    // Requests through the router are counted by route class.
6218
    call(&h.app, "GET", "/andy/demo", None, None).await;
6219
    let text = oxygenhub::metrics::render(&h.app).await;
6220
    assert!(text.contains("oxyhub_http_requests_total{route=\"page:repository\",method=\"GET\",status=\"2xx\"}"), "{text}");
6221
    assert!(text.contains("oxyhub_http_request_duration_seconds_bucket{route=\"page:repository\",method=\"GET\",le=\"+Inf\"}"));
6222
}
6223
6224
/// Insights (oxygenhub#257): a job is ready when it could run (queued, its
6225
/// dependencies passed), so its pickup time is from then to its claim; the
6226
/// repository's page charts its jobs, an owner's numbers are its own and
6227
/// the site's are the administrators'.
6228
#[tokio::test(flavor = "multi_thread")]
6229
async fn insights_chart_pickup_from_when_a_job_could_run() {
6230
    let h = hub().await;
6231
    create(&h.app, "andy", "demo").await;
6232
    let work = tempfile::tempdir().unwrap();
6233
    let c = client(&format!("{}/andy/demo", h.base), work.path());
6234
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
6235
    write(work.path(), "test.sh", "echo ok\n");
6236
    c.snapshot("test").unwrap();
6237
    c.commit("Add a pipeline", &[]).unwrap();
6238
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6239
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
6240
    let mut finished = std::collections::HashMap::new();
6241
    for want in ["build", "lint", "test"] {
6242
        let j = claim(&h.app).await.expect("a job");
6243
        assert_eq!(j["job"]["name"].as_str(), Some(want));
6244
        let id = j["job_id"].as_i64().unwrap();
6245
        let row = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
6246
        let (queued, ready, started) = (row.queued_ms.unwrap(), row.ready_ms.unwrap(), row.started_ms.unwrap());
6247
        assert!(queued <= ready && ready <= started, "{want}: {queued} {ready} {started}");
6248
        if want == "test" {
6249
            assert_eq!(Some(ready), finished["build"], "ready when build passed, not when it was queued");
6250
        }
6251
        let ph = j["pipeline_hash"].as_str().unwrap();
6252
        let st = finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt(want, ph, 0) })).await;
6253
        assert_eq!(st, StatusCode::NO_CONTENT);
6254
        finished.insert(want, db::flow::job(&h.app.db, id).await.unwrap().unwrap().finished_ms);
6255
    }
6256
    let (st, page) = call(&h.app, "GET", "/andy/demo/insights", None, None).await;
6257
    assert_eq!(st, StatusCode::OK, "{page}");
6258
    assert!(page.contains("<span class=\"kpi-v\">3</span><span class=\"kpi-l\">jobs finished"), "{page}");
6259
    assert!(page.contains("100% passed"), "{page}");
6260
    assert_eq!(page.matches("<svg class=\"chart\"").count(), 5, "five charts");
6261
    assert!(page.contains("class=\"bar s-ok\""), "the passed jobs drawn");
6262
    assert!(page.contains("data-refresh=\"30\" data-fragment=\"insights\""), "it refreshes itself");
6263
    assert!(page.contains("<summary class=\"on\">More</summary>"), "the bar's More menu holds it");
6264
    let (_, wall) = call(&h.app, "GET", "/andy/demo/insights?range=7d&wall=1", None, None).await;
6265
    assert!(wall.contains("<body class=\"wall\"") && wall.contains("the last 7 days") && wall.contains("leave the wall view"), "{wall}");
6266
    // An owner's numbers are not anyone's; the site's are administrators'.
6267
    assert_eq!(call(&h.app, "GET", "/insights/andy", None, None).await.0, StatusCode::NOT_FOUND);
6268
    assert_eq!(call(&h.app, "GET", "/admin/insights", None, None).await.0, StatusCode::NOT_FOUND);
6269
    let res = oxygenhub::router(h.app.clone())
6270
        .oneshot(
6271
            Request::post("/register")
6272
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
6273
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
6274
                .unwrap(),
6275
        )
6276
        .await
6277
        .unwrap();
6278
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
6279
    let andy = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap();
6280
    db::accounts::set_admin(&h.app.db, andy.id, true).await.unwrap();
6281
    for path in ["/insights/andy", "/admin/insights?runner=test-1&range=1h"] {
6282
        let res = oxygenhub::router(h.app.clone())
6283
            .oneshot(Request::get(path).header(header::COOKIE, cookie.clone()).body(Body::empty()).unwrap())
6284
            .await
6285
            .unwrap();
6286
        let st = res.status();
6287
        let body = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
6288
        assert_eq!(st, StatusCode::OK, "{path}: {body}");
6289
        assert!(body.contains("<svg class=\"chart\""), "{path}");
6290
    }
6291
}
6292
6293
/// Readers never wait (oxygenhub#249): a page, the API and a fetch's refs
6294
/// answer while a writer (a push, a gc) holds the repository; writers take
6295
/// turns; deleting or moving it waits for everyone and holds off newcomers.
6296
#[tokio::test(flavor = "multi_thread")]
6297
async fn reads_do_not_wait_for_a_writer() {
6298
    use std::time::Duration;
6299
    let h = hub().await;
6300
    create(&h.app, "andy", "demo").await;
6301
    let work = tempfile::tempdir().unwrap();
6302
    let c = client(&format!("{}/andy/demo", h.base), work.path());
6303
    write(work.path(), "a.txt", "a\n");
6304
    c.commit("A change", &[]).unwrap();
6305
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6306
    let name = RepoName::parse("andy/demo").unwrap();
6307
    let writer = h.app.repos.write_guard(&name).await;
6308
    for path in ["/andy/demo", "/andy/demo/changes/main", "/api/v1/repos/andy/demo/bookmarks"] {
6309
        let (st, body) = tokio::time::timeout(Duration::from_secs(10), call(&h.app, "GET", path, None, None))
6310
            .await
6311
            .unwrap_or_else(|_| panic!("{path} waited for the writer"));
6312
        assert_eq!(st, StatusCode::OK, "{path}: {body}");
6313
    }
6314
    let refs = tokio::time::timeout(Duration::from_secs(10), call(&h.app, "POST", "/andy/demo/oxy/v1/refs", Some("site"), None)).await;
6315
    assert!(refs.is_ok(), "a fetch's refs waited for the writer");
6316
    assert!(tokio::time::timeout(Duration::from_millis(300), h.app.repos.write_guard(&name)).await.is_err(), "writers take turns");
6317
    assert!(tokio::time::timeout(Duration::from_millis(300), h.app.repos.exclusive_guard(&name)).await.is_err(), "a delete waits");
6318
    drop(writer);
6319
    let all = tokio::time::timeout(Duration::from_secs(5), h.app.repos.exclusive_guard(&name)).await.expect("then it runs");
6320
    assert!(
6321
        tokio::time::timeout(Duration::from_millis(300), h.app.repos.read_guard(&name)).await.is_err(),
6322
        "nothing reads a repository being deleted"
6323
    );
6324
    drop(all);
6325
}
6326
6327
/// Live L5 (docs/live.md, oxygenhub#207): the issue page's timeline
6328
/// listens on the issue's topic and the repository's, the overview's latest
6329
/// change and bookmarks on the repository's, and its Diffusion card and the
6330
/// Diffusion tab on the repository's Diffusion topic.
6331
#[tokio::test(flavor = "multi_thread")]
6332
async fn the_issue_overview_and_diffusion_pages_listen_on_their_topics() {
6333
    let h = hub().await;
6334
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
6335
    create(&h.app, "andy", "demo").await;
6336
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
6337
    let work = tempfile::tempdir().unwrap();
6338
    let c = client(&format!("{}/andy/demo", h.base), work.path());
6339
    write(work.path(), "a.txt", "a\n");
6340
    c.snapshot("t").unwrap();
6341
    c.commit("a", &[]).unwrap();
6342
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6343
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/issues", Some("site"), Some(r#"{"title":"Broken"}"#.into())).await;
6344
    assert!(st.is_success(), "{st} {body}");
6345
    let repo = format!("repo:{}", row.id);
6346
    let (_, issue) = call(&h.app, "GET", "/andy/demo/issue/1", None, None).await;
6347
    assert!(issue.contains(&format!("data-live=\"{repo}/issue:1 {repo}\" data-fragment=\"timeline\"")), "the issue's timeline");
6348
    let (_, overview) = call(&h.app, "GET", "/andy/demo", None, None).await;
6349
    assert!(overview.contains(&format!("data-live=\"{repo}\" data-fragment=\"latest\"")), "the latest change");
6350
    assert!(overview.contains(&format!("data-live=\"{repo}\" data-fragment=\"bookmarks\"")), "the bookmarks");
6351
    let (_, diffusion) = call(&h.app, "GET", "/andy/demo/diffusion", None, None).await;
6352
    assert!(diffusion.contains(&format!("data-live=\"diffusion:{} {repo}\" data-fragment=\"diffusion\"", row.id)), "the Diffusion tab");
6353
}
6354
6355
/// Keyless step 4c (oxygenhub#241): when a key the hub certified moves a
6356
/// bookmark, the hub signs when it accepted the update and serves that
6357
/// with the bookmark, so a fetch checks the certificate at the hub's time
6358
/// rather than the time the key claimed.
6359
#[tokio::test(flavor = "multi_thread")]
6360
async fn the_hub_countersigns_an_update_by_a_key_it_certified() {
6361
    use oxy_core::attest::AttestBody;
6362
    use oxy_core::cert::{Certificate, SignedCertificate};
6363
    use oxy_core::identity::Scope;
6364
    use oxy_core::repo::IdentityScope;
6365
    let h = hub().await;
6366
    create(&h.app, "andy", "demo").await;
6367
    let url = format!("{}/andy/demo", h.base);
6368
    let work = tempfile::tempdir().unwrap();
6369
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
6370
    a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
6371
    write(&work.path().join("a"), "a.txt", "a\n");
6372
    a.commit("a", &[]).unwrap();
6373
    a.policy_init().unwrap();
6374
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6375
    let hub_id = h.app.hub_key.identity.clone();
6376
    a.policy_grant_subject("agent:claude@andy", hub_id.clone(), Scope::CHANGES | Scope::REFS, None).unwrap();
6377
    assert!(a.push("origin", false).unwrap().iter().any(|r| r.name == "policy" && r.ok));
6378
6379
    // An agent whose fresh key the hub certified pushes.
6380
    let mut b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(work.path().join("home-b"));
6381
    b.config.set("remote.origin.token", "site").unwrap();
6382
    b.save_config().unwrap();
6383
    let (_, key) = b.create_identity("claude", "[email protected]", IdentityScope::User).unwrap();
6384
    let (_, secret) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
6385
    let now = db::now_ms() as u64;
6386
    let cert = SignedCertificate::sign(
6387
        Certificate {
6388
            key,
6389
            issuer: hub_id.hash(),
6390
            subject: "agent:claude@andy".into(),
6391
            claims: vec![],
6392
            scope: Scope::CHANGES | Scope::REFS,
6393
            not_before: now - 60_000,
6394
            expires: now + 600_000,
6395
            grant: None,
6396
        },
6397
        &hub_id,
6398
        &secret,
6399
    );
6400
    b.store().put_identity(&hub_id).unwrap();
6401
    b.store().put_certificate(&cert).unwrap();
6402
    write(&work.path().join("b"), "b.txt", "agent work\n");
6403
    b.commit("work", &[]).unwrap();
6404
    let r = b.push("origin", false).unwrap();
6405
    assert!(r.iter().all(|x| x.ok), "{r:?}");
6406
6407
    // The hub serves its acceptance of that update, signed by its key.
6408
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
6409
    let main = refs.refs.iter().find(|r| r.name == "main").unwrap();
6410
    let (attest, acc) = (main.attestation.clone().unwrap(), main.accepted.clone().expect("an acceptance"));
6411
    assert!(matches!(acc.attest.body, AttestBody::Accepted { attest: r } if r == attest.attest.hash()));
6412
    assert_eq!(acc.sigs[0].key, hub_id.hash());
6413
    assert!(acc.attest.hlc.wall_ms >= now);
6414
    // An update signed by a long-lived key gets none.
6415
    a.pull("origin").unwrap();
6416
    write(&work.path().join("a"), "a.txt", "again\n");
6417
    a.commit("again", &[]).unwrap();
6418
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6419
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
6420
    assert!(refs.refs.iter().find(|r| r.name == "main").unwrap().accepted.is_none());
6421
}
6422
6423
/// A keyless agent's release tag (oxygen#129): a key the hub certified
6424
/// creates a tag and pushes it under the policy's subject grant; the hub
6425
/// accepts it, countersigns when, logs both and serves them with the tag,
6426
/// and a fresh clone fetches it at the hub's time rather than the tag's.
6427
#[tokio::test(flavor = "multi_thread")]
6428
async fn a_tag_by_a_key_the_hub_certified_is_accepted_and_fetched() {
6429
    use oxy_core::attest::AttestBody;
6430
    use oxy_core::cert::{Certificate, SignedCertificate};
6431
    use oxy_core::identity::Scope;
6432
    use oxy_core::repo::IdentityScope;
6433
    use oxy_core::tlog::Entry;
6434
    let h = hub().await;
6435
    create(&h.app, "andy", "demo").await;
6436
    let url = format!("{}/andy/demo", h.base);
6437
    let work = tempfile::tempdir().unwrap();
6438
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
6439
    a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
6440
    write(&work.path().join("a"), "a.txt", "a\n");
6441
    a.commit("a", &[]).unwrap();
6442
    a.policy_init().unwrap();
6443
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6444
    let hub_id = h.app.hub_key.identity.clone();
6445
    a.policy_grant_subject("agent:claude@andy", hub_id.clone(), Scope::CHANGES | Scope::REFS, None).unwrap();
6446
    assert!(a.push("origin", false).unwrap().iter().any(|r| r.name == "policy" && r.ok));
6447
6448
    // An agent whose fresh key the hub certified tags what it fetched.
6449
    let mut b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(work.path().join("home-b"));
6450
    b.config.set("remote.origin.token", "site").unwrap();
6451
    b.save_config().unwrap();
6452
    let (_, key) = b.create_identity("claude", "[email protected]", IdentityScope::User).unwrap();
6453
    let (_, secret) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
6454
    let now = db::now_ms() as u64;
6455
    let cert = SignedCertificate::sign(
6456
        Certificate {
6457
            key,
6458
            issuer: hub_id.hash(),
6459
            subject: "agent:claude@andy".into(),
6460
            claims: vec![],
6461
            scope: Scope::CHANGES | Scope::REFS,
6462
            not_before: now - 60_000,
6463
            expires: now + 600_000,
6464
            grant: None,
6465
        },
6466
        &hub_id,
6467
        &secret,
6468
    );
6469
    b.store().put_identity(&hub_id).unwrap();
6470
    b.store().put_certificate(&cert).unwrap();
6471
    let heads = b.bookmark_heads().unwrap();
6472
    b.tag_create("v0.2.0", &heads, "OxygenFlow 0.2.0").unwrap();
6473
    let r = b.push("origin", false).unwrap();
6474
    assert!(r.iter().any(|x| x.name == "tags/v0.2.0" && x.ok), "{r:?}");
6475
6476
    // The hub serves its acceptance of the tag, signed by its key, and
6477
    // logs both.
6478
    h.app.tlog.refresh_checkpoint(&hub_id, &secret).unwrap();
6479
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
6480
    let tag = refs.tags.iter().find(|t| t.name == "v0.2.0").expect("the tag");
6481
    let (attest, acc) = (tag.attestation.clone().unwrap(), tag.accepted.clone().expect("an acceptance"));
6482
    assert!(matches!(acc.attest.body, AttestBody::Accepted { attest: r } if r == attest.attest.hash()));
6483
    assert_eq!(acc.sigs[0].key, hub_id.hash());
6484
    assert!(acc.attest.hlc.wall_ms >= now);
6485
    let logged = tag.logged.as_ref().expect("the tag's place in the log");
6486
    let entry = Entry::decode(&logged.entry).unwrap();
6487
    assert_eq!((entry.kind.as_str(), entry.object), ("tag", attest.attest.hash()));
6488
    let logged_acceptance = db::tlog::entry_of(&h.app.db, &acc.attest.hash().to_hex(), "accepted").await.unwrap();
6489
    assert!(logged_acceptance.is_some(), "the acceptance is logged too");
6490
6491
    // A fresh clone takes the tag at the hub's time.
6492
    let c = Repo::clone(&url, &work.path().join("c")).unwrap().with_home(work.path().join("home-c"));
6493
    assert_eq!(c.tag_heads("v0.2.0").unwrap(), Some(heads));
6494
    let report = c.fetch("origin").unwrap();
6495
    assert!(report.skipped.is_empty(), "{:?}", report.skipped);
6496
    // Andy's checkout too, the tag signed by the agent's key.
6497
    a.pull("origin").unwrap();
6498
    let t = a.tags().unwrap().into_iter().find(|t| t.name == "v0.2.0").expect("pulled");
6499
    assert_eq!(t.signer.as_deref(), Some("claude"));
6500
6501
    // oxy 0.5.0 and older, which send no `Oxy-Features`, refuse a tag only a
6502
    // certificate authorizes and, with it, the whole clone (oxygen#131): the
6503
    // hub leaves it out of their refs answer, and Andy's own tag in.
6504
    a.tag_create("v0.1.0", &a.bookmark_heads().unwrap(), "by Andy").unwrap();
6505
    assert!(a.push("origin", false).unwrap().iter().any(|r| r.name == "tags/v0.1.0" && r.ok));
6506
    let bare = oxy_core::protocol::http_get(&format!("{url}/oxy/v1/refs"), &RemoteOptions::default()).unwrap();
6507
    let (_, old) = oxy_core::protocol::wire::decode_refs(&bare).unwrap();
6508
    let names: Vec<String> = old.tags.into_iter().map(|t| t.name).collect();
6509
    assert_eq!(names, ["v0.1.0"], "no Oxy-Features header");
6510
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
6511
    let mut names: Vec<String> = refs.tags.into_iter().map(|t| t.name).collect();
6512
    names.sort();
6513
    assert_eq!(names, ["v0.1.0", "v0.2.0"], "a current client declares certified-tags");
6514
}
6515
6516
/// Keyless step 5 (oxygenhub#241): Andy grants an agent with his own key;
6517
/// the agent, holding only the grant token, commits and pushes in Andy's
6518
/// name with fresh keys the hub certifies under the grant. A grant by a
6519
/// key not linked to the account, or for another account's agent, is
6520
/// refused; a revoked grant certifies no more.
6521
#[tokio::test(flavor = "multi_thread")]
6522
async fn an_agent_with_a_grant_pushes_in_its_owner_s_name() {
6523
    use oxy_core::cert::{Grant, SignedGrant};
6524
    use oxy_core::identity::{Identity, Scope, SecretKey};
6525
    use oxy_core::repo::{IdentityScope, SignatureStatus};
6526
    let h = hub().await;
6527
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
6528
    let (pat, pat_hash) = oxygenhub::auth::new_token();
6529
    db::accounts::create_token(&h.app.db, andy.id, "cli", &pat_hash, "repo:write", "", None).await.unwrap();
6530
    create(&h.app, "andy", "demo").await;
6531
    let url = format!("{}/andy/demo", h.base);
6532
    let work = tempfile::tempdir().unwrap();
6533
    // Andy's checkout, its policy granting the agent's subject.
6534
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
6535
    let (andy_key, andy_id) = a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
6536
    db::accounts::link_identity(&h.app.db, andy.id, &andy_key.to_hex(), "Andy", "[email protected]", &andy_id.encode()).await.unwrap();
6537
    write(&work.path().join("a"), "a.txt", "a\n");
6538
    a.commit("a", &[]).unwrap();
6539
    a.policy_init().unwrap();
6540
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6541
    let hub_id = h.app.hub_key.identity.clone();
6542
    a.policy_grant_subject("agent:claude@andy", hub_id.clone(), Scope::CHANGES | Scope::REFS, None).unwrap();
6543
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6544
6545
    // Andy grants the agent, as `oh agent grant claude` does.
6546
    let (_, andy_sk) = a.secret_key().unwrap().unwrap();
6547
    let now = db::now_ms() as u64;
6548
    let grant = |by: &Identity, sk: &SecretKey, subject: &str| {
6549
        SignedGrant::sign(
6550
            Grant {
6551
                grantor: by.hash(),
6552
                subject: subject.into(),
6553
                issuer: hub_id.hash(),
6554
                scope: Scope::CHANGES | Scope::SEAL | Scope::REFS,
6555
                not_before: now - 60_000,
6556
                expires: now + 86_400_000,
6557
            },
6558
            by,
6559
            sk,
6560
        )
6561
    };
6562
    let post = |g: SignedGrant| {
6563
        let (app, pat) = (h.app.clone(), pat.clone());
6564
        let body = serde_json::json!({ "grant": oxy_core::dsse::base64(&g.encode()) }).to_string();
6565
        async move { call(&app, "POST", "/api/v1/agents/grants", Some(&pat), Some(body)).await }
6566
    };
6567
    let stray_sk = SecretKey::generate();
6568
    let stray = stray_sk.identity("stray", "[email protected]", 1);
6569
    let (st, body) = post(grant(&stray, &stray_sk, "agent:claude@andy")).await;
6570
    assert_eq!(st, StatusCode::FORBIDDEN, "a key not linked to the account: {body}");
6571
    let (st, body) = post(grant(&andy_id, &andy_sk, "agent:claude@mallory")).await;
6572
    assert_eq!(st, StatusCode::BAD_REQUEST, "another account's agent: {body}");
6573
    let (st, body) = post(grant(&andy_id, &andy_sk, "agent:claude@andy")).await;
6574
    assert_eq!(st, StatusCode::CREATED, "{body}");
6575
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
6576
    let token = v["token"].as_str().unwrap().to_string();
6577
    assert!(token.starts_with("oxyagent_"));
6578
    let grant_id = v["id"].as_i64().unwrap();
6579
6580
    // The agent: a home holding only the grant token, Andy the author.
6581
    let agent_home = work.path().join("home-claude");
6582
    oxy_core::credentials::Credentials::at(&agent_home).save_grant(&h.base, &token).unwrap();
6583
    let agent = || {
6584
        let n = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
6585
        let dir = work.path().join(format!("claude-{n}"));
6586
        let mut r = Repo::clone(&url, &dir).unwrap().with_home(agent_home.clone());
6587
        // The grant token is its only credential: it pushes with it too.
6588
        r.config.set("remote.origin.token", &token).unwrap();
6589
        r.save_config().unwrap();
6590
        r.set_user_config("author.key", &andy_key.to_hex()).unwrap();
6591
        r.set_user_config("author.signer", "keyless").unwrap();
6592
        (r, dir)
6593
    };
6594
    let (claude, dir) = agent();
6595
    assert!(!agent_home.join("keys").exists(), "no key on disk");
6596
    write(&dir, "work.txt", "agent work\n");
6597
    let change = claude.commit("Agent work", &[]).unwrap();
6598
    let r = claude.push("origin", false).unwrap();
6599
    assert!(r.iter().all(|x| x.ok), "{r:?}");
6600
    let signer = claude.signing_key().expect("a certified key");
6601
    assert_ne!(signer, andy_key);
6602
    assert!(!agent_home.join("keys").exists(), "still no key on disk");
6603
6604
    // The hub holds it in Andy's name, sealed by the certified key, and
6605
    // countersigned when it accepted the update.
6606
    let host = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
6607
    assert_eq!(host.store().get_change_meta(&change).unwrap().author, andy_key);
6608
    assert!(matches!(
6609
        host.authenticate_change(&change).unwrap(),
6610
        SignatureStatus::Valid { key, sealed: true, .. } if key == signer
6611
    ));
6612
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
6613
    assert!(refs.refs.iter().find(|r| r.name == "main").unwrap().accepted.is_some());
6614
    a.pull("origin").unwrap();
6615
    assert!(matches!(a.authenticate_change(&change).unwrap(), SignatureStatus::Valid { .. }));
6616
6617
    // oxygen#134: in a repository that has never seen Andy's identity, the
6618
    // agent's change still verifies, locally and on the hub: the grant's
6619
    // signer comes with the certificate and travels with the push.
6620
    create(&h.app, "andy", "fresh").await;
6621
    let fresh_url = format!("{}/andy/fresh", h.base);
6622
    let fresh_dir = work.path().join("claude-fresh");
6623
    let mut fresh = client(&fresh_url, &fresh_dir).with_home(agent_home.clone());
6624
    fresh.config.set("remote.origin.token", &token).unwrap();
6625
    fresh.save_config().unwrap();
6626
    fresh.set_user_config("author.key", &andy_key.to_hex()).unwrap();
6627
    fresh.set_user_config("author.signer", "keyless").unwrap();
6628
    assert!(fresh.store().get_identity(&andy_key).is_err(), "the fresh repository has never seen Andy");
6629
    write(&fresh_dir, "first.txt", "first\n");
6630
    let first = fresh.commit("First, by the agent", &[]).unwrap();
6631
    let r = fresh.push("origin", false).unwrap();
6632
    assert!(r.iter().all(|x| x.ok), "{r:?}");
6633
    assert!(matches!(fresh.authenticate_change(&first).unwrap(), SignatureStatus::Valid { .. }), "locally");
6634
    let fresh_host = h.app.repos.open(&RepoName::parse("andy/fresh").unwrap()).unwrap();
6635
    assert!(
6636
        matches!(fresh_host.authenticate_change(&first).unwrap(), SignatureStatus::Valid { sealed: true, .. }),
6637
        "on the hub: {:?}",
6638
        fresh_host.authenticate_change(&first).unwrap()
6639
    );
6640
6641
    // oxygen#82: Andy rotates. A home with `author.for` follows his newest
6642
    // identity, which the hub names with each certificate, and its changes
6643
    // still verify by the grant his earlier key made.
6644
    let rot = a.rotate_identity().unwrap();
6645
    db::accounts::link_identity(&h.app.db, andy.id, &rot.new.to_hex(), "Andy", "[email protected]", &rot.identity.encode()).await.unwrap();
6646
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6647
    let (mut warm, dir) = agent();
6648
    warm.set_user_config("author.for", "andy").unwrap();
6649
    write(&dir, "warm.txt", "before the hub has said\n");
6650
    warm.commit("Warm", &[]).unwrap();
6651
    assert!(warm.push("origin", false).unwrap().iter().all(|r| r.ok));
6652
    let followed = std::fs::read_to_string(agent_home.join("keys").join("author.for")).unwrap();
6653
    assert_eq!(followed.trim(), rot.new.to_hex(), "the hub named Andy's newest identity");
6654
    let (follower, dir) = agent();
6655
    assert_eq!(follower.config.author_key, Some(rot.new));
6656
    write(&dir, "follow.txt", "as Andy's newest identity\n");
6657
    let followed = follower.commit("Followed", &[]).unwrap();
6658
    assert!(follower.push("origin", false).unwrap().iter().all(|r| r.ok));
6659
    assert_eq!(host.store().get_change_meta(&followed).unwrap().author, rot.new);
6660
    assert!(
6661
        matches!(host.authenticate_change(&followed).unwrap(), SignatureStatus::Valid { sealed: true, .. }),
6662
        "{:?}",
6663
        host.authenticate_change(&followed).unwrap()
6664
    );
6665
6666
    // Revoked: the next command gets no certificate.
6667
    let (st, _) = call(&h.app, "DELETE", &format!("/api/v1/agents/grants/{grant_id}"), Some(&pat), None).await;
6668
    assert_eq!(st, StatusCode::NO_CONTENT);
6669
    let (late, dir) = agent();
6670
    write(&dir, "late.txt", "after the revocation\n");
6671
    late.commit("Late", &[]).unwrap();
6672
    let err = late.push("origin", false).unwrap_err().to_string();
6673
    assert!(err.contains("not valid") || err.contains("would not certify"), "{err}");
6674
    // The hub recorded the push as the agent's, for its owner.
6675
    let by_agent: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM pushes WHERE via = 'claude'").fetch_one(&h.app.db).await.unwrap();
6676
    assert!(by_agent >= 1, "recorded as via the agent");
6677
    let (_, body) = call(&h.app, "GET", "/api/v1/agents/grants", Some(&pat), None).await;
6678
    let list: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
6679
    assert!(list[0]["revoked_ms"].is_i64() && list[0].get("token").is_none(), "{body}");
6680
}
6681
6682
/// oxygenhub#267, newest run wins: a proposal's new run supersedes its
6683
/// older runs still live, as a push run does its bookmark's; a repository
6684
/// that keeps running runs has only the queued ones cancelled; manual
6685
/// runs and reruns supersede nothing and nothing supersedes them.
6686
#[tokio::test(flavor = "multi_thread")]
6687
async fn newest_run_wins() {
6688
    use oxy_core::hash::ChangeHash;
6689
    let h = hub().await;
6690
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
6691
    create(&h.app, "andy", "newest").await;
6692
    let url = format!("{}/andy/newest", h.base);
6693
    let work = tempfile::tempdir().unwrap();
6694
    let c = client(&url, work.path());
6695
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
6696
    write(work.path(), "test.sh", "echo ok\n");
6697
    c.commit("Start", &[]).unwrap();
6698
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6699
    let pushed = runs_of(&h.app, "andy", "newest").await[0].clone();
6700
    assert_eq!((pushed.number, pushed.trigger.as_str()), (1, "push"));
6701
    let heads: Vec<ChangeHash> = pushed.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
6702
    let start = |row: db::repos::RepoRow, bookmark: &'static str, trigger: &'static str| {
6703
        let (app, state, heads) = (h.app.clone(), pushed.state.clone(), heads.clone());
6704
        async move {
6705
            oxygenhub::flow::start_run_scoped(&app, &row, bookmark, &state, &heads, "andy", trigger, None).await.unwrap().expect("a run")
6706
        }
6707
    };
6708
    let row = db::repos::get(&h.app.db, "andy", "newest").await.unwrap().unwrap();
6709
    let run = |n: i64| {
6710
        let (app, id) = (h.app.clone(), row.id);
6711
        async move { db::flow::run(&app.db, id, n).await.unwrap().unwrap() }
6712
    };
6713
    let superseded_by = |n: i64, by: i64| {
6714
        let app = h.app.clone();
6715
        let run = run(n);
6716
        async move {
6717
            let r = run.await;
6718
            assert_eq!(r.status, "cancelled", "run #{n} is superseded");
6719
            let jobs = db::flow::jobs(&app.db, r.id).await.unwrap();
6720
            let why = format!("superseded by run #{by}");
6721
            assert!(jobs.iter().all(|j| j.status == "cancelled" && j.error == why), "{jobs:?}");
6722
        }
6723
    };
6724
6725
    // A proposal's new run supersedes its older one, not another
6726
    // proposal's, nor the push run of a bookmark.
6727
    assert_eq!(start(row.clone(), "proposal/7", "proposal").await, 2);
6728
    assert_eq!(start(row.clone(), "proposal/7", "proposal").await, 3);
6729
    superseded_by(2, 3).await;
6730
    assert_eq!(start(row.clone(), "proposal/8", "proposal").await, 4);
6731
    assert!(run(3).await.live(), "another proposal's run is not superseded");
6732
    assert!(run(1).await.live(), "a proposal's run leaves push runs alone");
6733
6734
    // Manual runs and reruns supersede nothing, and a push supersedes
6735
    // only push runs.
6736
    assert_eq!(start(row.clone(), "main", "manual").await, 5);
6737
    assert_eq!(start(row.clone(), "main", "rerun:1:push").await, 6);
6738
    assert!(run(1).await.live(), "a manual run or a rerun supersedes nothing");
6739
    assert_eq!(start(row.clone(), "main", "push").await, 7);
6740
    superseded_by(1, 7).await;
6741
    assert!(run(5).await.live() && run(6).await.live(), "a push leaves manual runs and reruns alone");
6742
6743
    // Kept running: a superseded run already running finishes; queued
6744
    // ones are still cancelled.
6745
    db::repos::set_flow_keep_running(&h.app.db, row.id, true).await.unwrap();
6746
    let kept = db::repos::get(&h.app.db, "andy", "newest").await.unwrap().unwrap();
6747
    assert!(kept.flow_keep_running);
6748
    let three = run(3).await;
6749
    sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = $1").bind(three.id).execute(&h.app.db).await.unwrap();
6750
    sqlx::query("UPDATE flow_jobs SET status = 'running' WHERE run_id = $1 AND name = 'build'")
6751
        .bind(three.id)
6752
        .execute(&h.app.db)
6753
        .await
6754
        .unwrap();
6755
    assert_eq!(start(kept.clone(), "proposal/7", "proposal").await, 8);
6756
    assert_eq!(start(kept.clone(), "proposal/7", "proposal").await, 9);
6757
    assert_eq!(run(3).await.status, "running", "a running run is kept");
6758
    superseded_by(8, 9).await;
6759
    // The default again: running runs are cancelled too.
6760
    db::repos::set_flow_keep_running(&h.app.db, row.id, false).await.unwrap();
6761
    let row = db::repos::get(&h.app.db, "andy", "newest").await.unwrap().unwrap();
6762
    assert_eq!(start(row.clone(), "proposal/7", "proposal").await, 10);
6763
    superseded_by(3, 10).await;
6764
    superseded_by(9, 10).await;
6765
}
6766
6767
/// oxygenhub#322: runners are offered the build their nearest update
6768
/// setting asks for, off unless some level turns it on; a test group of
6769
/// chosen runners tries it first.
6770
#[tokio::test(flavor = "multi_thread")]
6771
async fn runners_are_offered_updates_by_their_nearest_setting() {
6772
    use oxy_core::identity::SecretKey;
6773
    let h = hub().await;
6774
    create(&h.app, "andy", "oxygenflow").await;
6775
    let res = oxygenhub::router(h.app.clone())
6776
        .oneshot(
6777
            Request::post("/register")
6778
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
6779
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
6780
                .unwrap(),
6781
        )
6782
        .await
6783
        .unwrap();
6784
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
6785
    let admin = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
6786
    db::accounts::set_admin(&h.app.db, admin.id, true).await.unwrap();
6787
    let web = |method: &'static str, path: &str, body: Option<String>| {
6788
        let (app, cookie, path) = (h.app.clone(), cookie.clone(), path.to_string());
6789
        async move {
6790
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
6791
            if body.is_some() {
6792
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
6793
            }
6794
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
6795
            let st = res.status();
6796
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
6797
        }
6798
    };
6799
    let (st, page) = web("GET", "/admin/runners/updates", None).await;
6800
    assert_eq!(st, StatusCode::OK, "{page}");
6801
    let csrf = {
6802
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
6803
        page[i..].split('"').next().unwrap().to_string()
6804
    };
6805
    assert_eq!(call(&h.app, "GET", "/admin/runners/updates", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
6806
    let mut creds = vec![];
6807
    for name in ["plex", "narvi"] {
6808
        let (_, page) = web("POST", "/admin/runners/token", Some(format!("_csrf={csrf}"))).await;
6809
        let i = page.find("--token ").unwrap() + "--token ".len();
6810
        let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
6811
        let identity = SecretKey::generate().identity(&format!("{name} (OxygenFlow runner)"), "", 1);
6812
        let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0 (build)", "max_jobs": 1 });
6813
        let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
6814
        let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
6815
        assert_eq!(st, StatusCode::OK, "{body}");
6816
        creds.push(serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string());
6817
    }
6818
    let ask = |who: usize| {
6819
        let (app, cred) = (h.app.clone(), creds[who].clone());
6820
        async move {
6821
            let (st, body) = call(&app, "GET", "/api/v1/flow/runner/update", Some(&cred), None).await;
6822
            assert_eq!(st, StatusCode::OK, "{body}");
6823
            serde_json::from_str::<flow_core::api::UpdateAnswer>(&body).unwrap()
6824
        }
6825
    };
6826
    let a = ask(0).await;
6827
    assert!(!a.policy.updates && a.offer.is_none(), "off unless chosen: {a:?}");
6828
    assert_eq!(a.note, "updates are off (default)");
6829
    assert_eq!(call(&h.app, "GET", "/api/v1/flow/runner/update", Some("flowrunner_nope"), None).await.0, StatusCode::UNAUTHORIZED);
6830
6831
    // A release of builds, and the site taking them from it.
6832
    let repo = db::repos::get(&h.app.db, "andy", "oxygenflow").await.unwrap().unwrap();
6833
    let rel = db::releases::create(&h.app.db, repo.id, "v0.2.0", "0.2.0", "", false, None).await.unwrap();
6834
    db::releases::add_asset(&h.app.db, rel.id, "flow-linux-x86_64", 42, &"ab".repeat(32), "application/octet-stream").await.unwrap();
6835
    let (_, page) = web("POST", "/admin/runners/updates/source", Some(format!("_csrf={csrf}&repo=andy%2Fnope"))).await;
6836
    assert!(page.contains("There is no repository"), "{page}");
6837
    let (_, page) = web("POST", "/admin/runners/updates/source", Some(format!("_csrf={csrf}&repo=andy%2Foxygenflow"))).await;
6838
    assert!(page.contains("runner builds come from andy/oxygenflow"), "{page}");
6839
6840
    // A test group of one chosen runner, with updates on: plex, not narvi.
6841
    let plex = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
6842
    let (_, page) =
6843
        web("POST", "/admin/runners/updates/groups", Some(format!("_csrf={csrf}&name=canary&mode=chosen&runner={}", plex.id))).await;
6844
    assert!(page.contains("Test group canary made: 1 chosen runners"), "{page}");
6845
    let group = db::runner_updates::groups(&h.app.db).await.unwrap().remove(0);
6846
    let (_, page) =
6847
        web("POST", "/admin/runners/updates/policy", Some(format!("_csrf={csrf}&scope=group&key={}&updates=on", group.id))).await;
6848
    assert!(page.contains("Saved for group canary: updates on."), "{page}");
6849
    let a = ask(0).await;
6850
    let offer = a.offer.clone().expect("plex is offered the build");
6851
    assert_eq!((offer.version.as_str(), offer.asset.as_str(), offer.blake3.len()), ("0.2.0", "flow-linux-x86_64", 64));
6852
    assert!(offer.url.starts_with("/andy/oxygenflow/asset/") && !offer.older, "{offer:?}");
6853
    assert_eq!(a.policy.from[0], "group canary");
6854
    assert!(ask(1).await.offer.is_none(), "narvi is not in the group");
6855
6856
    // The site's dry run reaches plex; narvi's own setting pins its version.
6857
    let (_, page) = web("POST", "/admin/runners/updates/policy", Some(format!("_csrf={csrf}&scope=site&updates=off&dry_run=on"))).await;
6858
    assert!(page.contains("Saved for the site"), "{page}");
6859
    let a = ask(0).await;
6860
    assert!(a.policy.dry_run && a.policy.from[3] == "site" && a.note.contains("dry run"), "{a:?}");
6861
    let narvi = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "narvi").unwrap();
6862
    web("POST", "/admin/runners/updates/policy", Some(format!("_csrf={csrf}&scope=runner&key={}&updates=on&channel=0.1.0", narvi.id)))
6863
        .await;
6864
    let b = ask(1).await;
6865
    assert!(b.policy.updates && b.offer.is_none() && b.note.contains("has no release"), "{b:?}");
6866
6867
    // Outside its window it waits.
6868
    let now = time::OffsetDateTime::now_utc().hour();
6869
    let (from, to) = ((now + 2) % 24, (now + 4) % 24);
6870
    web(
6871
        "POST",
6872
        "/admin/runners/updates/policy",
6873
        Some(format!("_csrf={csrf}&scope=group&key={}&updates=on&window={from:02}-{to:02}", group.id)),
6874
    )
6875
    .await;
6876
    let a = ask(0).await;
6877
    assert!(a.offer.is_none() && a.note.contains("waits for its window"), "{a:?}");
6878
6879
    // Mistakes are refused, saying why.
6880
    let (_, page) = web("POST", "/admin/runners/updates/policy", Some(format!("_csrf={csrf}&scope=site&channel=latest"))).await;
6881
    assert!(page.contains("A channel is stable, canary or a version"), "{page}");
6882
    let (_, page) = web("POST", "/admin/runners/updates/policy", Some(format!("_csrf={csrf}&scope=site&window=9"))).await;
6883
    assert!(page.contains("a window is two hours"), "{page}");
6884
    let (_, page) = web("POST", "/admin/runners/updates/groups", Some(format!("_csrf={csrf}&name=farm&mode=percent&percent=0"))).await;
6885
    assert!(page.contains("A percentage is a whole number from 1 to 100."), "{page}");
6886
6887
    // What a runner says shows on the page and in the audit log.
6888
    let report = serde_json::json!({ "note": "dry run: flow 0.2.0 checks out" }).to_string();
6889
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runner/update", Some(&creds[0]), Some(report)).await.0, StatusCode::NO_CONTENT);
6890
    let (_, page) = web("GET", "/admin/runners/updates", None).await;
6891
    assert!(page.contains("dry run: flow 0.2.0 checks out") && page.contains(">canary</span>"), "{page}");
6892
    assert!(page.contains("updates on (group canary)") && page.contains("updates on (runner) · channel 0.1.0 (runner)"), "{page}");
6893
6894
    // The same through the API (`oh runner-updates`), for administrators only.
6895
    let (_, tokens) = web("GET", "/settings/tokens", None).await;
6896
    let tcsrf = {
6897
        let i = tokens.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
6898
        tokens[i..].split('"').next().unwrap().to_string()
6899
    };
6900
    let (_, made) = web("POST", "/settings/tokens", Some(format!("_csrf={tcsrf}&name=admin&scopes=user%3Aread"))).await;
6901
    let i = made.find("oxyhub_").unwrap();
6902
    let admin_token: String = made[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
6903
    let (st, body) = call(&h.app, "GET", "/api/v1/admin/runner-updates", Some(&admin_token), None).await;
6904
    assert_eq!(st, StatusCode::OK, "{body}");
6905
    let all: hub_api::RunnerUpdates = serde_json::from_str(&body).unwrap();
6906
    assert_eq!(all.repo, "andy/oxygenflow");
6907
    assert!(all.settings.iter().any(|s| s.scope == "group" && s.updates == Some(true) && s.window.is_some()), "{all:?}");
6908
    let plex_row = all.runners.iter().find(|r| r.name == "plex").unwrap();
6909
    assert!(plex_row.updates && plex_row.from[0] == "group canary" && plex_row.groups == ["canary"], "{plex_row:?}");
6910
    let put = |body: serde_json::Value| {
6911
        let (app, t) = (h.app.clone(), admin_token.clone());
6912
        async move { call(&app, "PUT", "/api/v1/admin/runner-updates/settings", Some(&t), Some(body.to_string())).await }
6913
    };
6914
    let (st, body) =
6915
        put(serde_json::json!({ "scope": "runner", "key": narvi.id.to_string(), "updates": true, "channel": "0.1.0", "dry_run": true }))
6916
            .await;
6917
    assert_eq!(st, StatusCode::OK, "{body}");
6918
    assert!(body.contains("Saved for runner narvi: updates on, channel 0.1.0, dry run on."), "{body}");
6919
    let (st, body) = put(serde_json::json!({ "scope": "site", "channel": "latest" })).await;
6920
    assert_eq!(st, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
6921
    assert_eq!(
6922
        call(&h.app, "GET", "/api/v1/admin/runner-updates", Some(&creds[0]), None).await.0,
6923
        StatusCode::UNAUTHORIZED,
6924
        "not a runner's"
6925
    );
6926
6927
    // #326: a build that rolls back on one runner is held for every other.
6928
    let report = serde_json::json!({ "note": "rolled back from flow 0.2.0 to 0.1.0: 3 starts without reaching the hub" }).to_string();
6929
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runner/update", Some(&creds[0]), Some(report)).await.0, StatusCode::NO_CONTENT);
6930
    let a = ask(0).await;
6931
    assert!(a.offer.is_none() && a.note.contains("flow 0.2.0 is held: it rolled back on plex (3 starts"), "{a:?}");
6932
    let (_, page) = web("GET", "/admin/runners/updates", None).await;
6933
    assert!(page.contains("Held builds") && page.contains("<strong>flow 0.2.0</strong>"), "{page}");
6934
    let (_, body) = call(&h.app, "GET", "/api/v1/admin/runner-updates", Some(&admin_token), None).await;
6935
    assert!(body.contains("\"version\":\"0.2.0\"") && body.contains("\"runner\":\"plex\""), "the hold through the API: {body}");
6936
    let (_, page) = web("POST", "/admin/runners/updates/holds/lift", Some(format!("_csrf={csrf}&version=0.2.0"))).await;
6937
    assert!(page.contains("flow 0.2.0 is offered again"), "{page}");
6938
    let (st, _) = call(&h.app, "POST", "/api/v1/admin/runner-updates/holds/0.2.0/lift", Some(&admin_token), Some("{}".into())).await;
6939
    assert_eq!(st, StatusCode::NOT_FOUND, "no longer held");
6940
    assert!(ask(0).await.note.contains("waits for its window"), "lifted: back to what its settings say");
6941
    let (_, page) = web("POST", "/admin/runners/updates/holds/lift", Some(format!("_csrf={csrf}&version=0.2.0"))).await;
6942
    assert!(page.contains("flow 0.2.0 is not held."), "{page}");
6943
6944
    // A group of a share: removed, its runners follow the levels above.
6945
    let (_, page) =
6946
        web("POST", &format!("/admin/runners/updates/groups/{}", group.id), Some(format!("_csrf={csrf}&mode=percent&percent=100"))).await;
6947
    assert!(page.contains("Test group canary is now 100% of its runners."), "{page}");
6948
    assert!(ask(1).await.policy.from[0] == "runner", "narvi's own setting is nearer than any group");
6949
    let (_, page) = web("POST", &format!("/admin/runners/updates/groups/{}/delete", group.id), Some(format!("_csrf={csrf}"))).await;
6950
    assert!(page.contains("Test group canary removed"), "{page}");
6951
    assert!(!ask(0).await.policy.updates, "back to the site's off");
6952
}
6953
6954
/// #323: a WASM job has no image, so its placement says nothing of one.
6955
#[tokio::test(flavor = "multi_thread")]
6956
async fn a_wasm_jobs_placement_names_no_image() {
6957
    let h = hub().await;
6958
    create(&h.app, "andy", "wasm").await;
6959
    let work = tempfile::tempdir().unwrap();
6960
    let c = client(&format!("{}/andy/wasm", h.base), work.path());
6961
    write(
6962
        work.path(),
6963
        ".flow/pipeline.kdl",
6964
        "schema-version 1\nsandbox \"w\" {\n    runtime \"wasm\"\n}\njob \"count\" {\n    sandbox \"w\"\n    exec \"count.wasm\"\n}\n",
6965
    );
6966
    write(work.path(), "count.wasm", "\0asm");
6967
    c.commit("A WASM job", &[]).unwrap();
6968
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6969
    runs_of(&h.app, "andy", "wasm").await;
6970
    let (st, body) =
6971
        call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(r#"{"runner":"test-1","runtimes":["wasm"]}"#.into())).await;
6972
    assert_eq!(st, StatusCode::OK, "{body}");
6973
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
6974
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
6975
    assert!(placed.starts_with("idle") && !placed.contains("image"), "{placed}");
6976
}
6977
6978
/// oxygenhub#322: an organisation's owners set their own runners' updates,
6979
/// test groups of their own runners, and nothing beyond them.
6980
#[tokio::test(flavor = "multi_thread")]
6981
async fn an_organisation_sets_its_own_runners_updates() {
6982
    use oxy_core::identity::SecretKey;
6983
    let h = hub().await;
6984
    let res = oxygenhub::router(h.app.clone())
6985
        .oneshot(
6986
            Request::post("/register")
6987
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
6988
                .body(Body::from("username=andy&email=andy%40example.com&password=correct-horse-battery&setup=test-setup"))
6989
                .unwrap(),
6990
        )
6991
        .await
6992
        .unwrap();
6993
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
6994
    let web = |method: &'static str, path: String, body: Option<String>| {
6995
        let (app, cookie) = (h.app.clone(), cookie.clone());
6996
        async move {
6997
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
6998
            if body.is_some() {
6999
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
7000
            }
7001
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
7002
            let st = res.status();
7003
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
7004
        }
7005
    };
7006
    let csrf_of = |page: &str| {
7007
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
7008
        page[i..].split('"').next().unwrap().to_string()
7009
    };
7010
    let (_, page) = web("GET", "/orgs/new".into(), None).await;
7011
    let csrf = csrf_of(&page);
7012
    web("POST", "/orgs/new".into(), Some(format!("_csrf={csrf}&name=acme&display_name=Acme"))).await;
7013
    // Two of acme's runners, and the site's (hub.toml's, from its first claim).
7014
    let mut creds = vec![];
7015
    for name in ["a1", "a2"] {
7016
        let (_, page) = web("POST", "/orgs/acme/settings/runners/token".into(), Some(format!("_csrf={csrf}"))).await;
7017
        let i = page.find("--token ").unwrap() + "--token ".len();
7018
        let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
7019
        let identity = SecretKey::generate().identity(name, "", 1);
7020
        let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "max_jobs": 1 });
7021
        let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
7022
        let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
7023
        assert_eq!(st, StatusCode::OK, "{body}");
7024
        creds.push(serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string());
7025
    }
7026
    claim(&h.app).await;
7027
    let all = db::runners::list(&h.app.db).await.unwrap();
7028
    let id = |n: &str| all.iter().find(|r| r.name == n).unwrap().id;
7029
    let set = |form: String| web("POST", "/orgs/acme/settings/runners/updates/policy".into(), Some(format!("_csrf={csrf}&{form}")));
7030
7031
    let (_, page) = set("scope=owner&key=acme&updates=on".into()).await;
7032
    assert!(page.contains("Saved for owner acme: updates on."), "{page}");
7033
    let (_, page) = set("scope=site&updates=on".into()).await;
7034
    assert!(page.contains("Choose the site, an owner, a test group or a runner."), "not the site's: {page}");
7035
    let (_, page) = set("scope=owner&key=andy&updates=on".into()).await;
7036
    assert!(page.contains("An organisation sets its own runners"), "{page}");
7037
    let (_, page) = set(format!("scope=runner&key={}&updates=on", id("test-1"))).await;
7038
    assert!(page.contains("That runner is gone."), "the site's runner is not acme's: {page}");
7039
7040
    // A test group of acme's runners; a runner not acme's is left out.
7041
    let (_, page) = web(
7042
        "POST",
7043
        "/orgs/acme/settings/runners/updates/groups".into(),
7044
        Some(format!("_csrf={csrf}&name=canary&owner=&mode=chosen&runner={}&runner={}", id("a1"), id("test-1"))),
7045
    )
7046
    .await;
7047
    assert!(page.contains("Test group canary made: 1 chosen runners"), "{page}");
7048
    let canary = db::runner_updates::groups(&h.app.db).await.unwrap().remove(0);
7049
    assert_eq!(canary.owner, "acme", "an organisation's groups are its own");
7050
    let (_, page) = set(format!("scope=group&key={}&channel=canary", canary.id)).await;
7051
    assert!(page.contains("Saved for group canary: channel canary."), "{page}");
7052
    let (_, page) = set(format!("scope=runner&key={}&updates=off", id("a2"))).await;
7053
    assert!(page.contains("Saved for runner a2: updates off."), "{page}");
7054
7055
    // A site group is not the organisation's to change.
7056
    let site = db::runner_updates::create_group(&h.app.db, "", "everyone", Some(100)).await.unwrap();
7057
    let (_, page) =
7058
        web("POST", format!("/orgs/acme/settings/runners/updates/groups/{}/delete", site.id), Some(format!("_csrf={csrf}"))).await;
7059
    assert!(page.contains("That test group is gone."), "{page}");
7060
    assert!(db::runner_updates::group(&h.app.db, site.id).await.unwrap().is_some());
7061
7062
    // The page shows it; each runner gets its policy.
7063
    let (_, page) = web("GET", "/orgs/acme/settings".into(), None).await;
7064
    assert!(page.contains("id=\"runner-updates\"") && page.contains(">canary <small"), "{page}");
7065
    assert!(page.contains("updates on (owner acme)") && page.contains("updates off (runner)"), "{page}");
7066
    let ask = |cred: String| {
7067
        let app = h.app.clone();
7068
        async move {
7069
            let (_, body) = call(&app, "GET", "/api/v1/flow/runner/update", Some(&cred), None).await;
7070
            serde_json::from_str::<flow_core::api::UpdateAnswer>(&body).unwrap().policy
7071
        }
7072
    };
7073
    let a1 = ask(creds[0].clone()).await;
7074
    assert!(a1.updates && a1.channel == "canary" && a1.from[..2] == ["owner acme".to_string(), "group canary".to_string()], "{a1:?}");
7075
    assert!(!ask(creds[1].clone()).await.updates, "a2's own setting wins");
7076
}