OXYGENHUB
◆ v0.6.1 oxygenhub / crates / hub / tests / flow.rs
348.1 KiB · Rust · last changed Hub: old clients are not sent tags only a certificate authorizes (refs oxygen#131) 16 days ago source blame history raw
42fa9554 Andy McCall ↶ 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();
c8684d44 Andy McCall 44
    // The first account's setup code (oxygenhub#245).
45
    config.registration.setup_code = "test-setup".into();
42fa9554 Andy McCall ↶ 46
    config.auth.push_tokens = vec!["site".into()];
4d2e44d7 Andy McCall ↶ 47
    config.flow.runner_tokens = vec!["runner-secret".into(), "runner-two".into(), "runner-three".into()];
42fa9554 Andy McCall ↶ 48
    config.flow.repos = vec!["andy/*".into()];
10708ab8 Andy McCall ↶ 49
    config.registration.mode = "open".into();
42fa9554 Andy McCall ↶ 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
736f6813 Andy McCall ↶ 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
42fa9554 Andy McCall ↶ 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
90326c96 Andy McCall ↶ 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
42fa9554 Andy McCall ↶ 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)]);
90326c96 Andy McCall ↶ 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;
42fa9554 Andy McCall ↶ 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);
9a065bc0 Andy McCall ↶ 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
    );
42fa9554 Andy McCall ↶ 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_"));
e8fa5369 Andy McCall ↶ 215
    let opts = RemoteOptions { token: Some(token.clone()), ..Default::default() };
42fa9554 Andy McCall ↶ 216
    open_remote(&url, &opts).unwrap().refs().unwrap();
217
    assert!(open_remote(&format!("{}/andy/secret", h.base), &opts).unwrap().refs().is_err(), "another repository");
e8fa5369 Andy McCall ↶ 218
    let bad = RemoteOptions { token: Some("flowjob_00".into()), ..Default::default() };
42fa9554 Andy McCall ↶ 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
    );
a0d4bbfb Andy McCall ↶ 281
    assert!(checks[2].summary.contains("exit 3") && checks[2].url.ends_with(&format!("/andy/demo/flow/{}", run.number)));
42fa9554 Andy McCall ↶ 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);
a0d4bbfb Andy McCall ↶ 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;
42fa9554 Andy McCall ↶ 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");
a0d4bbfb Andy McCall ↶ 294
    let (st, live) = call(&h.app, "GET", &format!("/andy/demo/flow/{}/live?after={a_id}:1", run.number), None, None).await;
42fa9554 Andy McCall ↶ 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);
a0d4bbfb Andy McCall ↶ 356
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", third.number), None, None).await;
42fa9554 Andy McCall ↶ 357
    assert!(page.contains("The pipeline is not valid"));
358
736f6813 Andy McCall ↶ 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
42fa9554 Andy McCall ↶ 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"));
736f6813 Andy McCall ↶ 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");
42fa9554 Andy McCall ↶ 417
}
fd3db644 Andy McCall ↶ 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;
25091e5c Andy McCall ↶ 422
    for n in ["base", "lib", "vault", "other", "app"] {
fd3db644 Andy McCall ↶ 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
    };
25091e5c Andy McCall ↶ 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();
fd3db644 Andy McCall ↶ 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();
a4f01d51 Andy McCall ↶ 452
    // Vault is private: a checkout with no token for this hub cannot add
2bbe88a8 Andy McCall ↶ 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).
fd3db644 Andy McCall ↶ 455
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'vault'").execute(&h.app.db).await.unwrap();
a4f01d51 Andy McCall ↶ 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");
370035a4 Andy McCall ↶ 461
    app.submodule_add(&format!("{}/andy/vault", h.base), "deps/vault", Some("main")).unwrap();
a4f01d51 Andy McCall ↶ 462
    let nested = Repo::open(&work.path().join("deps/vault")).unwrap();
2bbe88a8 Andy McCall ↶ 463
    assert!(nested.config.remote_tokens.is_empty(), "no token is copied into a subrepo");
464
    nested.fetch("origin").unwrap();
370035a4 Andy McCall ↶ 465
    // The pusher below is the site token, which has no account: it cannot read vault.
fd3db644 Andy McCall ↶ 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();
25091e5c Andy McCall ↶ 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<_>>()));
370035a4 Andy McCall ↶ 478
    let _ = std::fs::remove_dir_all(work.path().join("deps/vault2"));
fd3db644 Andy McCall ↶ 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"));
afd0be38 Andy McCall ↶ 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
    );
fd3db644 Andy McCall ↶ 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
    };
25091e5c Andy McCall ↶ 498
    assert!(read("app") && read("lib") && read("base"));
fd3db644 Andy McCall ↶ 499
    assert!(!read("vault"), "not pinned for this pusher");
500
    assert!(!read("other"), "public, but not the job's to read");
501
}
941abdd6 Andy McCall ↶ 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
}
9008bf6c Andy McCall ↶ 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;
a0d4bbfb Andy McCall ↶ 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
    }
9008bf6c Andy McCall ↶ 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
    }
a0d4bbfb Andy McCall ↶ 565
    let plain = runs_of(&h.app, "other", "plain").await;
566
    assert_eq!(plain.len(), 1, "turned on");
55673c65 Andy McCall ↶ 567
    // andy/first has a job running, so plain's goes next (repositories take
568
    // turns, #244), and its run says where it stands.
bf3d0754 Andy McCall ↶ 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;
55673c65 Andy McCall ↶ 572
    assert!(page.contains("Waiting for a runner: 1st in line") && page.contains("Running now: andy/first #1"), "{page}");
bf3d0754 Andy McCall ↶ 573
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/other/plain/flow/runs/1", None, None).await;
55673c65 Andy McCall ↶ 574
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["queue_position"], 1);
bf3d0754 Andy McCall ↶ 575
    let (_, list) = call(&h.app, "GET", "/other/plain/flow", None, None).await;
55673c65 Andy McCall ↶ 576
    assert!(list.contains("queued, 1st in line"), "{list}");
a0d4bbfb Andy McCall ↶ 577
    // Runs are numbered per repository: this is plain's first, whatever
578
    // other repositories ran before.
579
    assert_eq!(plain[0].number, 1);
90326c96 Andy McCall ↶ 580
    let checks = checks_when(&h.app, row.id, &plain[0].state, 3).await;
a0d4bbfb Andy McCall ↶ 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}");
9008bf6c Andy McCall ↶ 584
    assert!(runs_of(&h.app, "andy", "quiet").await.is_empty(), "turned off despite andy/*");
585
}
1edac4b6 Andy McCall ↶ 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
4f692533 Andy McCall ↶ 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
1edac4b6 Andy McCall ↶ 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() {
3b1bc27f Andy McCall 654
            sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE id = $1").bind(j.id).execute(&h.app.db).await.unwrap();
1edac4b6 Andy McCall ↶ 655
        }
3b1bc27f Andy McCall 656
        sqlx::query("UPDATE flow_runs SET status = 'passed', finished_ms = 1 WHERE id = $1").bind(r.id).execute(&h.app.db).await.unwrap();
1edac4b6 Andy McCall ↶ 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}");
4f692533 Andy McCall ↶ 660
    let third = db::flow::run(&h.app.db, row.id, 4).await.unwrap().unwrap();
348f8c4b Andy McCall ↶ 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
    );
c889911b Andy McCall ↶ 665
    assert_eq!(third.trigger, "rerun:1:push", "a rerun keeps the event it repeats");
1edac4b6 Andy McCall ↶ 666
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, &third.state).await.unwrap();
667
    assert!(
4f692533 Andy McCall ↶ 668
        checks.iter().all(|c| c.status == "queued" && c.url.ends_with("/flow/4")),
1edac4b6 Andy McCall ↶ 669
        "the re-run's checks replace the old ones: {checks:?}"
670
    );
4f692533 Andy McCall ↶ 671
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/4", None, None).await;
1edac4b6 Andy McCall ↶ 672
    assert!(page.contains("re-run of #1 by andy"));
673
    assert!(!page.contains("RE-RUN"), "anonymous viewers get no button");
674
0650d94e Andy McCall ↶ 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
1edac4b6 Andy McCall ↶ 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}");
4f692533 Andy McCall ↶ 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");
90326c96 Andy McCall ↶ 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}");
1edac4b6 Andy McCall ↶ 765
}
cc19697f Andy McCall ↶ 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
}
a3c8288b Andy McCall ↶ 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");
16ee5d19 Andy McCall ↶ 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}");
a3c8288b Andy McCall ↶ 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);
076c7a7c Andy McCall ↶ 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");
681db69e Andy McCall ↶ 926
    let unb64 = |t: &str| oxy_core::dsse::base64_decode(t).expect("base64");
076c7a7c Andy McCall ↶ 927
    let payload = unb64(env["payload"].as_str().unwrap());
928
    let sig = unb64(env["signatures"][0]["sig"].as_str().unwrap());
929
    let signed = oxygenhub::provenance::pae("application/vnd.in-toto+json", &payload);
930
    ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, h.app.hub_key.identity.ed25519_pk)
931
        .verify(&signed, &sig)
932
        .expect("the hub's key signed the envelope");
933
    let statement: serde_json::Value = serde_json::from_slice(&payload).unwrap();
934
    use sha2::Digest;
935
    assert_eq!(statement["subject"][0]["digest"]["sha256"], hex::encode(sha2::Sha256::digest(&body)));
936
    assert_eq!(statement["predicateType"], "https://slsa.dev/provenance/v1");
937
    assert_eq!(statement["predicate"]["buildDefinition"]["externalParameters"]["job"], "build");
938
    assert_eq!(statement["predicate"]["runDetails"]["byproducts"][0]["digest"]["oxygen-attestation"], "a1b2");
939
    let (_, pem) = get_bytes(&h.app, "/.well-known/oxyhub-signing.pem").await;
940
    let pem = String::from_utf8(pem).unwrap();
941
    let der = unb64(pem.lines().filter(|l| !l.starts_with("-----")).collect::<String>().as_str());
942
    assert_eq!(&der[der.len() - 32..], &h.app.hub_key.identity.ed25519_pk[..], "the PEM holds the hub's key");
943
    sqlx::query("UPDATE flow_jobs SET receipt_attest = '', receipt_signer = '' WHERE id = $1").bind(id).execute(&h.app.db).await.unwrap();
10708ab8 Andy McCall ↶ 944
45977501 Andy McCall ↶ 945
    // The nightly gc keeps it (#126): only the database names it, so with
946
    // no grace period a gc that did not root it would prune it at once.
947
    {
948
        let name = RepoName::parse("andy/demo").unwrap();
949
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
950
        hosted.config.set("core.gc-grace", "0").unwrap();
951
        hosted.save_config().unwrap();
952
    }
953
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
954
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
955
    let (st, got) = get_bytes(&h.app, &link).await;
956
    assert_eq!((st, got == body), (StatusCode::OK, true), "the artifact survives gc");
957
10708ab8 Andy McCall ↶ 958
    // A writer attaches the artifact to a release from the run page; the
959
    // release then names the run and job that built it, as does the API.
960
    let form = |f: String| {
961
        Request::post("/register").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(Body::from(f)).unwrap()
962
    };
963
    let res = oxygenhub::router(h.app.clone())
c8684d44 Andy McCall 964
        .oneshot(form("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup".into()))
10708ab8 Andy McCall ↶ 965
        .await
966
        .unwrap();
967
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
968
    let with_cookie = |method: &str, path: &str, body: Option<String>| {
969
        let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie.clone());
970
        if body.is_some() {
971
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
972
        }
973
        req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()
974
    };
975
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
976
    db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
977
    let res = oxygenhub::router(h.app.clone()).oneshot(with_cookie("GET", &format!("/andy/demo/flow/{}", run.number), None)).await.unwrap();
978
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
979
    let attach = format!("/andy/demo/flow/{}/artifacts/build/tool/attach", run.number);
980
    assert!(page.contains(&attach), "a writer is offered the release");
981
    let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
982
    let csrf = page[i..].split('"').next().unwrap().to_string();
983
    let release_id = db::releases::list(&h.app.db, row.id).await.unwrap()[0].id;
984
    let res = oxygenhub::router(h.app.clone())
985
        .oneshot(with_cookie("POST", &attach, Some(format!("_csrf={csrf}&release={release_id}"))))
986
        .await
987
        .unwrap();
988
    assert_eq!(res.status(), StatusCode::SEE_OTHER);
989
    let (_, page) = call(&h.app, "GET", "/andy/demo/releases/tag/v1", None, None).await;
990
    assert!(
991
        page.contains(">tool</a>") && page.contains(&format!("built by <a href=\"/andy/demo/flow/{0}\">run #{0}</a> build", run.number)),
992
        "{page}"
993
    );
994
    let (_, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases", None, None).await;
995
    let api: serde_json::Value = serde_json::from_str(&api).unwrap();
996
    let asset = &api[0]["assets"][0];
997
    assert_eq!(
998
        (asset["name"].as_str(), asset["built_by"]["run"].as_i64(), asset["built_by"]["job"].as_str()),
999
        (Some("tool"), Some(run.number), Some("build"))
1000
    );
1001
    assert!(asset["built_by"]["receipt"].is_null(), "that receipt was not signed");
97fc47fe Andy McCall ↶ 1002
    assert!(asset["built_by"]["provenance_url"].is_null(), "no signed receipt, no provenance");
1003
1004
    // With a kept signed receipt, the asset links its provenance (#239).
1005
    sqlx::query("UPDATE flow_jobs SET receipt_attest = 'a1b2', receipt_signer = 'earth-1' WHERE run_id = $1 AND name = 'build'")
1006
        .bind(run.id)
1007
        .execute(&h.app.db)
1008
        .await
1009
        .unwrap();
1010
    let want = format!("/andy/demo/flow/{}/artifacts/build/tool/provenance", run.number);
1011
    let (_, page) = call(&h.app, "GET", "/andy/demo/releases/tag/v1", None, None).await;
1012
    assert!(page.contains(&format!("href=\"{want}\"")), "{page}");
1013
    let (_, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases", None, None).await;
1014
    let api: serde_json::Value = serde_json::from_str(&api).unwrap();
1015
    assert!(api[0]["assets"][0]["built_by"]["provenance_url"].as_str().unwrap().ends_with(&want));
a3c8288b Andy McCall ↶ 1016
}
df940d75 Andy McCall ↶ 1017
d29070fa Andy McCall ↶ 1018
/// oxygenflow#37: a failing job keeps a `when "always"` artifact; its
1019
/// receipt names none, and the run page says the file is outside it.
a36bab6b Andy McCall ↶ 1020
async fn upload_report_file(app: &Shared, job: i64, name: &str, path: &str, bytes: &[u8]) -> (StatusCode, String) {
1021
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/reports/{name}/files"))
1022
        .header(header::AUTHORIZATION, "Bearer runner-secret")
1023
        .header(header::CONTENT_TYPE, "application/octet-stream")
1024
        .header("X-Flow-Report-Path", path)
1025
        .body(Body::from(bytes.to_vec()))
1026
        .unwrap();
1027
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
1028
    let status = res.status();
1029
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1030
}
1031
1032
/// #127: a report's files arrive one by one, then its manifest as the
1033
/// report's artifact; the hub indexes the declaration, metrics and files,
1034
/// and gc keeps every file.
1035
#[tokio::test(flavor = "multi_thread")]
1036
async fn reports_are_kept_file_by_file_and_indexed() {
1037
    let h = hub().await;
1038
    create(&h.app, "andy", "demo").await;
1039
    let url = format!("{}/andy/demo", h.base);
1040
    let work = tempfile::tempdir().unwrap();
1041
    let c = client(&url, work.path());
1042
    write(
1043
        work.path(),
1044
        ".flow/pipeline.kdl",
1045
        &format!(
1046
            "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"
1047
        ),
1048
    );
1049
    c.snapshot("test").unwrap();
1050
    c.commit("Measure frames", &[]).unwrap();
1051
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1052
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1053
    let a = claim(&h.app).await.unwrap();
1054
    let id = a["job_id"].as_i64().unwrap();
1055
1056
    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";
1057
    let page = b"<p>frames</p>".to_vec();
1058
    let data: Vec<u8> = (0..100_000u32).map(|i| (i % 241) as u8).collect();
c8df33a6 Andy McCall ↶ 1059
    let (page_bytes, data_bytes) = (page.clone(), data.clone());
a36bab6b Andy McCall ↶ 1060
    let files: [(&str, &[u8]); 3] = [("data/frames.csv", &data), ("index.html", &page), ("report.toml", toml)];
1061
1062
    assert_eq!(upload_report_file(&h.app, id, "tool", "report.toml", toml).await.0, StatusCode::BAD_REQUEST, "not a report");
1063
    assert_eq!(upload_report_file(&h.app, id, "frame-timing", "../x", toml).await.0, StatusCode::BAD_REQUEST, "not a clean path");
1064
    let mut listed = vec![];
1065
    for (path, bytes) in files {
1066
        let (st, text) = upload_report_file(&h.app, id, "frame-timing", path, bytes).await;
1067
        assert_eq!(st, StatusCode::OK, "{text}");
1068
        let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1069
        assert_eq!(blob, oxy_core::repo::Repo::blob_ref(bytes).to_hex());
1070
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1071
    }
1072
    let mut missing = listed.clone();
1073
    missing.push(serde_json::json!({ "path": "assets/x.js", "blob": "ab".repeat(32), "size": 1 }));
1074
    let (st, text) =
1075
        upload(&h.app, id, "frame-timing", &serde_json::to_vec(&serde_json::json!({ "version": 1, "files": missing })).unwrap()).await;
1076
    assert_eq!(st, StatusCode::BAD_REQUEST, "a file never uploaded: {text}");
1077
    assert!(text.contains("assets/x.js"), "{text}");
1078
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed })).unwrap();
1079
    let (st, text) = upload(&h.app, id, "frame-timing", &manifest).await;
1080
    assert_eq!(st, StatusCode::OK, "{text}");
1081
1082
    let (kind, title, summary, files_n, bytes): (String, String, String, i64, i64) =
3b1bc27f Andy McCall 1083
        sqlx::query_as("SELECT kind, title, summary, files, bytes FROM reports WHERE job_id = $1 AND name = 'frame-timing'")
a36bab6b Andy McCall ↶ 1084
            .bind(id)
1085
            .fetch_one(&h.app.db)
1086
            .await
1087
            .unwrap();
1088
    assert_eq!((kind.as_str(), title.as_str(), summary.as_str()), ("performance", "Frame timing", "Median 16.4 ms"));
1089
    assert_eq!((files_n, bytes), (3, (data.len() + page.len() + toml.len()) as i64));
3b1bc27f Andy McCall 1090
    let rid: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE job_id = $1").bind(id).fetch_one(&h.app.db).await.unwrap();
a36bab6b Andy McCall ↶ 1091
    let m = oxygenhub::reports::metrics(&h.app.db, rid).await.unwrap();
1092
    assert_eq!((m[0].key.as_str(), m[0].value, m[0].fail_above), ("median_ms", 16.4, Some(20.0)));
1093
    let log = db::flow::log(&h.app.db, id, 0, 1000).await.unwrap();
1094
    assert!(log.iter().any(|r| r.text.contains("report frame-timing: performance \"Frame timing\", 1 metric")), "{log:?}");
c8df33a6 Andy McCall ↶ 1095
1096
    // The threshold is a check on the run's state, passing at 16.4.
1097
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
1098
    let c = checks.iter().find(|c| c.name == "report/frame-timing/median_ms").expect("a check per threshold");
1099
    assert_eq!(c.status, "passed", "{c:?}");
1100
    assert!(c.summary.contains("16.4 ms") && c.url.contains("/reports/frame-timing?id="), "{c:?}");
1101
1102
    // The Reports tab, the report's page, and its own page in a sandbox.
1103
    let (_, page) = call(&h.app, "GET", "/andy/demo", None, None).await;
1104
    assert!(page.contains(">Reports</a>"), "the tab");
1105
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports", None, None).await;
1106
    assert!(st == StatusCode::OK && page.contains("Frame timing") && page.contains("median_ms"), "{st}");
1107
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1108
    assert!(st == StatusCode::OK && page.contains("fails above 20") && page.contains("sandbox=\"allow-scripts\""), "{st}");
1109
    let src = page.split("class=\"rep-frame\" src=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
1110
    assert!(src.ends_with("/index.html"), "{src}");
1111
    let res = oxygenhub::router(h.app.clone()).oneshot(Request::get(&src).body(Body::empty()).unwrap()).await.unwrap();
1112
    assert_eq!(res.status(), StatusCode::OK);
1113
    let csp = res.headers()[header::CONTENT_SECURITY_POLICY].to_str().unwrap().to_string();
1114
    assert!(csp.starts_with("sandbox allow-scripts;") && csp.contains("default-src 'none'"), "{csp}");
d74ce22f Andy McCall ↶ 1115
    // The site's own policy and frame refusal stay off it: report frames are framed (#222).
1116
    assert!(
1117
        res.headers().get(header::X_FRAME_OPTIONS).is_none() && res.headers().get(header::CONTENT_SECURITY_POLICY_REPORT_ONLY).is_none()
1118
    );
1119
    assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
c8df33a6 Andy McCall ↶ 1120
    assert_eq!(res.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*");
f3e5e2bc Andy McCall ↶ 1121
    // The page as kept, with the frame script that sizes the frame added.
1122
    let served = res.into_body().collect().await.unwrap().to_bytes().to_vec();
1123
    assert!(served.starts_with(&page_bytes), "the report's page");
1124
    assert!(String::from_utf8_lossy(&served).contains("/static/report-frame.js"), "with the frame script");
1125
    let (st, _) = get_bytes(&h.app, "/static/report.css").await;
1126
    assert_eq!(st, StatusCode::OK, "the stylesheet a report may link");
c8df33a6 Andy McCall ↶ 1127
    let data = src.replace("/index.html", "/data/frames.csv");
1128
    assert_eq!(get_bytes(&h.app, &data).await, (StatusCode::OK, data_bytes.clone()));
1129
    // A link with another report's MAC, or a file it lacks, finds nothing.
95b525b0 Andy McCall ↶ 1130
    // A second run of the report: the timeline has two stops, and the
1131
    // first can be compared with it (RP4).
1132
    let first: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE name = 'frame-timing'").fetch_one(&h.app.db).await.unwrap();
1133
    let second: i64 = sqlx::query_scalar(
1134
        "INSERT INTO reports (repo_id, name, kind, title, summary, context, run_id, job_id, run_number, job, bookmark, state, manifest, files, bytes, created_ms) \
3b1bc27f Andy McCall 1135
         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",
95b525b0 Andy McCall ↶ 1136
    )
1137
    .bind(first)
1138
    .fetch_one(&h.app.db)
1139
    .await
1140
    .unwrap();
1141
    sqlx::query(
3b1bc27f Andy McCall 1142
        "INSERT INTO report_metrics (report_id, key, value, unit, better, fail_above) VALUES ($1, 'median_ms', 18.0, 'ms', 'lower', 20)",
95b525b0 Andy McCall ↶ 1143
    )
1144
    .bind(second)
1145
    .execute(&h.app.db)
1146
    .await
1147
    .unwrap();
1148
    let (_, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1149
    assert_eq!(page.matches("data-tl-stop").count(), 2, "a stop per run");
1150
    assert!(page.contains("Median 18.0 ms"), "the newest run is shown");
1151
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/frame-timing?id={first}&compare={second}&play=3"), None, None).await;
1152
    assert!(page.contains("This run against run #2") && page.contains("-1.6"), "every metric against the other run");
1153
    let stop = page.split("data-tl-stop").next().unwrap_or("").rsplit("href=").next().unwrap_or("").to_string();
1154
    assert!(page.contains("data-play=\"3\""), "playing");
1155
    assert!(stop.contains("play") && stop.contains('3'), "playing carries on from stop to stop: {stop}");
1156
    assert!(page.contains("data-report-runs="), "the frame interface knows the runs");
c8df33a6 Andy McCall ↶ 1157
    let forged = src.replacen("/files/", "/files/9", 1);
1158
    assert_eq!(get_bytes(&h.app, &forged).await.0, StatusCode::NOT_FOUND);
1159
    assert_eq!(get_bytes(&h.app, &src.replace("/index.html", "/secret.txt")).await.0, StatusCode::NOT_FOUND);
a36bab6b Andy McCall ↶ 1160
    let _ = run;
1161
1162
    // gc keeps every file: only the database names them.
1163
    {
1164
        let name = RepoName::parse("andy/demo").unwrap();
1165
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
1166
        hosted.config.set("core.gc-grace", "0").unwrap();
1167
        hosted.save_config().unwrap();
1168
    }
1169
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
1170
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
1171
    let hosted = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
1172
    for (path, bytes) in files {
1173
        assert_eq!(hosted.read_blob(&oxy_core::repo::Repo::blob_ref(bytes)).unwrap(), bytes, "{path} survives gc");
1174
    }
1175
}
1176
d29070fa Andy McCall ↶ 1177
#[tokio::test(flavor = "multi_thread")]
1178
async fn a_failing_job_keeps_an_artifact_outside_its_receipt() {
1179
    let h = hub().await;
1180
    create(&h.app, "andy", "demo").await;
1181
    let url = format!("{}/andy/demo", h.base);
1182
    let work = tempfile::tempdir().unwrap();
1183
    let c = client(&url, work.path());
1184
    write(
1185
        work.path(),
1186
        ".flow/pipeline.kdl",
1187
        &format!(
336c953a Andy McCall ↶ 1188
            "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"
d29070fa Andy McCall ↶ 1189
        ),
1190
    );
1191
    c.snapshot("test").unwrap();
1192
    c.commit("Test", &[]).unwrap();
1193
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1194
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1195
    let a = claim(&h.app).await.unwrap();
336c953a Andy McCall ↶ 1196
    assert_eq!(a["job"]["outputs"][0]["always"], true, "the runner is told to keep it from a failing job");
d29070fa Andy McCall ↶ 1197
    let id = a["job_id"].as_i64().unwrap();
0b203bbf Andy McCall ↶ 1198
    // A JUnit report (#114): parsed on upload, counted, failures listed.
1199
    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>"#;
1200
    let (st, text) = upload(&h.app, id, "junit", xml).await;
d29070fa Andy McCall ↶ 1201
    assert_eq!(st, StatusCode::OK, "{text}");
1202
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1203
    let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), 1);
1204
    r["outputs"] = serde_json::json!([blob]);
1205
    assert_eq!(
1206
        finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r.clone() })).await,
1207
        StatusCode::BAD_REQUEST,
1208
        "a failing receipt names no outputs"
1209
    );
1210
    r["outputs"] = serde_json::json!([]);
1211
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r })).await, StatusCode::NO_CONTENT);
1212
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
1213
    assert!(page.contains(&format!("/andy/demo/flow/{}/artifacts/test/junit", run.number)), "listed");
1214
    assert!(page.contains("not in its receipt"), "marked");
0b203bbf Andy McCall ↶ 1215
    assert!(page.contains("2 tests: 1 failed"), "counts beside the job");
1216
    assert!(page.contains("tests.test_io::test_write") && page.contains("disk full") && page.contains("OSError"), "the failure");
1217
    assert!(page.contains("tests: 2 tests: 1 failed in 2.0 s"), "said in the job's log");
d29070fa Andy McCall ↶ 1218
}
1219
df940d75 Andy McCall ↶ 1220
/// A release's trust report (hub spec §9.1): a signed tag, an asset built
1221
/// by a job with a signed receipt from the tagged state, and one uploaded
1222
/// by hand; the page, its JSON export and the API.
1223
#[tokio::test(flavor = "multi_thread")]
1224
async fn a_release_is_audited_from_authors_to_receipts() {
1225
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
1226
    use oxy_core::identity::SecretKey;
1227
    use oxy_core::objects::StateObject;
1228
    use oxy_core::receipt::SignedReceipt;
1229
    let h = hub().await;
1230
    create(&h.app, "andy", "demo").await;
1231
    let url = format!("{}/andy/demo", h.base);
1232
    let work = tempfile::tempdir().unwrap();
1233
    let mut c = client(&url, work.path());
1234
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
1235
    write(
1236
        work.path(),
1237
        ".flow/pipeline.kdl",
1238
        &format!(
1239
            "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"
1240
        ),
1241
    );
1242
    c.snapshot("test").unwrap();
1243
    c.commit("Build a tool", &[]).unwrap();
1244
    let heads = c.bookmark_heads().unwrap();
1245
    c.tag_create("v1", &heads, "first").unwrap();
1246
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1247
1248
    // The runner builds, uploads the artifact and signs its receipt.
1249
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1250
    let a = claim(&h.app).await.unwrap();
1251
    let id = a["job_id"].as_i64().unwrap();
1252
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
1253
    let (_, text) = upload(&h.app, id, "tool", &body).await;
1254
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1255
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
1256
    r["outputs"] = serde_json::json!([blob]);
1257
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
1258
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
1259
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
1260
    let sk = SecretKey::generate();
1261
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
1262
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
1263
    let signed = hex::encode(SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/1"), &runner, &sk).encode());
1264
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
1265
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
1266
1267
    // A release with the built asset and a file uploaded by hand.
1268
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1269
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
1270
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
1271
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "notes.txt", "", b"by hand\n").await.unwrap();
1272
1273
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
1274
    assert_eq!(st, StatusCode::OK);
1275
    for want in [
1276
        "Tag v1 is signed",
1277
        "The one change in the release is authenticated",
1278
        "tool: signed receipt from run #1 build",
1279
        "a runner key of this hub",
edcef275 Andy McCall ↶ 1280
        "The tagged state is one change",
df940d75 Andy McCall ↶ 1281
        "tool: built from the tagged state",
1282
        "tool: pinned environment",
1283
        "notes.txt: no build found",
1284
        "<svg class=\"trust-graph\"",
bf5101d3 Andy McCall ↶ 1285
        // oxygenhub#79: a summary of badges, badges in the graph, and the
1286
        // graph drawn at its own size rather than stretched to the page.
1287
        "Tag signed by",
1288
        "1 of 1 changes signed or sealed",
1289
        "1 of 2 assets built and attested by OxygenFlow",
1290
        "attested build",
1291
        "uploaded by hand",
1292
        "receipt verified",
1293
        "class=\"shackle\"",
1294
        "<title>notes.txt:",
df940d75 Andy McCall ↶ 1295
    ] {
1296
        assert!(page.contains(want), "missing {want:?}");
1297
    }
bf5101d3 Andy McCall ↶ 1298
    let svg = &page[page.find("<svg class=\"trust-graph\"").unwrap()..];
1299
    assert!(svg[..200].contains(" width=\"") && svg[..200].contains(" height=\""), "the graph has its own size: {}", &svg[..200]);
df940d75 Andy McCall ↶ 1300
    let (_, releases) = call(&h.app, "GET", "/andy/demo/releases", None, None).await;
1301
    assert!(releases.contains("/andy/demo/releases/trust/v1"), "the release links its audit");
1302
1303
    // The export carries the signed receipt, which checks on its own.
1304
    let (st, json) = call(&h.app, "GET", "/andy/demo/releases/trust/v1?format=json", None, None).await;
1305
    assert_eq!(st, StatusCode::OK);
1306
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
1307
    assert_eq!((t["tag"].as_str(), t["tag_signature"].as_str(), t["changes"].as_i64()), (Some("v1"), Some("valid"), Some(1)));
1308
    assert_eq!(t["authors"][0]["who"]["name"], "Andy");
1309
    let tool = t["assets"].as_array().unwrap().iter().find(|a| a["name"] == "tool").unwrap();
1310
    let hex_receipt = tool["build"]["signed_receipt"].as_str().unwrap();
1311
    let sr = SignedReceipt::decode(&hex::decode(hex_receipt).unwrap()).unwrap();
1312
    sr.verify().unwrap();
1313
    assert_eq!(sr.receipt.outputs[0].to_hex(), blob);
1314
    let audit = t["audit"].as_array().unwrap();
1315
    assert!(audit.iter().any(|c| c["verdict"] == "warn" && c["title"].as_str().unwrap().starts_with("notes.txt")));
1316
    assert!(!audit.iter().any(|c| c["verdict"] == "fail"), "{audit:?}");
1317
    // The API gives the same report; an unknown release is a 404.
1318
    let (st, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v1", None, None).await;
1319
    assert_eq!(st, StatusCode::OK);
1320
    assert_eq!(serde_json::from_str::<serde_json::Value>(&api).unwrap()["assets"].as_array().unwrap().len(), 2);
1321
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1322
    assert_eq!(call(&h.app, "GET", "/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1323
}
b6b7e4cf Andy McCall ↶ 1324
1325
/// Runners (hub spec §13.2): an administrator makes a registration token,
1326
/// a runner registers with it (binding its key), claims, shows on Admin →
1327
/// Runners with its history, and is drained, disabled and removed.
1328
#[tokio::test(flavor = "multi_thread")]
1329
async fn runners_register_show_their_history_and_are_drained_and_removed() {
1330
    use oxy_core::identity::SecretKey;
1331
    let h = hub().await;
1332
    create(&h.app, "andy", "demo").await;
1333
    // A signed-in site administrator.
1334
    let res = oxygenhub::router(h.app.clone())
1335
        .oneshot(
1336
            Request::post("/register")
1337
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
c8684d44 Andy McCall 1338
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
b6b7e4cf Andy McCall ↶ 1339
                .unwrap(),
1340
        )
1341
        .await
1342
        .unwrap();
1343
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1344
    let admin = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
1345
    db::accounts::set_admin(&h.app.db, admin.id, true).await.unwrap();
1346
    let web = |method: &'static str, path: String, body: Option<String>| {
1347
        let (app, cookie) = (h.app.clone(), cookie.clone());
1348
        async move {
1349
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1350
            if body.is_some() {
1351
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1352
            }
1353
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1354
            let st = res.status();
1355
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1356
        }
1357
    };
1358
    let csrf_of = |page: &str| {
1359
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1360
        page[i..].split('"').next().unwrap().to_string()
1361
    };
1362
    let (st, page) = web("GET", "/admin/runners".into(), None).await;
1363
    assert_eq!(st, StatusCode::OK);
1364
    assert!(page.contains("No runners yet"));
1365
    assert_eq!(call(&h.app, "GET", "/admin/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1366
1367
    // A one-time registration token, shown once with the command.
1368
    let (_, page) = web("POST", "/admin/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1369
    let i = page.find("--token ").unwrap() + "--token ".len();
1370
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1371
    assert!(token.starts_with("flowreg_"), "{token}");
1372
1373
    // The runner registers, binding its key; the token then is spent.
1374
    let sk = SecretKey::generate();
1375
    let identity = sk.identity("plex (OxygenFlow runner)", "", 1);
1376
    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 });
1377
    let reg = serde_json::json!({ "token": token, "name": "plex", "identity": hex::encode(identity.encode()), "info": info });
1378
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1379
    assert_eq!(st, StatusCode::OK, "{body}");
1380
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1381
    assert!(credential.starts_with("flowrunner_"));
1382
    assert_eq!(
1383
        call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0,
1384
        StatusCode::FORBIDDEN,
1385
        "used once"
1386
    );
1387
1388
    // It claims with its credential; the hub.toml runner shows too.
1389
    let claim_as = |who: String| {
1390
        let app = h.app.clone();
1391
        let info = info.clone();
1392
        async move {
1393
            let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
1394
            call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await
1395
        }
1396
    };
1397
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "nothing queued");
1398
    assert_eq!(claim(&h.app).await, None);
1399
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1400
    assert!(
1401
        page.contains(">plex</strong>") && page.contains("st-online") && page.contains("x86_64 · linux") && page.contains("big-disk"),
1402
        "{page}"
1403
    );
1404
    assert!(page.contains(">test-1</strong>") && page.contains("hub.toml"), "the configured runner, by its claimed name");
1405
    let plex = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1406
    assert_eq!(plex.key, identity.hash().to_hex(), "bound at registration");
1407
1408
    // A run: plex takes a job, and its history shows it.
1409
    let url = format!("{}/andy/demo", h.base);
1410
    let work = tempfile::tempdir().unwrap();
1411
    let c = client(&url, work.path());
1412
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1413
    c.snapshot("test").unwrap();
1414
    c.commit("Add a pipeline", &[]).unwrap();
1415
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1416
    runs_of(&h.app, "andy", "demo").await;
1417
    let (st, body) = claim_as(credential.clone()).await;
1418
    assert_eq!(st, StatusCode::OK, "{body}");
1419
    let job: serde_json::Value = serde_json::from_str(&body).unwrap();
1420
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1421
    assert!(
1422
        page.contains("andy/demo") && page.contains(job["job"]["name"].as_str().unwrap()) && page.contains("Running now</dt><dd>1 job"),
1423
        "{page}"
1424
    );
b66e70b7 Andy McCall ↶ 1425
    // The queue on Admin → Runners and through the API (#41, part 4).
1426
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
e9b9619c Andy McCall ↶ 1427
    assert!(page.contains("id=\"queue\"") && page.contains(">plex</a></td>"), "{page}");
1428
    // Connectivity and what it is doing, kept apart (#243); its status
1429
    // opens the queue filtered to it, and the filters keep and drop jobs.
1430
    assert!(page.contains("running 1 of ") && page.contains("/admin/runners?runner=plex#queue"), "{page}");
1431
    let (_, only) = web("GET", "/admin/runners?runner=plex".into(), None).await;
1432
    assert!(only.contains(">plex</a></td>") && only.contains(" of ") && only.contains(">all</a>"), "{only}");
1433
    let (_, none) = web("GET", "/admin/runners?runner=nobody&status=running".into(), None).await;
1434
    assert!(none.contains("Nothing matches."), "{none}");
1435
    // A busy runner claims nothing; its heartbeat keeps it online.
1436
    sqlx::query("UPDATE flow_runners SET last_seen_ms = 0 WHERE id = $1").bind(plex.id).execute(&h.app.db).await.unwrap();
1437
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1438
    assert!(page.contains("st-offline"), "quiet for long: offline");
1439
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/heartbeat", Some(&credential), None).await.0, StatusCode::NO_CONTENT);
1440
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/heartbeat", Some("flowrunner_nope"), None).await.0, StatusCode::UNAUTHORIZED);
1441
    let plex_now = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1442
    assert_eq!(plex_now.connectivity(), "online");
b66e70b7 Andy McCall ↶ 1443
    let (_, tokens) = web("GET", "/settings/tokens".into(), None).await;
1444
    let (_, made) = web("POST", "/settings/tokens".into(), Some(format!("_csrf={}&name=admin&scopes=user%3Aread", csrf_of(&tokens)))).await;
1445
    let i = made.find("oxyhub_").unwrap();
1446
    let admin_token: String = made[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
1447
    let (st, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1448
    assert_eq!(st, StatusCode::OK, "{body}");
1449
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1450
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1451
    assert_eq!((plex_row["running"].as_i64(), plex_row["arch"].as_str()), (Some(1), Some("x86_64")));
7f5f6c05 Andy McCall ↶ 1452
    // A runner's own labels and time limit from its page (#98).
1453
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1454
    let (st, _) = web(
1455
        "POST",
1456
        format!("/admin/runners/{}/limits", plex.id),
1457
        Some(format!("_csrf={}&labels=gpu%2C+plex&timeout_minutes=5", csrf_of(&page))),
1458
    )
1459
    .await;
1460
    assert_eq!(st, StatusCode::SEE_OTHER);
1461
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1462
    assert!(page.contains(">gpu<") && page.contains("5 min for its jobs"), "{page}");
1463
    let (_, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1464
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1465
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1466
    assert!(plex_row["labels"].as_array().unwrap().iter().any(|l| l == "gpu"), "{plex_row}");
1467
    let (st, _) = web(
1468
        "POST",
1469
        format!("/admin/runners/{}/limits", plex.id),
1470
        Some(format!("_csrf={}&labels=bad%20label%21&timeout_minutes=", csrf_of(&page))),
1471
    )
1472
    .await;
1473
    assert_eq!(st, StatusCode::BAD_REQUEST, "a label with a space or punctuation is refused");
b66e70b7 Andy McCall ↶ 1474
    let (_, body) = call(&h.app, "GET", "/api/v1/runners/queue", Some(&admin_token), None).await;
1475
    let queue: serde_json::Value = serde_json::from_str(&body).unwrap();
1476
    assert!(queue.as_array().unwrap().iter().any(|q| q["status"] == "running" && q["runner"] == "plex"), "{queue}");
1477
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/runners/{}/jobs", plex.id), Some(&admin_token), None).await;
1478
    let jobs: serde_json::Value = serde_json::from_str(&body).unwrap();
1479
    assert_eq!(jobs[0]["repo"], "andy/demo", "{jobs}");
1480
    assert_eq!(call(&h.app, "GET", "/api/v1/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
b6b7e4cf Andy McCall ↶ 1481
1482
    // Draining: no new work; removing while busy is refused.
1483
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1484
    let csrf = csrf_of(&page);
1485
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=draining"))).await;
1486
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "a draining runner takes nothing");
1487
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1488
    assert!(page.contains("is running jobs: drain it first"), "{page}");
1489
    // Its job finishes; disabled, it is refused; removed, its credential is dead.
1490
    let id = job["job_id"].as_i64().unwrap();
1491
    let done = call(
1492
        &h.app,
1493
        "POST",
1494
        &format!("/api/v1/flow/jobs/{id}/finish"),
1495
        Some(&credential),
1496
        Some(r#"{"exit_code":0,"duration_ms":5}"#.into()),
1497
    )
1498
    .await;
1499
    assert_eq!(done.0, StatusCode::NO_CONTENT);
1500
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=disabled"))).await;
1501
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::FORBIDDEN);
1502
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1503
    assert!(page.contains("Removed plex."), "{page}");
1504
    assert_eq!(claim_as(credential).await.0, StatusCode::UNAUTHORIZED);
1505
}
74be9796 Andy McCall ↶ 1506
1507
/// Runner scopes (oxygenhub#41): a runner registered for one repository, or
1508
/// one owner, takes only those jobs; a site runner takes any.
1509
#[tokio::test(flavor = "multi_thread")]
1510
async fn scoped_runners_take_only_their_scope() {
1511
    use oxy_core::identity::SecretKey;
1512
    let h = hub().await;
1513
    create(&h.app, "andy", "demo").await;
1514
    create(&h.app, "andy", "other").await;
1515
    let register = |scope: db::runners::Scope, name: &'static str| {
1516
        let app = h.app.clone();
1517
        async move {
1518
            let token = format!("flowreg_{name}");
1519
            db::runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &scope).await.unwrap();
1520
            let identity = SecretKey::generate().identity(name, "", 1);
1521
            let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1522
            let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
1523
            let (st, body) = call(&app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1524
            assert_eq!(st, StatusCode::OK, "{body}");
1525
            serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string()
1526
        }
1527
    };
1528
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1529
    let only_demo = register(db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) }, "demo-runner").await;
1530
    let carols = register(db::runners::Scope { owner: "carol".into(), repo_id: None }, "carol-runner").await;
1531
    let andys = register(db::runners::Scope { owner: "andy".into(), repo_id: None }, "andy-runner").await;
1532
    let claim_as = |who: String| {
1533
        let app = h.app.clone();
1534
        async move {
1535
            let body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"] }).to_string();
1536
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await;
1537
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["repo"].as_str().unwrap().to_string())
1538
        }
1539
    };
1540
    // Jobs queued in andy/other only.
1541
    let work = tempfile::tempdir().unwrap();
1542
    let c = client(&format!("{}/andy/other", h.base), work.path());
1543
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1544
    c.snapshot("t").unwrap();
1545
    c.commit("pipeline", &[]).unwrap();
1546
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1547
    assert!(!runs_of(&h.app, "andy", "other").await.is_empty());
1548
    assert_eq!(claim_as(only_demo.clone()).await, None, "nothing of andy/demo is queued");
1549
    assert_eq!(claim_as(carols).await, None, "nothing of carol's");
1550
    assert_eq!(claim_as(andys).await.as_deref(), Some("andy/other"), "the owner's runner takes its repositories' jobs");
1551
    // The site runner (hub.toml) takes any.
1552
    assert_eq!(claim(&h.app).await.unwrap()["repo"], "andy/other");
1553
    assert_eq!(claim_as(only_demo).await, None, "still nothing of its own");
1554
}
7974adb0 Andy McCall ↶ 1555
1556
/// Settings → Runners (oxygenhub#41, part 2b): a repository's admin adds a
1557
/// runner for that repository alone, sees which runners serve it, and
1558
/// removes only its own.
1559
#[tokio::test(flavor = "multi_thread")]
1560
async fn repository_admins_add_and_remove_their_own_runners() {
1561
    use oxy_core::identity::SecretKey;
1562
    let h = hub().await;
1563
    let res = oxygenhub::router(h.app.clone())
1564
        .oneshot(
1565
            Request::post("/register")
1566
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
c8684d44 Andy McCall 1567
                .body(Body::from("username=andy&email=andy%40example.com&password=correct-horse-battery&setup=test-setup"))
7974adb0 Andy McCall ↶ 1568
                .unwrap(),
1569
        )
1570
        .await
1571
        .unwrap();
1572
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1573
    create(&h.app, "andy", "demo").await;
1574
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1575
    let web = |method: &'static str, path: String, body: Option<String>| {
1576
        let (app, cookie) = (h.app.clone(), cookie.clone());
1577
        async move {
1578
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1579
            if body.is_some() {
1580
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1581
            }
1582
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1583
            let st = res.status();
1584
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1585
        }
1586
    };
1587
    let csrf_of = |page: &str| {
1588
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1589
        page[i..].split('"').next().unwrap().to_string()
1590
    };
c7067c7b Andy McCall 1591
    let (st, page) = web("GET", "/andy/demo/settings/runners".into(), None).await;
7974adb0 Andy McCall ↶ 1592
    assert_eq!(st, StatusCode::OK);
c7067c7b Andy McCall 1593
    assert!(page.contains("<h2>Runners</h2>"), "the owner sees the page");
7974adb0 Andy McCall ↶ 1594
    let (_, page) = web("POST", "/andy/demo/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1595
    let i = page.find("--token ").unwrap() + "--token ".len();
1596
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1597
    let identity = SecretKey::generate().identity("mine", "", 1);
1598
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1599
    let reg = serde_json::json!({ "token": token, "name": "mine", "identity": hex::encode(identity.encode()), "info": info });
1600
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1601
    assert_eq!(st, StatusCode::OK, "{body}");
1602
    let mine = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "mine").unwrap();
1603
    assert_eq!(mine.scope(), db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) });
1604
    // The site's runner (hub.toml, from its first claim) serves it too, but is not the owner's to remove.
1605
    claim(&h.app).await;
1606
    let site = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "test-1").unwrap();
c7067c7b Andy McCall 1607
    let (_, page) = web("GET", "/andy/demo/settings/runners".into(), None).await;
7974adb0 Andy McCall ↶ 1608
    assert!(page.contains("<strong>mine</strong>") && page.contains("this repository"), "{page}");
1609
    assert!(page.contains("<strong>test-1</strong>") && page.contains("the whole site"), "{page}");
1610
    let csrf = csrf_of(&page);
1611
    let (st, _) = web("POST", format!("/andy/demo/settings/runners/{}/remove", site.id), Some(format!("_csrf={csrf}"))).await;
1612
    assert_eq!(st, StatusCode::NOT_FOUND, "not the repository's own");
c7067c7b Andy McCall 1613
    let (st, _) = web("POST", format!("/andy/demo/settings/runners/{}/remove", mine.id), Some(format!("_csrf={csrf}"))).await;
1614
    assert_eq!(st, StatusCode::SEE_OTHER, "back to the Runners page");
1615
    let (_, page) = web("GET", "/andy/demo/settings/runners?notice=x".into(), None).await;
1616
    assert!(!page.contains("<strong>mine</strong>"), "{page}");
7974adb0 Andy McCall ↶ 1617
    assert!(db::runners::get(&h.app.db, mine.id).await.unwrap().is_none());
1618
1619
    // The same for an organisation's owner.
1620
    let (_, page) = web("GET", "/orgs/new".into(), None).await;
1621
    web("POST", "/orgs/new".into(), Some(format!("_csrf={}&name=acme&display_name=Acme", csrf_of(&page)))).await;
1622
    let (st, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1623
    assert_eq!(st, StatusCode::OK);
1624
    let (_, page) = web("POST", "/orgs/acme/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1625
    let i = page.find("--token ").unwrap() + "--token ".len();
1626
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1627
    let identity = SecretKey::generate().identity("acme-runner", "", 1);
1628
    let reg = serde_json::json!({ "token": token, "name": "acme-runner", "identity": hex::encode(identity.encode()), "info": info });
1629
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0, StatusCode::OK);
1630
    let acme = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "acme-runner").unwrap();
1631
    assert_eq!(acme.scope(), db::runners::Scope { owner: "acme".into(), repo_id: None });
1632
    let (_, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1633
    assert!(page.contains("<strong>acme-runner</strong>") && page.contains("the organisation's repositories"), "{page}");
1634
    let (_, page) = web("POST", format!("/orgs/acme/settings/runners/{}/remove", acme.id), Some(format!("_csrf={}", csrf_of(&page)))).await;
1635
    assert!(page.contains("acme-runner removed"), "{page}");
1636
}
c4c87f48 Andy McCall ↶ 1637
1638
/// runs-on (oxygenhub#41, part 3): a job that asks for a label goes only to
1639
/// a runner that has it, and waits for one otherwise.
1640
#[tokio::test(flavor = "multi_thread")]
1641
async fn jobs_that_ask_for_labels_wait_for_a_runner_with_them() {
1642
    use oxy_core::identity::SecretKey;
1643
    let h = hub().await;
1644
    create(&h.app, "andy", "demo").await;
1645
    let work = tempfile::tempdir().unwrap();
1646
    let c = client(&format!("{}/andy/demo", h.base), work.path());
1647
    let cross = "job \"cross\" {\n    sandbox \"alpine\"\n    runs-on \"riscv64\"\n    exec \"true\"\n}\n";
1648
    write(work.path(), ".flow/pipeline.kdl", &pipeline(cross));
1649
    c.snapshot("t").unwrap();
1650
    c.commit("pipeline", &[]).unwrap();
1651
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1652
    assert!(!runs_of(&h.app, "andy", "demo").await.is_empty());
1653
    // The site runner has no labels: it takes the others, never cross.
1654
    let mut taken = Vec::new();
1655
    while let Some(j) = claim(&h.app).await {
1656
        taken.push(j["job"]["name"].as_str().unwrap().to_string());
1657
    }
1658
    assert!(!taken.contains(&"cross".to_string()) && taken.contains(&"lint".to_string()), "{taken:?}");
1659
    let queue = db::flow::queue(&h.app.db).await.unwrap();
1660
    let waiting = queue.iter().find(|q| q.job == "cross").unwrap();
1661
    assert_eq!((waiting.status.as_str(), waiting.needs()), ("queued", vec!["riscv64".to_string()]));
1662
    // A runner registered with the label takes it.
1663
    let token = "flowreg_riscv";
1664
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
1665
    let identity = SecretKey::generate().identity("visionfive", "", 1);
1666
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": ["riscv64"], "max_jobs": 1 });
1667
    let reg = serde_json::json!({ "token": token, "name": "visionfive", "identity": hex::encode(identity.encode()), "info": info });
1668
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1669
    assert_eq!(st, StatusCode::OK, "{body}");
1670
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1671
    let claim_body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"], "info": info }).to_string();
1672
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(claim_body)).await;
1673
    assert_eq!(st, StatusCode::OK, "{body}");
1674
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"], "cross");
1675
}
070a7b64 Andy McCall ↶ 1676
1677
/// oxygenhub#71: a job its runner stopped reporting (restarted, or lost
1678
/// the hub as the job ended) is ended once it has run past the time limit
1679
/// and a grace: an error with the reason, its dependents skipped and its
1680
/// run settled, as if the runner had reported the error.
1681
#[tokio::test(flavor = "multi_thread")]
1682
async fn a_job_no_runner_reports_is_ended_after_the_time_limit() {
1683
    let h = hub().await;
1684
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1685
    create(&h.app, "andy", "lost").await;
1686
    let url = format!("{}/andy/lost", h.base);
1687
    let work = tempfile::tempdir().unwrap();
1688
    let c = client(&url, work.path());
1689
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1690
    write(work.path(), "test.sh", "echo ok\n");
1691
    c.commit("Add a pipeline", &[]).unwrap();
1692
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1693
    assert_eq!(runs_of(&h.app, "andy", "lost").await.len(), 1);
1694
    let job = claim(&h.app).await.expect("a job to claim");
1695
    let id = job["job_id"].as_i64().unwrap();
1696
1697
    // Running, but well within the limit: left alone.
1698
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 0);
1699
    // Started long ago and never reported: ended.
1700
    let old = db::now_ms() - 24 * 3600 * 1000;
3b1bc27f Andy McCall 1701
    sqlx::query("UPDATE flow_jobs SET started_ms = $1 WHERE id = $2").bind(old).bind(id).execute(&h.app.db).await.unwrap();
070a7b64 Andy McCall ↶ 1702
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 1);
1703
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1704
    assert_eq!(j.status, "error");
1705
    assert!(j.error.starts_with("lost:"), "{}", j.error);
1706
    let run = &runs_of(&h.app, "andy", "lost").await[0];
1707
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
1708
    assert!(jobs.iter().all(|j| j.status != "running"), "nothing left running");
1709
    // A late report, should one come, does not overwrite the ending.
1710
    assert_ne!(finish(&h.app, id, serde_json::json!({ "exit_code": 0 })).await, StatusCode::NO_CONTENT);
1711
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "error");
1712
}
b0612e7d Andy McCall ↶ 1713
1714
/// oxygenhub#73: a runner that lists the images it holds is offered only
1715
/// the jobs whose rootfs is among them; one that does not say gets any.
1716
#[tokio::test(flavor = "multi_thread")]
1717
async fn a_runner_is_offered_only_jobs_whose_image_it_holds() {
1718
    let h = hub().await;
1719
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1720
    create(&h.app, "andy", "images").await;
1721
    let url = format!("{}/andy/images", h.base);
1722
    let work = tempfile::tempdir().unwrap();
1723
    let c = client(&url, work.path());
1724
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1725
    write(work.path(), "test.sh", "echo ok\n");
1726
    c.commit("Add a pipeline", &[]).unwrap();
1727
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1728
    assert_eq!(runs_of(&h.app, "andy", "images").await.len(), 1);
1729
    let claim_with = |images: Vec<String>| {
1730
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "images": images }).to_string();
1731
        let app = h.app.clone();
1732
        async move {
1733
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await;
1734
            (st, body)
1735
        }
1736
    };
1737
    let (st, _) = claim_with(vec!["ab".repeat(32)]).await;
1738
    assert_eq!(st, StatusCode::NO_CONTENT, "no job for a runner without the image");
1739
    let jobs = db::flow::jobs(&h.app.db, runs_of(&h.app, "andy", "images").await[0].id).await.unwrap();
1740
    let rootfs: serde_json::Value = serde_json::from_str(&jobs[0].sandbox).unwrap();
1741
    let rootfs = rootfs["rootfs"].as_str().unwrap().to_string();
1742
    let (st, body) = claim_with(vec!["ab".repeat(32), rootfs]).await;
1743
    assert_eq!(st, StatusCode::OK, "{body}");
1744
}
eef677c4 Andy McCall ↶ 1745
1746
/// oxygenhub#71: a runner that lists the jobs it holds has the others it
1747
/// was given ended at once (it restarted, or never received them), not at
1748
/// the time limit; a held job is left alone.
1749
#[tokio::test(flavor = "multi_thread")]
1750
async fn a_job_its_runner_no_longer_holds_is_ended_at_its_next_claim() {
1751
    let h = hub().await;
1752
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1753
    create(&h.app, "andy", "held").await;
1754
    let url = format!("{}/andy/held", h.base);
1755
    let work = tempfile::tempdir().unwrap();
1756
    let c = client(&url, work.path());
1757
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1758
    write(work.path(), "test.sh", "echo ok\n");
1759
    c.commit("Add a pipeline", &[]).unwrap();
1760
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1761
    assert_eq!(runs_of(&h.app, "andy", "held").await.len(), 1);
1762
    let id = claim(&h.app).await.expect("a job to claim")["job_id"].as_i64().unwrap();
1763
    let claim_holding = |holding: Vec<i64>| {
1764
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "holding": holding }).to_string();
1765
        let app = h.app.clone();
1766
        async move { call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await.0 }
1767
    };
1768
    claim_holding(vec![id]).await;
1769
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "running", "a held job stays");
1770
    claim_holding(vec![]).await;
1771
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1772
    assert_eq!(j.status, "error");
1773
    assert!(j.error.starts_with("lost:") && j.error.contains("no longer holds"), "{}", j.error);
1774
    let run = &runs_of(&h.app, "andy", "held").await[0];
1775
    assert!(db::flow::jobs(&h.app.db, run.id).await.unwrap().iter().all(|j| j.status != "running"), "the run settles");
1776
}
d7ce41ac Andy McCall ↶ 1777
1778
/// oxygen#59: a job with a `scope` runs on a push only when the push's
1779
/// changes touch a path it names (a release job, when Cargo.toml's version
1780
/// moves); a bookmark's first run and manual runs have every job.
1781
#[tokio::test(flavor = "multi_thread")]
1782
async fn a_scoped_job_runs_only_when_a_push_touches_its_paths() {
1783
    let h = hub().await;
1784
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1785
    create(&h.app, "andy", "scoped").await;
1786
    let url = format!("{}/andy/scoped", h.base);
1787
    let work = tempfile::tempdir().unwrap();
1788
    let c = client(&url, work.path());
1789
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\" \"packaging/**\"\n    exec \"true\"\n}\n";
1790
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1791
    write(work.path(), "test.sh", "echo ok\n");
1792
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1793
    c.commit("Start", &[]).unwrap();
1794
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1795
    let names = |app: Shared, n: usize| async move {
1796
        let mut runs = Vec::new();
1797
        for _ in 0..100 {
1798
            runs = runs_of(&app, "andy", "scoped").await;
1799
            if runs.len() >= n {
1800
                break;
1801
            }
1802
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1803
        }
1804
        assert_eq!(runs.len(), n, "runs");
1805
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1806
        j.sort();
745d225d Andy McCall ↶ 1807
        // Passed, so the next push is scoped against it, not superseding it.
3b1bc27f Andy McCall 1808
        sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(runs[0].id).execute(&app.db).await.unwrap();
d7ce41ac Andy McCall ↶ 1809
        j
1810
    };
1811
    assert_eq!(names(h.app.clone(), 1).await, ["build", "dist", "lint", "test"], "the first run has every job");
1812
    write(work.path(), "test.sh", "echo still ok\n");
1813
    c.commit("Edit the test", &[]).unwrap();
1814
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1815
    assert_eq!(names(h.app.clone(), 2).await, ["build", "lint", "test"], "dist is out of scope");
1816
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1817
    c.commit("Release 0.1.1", &[]).unwrap();
1818
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1819
    assert_eq!(names(h.app.clone(), 3).await, ["build", "dist", "lint", "test"], "a version bump runs dist");
1820
}
5dead1f4 Andy McCall ↶ 1821
745d225d Andy McCall ↶ 1822
/// oxygenflow#32: a run still going is cancelled from the API, the web or
1823
/// by a newer push to its bookmark; its runner is refused from then on,
1824
/// and the next push is scoped past the cancelled run.
1825
#[tokio::test(flavor = "multi_thread")]
1826
async fn runs_are_cancelled_by_hand_or_by_a_newer_push() {
1827
    let h = hub().await;
1828
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1829
    create(&h.app, "andy", "stop").await;
1830
    let url = format!("{}/andy/stop", h.base);
1831
    let work = tempfile::tempdir().unwrap();
1832
    let c = client(&url, work.path());
1833
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\"\n    exec \"true\"\n}\n";
1834
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1835
    write(work.path(), "test.sh", "echo ok\n");
1836
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1837
    c.commit("Start", &[]).unwrap();
1838
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1839
    let wait_runs = |app: Shared, n: usize| async move {
1840
        for _ in 0..100 {
1841
            let runs = runs_of(&app, "andy", "stop").await;
1842
            if runs.len() >= n {
1843
                return runs;
1844
            }
1845
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1846
        }
1847
        panic!("no run {n}");
1848
    };
1849
    let first = wait_runs(h.app.clone(), 1).await;
3b1bc27f Andy McCall 1850
    sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(first[0].id).execute(&h.app.db).await.unwrap();
1851
    sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE run_id = $1").bind(first[0].id).execute(&h.app.db).await.unwrap();
745d225d Andy McCall ↶ 1852
1853
    // Run 2 (a version bump) has a job running when run 3 is pushed.
1854
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1855
    c.commit("Release 0.1.1", &[]).unwrap();
1856
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1857
    wait_runs(h.app.clone(), 2).await;
1858
    let job = claim(&h.app).await.expect("a job of run 2");
1859
    let id = job["job_id"].as_i64().unwrap();
1860
    write(work.path(), "test.sh", "echo still ok\n");
1861
    c.commit("Edit the test", &[]).unwrap();
1862
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1863
    let runs = wait_runs(h.app.clone(), 3).await;
1864
    let third = &runs[0];
1865
    let mut second = runs[1].clone();
1866
    for _ in 0..100 {
1867
        second = db::flow::run_by_id(&h.app.db, runs[1].id).await.unwrap().unwrap();
1868
        if !second.live() {
1869
            break;
1870
        }
1871
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1872
    }
1873
    assert_eq!(second.status, "cancelled", "a newer push supersedes a run still going");
1874
    let jobs = db::flow::jobs(&h.app.db, second.id).await.unwrap();
1875
    assert!(jobs.iter().all(|j| j.status == "cancelled" && j.error == "superseded by run #3"), "{jobs:?}");
1876
    let mut names: Vec<String> = db::flow::jobs(&h.app.db, third.id).await.unwrap().into_iter().map(|j| j.name).collect();
1877
    names.sort();
1878
    assert_eq!(names, ["build", "dist", "lint", "test"], "run 3 also checks what run 2 would have: the version bump");
1879
    let mut checks = vec![];
1880
    for _ in 0..100 {
1881
        checks = db::hooks::checks_for_state(&h.app.db, second.repo_id, &second.state).await.unwrap();
1882
        if checks.iter().all(|c| c.status == "cancelled") {
1883
            break;
1884
        }
1885
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1886
    }
1887
    assert!(checks.iter().all(|c| c.status == "cancelled"), "{checks:?}");
1888
    // The runner of the cancelled job is refused, so it stops the job.
1889
    let (st, _) =
1890
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(r#"{"records":[]}"#.into())).await;
1891
    assert_eq!(st, StatusCode::CONFLICT);
1892
1893
    // By hand: the API, then a run already ended is refused.
1894
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
1895
    assert_eq!(st, StatusCode::OK, "{body}");
1896
    let third = db::flow::run_by_id(&h.app.db, third.id).await.unwrap().unwrap();
1897
    assert_eq!(third.status, "cancelled");
1898
    assert!(db::flow::jobs(&h.app.db, third.id).await.unwrap().iter().all(|j| j.error == "cancelled by andy"));
1899
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
1900
    assert!(st == StatusCode::CONFLICT && body.contains("already cancelled"), "{st} {body}");
1901
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", None, None).await;
1902
    assert_ne!(st, StatusCode::OK, "anonymous callers cannot cancel");
1903
    let (_, page) = call(&h.app, "GET", "/andy/stop/flow/3", None, None).await;
1904
    assert!(page.contains("⊘") && !page.contains("CANCEL</button>"), "a cancelled run shows so, with no button");
1905
}
1906
5dead1f4 Andy McCall ↶ 1907
/// oxygenflow#23 and oxygenhub#89: a job runs under its pipeline's
1908
/// timeout, capped at the site's maximum, else the site's default; and the
1909
/// hub gives a job up only past its own limit.
1910
#[tokio::test(flavor = "multi_thread")]
1911
async fn a_job_runs_under_its_own_time_limit_within_the_sites() {
1912
    let h = hub().await;
1913
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1914
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_DEFAULT, "30").await.unwrap();
1915
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_MAX, "120").await.unwrap();
1916
    create(&h.app, "andy", "limits").await;
1917
    let url = format!("{}/andy/limits", h.base);
1918
    let work = tempfile::tempdir().unwrap();
1919
    let c = client(&url, work.path());
1920
    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";
1921
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1922
    write(work.path(), "test.sh", "echo ok\n");
1923
    c.commit("Add a pipeline", &[]).unwrap();
1924
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1925
    assert_eq!(runs_of(&h.app, "andy", "limits").await.len(), 1);
1926
    let mut limits = std::collections::HashMap::new();
1927
    let mut ids = std::collections::HashMap::new();
1928
    while let Some(j) = claim(&h.app).await {
1929
        let name = j["job"]["name"].as_str().unwrap().to_string();
1930
        limits.insert(name.clone(), j["timeout_s"].as_u64().unwrap());
1931
        ids.insert(name, j["job_id"].as_i64().unwrap());
1932
    }
1933
    assert_eq!(limits["slow"], 5400, "its own");
1934
    assert_eq!(limits["huge"], 7200, "cut to the site's maximum");
1935
    assert_eq!(limits["build"], 1800, "the site's default");
1936
    // 40 minutes in: past the default and its grace, within slow's limit.
1937
    let started = db::now_ms() - 40 * 60 * 1000;
3b1bc27f Andy McCall 1938
    sqlx::query("UPDATE flow_jobs SET started_ms = $1").bind(started).execute(&h.app.db).await.unwrap();
5dead1f4 Andy McCall ↶ 1939
    oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap();
1940
    let status = |id: i64| {
1941
        let app = h.app.clone();
1942
        async move { db::flow::job(&app.db, id).await.unwrap().unwrap().status }
1943
    };
1944
    assert_eq!(status(ids["build"]).await, "error", "past its 30 minutes");
1945
    assert_eq!(status(ids["slow"]).await, "running", "within its 90");
1946
    assert_eq!(status(ids["huge"]).await, "running", "within its 120");
1947
}
c889911b Andy McCall ↶ 1948
1949
/// oxygenflow#24: a job's `on` decides which events start it: a pushed
1950
/// tag runs only the jobs that name it; a push to a bookmark the pipeline
1951
/// does not name starts no run; a rerun repeats its run's event.
1952
#[tokio::test(flavor = "multi_thread")]
1953
async fn on_decides_which_events_start_a_job() {
1954
    let h = hub().await;
1955
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1956
    create(&h.app, "andy", "events").await;
1957
    let url = format!("{}/andy/events", h.base);
1958
    let work = tempfile::tempdir().unwrap();
1959
    let c = client(&url, work.path());
1960
    let text = format!(
1961
        "on {{\n    push \"main\"\n    manual\n}}\n{}job \"dist\" {{\n    sandbox \"alpine\"\n    on {{\n        tag \"v*\"\n    }}\n    exec \"true\"\n}}\n",
1962
        pipeline("")
1963
    );
1964
    // `on` must come after schema-version; pipeline() starts with it.
1965
    let text = text.replacen(
1966
        "on {\n    push \"main\"\n    manual\n}\nschema-version 1\n",
1967
        "schema-version 1\non {\n    push \"main\"\n    manual\n}\n",
1968
        1,
1969
    );
1970
    write(work.path(), ".flow/pipeline.kdl", &text);
1971
    write(work.path(), "test.sh", "echo ok\n");
1972
    c.commit("Start", &[]).unwrap();
1973
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1974
    let jobs_of_latest = |app: Shared, n: usize| async move {
1975
        let mut runs = Vec::new();
1976
        for _ in 0..100 {
1977
            runs = runs_of(&app, "andy", "events").await;
1978
            if runs.len() >= n {
1979
                break;
1980
            }
1981
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1982
        }
1983
        assert_eq!(runs.len(), n, "runs");
1984
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1985
        j.sort();
1986
        (runs[0].clone(), j)
1987
    };
1988
    let (_, j) = jobs_of_latest(h.app.clone(), 1).await;
1989
    assert_eq!(j, ["build", "lint", "test"], "a push to main: no dist");
1990
    // A tag: only dist.
1991
    let heads = c.bookmark_heads().unwrap();
1992
    c.tag_create("v1.0.0", &heads, "first").unwrap();
1993
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1994
    let (run, j) = jobs_of_latest(h.app.clone(), 2).await;
1995
    assert_eq!(j, ["dist"], "a tag runs only what names it");
1996
    assert_eq!(run.trigger, "tag:v1.0.0");
1997
    // A rerun repeats the tag's event.
1998
    let row = db::repos::get(&h.app.db, "andy", "events").await.unwrap().unwrap();
1999
    db::flow::finish(
2000
        &h.app.db,
2001
        db::flow::jobs(&h.app.db, run.id).await.unwrap()[0].id,
2002
        db::flow::Outcome { status: "passed", exit_code: Some(0), error: "", receipt: "", receipt_hash: "" },
2003
    )
2004
    .await
2005
    .unwrap();
2006
    let run = db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap();
2007
    oxygenhub::flow::rerun(&h.app, &row, &run, "andy").await.unwrap();
2008
    let (_, j) = jobs_of_latest(h.app.clone(), 3).await;
2009
    assert_eq!(j, ["dist"], "the rerun is the tag's run again");
2010
    // A bookmark the pipeline does not name starts nothing.
2011
    c.bookmark_create("develop", None).unwrap();
2012
    assert!(c.push_bookmark("origin", "develop", false).unwrap().iter().all(|r| r.ok));
2013
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
2014
    assert_eq!(runs_of(&h.app, "andy", "events").await.len(), 3, "no run for develop");
348f8c4b Andy McCall ↶ 2015
}
2016
2017
/// oxygenflow#24: a job with a `schedule` line runs on the default
2018
/// bookmark when the line comes due, and only then; other jobs stay out.
2019
#[tokio::test(flavor = "multi_thread")]
2020
async fn scheduled_jobs_run_when_due() {
2021
    let h = hub().await;
2022
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2023
    create(&h.app, "andy", "nightly").await;
2024
    let url = format!("{}/andy/nightly", h.base);
2025
    let work = tempfile::tempdir().unwrap();
2026
    let c = client(&url, work.path());
2027
    // An odd minute, so the hub's own ticker cannot fire it during the test.
2028
    let extra = "job \"nightly\" {\n    sandbox \"alpine\"\n    on {\n        schedule \"17 4 29 2 *\"\n    }\n    exec \"true\"\n}\n";
2029
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
2030
    write(work.path(), "test.sh", "echo ok\n");
2031
    c.commit("Start", &[]).unwrap();
2032
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2033
    assert_eq!(runs_of(&h.app, "andy", "nightly").await.len(), 1);
2034
    let first = runs_of(&h.app, "andy", "nightly").await;
2035
    let names: Vec<String> = db::flow::jobs(&h.app.db, first[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
2036
    assert!(!names.contains(&"nightly".to_string()), "a push does not run a scheduled job");
2037
    use flow_core::pipeline::When;
2038
    let not_yet = When { minute: 16, hour: 4, day: 29, month: 2, weekday: 4 };
2039
    assert_eq!(oxygenhub::flow::run_due(&h.app, not_yet).await, 0);
2040
    let due = When { minute: 17, ..not_yet };
2041
    assert_eq!(oxygenhub::flow::run_due(&h.app, due).await, 1);
2042
    let runs = runs_of(&h.app, "andy", "nightly").await;
2043
    assert_eq!(runs.len(), 2);
2044
    assert_eq!(runs[0].trigger, "schedule");
2045
    let names: Vec<String> = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
2046
    assert_eq!(names, ["nightly"]);
2047
    assert_eq!(runs[0].bookmark, "main", "on the default bookmark");
c889911b Andy McCall ↶ 2048
}
2a83f530 Andy McCall ↶ 2049
2050
#[tokio::test(flavor = "multi_thread")]
2051
async fn variables_from_three_levels_reach_a_job_inner_overriding_outer() {
2052
    use oxygenhub::levels::Scope;
2053
    use oxygenhub::variables;
2054
    let h = hub().await;
2055
    let app = &h.app;
2056
    // Andy, the site's administrator, owns the acme organisation.
2057
    let res = oxygenhub::router(app.clone())
2058
        .oneshot(
2059
            Request::post("/register")
2060
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
c8684d44 Andy McCall 2061
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
2a83f530 Andy McCall ↶ 2062
                .unwrap(),
2063
        )
2064
        .await
2065
        .unwrap();
2066
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
2067
    let andy = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
2068
    db::accounts::create_org(&app.db, "acme", "Acme", andy.id).await.unwrap();
2069
    create(app, "acme", "app").await;
2070
    let page = |path: &str, form: Option<String>| {
2071
        let mut req =
2072
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2073
        if form.is_some() {
2074
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2075
        }
2076
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
c7067c7b Andy McCall 2077
        let (app, cookie) = (app.clone(), cookie.clone());
2a83f530 Andy McCall ↶ 2078
        async move {
c7067c7b Andy McCall 2079
            let mut res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
2080
            // A repository settings form returns to its page (#278).
2081
            let back =
2082
                res.headers().get(header::LOCATION).and_then(|v| v.to_str().ok()).filter(|l| l.contains("/settings/")).map(String::from);
2083
            if let Some(to) = back {
2084
                let req = Request::get(to).header(header::COOKIE, cookie).body(Body::empty()).unwrap();
2085
                res = oxygenhub::router(app).oneshot(req).await.unwrap();
2086
            }
2a83f530 Andy McCall ↶ 2087
            let status = res.status();
2088
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2089
            (status, body)
2090
        }
2091
    };
2092
    let csrf_of = |page: &str| {
2093
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2094
        page[i..].split('"').next().unwrap().to_string()
2095
    };
2096
2097
    // The site sets CC and LANG, the organisation its own CC, the
2098
    // repository RUST_LOG from its settings page.
2099
    variables::set(&app.db, Scope::Site, "CC", "gcc").await.unwrap();
2100
    variables::set(&app.db, Scope::Site, "LANG", "C").await.unwrap();
2101
    let org = db::accounts::org_by_name(&app.db, "acme").await.unwrap().unwrap();
2102
    variables::set(&app.db, Scope::Org(org.id), "CC", "clang").await.unwrap();
c7067c7b Andy McCall 2103
    let (st, settings) = page("/acme/app/settings/variables", None).await;
2a83f530 Andy McCall ↶ 2104
    assert_eq!(st, StatusCode::OK, "{settings}");
2105
    assert!(settings.contains("Inherited") && settings.contains("the acme organisation") && settings.contains("overridden"), "{settings}");
2106
    let csrf = csrf_of(&settings);
2107
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=RUST_LOG&value=debug"))).await;
2108
    assert!(body.contains("RUST_LOG set.") && body.contains("<code>debug</code>"), "{body}");
2109
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=FLOW_REPO&value=x"))).await;
2110
    assert!(body.contains("not FLOW_"), "{body}");
2111
    let repo = db::repos::get(&app.db, "acme", "app").await.unwrap().unwrap();
2112
    db::repos::set_flow(&app.db, repo.id, "on").await.unwrap();
2113
    let env = variables::env_for_repo(&app.db, &repo).await.unwrap();
2114
    assert_eq!(
2115
        env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect::<Vec<_>>(),
2116
        [("CC", "clang"), ("LANG", "C"), ("RUST_LOG", "debug")],
2117
        "the organisation's CC wins over the site's"
2118
    );
2119
2120
    // A claim carries them.
2121
    let url = format!("{}/acme/app", h.base);
2122
    let work = tempfile::tempdir().unwrap();
2123
    let c = client(&url, work.path());
2124
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2125
    write(work.path(), "test.sh", "echo ok\n");
2126
    c.snapshot("test").unwrap();
2127
    c.commit("Add a pipeline", &[]).unwrap();
2128
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2129
    let runs = runs_of(app, "acme", "app").await;
2130
    assert_eq!(runs.len(), 1, "{runs:?}");
2131
    let got = claim(app).await.unwrap_or_else(|| panic!("a job: {:?}", runs[0]));
2132
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "LANG": "C", "RUST_LOG": "debug" }), "{got}");
2133
2134
    // Removing a site variable from the admin page takes effect at the next claim.
2135
    let (_, admin) = page("/admin", None).await;
2136
    assert!(admin.contains("Variables") && admin.contains("<code>gcc</code>"), "{admin}");
2137
    let (_, body) = page("/admin/variables", Some(format!("_csrf={}&action=delete&name=LANG", csrf_of(&admin)))).await;
2138
    assert!(body.contains("LANG removed."), "{body}");
2139
    let got = claim(app).await.expect("another job");
2140
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "RUST_LOG": "debug" }), "{got}");
2141
}
4ac01a73 Andy McCall ↶ 2142
2143
#[tokio::test(flavor = "multi_thread")]
2144
async fn secrets_a_job_declares_come_with_the_claim_and_never_reach_the_log() {
2145
    let h = hub().await;
2146
    let app = &h.app;
2147
    let res = oxygenhub::router(app.clone())
2148
        .oneshot(
2149
            Request::post("/register")
2150
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
c8684d44 Andy McCall 2151
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
4ac01a73 Andy McCall ↶ 2152
                .unwrap(),
2153
        )
2154
        .await
2155
        .unwrap();
2156
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
2157
    let page = |path: &str, form: Option<String>| {
2158
        let mut req =
2159
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2160
        if form.is_some() {
2161
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2162
        }
2163
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
c7067c7b Andy McCall 2164
        let (app, cookie) = (app.clone(), cookie.clone());
4ac01a73 Andy McCall ↶ 2165
        async move {
c7067c7b Andy McCall 2166
            let mut res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
2167
            // A repository settings form returns to its page (#278).
2168
            let back =
2169
                res.headers().get(header::LOCATION).and_then(|v| v.to_str().ok()).filter(|l| l.contains("/settings/")).map(String::from);
2170
            if let Some(to) = back {
2171
                let req = Request::get(to).header(header::COOKIE, cookie).body(Body::empty()).unwrap();
2172
                res = oxygenhub::router(app).oneshot(req).await.unwrap();
2173
            }
4ac01a73 Andy McCall ↶ 2174
            let status = res.status();
2175
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2176
            (status, body)
2177
        }
2178
    };
2179
    let csrf_of = |page: &str| {
2180
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2181
        page[i..].split('"').next().unwrap().to_string()
2182
    };
2183
    create(app, "andy", "demo").await;
2184
    // The site sets deploy-token; the repository overrides it. Neither
2185
    // page shows a value, only that it is set.
2186
    let (_, admin) = page("/admin", None).await;
2187
    let csrf = csrf_of(&admin);
2188
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=deploy-token&value=site-level-value"))).await;
2189
    assert!(body.contains("deploy-token set.") && !body.contains("site-level-value"), "{body}");
2190
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=bad+name&value=x"))).await;
2191
    assert!(body.contains("name is 1 to 64 of"), "{body}");
c7067c7b Andy McCall 2192
    let (_, settings) = page("/andy/demo/settings/secrets", None).await;
4ac01a73 Andy McCall ↶ 2193
    assert!(
2194
        settings.contains("Secrets") && settings.contains("<code>deploy-token</code>") && settings.contains("the site</td>"),
2195
        "{settings}"
2196
    );
2197
    let csrf_r = csrf_of(&settings);
2198
    let (_, body) =
2199
        page("/andy/demo/settings/secrets", Some(format!("_csrf={csrf_r}&action=set&name=deploy-token&value=hunter22-repo-value"))).await;
2200
    assert!(body.contains("deploy-token set.") && body.contains("overridden") && !body.contains("hunter22"), "{body}");
2201
    let repo = db::repos::get(&app.db, "andy", "demo").await.unwrap().unwrap();
2202
    assert!(
2203
        !String::from_utf8_lossy(&oxygenhub::secrets::list(&app.db, oxygenhub::levels::Scope::Repo(repo.id)).await.unwrap()[0].value)
2204
            .contains("hunter22"),
2205
        "sealed at rest"
2206
    );
2207
2208
    // A job that declares the secret, and one the levels do not hold.
2209
    let url = format!("{}/andy/demo", h.base);
2210
    let work = tempfile::tempdir().unwrap();
2211
    let c = client(&url, work.path());
2212
    write(
2213
        work.path(),
2214
        ".flow/pipeline.kdl",
2215
        &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"),
2216
    );
2217
    write(work.path(), "test.sh", "echo ok\n");
2218
    c.snapshot("test").unwrap();
2219
    c.commit("Add a pipeline", &[]).unwrap();
2220
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2221
    let runs = runs_of(app, "andy", "demo").await;
2222
    let jobs = match runs.first() {
2223
        Some(r) => db::flow::jobs(&app.db, r.id).await.unwrap().iter().map(|j| format!("{}:{}", j.name, j.status)).collect::<Vec<_>>(),
2224
        None => vec![],
2225
    };
2226
    let mut deploy = None;
2227
    for _ in 0..50 {
2228
        let Some(got) = claim(app).await else {
2229
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2230
            continue;
2231
        };
2232
        if got["job"]["name"] == "deploy" {
2233
            deploy = Some(got);
2234
            break;
2235
        }
2236
        assert_eq!(got["secrets"], serde_json::Value::Null, "{got}");
2237
    }
2238
    let got = deploy.unwrap_or_else(|| panic!("the deploy job: runs {runs:?} jobs {jobs:?}"));
2239
    assert_eq!(
2240
        got["secrets"],
2241
        serde_json::json!([{ "name": "deploy-token", "path": "/run/secrets/token", "value": "hunter22-repo-value" }]),
2242
        "the repository's value, the missing one left out: {got}"
2243
    );
2244
    let id = got["job_id"].as_i64().unwrap();
2245
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2246
    assert!(log.iter().any(|l| l.stream == "flow" && l.text.contains("secret \"missing\" is not set")), "{log:?}");
2247
2248
    // The value never reaches the stored log, plain or base64.
2249
    let records = serde_json::json!({ "records": [
2250
        { "t": 1, "stream": "out", "text": "token=hunter22-repo-value" },
2251
        { "t": 2, "stream": "err", "text": "b64 aHVudGVyMjItcmVwby12YWx1ZQ== end" },
2252
    ] });
2253
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2254
    assert_eq!(st, StatusCode::NO_CONTENT);
2255
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2256
    let texts: Vec<&str> = log.iter().map(|l| l.text.as_str()).collect();
2257
    assert!(texts.contains(&"token=***") && texts.contains(&"b64 *** end"), "{texts:?}");
2258
    assert!(!texts.iter().any(|t| t.contains("hunter22")), "{texts:?}");
2259
}
d1727c57 Andy McCall ↶ 2260
2261
#[tokio::test(flavor = "multi_thread")]
2262
async fn a_job_s_identity_is_a_signed_token_the_discovery_document_lets_anyone_verify() {
2263
    let h = hub().await;
2264
    let app = &h.app;
2265
    let (st, disc) = call(app, "GET", "/.well-known/openid-configuration", None, None).await;
2266
    assert_eq!(st, StatusCode::OK, "{disc}");
2267
    let disc: serde_json::Value = serde_json::from_str(&disc).unwrap();
2268
    assert_eq!(disc["issuer"], h.base.as_str());
2269
    assert_eq!(disc["jwks_uri"], format!("{}/.well-known/jwks.json", h.base));
2270
    let (st, jwks) = call(app, "GET", "/.well-known/jwks.json", None, None).await;
2271
    assert_eq!(st, StatusCode::OK, "{jwks}");
2272
    let jwks: serde_json::Value = serde_json::from_str(&jwks).unwrap();
2273
    assert_eq!(jwks["keys"][0]["alg"], "RS256");
2274
    let kid = jwks["keys"][0]["kid"].as_str().unwrap().to_string();
2275
2276
    create(app, "andy", "demo").await;
2277
    let url = format!("{}/andy/demo", h.base);
2278
    let work = tempfile::tempdir().unwrap();
2279
    let c = client(&url, work.path());
2280
    write(
2281
        work.path(),
2282
        ".flow/pipeline.kdl",
2283
        &pipeline("job \"deploy\" {\n    sandbox \"alpine\"\n    identity \"sts.amazonaws.com\" {\n        mount-path \"/run/secrets/aws-token\"\n    }\n    exec \"deploy\"\n}\n"),
2284
    );
2285
    write(work.path(), "test.sh", "echo ok\n");
2286
    c.snapshot("test").unwrap();
2287
    c.commit("Add a pipeline", &[]).unwrap();
2288
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2289
    let mut deploy = None;
2290
    for _ in 0..50 {
2291
        let Some(got) = claim(app).await else {
2292
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2293
            continue;
2294
        };
2295
        if got["job"]["name"] == "deploy" {
2296
            deploy = Some(got);
2297
            break;
2298
        }
2299
    }
2300
    let got = deploy.expect("the deploy job");
2301
    let secrets = got["secrets"].as_array().expect("secrets");
2302
    assert_eq!(secrets.len(), 1);
2303
    assert_eq!(
2304
        (secrets[0]["name"].as_str(), secrets[0]["path"].as_str()),
2305
        (Some("identity:sts.amazonaws.com"), Some("/run/secrets/aws-token"))
2306
    );
2307
    let token = secrets[0]["value"].as_str().unwrap().to_string();
2308
    let issuer = app.oidc().await.unwrap();
2309
    assert_eq!(issuer.kid, kid, "the key the JWKS publishes signed it");
2310
    let claims = issuer.verify(&token, "sts.amazonaws.com", db::now_ms()).expect("verifies");
2311
    assert_eq!(claims["sub"], "repo:andy/demo:bookmark:main");
2312
    assert_eq!(claims["repository"], "andy/demo");
2313
    assert_eq!(claims["job"], "deploy");
2314
    assert_eq!(claims["run_number"], 1);
2315
    assert_eq!(claims["runner"], "test-1");
2316
    assert_eq!(claims["iss"], h.base.as_str());
2317
    assert!(claims["state"].as_str().unwrap().len() == 64);
2318
    // A job that prints its token leaves *** in the log.
2319
    let id = got["job_id"].as_i64().unwrap();
2320
    let records = serde_json::json!({ "records": [{ "t": 1, "stream": "out", "text": format!("TOKEN={token} end") }] });
2321
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2322
    assert_eq!(st, StatusCode::NO_CONTENT);
2323
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2324
    assert!(log.iter().any(|l| l.text == "TOKEN=*** end"), "{log:?}");
2325
}
efd29a00 Andy McCall ↶ 2326
2327
#[tokio::test(flavor = "multi_thread")]
2328
async fn jobs_are_offered_only_to_runners_of_their_architecture() {
2329
    let h = hub().await;
2330
    let app = &h.app;
2331
    create(app, "andy", "demo").await;
2332
    let url = format!("{}/andy/demo", h.base);
2333
    let work = tempfile::tempdir().unwrap();
2334
    let c = client(&url, work.path());
2335
    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)));
2336
    write(work.path(), "test.sh", "echo ok\n");
2337
    c.snapshot("test").unwrap();
2338
    c.commit("Add a pipeline", &[]).unwrap();
2339
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2340
    let claim_as = |arch: &'static str, archs: serde_json::Value| {
2341
        let app = app.clone();
2342
        async move {
2343
            let body = serde_json::json!({
2344
                "runner": format!("{arch}-1"), "runtimes": ["microvm"],
2345
                "info": { "arch": arch, "os": "linux", "version": "t", "labels": [], "max_jobs": 1 },
2346
                "image_archs": archs,
2347
            });
2348
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
2349
            match st {
2350
                StatusCode::NO_CONTENT => None,
2351
                StatusCode::OK => {
2352
                    Some(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"].as_str().unwrap().to_string())
2353
                }
2354
                other => panic!("claim: {other} {body}"),
2355
            }
2356
        }
2357
    };
2358
    // An x86_64 runner that says the alpine image is x86_64: it takes the
2359
    // alpine jobs, never the one that asks for riscv64.
2360
    let rootfs = pipeline("").split("cas://blob/").nth(1).unwrap()[..64].to_string();
2361
    for _ in 0..50 {
2362
        if !runs_of(app, "andy", "demo").await.is_empty() {
2363
            break;
2364
        }
2365
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2366
    }
2367
    let runs = runs_of(app, "andy", "demo").await;
2368
    assert_eq!(runs.len(), 1, "{runs:?}");
2369
    let mut taken = vec![];
2370
    while let Some(j) = claim_as("x86_64", serde_json::json!({ rootfs.clone(): "x86_64" })).await {
2371
        taken.push(j);
2372
    }
2373
    assert_eq!(taken, ["build", "lint"], "test waits for build; flash is for riscv64");
2374
    // A riscv64 runner: the alpine image is known to be x86_64, so only flash.
2375
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await.as_deref(), Some("flash"));
2376
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await, None);
2377
    let (_, queue) = call(app, "GET", "/admin/runners", None, None).await;
2378
    let _ = queue;
2379
}
4d2e44d7 Andy McCall ↶ 2380
2381
/// OxygenFlow spec §11.5: a runner hands back a job it cannot run. The
2382
/// job is queued again and not offered to that runner again, the decline
2383
/// shows on the run's page and is kept for the runner's, and once three
2384
/// runners have declined it the job ends as unplaceable with their reasons.
2385
#[tokio::test(flavor = "multi_thread")]
2386
async fn a_declined_job_goes_to_another_runner_or_ends_unplaceable() {
2387
    let h = hub().await;
2388
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2389
    create(&h.app, "andy", "declines").await;
2390
    let url = format!("{}/andy/declines", h.base);
2391
    let work = tempfile::tempdir().unwrap();
2392
    let c = client(&url, work.path());
2393
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2394
    write(work.path(), "test.sh", "echo ok\n");
2395
    c.commit("Add a pipeline", &[]).unwrap();
2396
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2397
    let run = runs_of(&h.app, "andy", "declines").await[0].clone();
2398
    let claim_as = |token: &'static str, name: &'static str| {
2399
        let app = h.app.clone();
2400
        async move {
2401
            let body = serde_json::json!({ "runner": name, "runtimes": ["microvm"] }).to_string();
2402
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(token), Some(body)).await;
2403
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap())
2404
        }
2405
    };
2406
    let decline = |token: &'static str, id: i64, reason: &'static str| {
2407
        let app = h.app.clone();
2408
        async move {
2409
            let body = serde_json::json!({ "reason": reason }).to_string();
2410
            call(&app, "POST", &format!("/api/v1/flow/jobs/{id}/decline"), Some(token), Some(body)).await.0
2411
        }
2412
    };
2413
    let job = claim_as("runner-secret", "earth-1").await.expect("a job");
2414
    // The other runners are known to the hub before they decline anything.
2415
    assert_eq!(decline("runner-two", job, "not mine").await, StatusCode::CONFLICT, "only the runner it runs on may decline it");
2416
    assert_eq!(decline("runner-secret", job, "the MicroVM tier needs /dev/kvm").await, StatusCode::NO_CONTENT);
2417
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2418
    assert_eq!((j.status.as_str(), j.runner.as_str()), ("queued", ""));
2419
    assert_eq!(j.waiting, "declined by earth-1: the MicroVM tier needs /dev/kvm; waiting for another runner");
2420
    // earth-1 is offered the other ready job, not this one, while it stays the same.
2421
    let next = claim_as("runner-secret", "earth-1").await.expect("the other ready job");
2422
    assert_ne!(next, job);
2423
    let page = call(&h.app, "GET", &format!("/andy/declines/flow/{}", run.number), None, None).await.1;
2424
    assert!(page.contains("Waiting: declined by earth-1: the MicroVM tier needs /dev/kvm"), "{page}");
2425
    assert_eq!(claim_as("runner-two", "plex-1").await, Some(job), "another runner takes it");
2426
    assert_eq!(decline("runner-two", job, "rootfs 36fc4e323804 is not on this runner").await, StatusCode::NO_CONTENT);
2427
    assert_eq!(claim_as("runner-three", "narvi").await, Some(job));
2428
    assert_eq!(decline("runner-three", job, "rootfs 36fc4e323804 is for x86_64; this runner is riscv64").await, StatusCode::NO_CONTENT);
2429
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2430
    assert_eq!(j.status, "error");
2431
    assert_eq!(
2432
        j.error,
2433
        "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"
2434
    );
2435
    let r = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex-1").unwrap();
2436
    let declined = db::flow::declines_of_runner(&h.app.db, r.id, 10).await.unwrap();
2437
    assert_eq!(declined.len(), 1);
2438
    assert_eq!((declined[0].job_id, declined[0].reason.as_str()), (job, "rootfs 36fc4e323804 is not on this runner"));
2439
    assert_eq!(r.tier_list(), vec!["microvm"]);
2440
}
554ccacf Andy McCall ↶ 2441
2442
/// oxygenhub#113: a job's artifact named `coverage` (LCOV) is read when
2443
/// it is uploaded. The job's log says what it found; the Coverage tab,
2444
/// the file view, the badge and the run page show it.
2445
#[tokio::test(flavor = "multi_thread")]
2446
async fn a_coverage_artifact_becomes_a_coverage_report() {
2447
    let h = hub().await;
2448
    create(&h.app, "andy", "cov").await;
2449
    let url = format!("{}/andy/cov", h.base);
2450
    let work = tempfile::tempdir().unwrap();
2451
    let c = client(&url, work.path());
2452
    write(
2453
        work.path(),
2454
        ".flow/pipeline.kdl",
2455
        &format!(
2456
            "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"
2457
        ),
2458
    );
2459
    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");
2460
    c.snapshot("test").unwrap();
2461
    c.commit("Code and coverage", &[]).unwrap();
2462
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2463
    let run = runs_of(&h.app, "andy", "cov").await.remove(0);
c8df33a6 Andy McCall ↶ 2464
    assert!(!call(&h.app, "GET", "/andy/cov", None, None).await.1.contains(">Reports</a>"), "no tab before a report");
554ccacf Andy McCall ↶ 2465
    let id = claim(&h.app).await.unwrap()["job_id"].as_i64().unwrap();
2466
2467
    let (st, text) = upload(&h.app, id, "coverage", b"this is not a report").await;
2468
    assert_eq!(st, StatusCode::OK, "a bad report never fails the upload: {text}");
2469
    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\
2470
SF:/src/src/gone.rs\nDA:1,1\nend_of_record\nSF:/usr/lib/rustlib/x.rs\nDA:1,1\nend_of_record\n";
2471
    let (st, text) = upload(&h.app, id, "coverage", lcov.as_bytes()).await;
2472
    assert_eq!(st, StatusCode::OK, "{text}");
2473
    let log: Vec<String> = db::flow::log(&h.app.db, id, 0, 50).await.unwrap().into_iter().map(|l| l.text).collect();
2474
    assert!(log.iter().any(|l| l.contains("coverage: this is not an LCOV report")), "{log:?}");
2475
    assert!(
2476
        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)"),
2477
        "{log:?}"
2478
    );
2479
2480
    let (st, page) = call(&h.app, "GET", "/andy/cov/coverage", None, None).await;
2481
    assert_eq!(st, StatusCode::OK);
c987c865 Andy McCall ↶ 2482
    assert!(
c8df33a6 Andy McCall ↶ 2483
        page.contains(">Reports</a>")
c987c865 Andy McCall ↶ 2484
            && page.contains("50.0%")
2485
            && page.contains("<strong>2</strong> of <strong>4</strong> relevant lines covered"),
2486
        "{page}"
2487
    );
554ccacf Andy McCall ↶ 2488
    assert!(page.contains("1 of 2") && page.contains("/andy/cov/coverage/") && page.contains("/file/src/lib.rs"), "{page}");
2489
    let report = crate_report(&h.app, run.id).await;
2490
    let (st, file) = call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/lib.rs"), None, None).await;
2491
    assert_eq!(st, StatusCode::OK, "{file}");
2492
    assert_eq!(file.matches("class=\"cov-hit\"").count(), 2, "{file}");
2493
    assert_eq!(file.matches("class=\"cov-miss\"").count(), 2, "{file}");
2494
    assert!(file.contains("3×"), "{file}");
2495
    assert_eq!(call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/gone.rs"), None, None).await.0, StatusCode::NOT_FOUND);
2496
    let (_, badge) = call(&h.app, "GET", "/andy/cov/coverage/badge.svg", None, None).await;
2497
    assert!(badge.contains("coverage: 50.0%"), "{badge}");
2498
    let (_, run_page) = call(&h.app, "GET", &format!("/andy/cov/flow/{}", run.number), None, None).await;
2499
    assert!(run_page.contains("coverage 50.0%"), "{run_page}");
617c2840 Andy McCall ↶ 2500
    // The API (#113).
2501
    let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/cov/coverage", None, None).await;
2502
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
2503
    assert_eq!((list[0]["percent"].as_f64(), list[0]["format"].as_str()), (Some(50.0), Some("lcov")), "{list}");
2504
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/cov/coverage/{report}"), None, None).await;
2505
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
2506
    assert_eq!((one["files"][0]["path"].as_str(), one["files"][0]["lines_hit"].as_i64()), (Some("src/lib.rs"), Some(2)), "{one}");
7edaff01 Andy McCall ↶ 2507
2508
    // The `coverage` check on the run's state: it reports, and with a
2509
    // minimum the repository sets, it fails below it.
2510
    let row = db::repos::get(&h.app.db, "andy", "cov").await.unwrap().unwrap();
2511
    let check = |checks: Vec<db::hooks::Check>| checks.into_iter().find(|c| c.name == "coverage").expect("a coverage check");
2512
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
2513
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "50.0%"));
2514
    assert!(c.url.ends_with(&format!("/andy/cov/coverage?report={report}")), "{}", c.url);
2515
    oxygenhub::coverage::set_rules(&h.app.db, row.id, oxygenhub::coverage::Rules { min: Some(60.0), max_drop: None }).await.unwrap();
2516
    assert_eq!(upload(&h.app, id, "coverage", lcov.as_bytes()).await.0, StatusCode::OK);
2517
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
2518
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "50.0%: below the minimum of 60%"));
554ccacf Andy McCall ↶ 2519
}
2520
2521
async fn crate_report(app: &Shared, run_id: i64) -> i64 {
2522
    oxygenhub::coverage::for_run(&app.db, run_id).await.unwrap()[0].id
2523
}
36e5a9c1 Andy McCall ↶ 2524
2525
/// The Tests tab (#114): three runs' JUnit reports on a bookmark; a test
2526
/// breaks in the second and is fixed in the third.
2527
#[tokio::test(flavor = "multi_thread")]
2528
async fn junit_reports_make_a_tests_tab() {
2529
    let h = hub().await;
2530
    create(&h.app, "andy", "t").await;
2531
    let url = format!("{}/andy/t", h.base);
2532
    let work = tempfile::tempdir().unwrap();
2533
    let c = client(&url, work.path());
2534
    write(
2535
        work.path(),
2536
        ".flow/pipeline.kdl",
2537
        &format!(
2538
            "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"
2539
        ),
2540
    );
c8df33a6 Andy McCall ↶ 2541
    assert!(!call(&h.app, "GET", "/andy/t", None, None).await.1.contains(">Reports</a>"));
36e5a9c1 Andy McCall ↶ 2542
    let case = |name: &str, ok: bool, secs: &str| {
2543
        if ok {
2544
            format!(r#"<testcase classname="t.suite" name="{name}" time="{secs}"/>"#)
2545
        } else {
2546
            format!(
2547
                r#"<testcase classname="t.suite" name="{name}" time="{secs}"><failure message="{name} broke">AssertionError</failure></testcase>"#
2548
            )
2549
        }
2550
    };
2551
    let runs = [
2552
        vec![case("a", true, "0.1"), case("b", true, "2.5"), case("c", true, "0.2")],
2553
        vec![case("a", true, "0.1"), case("b", false, "2.6"), case("c", true, "0.2"), case("d", true, "0.3")],
2554
        vec![case("a", true, "0.1"), case("b", true, "2.4"), case("c", true, "0.2"), case("d", true, "0.3")],
2555
    ];
2556
    for (i, cases) in runs.iter().enumerate() {
2557
        write(work.path(), "n.txt", &i.to_string());
2558
        c.snapshot("test").unwrap();
2559
        c.commit(&format!("Run {i}"), &[]).unwrap();
2560
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2561
        // The run is made after the push answers.
2562
        let mut a = None;
2563
        for _ in 0..100 {
2564
            a = claim(&h.app).await;
2565
            if a.is_some() {
2566
                break;
2567
            }
2568
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2569
        }
2570
        let a = a.expect("a job to claim");
2571
        let id = a["job_id"].as_i64().unwrap();
2572
        let xml = format!("<testsuites><testsuite name=\"t\">{}</testsuite></testsuites>", cases.concat());
2573
        assert_eq!(upload(&h.app, id, "junit", xml.as_bytes()).await.0, StatusCode::OK);
2574
        let failed = cases.iter().any(|c| c.contains("<failure"));
2575
        let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), failed as u32);
2576
        if !failed {
2577
            r["outputs"] = serde_json::json!([oxy_core::repo::Repo::blob_ref(xml.as_bytes()).to_hex()]);
2578
        }
2579
        let code = failed as i32;
2580
        assert_eq!(
2581
            finish(&h.app, id, serde_json::json!({ "exit_code": code, "duration_ms": 700, "receipt": r })).await,
2582
            StatusCode::NO_CONTENT
2583
        );
2584
    }
2585
    let (st, page) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
2586
    assert_eq!(st, StatusCode::OK, "{page}");
2587
    if let Some(out) = std::env::var_os("OXYHUB_DUMP_TESTS_PAGE") {
2588
        std::fs::write(out, &page).unwrap();
2589
    }
c8df33a6 Andy McCall ↶ 2590
    assert!(page.contains(">Reports</a>"), "the tab");
36e5a9c1 Andy McCall ↶ 2591
    assert!(page.contains("100%") && page.contains("of 4 tests passed"), "the latest run passes");
2592
    assert!(page.contains("1 fixed") && page.contains("t.suite::b"), "b fixed against the run before");
2593
    assert!(page.contains("1 ✕") && page.contains("2 ✓"), "b is flaky: {page}");
2594
    assert!(page.contains("<svg class=\"cov-chart\""), "charts");
2595
    // The slowest first.
2596
    let slow = page.find("Slowest tests").unwrap();
2597
    assert!(page[slow..].find("t.suite::b").unwrap() < page[slow..].find("t.suite::d").unwrap());
2598
    // The second run, picked: b newly failing, its failure listed.
2599
    let row = db::repos::get(&h.app.db, "andy", "t").await.unwrap().unwrap();
2600
    let second = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap()[1].id;
2601
    let (_, page) = call(&h.app, "GET", &format!("/andy/t/tests?report={second}"), None, None).await;
2602
    assert!(page.contains("1 failing") && page.contains("Newly failing") && page.contains("b broke"), "{page}");
2603
    assert!(page.contains("1 new tests"), "d is new");
617c2840 Andy McCall ↶ 2604
2605
    // The API (#114): the bookmark's reports newest first, and one with
2606
    // its failed cases.
2607
    let (st, list) = call(&h.app, "GET", "/api/v1/repos/andy/t/tests", None, None).await;
2608
    assert_eq!(st, StatusCode::OK, "{list}");
2609
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
2610
    assert_eq!(list.as_array().unwrap().len(), 3);
2611
    assert_eq!((list[0]["tests"].as_i64(), list[1]["failed"].as_i64()), (Some(4), Some(1)));
2612
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}?status=failed"), None, None).await;
2613
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
2614
    assert_eq!(one["cases"].as_array().unwrap().len(), 1);
2615
    assert_eq!((one["cases"][0]["name"].as_str(), one["cases"][0]["message"].as_str()), (Some("b"), Some("b broke")));
2616
    let (_, all) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}"), None, None).await;
2617
    assert_eq!(serde_json::from_str::<serde_json::Value>(&all).unwrap()["cases"].as_array().unwrap().len(), 4);
2618
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/t/tests/99999", None, None).await.0, StatusCode::NOT_FOUND);
3d5c825a Andy McCall ↶ 2619
2620
    // The `tests` check names what broke against main.
2621
    let reports = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap();
2622
    let check = |state: String| {
2623
        let app = h.app.clone();
2624
        async move { db::hooks::checks_for_state(&app.db, row.id, &state).await.unwrap().into_iter().find(|c| c.name == "tests").unwrap() }
2625
    };
2626
    let c = check(reports[1].state.clone()).await;
2627
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "1 failing; 1 new against main: t.suite::b"));
2628
    let c = check(reports[0].state.clone()).await;
2629
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "4 passed"));
2630
2631
    // One test's history: b passed, failed, passed.
2632
    let (_, tab) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
2633
    assert!(
2634
        tab.contains("/andy/t/tests/case?classname=t.suite&amp;name=b") || tab.contains("/andy/t/tests/case?classname=t.suite&name=b"),
2635
        "linked"
2636
    );
2637
    let (st, hist) = call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=b", None, None).await;
2638
    assert_eq!(st, StatusCode::OK, "{hist}");
2639
    assert!(hist.contains("2 passed") && hist.contains("1 failed") && hist.contains("b broke"), "{hist}");
2640
    assert_eq!(call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=nope", None, None).await.0, StatusCode::NOT_FOUND);
36e5a9c1 Andy McCall ↶ 2641
}
67040b15 Andy McCall ↶ 2642
2643
/// oxygenhub#28: a queued job no runner can take says why, in the API, on
2644
/// the run page (its panel open) and in its check.
2645
#[tokio::test(flavor = "multi_thread")]
2646
async fn a_job_no_runner_can_take_says_why() {
2647
    let h = hub().await;
2648
    create(&h.app, "andy", "demo").await;
2649
    let url = format!("{}/andy/demo", h.base);
2650
    let work = tempfile::tempdir().unwrap();
2651
    let c = client(&url, work.path());
2652
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2653
    write(work.path(), "test.sh", "echo ok\n");
2654
    c.commit("Add a pipeline", &[]).unwrap();
2655
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2656
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
2657
2658
    // One runner, online, holding another image only.
2659
    let r = db::runners::configured(&h.app.db, &blake3::hash(b"elsewhere").to_hex(), "earth-9").await.unwrap();
2660
    db::runners::seen(&h.app.db, r.id, None, None).await.unwrap();
2661
    let other = "ab".repeat(32);
92a797b2 Andy McCall ↶ 2662
    db::runners::set_offer(&h.app.db, r.id, &["microvm".to_string()], Some(&[other]), false, "p").await.unwrap();
67040b15 Andy McCall ↶ 2663
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2664
2665
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2666
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
2667
    let build = v["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "build").unwrap().clone();
2668
    let why = build["waiting"].as_str().unwrap_or_default().to_string();
2669
    assert!(why.contains("earth-9 does not hold image") && why.contains(&ROOTFS[..12]), "{body}");
2670
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/1", None, None).await;
2671
    assert!(page.contains("data-waiting") && page.contains("does not hold image"), "the run page says it");
13b27cb2 Andy McCall ↶ 2672
    // The check says it too. The hub's own placement pass runs beside this
2673
    // test's: if it lands a reading from before the runner's offer, the
2674
    // next pass puts it right.
2675
    let mut summary = String::new();
2676
    for _ in 0..40 {
2677
        let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
2678
        summary = checks.iter().find(|c| c.name == "flow/build").unwrap().summary.clone();
2679
        if summary.contains("does not hold image") {
2680
            break;
2681
        }
2682
        let build = db::flow::jobs(&h.app.db, run.id).await.unwrap().into_iter().find(|j| j.name == "build").unwrap();
2683
        db::flow::set_waiting(&h.app.db, build.id, "").await.unwrap();
2684
        oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2685
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2686
    }
2687
    assert!(summary.contains("does not hold image"), "{summary}");
67040b15 Andy McCall ↶ 2688
}
92a797b2 Andy McCall ↶ 2689
58cbf424 Andy McCall ↶ 2690
/// A job a runner could take but that still waits says why (#259): the
2691
/// runners that can take it are busy, or have a free slot without the room
2692
/// for it; and how many ready jobs come first.
2693
#[tokio::test(flavor = "multi_thread")]
2694
async fn a_job_waiting_for_a_busy_runner_says_so() {
2695
    let h = hub().await;
2696
    create(&h.app, "andy", "demo").await;
2697
    let url = format!("{}/andy/demo", h.base);
2698
    let work = tempfile::tempdir().unwrap();
2699
    let c = client(&url, work.path());
2700
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2701
    write(work.path(), "test.sh", "echo ok\n");
2702
    c.commit("Add a pipeline", &[]).unwrap();
2703
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2704
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
2705
    // One runner holding the image, its one slot taken by lint.
2706
    let r = db::runners::configured(&h.app.db, &blake3::hash(b"busy").to_hex(), "earth-9").await.unwrap();
2707
    db::runners::seen(&h.app.db, r.id, None, None).await.unwrap();
2708
    db::runners::set_offer(&h.app.db, r.id, &["microvm".to_string()], Some(&[ROOTFS.to_string()]), false, "p").await.unwrap();
2709
    sqlx::query(
2710
        "UPDATE flow_jobs SET status = 'running', runner_id = $1, runner = 'earth-9', started_ms = $2 WHERE run_id = $3 AND name = 'lint'",
2711
    )
2712
    .bind(r.id)
2713
    .bind(db::now_ms())
2714
    .bind(run.id)
2715
    .execute(&h.app.db)
2716
    .await
2717
    .unwrap();
2718
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2719
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
2720
    let build = jobs.iter().find(|j| j.name == "build").unwrap();
2721
    assert!(build.waiting.contains("the runners that can take it are busy: earth-9 busy (1 of 1)"), "{}", build.waiting);
2722
    // A second slot it hasn't used: free, but not the room for this job.
2723
    sqlx::query("UPDATE flow_runners SET max_jobs = 2 WHERE id = $1").bind(r.id).execute(&h.app.db).await.unwrap();
2724
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2725
    let build = db::flow::jobs(&h.app.db, run.id).await.unwrap().into_iter().find(|j| j.name == "build").unwrap();
2726
    assert!(build.waiting.contains("earth-9 has a free slot (1 of 2) but not the memory or disk for it now"), "{}", build.waiting);
2727
}
2728
92a797b2 Andy McCall ↶ 2729
async fn put_bytes(app: &Shared, path: &str, bearer: &str, bytes: Vec<u8>) -> (StatusCode, String) {
2730
    let req = Request::put(path)
2731
        .header(header::AUTHORIZATION, format!("Bearer {bearer}"))
2732
        .header(header::CONTENT_TYPE, "application/octet-stream")
2733
        .body(Body::from(bytes))
2734
        .unwrap();
2735
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
2736
    let st = res.status();
2737
    (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
2738
}
2739
2740
/// oxygenflow#39: an image is sent as the chunks the hub lacks and then its
2741
/// manifest, checked against its hash; runners fetch it; and a job whose
2742
/// image only the hub holds is offered to a runner that fetches, not to one
2743
/// that does not.
2744
#[tokio::test(flavor = "multi_thread")]
2745
async fn images_are_sent_by_chunk_and_offered_to_runners_that_fetch() {
2746
    let h = hub().await;
2747
    // The site token acts as the first site administrator.
2748
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2749
    // An image: bytes, a run of zeros, more bytes.
2750
    let mut image: Vec<u8> = (0..400_000u32).map(|i| (i % 251) as u8).collect();
2751
    image.extend(std::iter::repeat_n(0u8, 2 << 20));
2752
    image.extend((0..100_000u32).map(|i| (i % 239) as u8));
2753
    let mut chunks = std::collections::HashMap::new();
2754
    let m = jet::images::scan(&image[..], Some("x86_64".into()), |c, b| {
2755
        chunks.insert(c.hash().to_string(), b.to_vec());
2756
        Ok(())
2757
    })
2758
    .unwrap();
2759
    let hash = m.hash.clone();
2760
2761
    // Which chunks the hub lacks: every one but zeros; a manifest before them is refused.
2762
    let ask = serde_json::json!({ "chunks": m.needed() }).to_string();
2763
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask.clone())).await;
2764
    assert_eq!(st, StatusCode::OK, "{body}");
2765
    let missing: Vec<String> = serde_json::from_str::<serde_json::Value>(&body).unwrap()["missing"]
2766
        .as_array()
2767
        .unwrap()
2768
        .iter()
2769
        .map(|v| v.as_str().unwrap().to_string())
2770
        .collect();
2771
    assert_eq!(missing.len(), m.needed().len());
2772
    let manifest = serde_json::to_string(&m).unwrap();
2773
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest.clone())).await;
2774
    assert!(st == StatusCode::CONFLICT && body.contains("was not sent"), "{st} {body}");
2775
    // A chunk is checked against its name; a runner token may not send.
2776
    let first = &missing[0];
2777
    assert_eq!(put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "site", vec![1, 2, 3]).await.0, StatusCode::BAD_REQUEST);
2778
    assert_ne!(
2779
        put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "runner-secret", chunks[first].clone()).await.0,
2780
        StatusCode::NO_CONTENT
2781
    );
2782
    for c in &missing {
2783
        let (st, body) = put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
2784
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
2785
    }
2786
    let (_, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask)).await;
2787
    assert!(body.contains("\"missing\":[]"), "{body}");
750579ec Andy McCall ↶ 2788
    // A large image's question fits (#147): 60,000 names, ~4 MB of JSON.
2789
    let many: Vec<String> = (0..60_000u32).map(|i| blake3::hash(&i.to_le_bytes()).to_hex().to_string()).collect();
2790
    let (st, body) =
2791
        call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(serde_json::json!({ "chunks": many }).to_string())).await;
2792
    assert_eq!(st, StatusCode::OK, "{}", &body[..body.len().min(200)]);
2793
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["missing"].as_array().unwrap().len(), 60_000);
92a797b2 Andy McCall ↶ 2794
    // A manifest naming another hash is refused; the right one is kept.
2795
    let mut wrong = m.clone();
2796
    wrong.hash = "ab".repeat(32);
2797
    let (st, _) =
2798
        call(&h.app, "PUT", &format!("/api/v1/flow/images/{}", wrong.hash), Some("site"), Some(serde_json::to_string(&wrong).unwrap()))
2799
            .await;
2800
    assert_eq!(st, StatusCode::CONFLICT, "chunks that make another image");
2801
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest)).await;
2802
    assert_eq!(st, StatusCode::CREATED, "{body}");
2803
2804
    // A runner fetches the manifest and the chunks, and the image comes back whole.
2805
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), Some("runner-secret"), None).await;
2806
    assert_eq!(st, StatusCode::OK, "{body}");
2807
    let got: jet::images::Manifest = serde_json::from_str(&body).unwrap();
2808
    assert_eq!(got, m);
2809
    let dir = tempfile::tempdir().unwrap();
2810
    let out = dir.path().join("img.ext4");
2811
    let mut fetched = Vec::new();
2812
    for c in got.needed() {
2813
        let req = Request::get(format!("/api/v1/flow/images/chunks/{c}"))
2814
            .header(header::AUTHORIZATION, "Bearer runner-secret")
2815
            .body(Body::empty())
2816
            .unwrap();
2817
        let res = oxygenhub::router(h.app.clone()).oneshot(req).await.unwrap();
2818
        assert_eq!(res.status(), StatusCode::OK);
2819
        let bytes = res.into_body().collect().await.unwrap().to_bytes().to_vec();
2820
        fetched.push((c.to_string(), bytes));
2821
    }
2822
    jet::images::assemble(&got, &out, |c| Ok(fetched.iter().find(|(h, _)| h == c.hash()).unwrap().1.clone())).unwrap();
2823
    assert_eq!(std::fs::read(&out).unwrap(), image);
2824
    assert_eq!(
2825
        call(&h.app, "GET", &format!("/api/v1/flow/images/{}", "cd".repeat(32)), Some("runner-secret"), None).await.0,
2826
        StatusCode::NOT_FOUND
2827
    );
2828
    assert_ne!(call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), None, None).await.0, StatusCode::OK, "not anonymous");
2829
2830
    // A job on that image: a runner holding no images and not fetching
2831
    // is offered nothing; one that fetches is offered it.
2832
    create(&h.app, "andy", "demo").await;
2833
    let url = format!("{}/andy/demo", 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!("schema-version 1\nsandbox \"img\" {{\n    rootfs \"cas://blob/{hash}\"\n}}\njob \"build\" {{\n    sandbox \"img\"\n    exec \"make\"\n}}\n"),
2840
    );
2841
    c.commit("Build on the image", &[]).unwrap();
2842
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2843
    runs_of(&h.app, "andy", "demo").await;
1c8276b9 Andy McCall ↶ 2844
    // #137: the run's images are held (by the hub), so no images check.
2845
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2846
    let run1 = db::flow::run(&h.app.db, row.id, 1).await.unwrap().unwrap();
2847
    let checks = checks_when(&h.app, row.id, &run1.state, 1).await;
2848
    assert!(checks.iter().all(|c| c.name != "pipeline/images"), "{checks:?}");
92a797b2 Andy McCall ↶ 2849
    let ask = |fetches: bool| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":[],"fetches_images":{fetches}}}"#);
2850
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(false))).await;
2851
    assert_eq!(st, StatusCode::NO_CONTENT, "it lacks the image and does not fetch");
2852
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2853
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2854
    assert!(body.contains("does not hold image"), "{body}");
2855
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(true))).await;
2856
    assert_eq!(st, StatusCode::OK, "it fetches, and the hub holds the image: {body}");
7829b7c7 Andy McCall ↶ 2857
    // oxygenhub#135: once claimed, the old waiting reason is gone.
2858
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2859
    assert!(!body.contains("waiting"), "a running job keeps no waiting reason: {body}");
92a797b2 Andy McCall ↶ 2860
}
40dd3f86 Andy McCall ↶ 2861
2862
/// oxygenhub#136: coverage measured on a workstation is uploaded for a
2863
/// bookmark's state, kept as uploaded by its account, shown so, and sets
2864
/// no check.
2865
#[tokio::test(flavor = "multi_thread")]
2866
async fn coverage_uploaded_from_a_workstation_says_so() {
2867
    let h = hub().await;
2868
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2869
    create(&h.app, "andy", "vk").await;
2870
    let url = format!("{}/andy/vk", h.base);
2871
    let work = tempfile::tempdir().unwrap();
2872
    let c = client(&url, work.path());
2873
    write(work.path(), "src/game.c", "int a;\nint b;\nint c;\nint d;\n");
2874
    c.commit("Game", &[]).unwrap();
2875
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2876
2877
    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";
2878
    let body = serde_json::json!({ "bookmark": "main", "content": lcov }).to_string();
2879
    let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", Some("site"), Some(body)).await;
2880
    assert_eq!(st, StatusCode::CREATED, "{out}");
2881
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
2882
    assert_eq!((v["uploaded_by"].as_str(), v["lines_hit"].as_i64(), v["lines_found"].as_i64()), (Some("andy"), Some(3), Some(4)));
2883
    assert_eq!(v["dropped"], 1, "a file outside the state is left out");
2884
    assert_eq!(v["bookmark"], "main");
2885
2886
    let (_, page) = call(&h.app, "GET", "/andy/vk/coverage", None, None).await;
2887
    assert!(page.contains("uploaded by andy") && page.contains("75.0%"), "the Coverage page says where it came from");
2888
    let (_, page) = call(&h.app, "GET", "/andy/vk/reports", None, None).await;
2889
    assert!(page.contains("uploaded by andy"), "and the Reports card");
2890
    let row = db::repos::get(&h.app.db, "andy", "vk").await.unwrap().unwrap();
2891
    let state = v["state"].as_str().unwrap();
2892
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, state).await.unwrap();
2893
    assert!(checks.iter().all(|c| c.name != "coverage"), "an upload sets no check: {checks:?}");
2894
2895
    // Readers cannot upload; bad reports and bookmarks are refused.
2896
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", None, Some(r#"{"content":"x"}"#.into())).await;
2897
    assert_ne!(st, StatusCode::CREATED);
2898
    let (st, _) = call(
2899
        &h.app,
2900
        "POST",
2901
        "/api/v1/repos/andy/vk/coverage",
2902
        Some("site"),
2903
        Some(r#"{"bookmark":"nope","content":"SF:a\nend_of_record\n"}"#.into()),
2904
    )
2905
    .await;
2906
    assert_eq!(st, StatusCode::BAD_REQUEST);
2907
}
2fb70d01 Andy McCall ↶ 2908
2909
/// oxygenflow#40: what a runner measured at its claim is kept and shown.
2910
#[tokio::test(flavor = "multi_thread")]
2911
async fn a_runners_facts_are_kept_from_its_claim() {
2912
    let h = hub().await;
2913
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2914
    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"}}"#;
2915
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.into())).await;
2916
    assert_eq!(st, StatusCode::NO_CONTENT, "nothing to run, but the facts are kept");
2917
    let (st, out) = call(&h.app, "GET", "/api/v1/runners", Some("site"), None).await;
2918
    assert_eq!(st, StatusCode::OK, "{out}");
2919
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
2920
    let r = &v[0];
2921
    assert_eq!(
2922
        (r["speed"].as_i64(), r["speed_class"].as_i64(), r["free_disk_mib"].as_i64(), r["load_x100"].as_i64()),
2923
        (Some(100), Some(3), Some(42000), Some(112))
2924
    );
2925
    let row = db::runners::list(&h.app.db).await.unwrap().remove(0);
2926
    assert_eq!(row.facts_line(), "speed 100 (class 3) · load 1.12 · 41 GiB free");
2927
}
44a3d2eb Andy McCall ↶ 2928
2929
/// oxygenflow#41: a job's peaks set what its next run needs; a runner
2930
/// without that much free disk is not offered it, and the reason says so.
2931
#[tokio::test(flavor = "multi_thread")]
2932
async fn a_jobs_next_run_needs_the_disk_its_last_took() {
2933
    let h = hub().await;
2934
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2935
    create(&h.app, "andy", "demo").await;
2936
    let url = format!("{}/andy/demo", h.base);
2937
    let work = tempfile::tempdir().unwrap();
2938
    let c = client(&url, work.path());
2939
    write(
2940
        work.path(),
2941
        ".flow/pipeline.kdl",
2942
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2943
    );
2944
    c.commit("Build", &[]).unwrap();
2945
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2946
    runs_of(&h.app, "andy", "demo").await;
2947
    let claim_with = |free: u64| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"facts":{{"free_disk_mib":{free}}}}}"#);
2948
2949
    // The first run has nothing to learn from: any runner takes it.
2950
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(500))).await;
2951
    assert_eq!(st, StatusCode::OK, "{body}");
2952
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2953
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 10, "peak_disk_mib": 8000, "peak_memory_mib": 900 });
2954
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
2955
    let job = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
2956
    assert_eq!((job.peak_disk_mib, job.peak_memory_mib), (Some(8000), Some(900)));
2957
2958
    // The next run needs 8000 MiB and a quarter more.
2959
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
2960
    assert_eq!(st, StatusCode::CREATED);
2961
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2962
    let run2 = db::flow::run(&h.app.db, repo.id, 2).await.unwrap().unwrap();
2963
    let next = db::flow::jobs(&h.app.db, run2.id).await.unwrap().remove(0);
2964
    assert_eq!(next.need_disk_mib, Some(8000 + 2000 + 64));
2965
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(9000))).await;
2966
    assert_eq!(st, StatusCode::NO_CONTENT, "9000 MiB free is not enough");
2967
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2968
    let waiting = db::flow::job(&h.app.db, next.id).await.unwrap().unwrap().waiting;
2969
    assert!(waiting.contains("8.8 GiB free; the job needs ~9.8 GiB"), "{waiting}");
2970
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(20_000))).await;
2971
    assert_eq!(st, StatusCode::OK, "a roomier runner takes it: {body}");
2972
}
501d8b26 Andy McCall ↶ 2973
2974
/// oxygenflow#42: a job another free runner would do better (it holds the
2975
/// image) is held from a runner that would fetch it, the better runner
2976
/// takes it, and the job says why it ran there.
2977
#[tokio::test(flavor = "multi_thread")]
2978
async fn a_job_waits_briefly_for_a_runner_that_holds_its_image() {
2979
    let h = hub().await;
2980
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2981
    // A second runner, with a token of its own.
2982
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
2983
    let ask = |images: &str| {
2984
        format!(
2985
            r#"{{"runner":"r","runtimes":["microvm"],"images":[{images}],"fetches_images":true,"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
2986
        )
2987
    };
2988
    let holder = ask(&format!("\"{ROOTFS}\""));
2989
    // earth-9 holds the image and is polling; nothing is queued yet.
2990
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder.clone())).await;
2991
    assert_eq!(st, StatusCode::NO_CONTENT);
2992
    // The hub holds the image too, so test-1 could fetch it.
3b1bc27f Andy McCall 2993
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES ($1, 1, 'x86_64', 1, 'andy', 0)")
501d8b26 Andy McCall ↶ 2994
        .bind(ROOTFS)
2995
        .execute(&h.app.db)
2996
        .await
2997
        .unwrap();
2998
2999
    create(&h.app, "andy", "demo").await;
3000
    let url = format!("{}/andy/demo", h.base);
3001
    let work = tempfile::tempdir().unwrap();
3002
    let c = client(&url, work.path());
3003
    write(
3004
        work.path(),
3005
        ".flow/pipeline.kdl",
3006
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
3007
    );
3008
    c.commit("Build", &[]).unwrap();
3009
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3010
    runs_of(&h.app, "andy", "demo").await;
3011
3012
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
3013
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner that holds the image");
3014
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
3015
    assert_eq!(st, StatusCode::OK, "{body}");
3016
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
3017
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
3018
    assert!(placed.starts_with("holds the image, idle, speed 100 (class 3)"), "{placed}");
3019
    assert!(placed.contains("held for a better runner"), "{placed}");
3020
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
3021
    assert!(body.contains("\"placed\":\"holds the image"), "{body}");
3022
}
20b8fe85 Andy McCall ↶ 3023
4fa0da12 Andy McCall ↶ 3024
/// oxygenflow#51: a job waits briefly for the runner holding its build
3025
/// cache, even when the other one holds its image too.
3026
#[tokio::test(flavor = "multi_thread")]
3027
async fn a_job_waits_briefly_for_the_runner_holding_its_build_cache() {
3028
    let h = hub().await;
3029
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3030
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
3031
    let slot = flow_core::api::cache_slot("andy/demo", "build");
3032
    let ask = |caches: &str| {
3033
        format!(
3034
            r#"{{"runner":"r","runtimes":["microvm"],"images":["{ROOTFS}"],"fetches_images":true,"caches":[{caches}],"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
3035
        )
3036
    };
3037
    let holder = ask(&format!("\"{slot}\""));
3038
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder.clone())).await;
3039
    assert_eq!(st, StatusCode::NO_CONTENT);
3040
3041
    create(&h.app, "andy", "demo").await;
3042
    let url = format!("{}/andy/demo", h.base);
3043
    let work = tempfile::tempdir().unwrap();
3044
    let c = client(&url, work.path());
3045
    write(
3046
        work.path(),
3047
        ".flow/pipeline.kdl",
3048
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
3049
    );
3050
    c.commit("Build", &[]).unwrap();
3051
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3052
    runs_of(&h.app, "andy", "demo").await;
3053
3054
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
3055
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner holding the build cache");
3056
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
3057
    assert_eq!(st, StatusCode::OK, "{body}");
3058
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
3059
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
3060
    assert!(placed.starts_with("holds its build cache, holds the image"), "{placed}");
3061
}
3062
c2be148c Andy McCall ↶ 3063
/// oxygenflow#54: when both runners hold a job's build cache, the job waits
3064
/// briefly for the one whose copy is fresher.
3065
#[tokio::test(flavor = "multi_thread")]
3066
async fn a_job_waits_briefly_for_the_fresher_build_cache() {
3067
    let h = hub().await;
3068
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3069
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
3070
    let slot = flow_core::api::cache_slot("andy/demo", "build");
3071
    let now = db::now_ms();
3072
    let ask = |kept: i64| {
3073
        format!(
3074
            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}}}}"#
3075
        )
3076
    };
3077
    // earth-9 kept its copy a minute ago; the other runner's is a day old.
3078
    let fresh = ask(now - 60_000);
3079
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(fresh.clone())).await;
3080
    assert_eq!(st, StatusCode::NO_CONTENT);
3081
3082
    create(&h.app, "andy", "demo").await;
3083
    let url = format!("{}/andy/demo", h.base);
3084
    let work = tempfile::tempdir().unwrap();
3085
    let c = client(&url, work.path());
3086
    write(
3087
        work.path(),
3088
        ".flow/pipeline.kdl",
3089
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
3090
    );
3091
    c.commit("Build", &[]).unwrap();
3092
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3093
    runs_of(&h.app, "andy", "demo").await;
3094
3095
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(now - 86_400_000))).await;
3096
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the fresher copy");
3097
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(fresh)).await;
3098
    assert_eq!(st, StatusCode::OK, "{body}");
3099
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
3100
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
3101
    assert!(placed.starts_with("holds its build cache (kept 1 min ago), holds the image"), "{placed}");
3102
}
3103
20b8fe85 Andy McCall ↶ 3104
/// oxygenhub#127 §3.3: report files expire beyond the newest 50 runs of a
3105
/// report on a bookmark other than the default; the default keeps all,
3106
/// and an expired report keeps its metrics.
3107
#[tokio::test(flavor = "multi_thread")]
3108
async fn report_files_expire_under_retention() {
3109
    let h = hub().await;
3110
    create(&h.app, "andy", "demo").await;
3111
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
3112
    let add = |bookmark: &'static str, at: i64| {
3113
        let db = h.app.db.clone();
3114
        async move {
3115
            let id: i64 = sqlx::query_scalar(
3116
                "INSERT INTO reports (repo_id, name, kind, title, summary, context, job, bookmark, state, files, bytes, created_ms) \
3b1bc27f Andy McCall 3117
                 VALUES ($1, 'perf', 'performance', 'Perf', '', '{}', 'perf', $2, 's', 1, 1, $3) RETURNING id",
20b8fe85 Andy McCall ↶ 3118
            )
3119
            .bind(repo.id)
3120
            .bind(bookmark)
3121
            .bind(at)
3122
            .fetch_one(&db)
3123
            .await
3124
            .unwrap();
3b1bc27f Andy McCall 3125
            sqlx::query("INSERT INTO report_files (report_id, path, blob, size) VALUES ($1, 'report.toml', $2, 1)")
20b8fe85 Andy McCall ↶ 3126
                .bind(id)
3127
                .bind(format!("{:064x}", id))
3128
                .execute(&db)
3129
                .await
3130
                .unwrap();
3b1bc27f Andy McCall 3131
            sqlx::query("INSERT INTO report_metrics (report_id, key, value, unit, better) VALUES ($1, 'ms', 1, '', '')")
20b8fe85 Andy McCall ↶ 3132
                .bind(id)
3133
                .execute(&db)
3134
                .await
3135
                .unwrap();
3136
            id
3137
        }
3138
    };
3139
    let main_old = add("main", 1).await;
3140
    add("main", 2).await;
3141
    let mut feature = Vec::new();
3142
    for at in 0..52 {
3143
        feature.push(add("feature", 10 + at).await);
3144
    }
3145
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 2, "the two oldest feature runs");
3146
    let files = |id: i64| {
3147
        let db = h.app.db.clone();
3148
        async move {
3b1bc27f Andy McCall 3149
            sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM report_files WHERE report_id = $1").bind(id).fetch_one(&db).await.unwrap()
20b8fe85 Andy McCall ↶ 3150
        }
3151
    };
3152
    assert_eq!((files(feature[0]).await, files(feature[1]).await, files(feature[2]).await), (0, 0, 1));
3153
    assert_eq!(files(main_old).await, 1, "the default bookmark keeps every run");
3154
    assert_eq!(oxygenhub::reports::metrics(&h.app.db, feature[0]).await.unwrap().len(), 1, "metrics are kept");
3155
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 0, "once");
3156
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/perf?id={}", feature[0]), None, None).await;
3157
    assert!(page.contains("files have expired"), "the page says so");
1c8276b9 Andy McCall ↶ 3158
}
3159
3160
/// #137: a run pinning an image neither the hub nor any runner holds sets a
3161
/// failing `pipeline/images` check saying how to send it; once it is held,
3162
/// a run of the same state turns the check to passed.
3163
#[tokio::test(flavor = "multi_thread")]
3164
async fn a_pipeline_pinning_an_image_nobody_holds_fails_a_check() {
3165
    let h = hub().await;
3166
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3167
    // The one runner reports holding no images.
3168
    let none = r#"{"runner":"test-1","runtimes":["microvm"],"images":[]}"#;
3169
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(none.into())).await;
3170
    assert_eq!(st, StatusCode::NO_CONTENT);
3171
    create(&h.app, "andy", "demo").await;
3172
    let url = format!("{}/andy/demo", h.base);
3173
    let work = tempfile::tempdir().unwrap();
3174
    let c = client(&url, work.path());
3175
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3176
    write(work.path(), "test.sh", "echo ok\n");
3177
    c.commit("Add a pipeline", &[]).unwrap();
3178
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3179
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
3180
    let checks = checks_when(&h.app, run.repo_id, &run.state, 4).await;
3181
    let check = checks.iter().find(|c| c.name == "pipeline/images").expect("an images check");
3182
    assert!(check.status == "failed" && check.summary.contains(&ROOTFS[..12]) && check.summary.contains("flow rootfs push"), "{check:?}");
3183
    // Once a runner holds it, a run of the state passes the check.
3184
    let holds = format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":["{ROOTFS}"]}}"#);
3185
    call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(holds)).await;
3186
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
3187
    assert_eq!(st, StatusCode::CREATED);
3188
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
3189
    let check = checks.iter().find(|c| c.name == "pipeline/images").unwrap();
3190
    assert_eq!(check.status, "passed", "{check:?}");
20b8fe85 Andy McCall ↶ 3191
}
a46d15e7 Andy McCall ↶ 3192
3193
/// The swarm's tracker (#144): a fetching runner is given the peers in its
3194
/// site that hold the image or are fetching it, and a ticket signed with
3195
/// the hub key; a runner not in a swarm is told how to join one.
3196
#[tokio::test(flavor = "multi_thread")]
3197
async fn the_tracker_names_peers_in_the_same_site_and_signs_a_ticket() {
3198
    let h = hub().await;
3199
    let app = &h.app;
3200
    let image = "ab".repeat(32);
3201
    let claim_as = |token: &'static str, name: &'static str, body: serde_json::Value| async move {
3202
        let mut b = serde_json::json!({ "runner": name, "runtimes": ["microvm"] });
3203
        b.as_object_mut().unwrap().extend(body.as_object().unwrap().clone());
3204
        let (st, out) = call(app, "POST", "/api/v1/flow/claim", Some(token), Some(b.to_string())).await;
3205
        assert_eq!(st, StatusCode::NO_CONTENT, "{out}");
3206
    };
3207
    let announce = |token: &'static str, state: &'static str| {
3208
        let body = serde_json::json!({ "image": image, "state": state }).to_string();
3209
        async move { call(app, "POST", "/api/v1/flow/swarm/announce", Some(token), Some(body)).await }
3210
    };
3211
    // A holds the image; B and C hold nothing; all three are in site "lab".
6adcd68b Andy McCall ↶ 3212
    claim_as(
3213
        "runner-secret",
3214
        "a",
3215
        serde_json::json!({ "images": [image], "swarm": { "addr": "10.0.0.1:7401", "site": "lab", "cert": "11".repeat(32) } }),
3216
    )
3217
    .await;
3218
    claim_as(
3219
        "runner-two",
3220
        "b",
3221
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.2:7401", "site": "lab", "cert": "22".repeat(32) } }),
3222
    )
3223
    .await;
3224
    claim_as(
3225
        "runner-three",
3226
        "c",
3227
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.3:7401", "site": "lab", "cert": "33".repeat(32) } }),
3228
    )
3229
    .await;
a46d15e7 Andy McCall ↶ 3230
3231
    let (st, body) = announce("runner-two", "fetching").await;
3232
    assert_eq!(st, StatusCode::OK, "{body}");
3233
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3234
    let names: Vec<(&str, bool)> = a.peers.iter().map(|p| (p.addr.as_str(), p.complete)).collect();
3235
    assert_eq!(names, vec![("10.0.0.1:7401", true)], "only A holds it so far");
6adcd68b Andy McCall ↶ 3236
    assert_eq!(a.peers[0].cert, "11".repeat(32), "with the fingerprint peers check it by");
a46d15e7 Andy McCall ↶ 3237
    let t = jet::swarm::Ticket::open(&a.ticket, &app.hub_key.identity, oxygenhub::db::now_ms() as u64).unwrap();
3238
    assert_eq!((t.name.as_str(), t.site.as_str()), ("b", "lab"));
3239
3240
    // C, fetching too, is told of A (whole) and B (fetching).
3241
    let (_, body) = announce("runner-three", "fetching").await;
3242
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3243
    let mut peers: Vec<(&str, bool)> = a.peers.iter().map(|p| (p.addr.as_str(), p.complete)).collect();
3244
    peers.sort();
3245
    assert_eq!(peers, vec![("10.0.0.1:7401", true), ("10.0.0.2:7401", false)]);
3246
3247
    // B is done: no longer offered as fetching. C moves site: no peers.
3248
    announce("runner-two", "done").await;
6adcd68b Andy McCall ↶ 3249
    claim_as(
3250
        "runner-three",
3251
        "c",
3252
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.3:7401", "site": "elsewhere", "cert": "33".repeat(32) } }),
3253
    )
3254
    .await;
a46d15e7 Andy McCall ↶ 3255
    let (_, body) = announce("runner-three", "fetching").await;
3256
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3257
    assert!(a.peers.is_empty(), "{:?}", a.peers);
6adcd68b Andy McCall ↶ 3258
3259
    // A runner without a certificate (an older flow) is not in the swarm.
3260
    claim_as("runner-secret", "a", serde_json::json!({ "images": [image], "swarm": { "addr": "10.0.0.1:7401", "site": "elsewhere" } }))
3261
        .await;
3262
    let (st, _) = announce("runner-secret", "fetching").await;
3263
    assert_eq!(st, StatusCode::CONFLICT);
a46d15e7 Andy McCall ↶ 3264
3265
    // A runner that left the swarm is told how to join; nonsense is refused.
3266
    claim_as("runner-two", "b", serde_json::json!({ "images": [] })).await;
3267
    let (st, body) = announce("runner-two", "fetching").await;
3268
    assert_eq!(st, StatusCode::CONFLICT);
3269
    assert!(body.contains("[runner.swarm]"), "{body}");
3270
    let (st, _) =
3271
        call(app, "POST", "/api/v1/flow/swarm/announce", Some("runner-secret"), Some(r#"{"image":"nope","state":"fetching"}"#.into()))
3272
            .await;
3273
    assert_eq!(st, StatusCode::BAD_REQUEST);
3274
    let (st, _) = call(
3275
        app,
3276
        "POST",
3277
        "/api/v1/flow/swarm/announce",
3278
        None,
3279
        Some(serde_json::json!({ "image": image, "state": "fetching" }).to_string()),
3280
    )
3281
    .await;
3282
    assert_eq!(st, StatusCode::UNAUTHORIZED);
3283
}
6ca0b971 Andy McCall ↶ 3284
3285
/// Admin › Runners › Images (C0): each image, where it is and what uses it.
3286
#[tokio::test(flavor = "multi_thread")]
3287
async fn the_images_page_says_where_each_image_is_and_what_uses_it() {
3288
    let h = hub().await;
3289
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3290
    create(&h.app, "andy", "demo").await;
3291
    let work = tempfile::tempdir().unwrap();
3292
    let c = client(&format!("{}/andy/demo", h.base), work.path());
3293
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3294
    write(work.path(), "test.sh", "echo ok\n");
3295
    c.commit("Add a pipeline", &[]).unwrap();
3296
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3297
    // A runner holds another image and shares it; the hub keeps a third.
3298
    let held = "cd".repeat(32);
3299
    let kept = "ef".repeat(32);
3300
    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) } });
3301
    let (st, out) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
3302
    assert!(st == StatusCode::NO_CONTENT || st == StatusCode::OK, "{st} {out}");
3b1bc27f Andy McCall 3303
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES ($1, 1048576, 'x86_64', 9, 'andy', 1)")
6ca0b971 Andy McCall ↶ 3304
        .bind(&kept)
3305
        .execute(&h.app.db)
3306
        .await
3307
        .unwrap();
3308
3309
    let res = oxygenhub::router(h.app.clone())
3310
        .oneshot(
3311
            Request::post("/register")
3312
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
c8684d44 Andy McCall 3313
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
6ca0b971 Andy McCall ↶ 3314
                .unwrap(),
3315
        )
3316
        .await
3317
        .unwrap();
3318
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
3319
    let carol = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
3320
    db::accounts::set_admin(&h.app.db, carol.id, true).await.unwrap();
3321
    let res = oxygenhub::router(h.app.clone())
3322
        .oneshot(Request::get("/admin/runners/images").header(header::COOKIE, cookie).body(Body::empty()).unwrap())
3323
        .await
3324
        .unwrap();
3325
    assert_eq!(res.status(), StatusCode::OK);
3326
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
3327
    let row = |hash: &str| {
3328
        let at = page.find(&format!("title=\"{hash}\"")).unwrap_or_else(|| panic!("{hash} is not on the page"));
3329
        let end = page[at..].find("</tr>").unwrap();
3330
        page[at..at + end].to_string()
3331
    };
3332
    let pinned = row(ROOTFS);
3333
    assert!(pinned.contains("nowhere") && pinned.contains("andy/demo") && pinned.contains("3 jobs"), "{pinned}");
3334
    let on_runner = row(&held);
3335
    assert!(on_runner.contains("img-holds") && on_runner.contains("earth-1") && !on_runner.contains("nowhere"), "{on_runner}");
3336
    let on_hub = row(&kept);
3337
    assert!(on_hub.contains("img-hub") && on_hub.contains("1.0 MiB") && on_hub.contains("x86_64"), "{on_hub}");
3338
    assert!(page.contains("earth-1 (home)"), "the swarm is named");
6246d1e5 Andy McCall ↶ 3339
    // The swarm backdrop (docs/backgrounds.md §2): the hub and the runners.
3340
    assert!(page.contains(r#"{"images":"#) && page.contains(r#""scene":"swarm""#) && page.contains(r#""earth-1""#), "the swarm's data");
6ca0b971 Andy McCall ↶ 3341
    assert_eq!(call(&h.app, "GET", "/admin/runners/images", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
3342
}
f677d627 Andy McCall ↶ 3343
3344
/// Diffusion D1 (#148): the reverse pin index. A repository that pins
3345
/// another as a subrepo is a consumer of it; the upstream's API and page
3346
/// say who, at which state, and how far behind its default bookmark.
3347
#[tokio::test(flavor = "multi_thread")]
3348
async fn consumers_of_a_subrepo_are_indexed_with_how_far_behind_they_are() {
3349
    let h = hub().await;
e7158350 Andy McCall ↶ 3350
    // The site token acts as the first site administrator.
3351
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
f677d627 Andy McCall ↶ 3352
    create(&h.app, "andy", "api").await;
3353
    create(&h.app, "andy", "game").await;
3354
    let api_work = tempfile::tempdir().unwrap();
3355
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
3356
    write(api_work.path(), "api.h", "v1\n");
3357
    api.snapshot("t").unwrap();
3358
    api.commit("api v1", &[]).unwrap();
3359
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3360
3361
    let game_work = tempfile::tempdir().unwrap();
3362
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
3363
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3364
    write(game_work.path(), "game.c", "int main;\n");
3365
    game.snapshot("t").unwrap();
3366
    game.commit("game on api v1", &[]).unwrap();
3367
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3368
3369
    let consumers = || async {
3370
        let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
3371
        assert_eq!(st, StatusCode::OK, "{body}");
3372
        serde_json::from_str::<Vec<serde_json::Value>>(&body).unwrap()
3373
    };
3374
    // The index is written by the push's after-work, a moment after the
3375
    // client hears the push succeeded.
3376
    let settle = |want: &'static (dyn Fn(&[serde_json::Value]) -> bool + Sync)| {
3377
        let consumers = &consumers;
3378
        async move {
3379
            for _ in 0..100 {
3380
                let list = consumers().await;
3381
                if want(&list) {
3382
                    return list;
3383
                }
3384
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3385
            }
3386
            consumers().await
3387
        }
3388
    };
3389
    let list = settle(&|l| !l.is_empty()).await;
3390
    assert_eq!(list.len(), 1, "{list:?}");
3391
    assert_eq!(
3392
        (list[0]["name"].as_str(), list[0]["path"].as_str(), list[0]["bookmark"].as_str()),
3393
        (Some("game"), Some("deps/api"), Some("main"))
3394
    );
3395
    assert_eq!(list[0]["behind"], 0);
3396
3397
    // The upstream moves on: the consumer is one change behind.
3398
    write(api_work.path(), "api.c", "v2\n");
3399
    api.snapshot("t").unwrap();
3400
    api.commit("api v2", &[]).unwrap();
3401
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3402
    assert_eq!(settle(&|l| l.first().is_some_and(|c| c["behind"] == 1)).await[0]["behind"], 1);
3403
    let (_, page) = call(&h.app, "GET", "/andy/api", None, None).await;
c9aacc0e Andy McCall ↶ 3404
    assert!(page.contains("Diffuses to") && page.contains("andy/game") && page.contains("1 behind"), "the page shows it");
f677d627 Andy McCall ↶ 3405
3406
    // A private consumer is not shown to someone who cannot read it.
3407
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'game'").execute(&h.app.db).await.unwrap();
3408
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", None, None).await;
3409
    assert_eq!(body.trim(), "[]");
3410
    let (_, page) = call(&h.app, "GET", "/andy/api", None, None).await;
3411
    assert!(!page.contains("andy/game"));
3412
    sqlx::query("UPDATE repositories SET visibility = 'public' WHERE name = 'game'").execute(&h.app.db).await.unwrap();
e7158350 Andy McCall ↶ 3413
1d634f69 Andy McCall ↶ 3414
    // A bump (DF3): one signed change on the target moving only the pin, on
3415
    // `diffusion/deps/api`; again with the same state, nothing new.
3416
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3417
    let api_row = db::repos::get(&h.app.db, "andy", "api").await.unwrap().unwrap();
3418
    let api_heads = api.bookmark_heads().unwrap();
3419
    let bumped = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, api_heads.clone()).await.unwrap();
3420
    let oxygenhub::diffusion::Bumped::Moved { bookmark, heads, .. } = bumped else { panic!("{bumped:?}") };
3421
    assert_eq!(bookmark, "diffusion/deps/api");
3422
    game.fetch("origin").unwrap();
3423
    let bump_state = game.load_state(&heads).unwrap().materialize();
3424
    let pin = match &bump_state.files["deps/api"].content {
3425
        oxy_core::state::FileContent::Opaque { blobs } => oxy_core::subrepo::Pin::decode(&game.read_blob(&blobs[0]).unwrap()).unwrap(),
3426
        other => panic!("{other:?}"),
3427
    };
3428
    assert!(
3429
        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 }),
3430
        "{pin:?}"
3431
    );
3432
    assert!(bump_state.files.contains_key("game.c"), "the rest of the game is as it was");
9aaa88b2 Andy McCall ↶ 3433
    assert!(matches!(
1d634f69 Andy McCall ↶ 3434
        oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, api_heads.clone()).await.unwrap(),
9aaa88b2 Andy McCall ↶ 3435
        oxygenhub::diffusion::Bumped::Already { .. }
3436
    ));
7a14bdae Andy McCall ↶ 3437
    // A state lacking changes the pin has (as when the consumer pinned an
3438
    // upstream proposal not landed yet) is combined with the pin, never
3439
    // dropping what it relies on.
1d634f69 Andy McCall ↶ 3440
    write(api_work.path(), "other.c", "v3\n");
3441
    api.snapshot("t").unwrap();
3442
    let v3 = api.commit("api v3, on its own", &[]).unwrap();
3443
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3444
    let only_v3 = api.load_state(&[v3]).unwrap().heads().to_vec();
7a14bdae Andy McCall ↶ 3445
    let combined = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, only_v3).await.unwrap();
3446
    let oxygenhub::diffusion::Bumped::Moved { heads: ch, .. } = combined else { panic!("{combined:?}") };
3447
    game.fetch("origin").unwrap();
3448
    let st = game.load_state(&ch).unwrap().materialize();
3449
    let pin = match &st.files["deps/api"].content {
3450
        oxy_core::state::FileContent::Opaque { blobs } => oxy_core::subrepo::Pin::decode(&game.read_blob(&blobs[0]).unwrap()).unwrap(),
3451
        other => panic!("{other:?}"),
3452
    };
3453
    let oxy_core::subrepo::Pin::Oxy { heads: pinned, .. } = pin else { panic!() };
3454
    let all = api.load_state(&pinned).unwrap();
3455
    // The game's main still pins v1 alone; combined with v3, it is both.
3456
    assert!(all.contains(&v3) && all.len() == 2, "v1 and v3, {} changes", all.len());
1d634f69 Andy McCall ↶ 3457
    // The upstream moves again: the same bookmark moves.
3458
    let newer = api.bookmark_heads().unwrap();
3459
    let again = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, newer).await.unwrap();
3460
    assert!(matches!(again, oxygenhub::diffusion::Bumped::Moved { ref bookmark, .. } if bookmark == "diffusion/deps/api"), "{again:?}");
3461
e7158350 Andy McCall ↶ 3462
    // Following is off by default; owners turn it on (DF2).
3463
    let put =
3464
        |body: &'static str, who: Option<&'static str>| call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", who, Some(body.into()));
3465
    let (st, body) = put(r#"{"follow":"green"}"#, Some("site")).await;
3466
    assert_eq!(st, StatusCode::OK, "{body}");
3467
    assert!(body.contains("\"follow\":\"green\"") && body.contains("\"from\":\"setting\""), "{body}");
3468
    assert_eq!(put(r#"{"follow":"sometimes"}"#, Some("site")).await.0, StatusCode::BAD_REQUEST);
3469
    assert_ne!(put(r#"{"follow":"any"}"#, None).await.0, StatusCode::OK, "not without a token");
3470
    let (_, body) = put(r#"{"follow":"default"}"#, Some("site")).await;
3471
    assert!(body.contains("\"follow\":\"off\"") && body.contains("\"from\":\"site\""), "{body}");
f677d627 Andy McCall ↶ 3472
3473
    // Dropping the subrepo drops the consumer.
3474
    game.submodule_remove("deps/api").unwrap();
3475
    std::fs::remove_dir_all(game_work.path().join("deps/api")).unwrap();
3476
    game.snapshot("t").unwrap();
3477
    game.commit("game without api", &[]).unwrap();
3478
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3479
    let left = settle(&|l| l.is_empty()).await;
3480
    assert!(left.is_empty(), "{left:?}");
3481
}
a7e6e8e6 Andy McCall ↶ 3482
3483
/// Diffusion D1 end to end (#148): a consumer that follows every move gets
3484
/// a bump proposal on a push; one that follows green gets it when the
3485
/// upstream's run passes. One proposal, kept up to date.
3486
#[tokio::test(flavor = "multi_thread")]
3487
async fn diffusion_proposes_a_bump_when_the_upstream_moves() {
3488
    let h = hub().await;
3489
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3490
    create(&h.app, "andy", "api").await;
3491
    create(&h.app, "andy", "game").await;
180dc43a Andy McCall ↶ 3492
    // Run every job of the upstream's newest run to a pass, keeping each claim.
3493
    let seen: std::sync::Mutex<Vec<serde_json::Value>> = std::sync::Mutex::new(Vec::new());
3494
    let seen = &seen;
3495
    let hub_app = &h.app;
3496
    let pass_all = move || async move {
3497
        let h_app = hub_app;
a7e6e8e6 Andy McCall ↶ 3498
        for _ in 0..20 {
180dc43a Andy McCall ↶ 3499
            let Some(a) = claim(h_app).await else {
a7e6e8e6 Andy McCall ↶ 3500
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
180dc43a Andy McCall ↶ 3501
                if !jobs_left(h_app).await {
a7e6e8e6 Andy McCall ↶ 3502
                    break;
3503
                }
3504
                continue;
3505
            };
180dc43a Andy McCall ↶ 3506
            seen.lock().unwrap().push(a.clone());
a7e6e8e6 Andy McCall ↶ 3507
            let id = a["job_id"].as_i64().unwrap();
3508
            let (name, ph) = (a["job"]["name"].as_str().unwrap().to_string(), a["pipeline_hash"].as_str().unwrap().to_string());
f7bcee49 Andy McCall ↶ 3509
            let st = finish(h_app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt(&name, &ph, 0) })).await;
3510
            // A run started in the background (a bump, a landing's run, #197)
3511
            // may supersede the one this job belongs to between its claim and
3512
            // its finish; then, and only then, the hub refuses the finish.
3513
            if st == StatusCode::CONFLICT {
3514
                let job = db::flow::job(&h_app.db, id).await.unwrap().unwrap();
3515
                assert_eq!(job.status, "cancelled", "refused only because a newer run cancelled it");
3516
                continue;
3517
            }
3518
            assert_eq!(st, StatusCode::NO_CONTENT);
a7e6e8e6 Andy McCall ↶ 3519
        }
3520
    };
3521
    let api_work = tempfile::tempdir().unwrap();
3522
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
3523
    write(api_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3524
    write(api_work.path(), "test.sh", "echo ok\n");
3525
    write(api_work.path(), "api.h", "v1\n");
3526
    api.snapshot("t").unwrap();
3527
    api.commit("api v1", &[]).unwrap();
3528
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3529
    pass_all().await;
3530
3531
    let game_work = tempfile::tempdir().unwrap();
3532
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
3533
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3534
    write(game_work.path(), "game.c", "int main;\n");
f01cb865 Andy McCall ↶ 3535
    write(game_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3536
    write(game_work.path(), "test.sh", "echo ok\n");
a7e6e8e6 Andy McCall ↶ 3537
    game.snapshot("t").unwrap();
3538
    game.commit("game on api v1", &[]).unwrap();
3539
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3540
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3541
    let bump = || async {
3542
        for _ in 0..100 {
3543
            let open = db::proposals::list(&h.app.db, game_row.id, &["open"]).await.unwrap();
3544
            if let Some(p) = open.into_iter().find(|p| p.source_bookmark == "diffusion/deps/api") {
3545
                return Some(p);
3546
            }
3547
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3548
        }
3549
        None
3550
    };
3551
3552
    // Off by default: an upstream move proposes nothing.
3553
    write(api_work.path(), "a2.c", "v2\n");
3554
    api.snapshot("t").unwrap();
3555
    api.commit("api v2: faster sprites", &[]).unwrap();
3556
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3557
    pass_all().await;
3558
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3559
    assert!(db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap().is_empty(), "off proposes nothing");
3560
3776b70d Andy McCall ↶ 3561
    // Turned on to follow every move: bumped at once to where the upstream
3562
    // is (v2), by the diffusion account; the next push updates it.
a7e6e8e6 Andy McCall ↶ 3563
    let put = |body: &'static str| call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(body.into()));
3564
    assert_eq!(put(r#"{"follow":"any"}"#).await.0, StatusCode::OK);
3776b70d Andy McCall ↶ 3565
    let first = bump().await.expect("caught up when turned on");
3566
    assert!(first.title.contains("1 change") && first.body.contains("api v2: faster sprites"), "{:?}", first.title);
f01cb865 Andy McCall ↶ 3567
    // The bump's pipeline runs, as a push of it would, so the proposal is tested.
3568
    let mut ran = false;
3569
    for _ in 0..100 {
3570
        if runs_of(&h.app, "andy", "game").await.iter().any(|r| r.bookmark == "diffusion/deps/api") {
3571
            ran = true;
3572
            break;
3573
        }
3574
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3575
    }
3576
    assert!(ran, "a run of the bump");
3577
    pass_all().await;
a7e6e8e6 Andy McCall ↶ 3578
    write(api_work.path(), "a3.c", "v3\n");
3579
    api.snapshot("t").unwrap();
3580
    api.commit("api v3: save slots past ten", &[]).unwrap();
3581
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3776b70d Andy McCall ↶ 3582
    let mut p = first.clone();
3583
    for _ in 0..100 {
3584
        p = bump().await.unwrap();
3585
        if p.body.contains("api v3") {
3586
            break;
3587
        }
3588
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3589
    }
3590
    assert_eq!(p.number, first.number, "the same proposal");
a7e6e8e6 Andy McCall ↶ 3591
    assert_eq!((p.author.as_str(), p.target.as_str()), ("diffusion", "main"));
3592
    assert!(p.title.contains("deps/api") && p.title.contains("andy/api") && p.title.contains("2 changes"), "{}", p.title);
3593
    assert!(p.body.contains("api v2: faster sprites") && p.body.contains("api v3: save slots past ten"), "{}", p.body);
3594
    let labels = db::issues::proposal_labels(&h.app.db, p.id).await.unwrap();
3595
    assert!(labels.iter().any(|l| l.name == "dependencies"));
3596
    pass_all().await;
3597
3598
    // Following green: a push alone does not move it; the passing run does,
3599
    // and the same proposal is brought up to date.
3600
    assert_eq!(put(r#"{"follow":"green"}"#).await.0, StatusCode::OK);
3601
    write(api_work.path(), "a4.c", "v4\n");
3602
    api.snapshot("t").unwrap();
3603
    api.commit("api v4: rsm_set cheaper", &[]).unwrap();
3604
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3605
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3606
    assert!(!bump().await.unwrap().body.contains("api v4"), "not before its run passes");
3607
    pass_all().await;
3608
    let mut updated = None;
3609
    for _ in 0..100 {
3610
        let p2 = bump().await.unwrap();
3611
        if p2.body.contains("api v4") {
3612
            updated = Some(p2);
3613
            break;
3614
        }
3615
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3616
    }
3617
    let p2 = updated.expect("brought up to date once the run passed");
3618
    assert_eq!(p2.number, p.number, "the same proposal");
3619
    assert!(p2.title.contains("3 changes"), "{}", p2.title);
3620
    assert_eq!(db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap().len(), 1, "never a pile of bumps");
3776b70d Andy McCall ↶ 3621
757195ad Andy McCall ↶ 3622
    // The views (#150): the upstream's Diffusion tab lists the game with its
3623
    // status; the game's tab and overview say what it follows.
3624
    pass_all().await;
3625
    let (st, page) = call(&h.app, "GET", "/andy/api/diffusion", None, None).await;
3626
    assert_eq!(st, StatusCode::OK);
c9aacc0e Andy McCall ↶ 3627
    assert!(page.contains("Diffuses to") && page.contains("andy/game") && page.contains(&format!("#{}", p2.number)), "the bump is listed");
757195ad Andy McCall ↶ 3628
    assert!(page.contains("df-green"), "a passing run of a checked upstream is green");
6246d1e5 Andy McCall ↶ 3629
    // The ripples backdrop: the page's own repositories and tones.
3630
    assert!(
3631
        page.contains(r#""scene":"ripples""#) && page.contains(r#"["andy/game","#) && page.contains(r#""repo":"andy/api""#),
3632
        "the ripples' data"
3633
    );
757195ad Andy McCall ↶ 3634
    let (_, page) = call(&h.app, "GET", "/andy/game/diffusion", None, None).await;
c9aacc0e Andy McCall ↶ 3635
    assert!(page.contains("Takes from") && page.contains("andy/api"));
757195ad Andy McCall ↶ 3636
    let (_, overview) = call(&h.app, "GET", "/andy/game", None, None).await;
c9aacc0e Andy McCall ↶ 3637
    assert!(overview.contains("Takes from") && overview.contains(">Diffusion</a>"), "the tab and the panel");
eb2a3502 Andy McCall ↶ 3638
    // Both directions through the API (#153), as the extension reads them.
3639
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/game/diffusion", Some("site"), None).await;
3640
    assert_eq!(st, StatusCode::OK, "{body}");
3641
    let d: hub_api::Diffusion = serde_json::from_str(&body).unwrap();
3642
    assert!(d.diffuses_to.is_empty(), "nothing pins the game");
3643
    let pin = d.takes_from.first().expect("the game takes from the api");
3644
    assert_eq!((pin.upstream.as_str(), pin.consumer.as_str()), ("andy/api", "andy/game"));
3645
    assert_eq!(pin.bump, Some(p2.number));
3646
    assert_eq!(pin.upstream_state.tone, "green", "{body}");
3647
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/diffusion", Some("site"), None).await;
3648
    let d: hub_api::Diffusion = serde_json::from_str(&body).unwrap();
3649
    assert!(d.takes_from.is_empty() && d.diffuses_to.iter().any(|p| p.consumer == "andy/game"), "{body}");
757195ad Andy McCall ↶ 3650
    let (st, _) = call(&h.app, "GET", "/admin/diffusion", None, None).await;
3651
    assert_eq!(st, StatusCode::NOT_FOUND, "administrators only");
3652
3653
    // Landing the bump on the hub moves the game's pin as a push would:
5d54cf74 Andy McCall ↶ 3654
    // the index follows, so it is no longer behind; even when the first
3655
    // write fails, as a busy database's would (#210: it is tried again).
3656
    let game = oxygenhub::db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3657
    oxygenhub::diffusion::fail_next_records(&h.app, game.id, 1);
757195ad Andy McCall ↶ 3658
    let (st, body) =
3659
        call(&h.app, "POST", &format!("/api/v1/repos/andy/game/proposals/{}/land", p2.number), Some("site"), Some("{}".into())).await;
3660
    assert_eq!(st, StatusCode::OK, "{body}");
3661
    let mut behind = serde_json::Value::Null;
3662
    for _ in 0..100 {
3663
        let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
3664
        let list: Vec<serde_json::Value> = serde_json::from_str(&list).unwrap();
3665
        behind = list.iter().find(|c| c["name"] == "game").map(|c| c["behind"].clone()).unwrap_or_default();
3666
        if behind == 0 {
3667
            break;
3668
        }
3669
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3670
    }
3671
    assert_eq!(behind, 0, "the index followed the landing");
5d54cf74 Andy McCall ↶ 3672
    assert_eq!(oxygenhub::diffusion::forced_left(&h.app, game.id), 0, "the first write did fail");
0e04dfc2 Andy McCall ↶ 3673
    // The reconciler (#210): an index left behind its bookmark (as when
3674
    // both writes failed) is mended from the bookmark itself, and a pass
3675
    // with nothing to mend changes nothing.
3676
    let pins_of = || async {
3b1bc27f Andy McCall 3677
        sqlx::query_scalar::<_, String>("SELECT heads FROM diffusion_pins WHERE consumer_id = $1")
0e04dfc2 Andy McCall ↶ 3678
            .bind(game.id)
3679
            .fetch_one(&h.app.db)
3680
            .await
3681
            .unwrap()
3682
    };
3683
    let right = pins_of().await;
3b1bc27f Andy McCall 3684
    sqlx::query("UPDATE diffusion_pins SET heads = 'stale' WHERE consumer_id = $1").bind(game.id).execute(&h.app.db).await.unwrap();
3685
    sqlx::query("DELETE FROM diffusion_indexed WHERE consumer_id = $1").bind(game.id).execute(&h.app.db).await.unwrap();
0e04dfc2 Andy McCall ↶ 3686
    let r = oxygenhub::diffusion::reconcile(&h.app).await;
3687
    assert!(r.reindexed >= 1, "{r:?}");
3688
    assert_eq!(pins_of().await, right, "the pin read again from the game's bookmark");
3689
    assert_eq!(oxygenhub::diffusion::reconcile(&h.app).await.reindexed, 0, "nothing left to mend");
757195ad Andy McCall ↶ 3690
180dc43a Andy McCall ↶ 3691
    // A private upstream: the bump's run (started by the diffusion account,
3692
    // which cannot read it) still gets the subrepo it bumps.
3693
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'api'").execute(&h.app.db).await.unwrap();
3694
    seen.lock().unwrap().clear();
3695
    write(api_work.path(), "a6.c", "v6\n");
3696
    api.snapshot("t").unwrap();
3697
    api.commit("api v6", &[]).unwrap();
3698
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4fa0da12 Andy McCall ↶ 3699
    // The bump's run starts in the background: wait for its job, under a
3700
    // loaded test run as well as alone.
3701
    let mut bump_job = None;
3702
    for _ in 0..100 {
3703
        pass_all().await;
3704
        bump_job = seen.lock().unwrap().iter().find(|c| c["repo"] == "andy/game" && c["bookmark"] == "diffusion/deps/api").cloned();
3705
        if bump_job.is_some() {
3706
            break;
3707
        }
3708
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
3709
    }
3710
    let bump_job = bump_job.expect("the bump's job ran");
180dc43a Andy McCall ↶ 3711
    let subs: Vec<&str> = bump_job["subrepos"].as_array().unwrap().iter().filter_map(|s| s["path"].as_str()).collect();
3712
    assert_eq!(subs, vec!["deps/api"], "{bump_job}");
3713
3776b70d Andy McCall ↶ 3714
    // A consumer turning Diffusion on is bumped at once to the upstream's
3715
    // newest passing state, without waiting for it to move again.
3716
    create(&h.app, "andy", "game2").await;
3717
    let g2_work = tempfile::tempdir().unwrap();
3718
    let g2 = client(&format!("{}/andy/game2", h.base), g2_work.path());
3719
    g2.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3720
    g2.snapshot("t").unwrap();
3721
    g2.commit("game2 on api", &[]).unwrap();
3722
    assert!(g2.push("origin", false).unwrap().iter().all(|r| r.ok));
3723
    // Its pin is api's newest state already: move api on, pass the run.
3724
    write(api_work.path(), "a5.c", "v5\n");
3725
    api.snapshot("t").unwrap();
3726
    api.commit("api v5", &[]).unwrap();
7e01a766 Andy McCall ↶ 3727
    let api_row = db::repos::get(&h.app.db, "andy", "api").await.unwrap().unwrap();
3728
    let runs_before = db::flow::runs(&h.app.db, api_row.id, 100, None).await.unwrap().len();
3776b70d Andy McCall ↶ 3729
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
7e01a766 Andy McCall ↶ 3730
    // The push's run is made in the background: wait for it, or pass_all
3731
    // can finish before it exists and v5 never passes (a flake under load).
3732
    for _ in 0..300 {
3733
        if db::flow::runs(&h.app.db, api_row.id, 100, None).await.unwrap().len() > runs_before {
3734
            break;
3735
        }
3736
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3737
    }
3776b70d Andy McCall ↶ 3738
    pass_all().await;
3739
    let g2_row = db::repos::get(&h.app.db, "andy", "game2").await.unwrap().unwrap();
3740
    for _ in 0..100 {
3b1bc27f Andy McCall 3741
        if sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
3776b70d Andy McCall ↶ 3742
            .bind(g2_row.id)
3743
            .fetch_one(&h.app.db)
3744
            .await
3745
            .unwrap()
3746
            > 0
3747
        {
3748
            break;
3749
        }
3750
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3751
    }
3752
    assert!(db::proposals::list(&h.app.db, g2_row.id, &[]).await.unwrap().is_empty(), "off until turned on");
3753
    let (st, _) = call(&h.app, "PUT", "/api/v1/repos/andy/game2/diffusion", Some("site"), Some(r#"{"follow":"green"}"#.into())).await;
3754
    assert_eq!(st, StatusCode::OK);
3755
    let mut caught = None;
5d54cf74 Andy McCall ↶ 3756
    // Up to 15 s: under a full parallel test run the bump can take a while.
3757
    for _ in 0..300 {
3776b70d Andy McCall ↶ 3758
        if let Some(p) = db::proposals::list(&h.app.db, g2_row.id, &["open"]).await.unwrap().into_iter().next() {
3759
            caught = Some(p);
3760
            break;
3761
        }
3762
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3763
    }
3764
    let caught = caught.expect("bumped as soon as it was turned on");
3765
    assert!(caught.body.contains("api v5") && caught.title.contains("1 change"), "{:?} {:?}", caught.title, caught.body);
0e04dfc2 Andy McCall ↶ 3766
    // A bump someone closed is a "no": the reconciler does not open it again.
3b1bc27f Andy McCall 3767
    sqlx::query("UPDATE proposals SET state = 'closed' WHERE id = $1").bind(caught.id).execute(&h.app.db).await.unwrap();
62cdf34d Andy McCall ↶ 3768
    // (The bump's own runs finishing may still propose again, as Diffusion
3769
    // does on an upstream's moves; the reconciler itself opens nothing.)
0e04dfc2 Andy McCall ↶ 3770
    let r = oxygenhub::diffusion::reconcile(&h.app).await;
62cdf34d Andy McCall ↶ 3771
    assert_eq!(r.caught_up, 0, "the reconciler respects the closed bump: {r:?}");
a7e6e8e6 Andy McCall ↶ 3772
}
3773
3774
/// Whether any job is queued or running.
3775
async fn jobs_left(app: &Shared) -> bool {
3776
    sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM flow_jobs WHERE status IN ('queued', 'running')")
3777
        .fetch_one(&app.db)
3778
        .await
3779
        .unwrap_or(0)
3780
        > 0
9aaa88b2 Andy McCall ↶ 3781
}
3782
3783
/// An upstream with no checks never turns green: a consumer following green
3784
/// still gets its bumps, marked amber, `upstream unverified` (#148).
3785
#[tokio::test(flavor = "multi_thread")]
3786
async fn bumps_from_an_upstream_without_checks_are_marked_unverified() {
3787
    let h = hub().await;
3788
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3789
    create(&h.app, "andy", "lib").await;
3790
    create(&h.app, "andy", "app").await;
3791
    let lib_work = tempfile::tempdir().unwrap();
3792
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
3793
    write(lib_work.path(), "lib.h", "v1\n");
3794
    lib.snapshot("t").unwrap();
3795
    lib.commit("lib v1", &[]).unwrap();
3796
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
3797
    let app_work = tempfile::tempdir().unwrap();
3798
    let app = client(&format!("{}/andy/app", h.base), app_work.path());
3799
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
c4e432da Andy McCall ↶ 3800
    // It watches lib.c: upstream changes touching it are flagged.
3801
    let modules = std::fs::read_to_string(app_work.path().join(".oxymodules")).unwrap();
3802
    write(app_work.path(), ".oxymodules", &format!("{modules}watch = lib.c\n"));
9aaa88b2 Andy McCall ↶ 3803
    app.snapshot("t").unwrap();
3804
    app.commit("app on lib", &[]).unwrap();
3805
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
3806
    let app_row = db::repos::get(&h.app.db, "andy", "app").await.unwrap().unwrap();
3807
    for _ in 0..100 {
3b1bc27f Andy McCall 3808
        if sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
9aaa88b2 Andy McCall ↶ 3809
            .bind(app_row.id)
3810
            .fetch_one(&h.app.db)
3811
            .await
3812
            .unwrap()
3813
            > 0
3814
        {
3815
            break;
3816
        }
3817
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3818
    }
3819
    let (st, _) = call(&h.app, "PUT", "/api/v1/repos/andy/app/diffusion", Some("site"), Some(r#"{"follow":"green"}"#.into())).await;
3820
    assert_eq!(st, StatusCode::OK);
3821
    write(lib_work.path(), "lib.c", "v2\n");
3822
    lib.snapshot("t").unwrap();
3823
    lib.commit("lib v2", &[]).unwrap();
3824
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
3825
    let mut found = None;
3826
    for _ in 0..100 {
3827
        if let Some(p) = db::proposals::list(&h.app.db, app_row.id, &["open"]).await.unwrap().into_iter().next() {
3828
            found = Some(p);
3829
            break;
3830
        }
3831
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3832
    }
3833
    let p = found.expect("a bump although the upstream never goes green");
3834
    assert!(p.body.contains("Upstream unverified"), "{}", p.body);
c4e432da Andy McCall ↶ 3835
    assert!(p.body.contains("Touches what you watch") && p.body.contains("touches `lib.c`") && p.body.contains("⚑"), "{}", p.body);
9aaa88b2 Andy McCall ↶ 3836
    let mut labels = Vec::new();
3837
    for _ in 0..100 {
3838
        labels = db::issues::proposal_labels(&h.app.db, p.id).await.unwrap().into_iter().map(|l| l.name).collect::<Vec<String>>();
3839
        if labels.len() == 2 {
3840
            break;
3841
        }
3842
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3843
    }
3844
    assert!(labels.contains(&"upstream unverified".to_string()) && labels.contains(&"dependencies".to_string()), "{labels:?}");
a7e6e8e6 Andy McCall ↶ 3845
}
d943160d Andy McCall ↶ 3846
3847
/// #134: when a proposal's target moves, its projected state is new; the
3848
/// hub runs the pipeline on it, so its checks are never for an older one.
3849
#[tokio::test(flavor = "multi_thread")]
3850
async fn a_moved_target_runs_its_open_proposals_again() {
3851
    let h = hub().await;
3852
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3853
    create(&h.app, "andy", "demo").await;
3854
    let work = tempfile::tempdir().unwrap();
3855
    let mut c = client(&format!("{}/andy/demo", h.base), work.path());
3856
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3857
    write(work.path(), "test.sh", "echo ok\n");
3858
    c.snapshot("t").unwrap();
3859
    let base = c.commit("base", &[]).unwrap();
3860
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3861
    // Two proposals, each main plus one change.
3862
    for (b, file) in [("fix-a", "a.txt"), ("fix-b", "b.txt")] {
3863
        c.bookmark_create(b, Some(&[base])).unwrap();
3864
        c.bookmark_switch(b, true).unwrap();
3865
        write(work.path(), file, "x\n");
3866
        c.snapshot("t").unwrap();
3867
        c.commit(&format!("add {file}"), &[]).unwrap();
3868
        assert!(c.push_bookmark("origin", b, false).unwrap().iter().all(|r| r.ok));
3869
        let body = serde_json::json!({ "title": b, "target": "main", "source": b }).to_string();
3870
        let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/demo/proposals", Some("site"), Some(body)).await;
3871
        assert_eq!(st, StatusCode::CREATED, "{out}");
3872
    }
3873
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
3874
    let props = db::proposals::list(&h.app.db, row.id, &["open"]).await.unwrap();
3875
    let a = props.iter().find(|p| p.source_bookmark == "fix-a").unwrap().number;
3876
    let b = props.iter().find(|p| p.source_bookmark == "fix-b").unwrap().number;
3877
    // Landing fix-a moves main: fix-b's projected state gets a run.
3878
    let (st, out) = call(&h.app, "POST", &format!("/api/v1/repos/andy/demo/proposals/{a}/land"), Some("site"), Some("{}".into())).await;
3879
    assert_eq!(st, StatusCode::OK, "{out}");
3880
    let label = format!("proposal/{b}");
3881
    let mut found = None;
3882
    for _ in 0..100 {
3883
        if let Some(r) = runs_of(&h.app, "andy", "demo").await.into_iter().find(|r| r.bookmark == label) {
3884
            found = Some(r);
3885
            break;
3886
        }
3887
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3888
    }
3889
    let run = found.expect("a run of fix-b's new projected state");
3890
    let projected = db::proposals::get(&h.app.db, row.id, b).await.unwrap().unwrap();
3891
    assert_eq!((run.trigger.as_str(), run.state.as_str()), ("proposal", projected.projected_state.as_str()), "on its projected state");
3892
    // Moving main again by a push does it once more; the same state is not run twice.
3893
    let before = runs_of(&h.app, "andy", "demo").await.len();
3894
    oxygenhub::web::proposals::settle_after_push(&h.app, &row, "main", "andy").await;
3895
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), before, "not again for the same state");
3896
}
93501da2 Andy McCall ↶ 3897
3898
/// Send image bytes to the hub as their chunks and then a manifest that
3899
/// names no architecture; the manifest as the hub answers it.
3900
async fn send_image(app: &Shared, image: &[u8]) -> (String, serde_json::Value) {
3901
    let mut chunks = std::collections::HashMap::new();
3902
    let m = jet::images::scan(image, None, |c, b| {
3903
        chunks.insert(c.hash().to_string(), b.to_vec());
3904
        Ok(())
3905
    })
3906
    .unwrap();
3907
    for c in m.needed() {
3908
        let (st, body) = put_bytes(app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
3909
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
3910
    }
3911
    let (st, body) =
3912
        call(app, "PUT", &format!("/api/v1/flow/images/{}", m.hash), Some("site"), Some(serde_json::to_string(&m).unwrap())).await;
3913
    assert_eq!(st, StatusCode::CREATED, "{body}");
3914
    (m.hash.clone(), serde_json::from_str(&body).unwrap())
3915
}
3916
3917
/// oxygenhub#173 (OxygenFlow spec §11.2, Andy's "detect and learn"): an
3918
/// image sent with no architecture is read from its own files, so a
3919
/// riscv64 runner is never offered an x86_64 image's jobs; an image
3920
/// nobody can read takes the architecture its first pass ran on.
3921
#[tokio::test(flavor = "multi_thread")]
3922
async fn an_image_names_its_own_architecture_and_a_pass_teaches_the_rest() {
3923
    use oxy_core::identity::SecretKey;
3924
    let h = hub().await;
3925
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3926
    // An ext4 image whose shell is x86_64, as `flow rootfs import` makes one.
3927
    let dir = tempfile::tempdir().unwrap();
3928
    let tree = dir.path().join("tree");
3929
    std::fs::create_dir_all(tree.join("bin")).unwrap();
3930
    let mut elf = vec![0u8; 64];
3931
    elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
3932
    elf[18..20].copy_from_slice(&0x3Eu16.to_le_bytes());
3933
    std::fs::write(tree.join("bin/sh"), &elf).unwrap();
3934
    let img = dir.path().join("rootfs.ext4");
3935
    let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
3936
    if !made.is_ok_and(|s| s.success()) {
3937
        eprintln!("mkfs.ext4 not found: skipped");
3938
        return;
3939
    }
3940
    let (x86, answer) = send_image(&h.app, &std::fs::read(&img).unwrap()).await;
3941
    assert_eq!(answer["arch"], "x86_64", "read from its shell: {answer}");
3942
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{x86}"), Some("runner-secret"), None).await;
3943
    assert_eq!(serde_json::from_str::<jet::images::Manifest>(&body).unwrap().arch.as_deref(), Some("x86_64"), "runners fetch it named");
3944
    // One nobody can read: no ext4, no shell.
3945
    let blob: Vec<u8> = (0..300_000u32).map(|i| (i % 241) as u8).collect();
3946
    let (unread, answer) = send_image(&h.app, &blob).await;
3947
    assert!(answer["arch"].is_null(), "{answer}");
3948
    let archs = db::flow::image_archs(&h.app.db).await.unwrap();
3949
    assert_eq!((archs.get(&x86).map(String::as_str), archs.get(&unread)), (Some("x86_64"), None));
3950
    // Kept images with none are read once at start.
3951
    sqlx::query("UPDATE jet_images SET arch = ''").execute(&h.app.db).await.unwrap();
3952
    sqlx::query("DELETE FROM flow_images").execute(&h.app.db).await.unwrap();
3953
    assert_eq!(oxygenhub::images::learn_archs(&h.app).await.unwrap(), 1);
3954
    assert_eq!(db::flow::image_archs(&h.app.db).await.unwrap().get(&x86).map(String::as_str), Some("x86_64"));
3955
3956
    // A job on each image.
3957
    create(&h.app, "andy", "arch").await;
3958
    let work = tempfile::tempdir().unwrap();
3959
    let c = client(&format!("{}/andy/arch", h.base), work.path());
3960
    let kdl = format!(
3961
        "schema-version 1\nsandbox \"unread\" {{\n    rootfs \"cas://blob/{unread}\"\n}}\nsandbox \"x86\" {{\n    rootfs \"cas://blob/{x86}\"\n}}\n\
3962
         job \"first\" {{\n    sandbox \"unread\"\n    exec \"make\"\n}}\njob \"second\" {{\n    sandbox \"x86\"\n    exec \"make\"\n    depends-on \"first\"\n}}\n\
3963
         job \"third\" {{\n    sandbox \"unread\"\n    exec \"make\"\n    depends-on \"first\"\n}}\n"
3964
    );
3965
    write(work.path(), ".flow/pipeline.kdl", &kdl);
3966
    c.commit("Jobs on two images", &[]).unwrap();
3967
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3968
    runs_of(&h.app, "andy", "arch").await;
3969
3970
    // The x86_64 runner passes the first job: its image is x86_64 now.
3971
    let x86_info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
3972
    let x86_claim =
3973
        serde_json::json!({ "runner": "earth", "runtimes": ["microvm"], "images": [], "fetches_images": true, "info": x86_info });
3974
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(x86_claim.to_string())).await;
3975
    assert_eq!(st, StatusCode::OK, "{body}");
3976
    let first: serde_json::Value = serde_json::from_str(&body).unwrap();
3977
    assert_eq!(first["job"]["name"], "first");
3978
    let ph = first["pipeline_hash"].as_str().unwrap();
3979
    let id = first["job_id"].as_i64().unwrap();
3980
    assert_eq!(
3981
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("first", ph, 0) })).await,
3982
        StatusCode::NO_CONTENT
3983
    );
3984
    assert_eq!(db::flow::image_archs(&h.app.db).await.unwrap().get(&unread).map(String::as_str), Some("x86_64"), "learned");
3985
3986
    // A riscv64 runner is offered neither: one read, one learned.
3987
    let token = "flowreg_narvi";
3988
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
3989
    let identity = SecretKey::generate().identity("narvi", "", 1);
3990
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
3991
    let reg = serde_json::json!({ "token": token, "name": "narvi", "identity": hex::encode(identity.encode()), "info": info });
3992
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
3993
    assert_eq!(st, StatusCode::OK, "{body}");
3994
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
3995
    let narvi =
3996
        serde_json::json!({ "runner": "narvi", "runtimes": ["microvm"], "images": [], "fetches_images": true, "info": info }).to_string();
3997
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(narvi)).await;
3998
    assert_eq!(st, StatusCode::NO_CONTENT, "the second job's image is x86_64 and the third's learned so: {body}");
3999
    for _ in 0..2 {
4000
        let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(x86_claim.to_string())).await;
4001
        assert_eq!(st, StatusCode::OK, "both go to x86_64: {body}");
4002
    }
4003
}
f4d6ef41 Andy McCall ↶ 4004
4005
/// Diffusion auto-land (docs/diffusion.md §4.2; Andy chose "opt-in, per
4006
/// repository", 2026-10-13): a consumer that chose `land = auto` has a bump
4007
/// landed by itself, as the diffusion account, once both halves are green;
4008
/// a bump from an upstream with no checks (amber) always waits.
4009
#[tokio::test(flavor = "multi_thread")]
4010
async fn a_consumer_that_chose_auto_lands_green_bumps_itself() {
4011
    let h = hub().await;
4012
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4013
    create(&h.app, "andy", "api").await;
4014
    create(&h.app, "andy", "game").await;
4015
    let hub_app = &h.app;
4016
    // Run every queued job to a pass.
4017
    let pass_all = move || async move {
4018
        for _ in 0..20 {
4019
            let Some(a) = claim(hub_app).await else {
4020
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4021
                if !jobs_left(hub_app).await {
4022
                    break;
4023
                }
4024
                continue;
4025
            };
4026
            let id = a["job_id"].as_i64().unwrap();
4027
            let (name, ph) = (a["job"]["name"].as_str().unwrap().to_string(), a["pipeline_hash"].as_str().unwrap().to_string());
4028
            assert_eq!(
4029
                finish(hub_app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt(&name, &ph, 0) })).await,
4030
                StatusCode::NO_CONTENT
4031
            );
4032
        }
4033
    };
4034
    let api_work = tempfile::tempdir().unwrap();
4035
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
4036
    write(api_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4037
    write(api_work.path(), "test.sh", "echo ok\n");
4038
    api.snapshot("t").unwrap();
4039
    api.commit("api v1", &[]).unwrap();
4040
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4041
    pass_all().await;
4042
    let game_work = tempfile::tempdir().unwrap();
4043
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
4044
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
4045
    write(game_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4046
    write(game_work.path(), "test.sh", "echo ok\n");
4047
    game.snapshot("t").unwrap();
4048
    game.commit("game on api v1", &[]).unwrap();
4049
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
4050
    pass_all().await;
4051
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
4052
    for _ in 0..100 {
3b1bc27f Andy McCall 4053
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
f4d6ef41 Andy McCall ↶ 4054
            .bind(game_row.id)
4055
            .fetch_one(&h.app.db)
4056
            .await
4057
            .unwrap();
4058
        if n > 0 {
4059
            break;
4060
        }
4061
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4062
    }
4063
    let (st, body) =
4064
        call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(r#"{"follow":"green","land":"auto"}"#.into())).await;
4065
    assert_eq!(st, StatusCode::OK, "{body}");
4066
    assert!(body.contains(r#""land":"auto""#), "{body}");
4067
    let (st, _) =
4068
        call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(r#"{"follow":"green","land":"soon"}"#.into())).await;
4069
    assert_eq!(st, StatusCode::BAD_REQUEST);
4070
4071
    // The upstream moves and passes: the bump is proposed, its run passes,
4072
    // and it lands by itself.
4073
    write(api_work.path(), "a2.c", "v2\n");
4074
    api.snapshot("t").unwrap();
4075
    api.commit("api v2: faster sprites", &[]).unwrap();
4076
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4077
    let mut landed = None;
4078
    for _ in 0..100 {
4079
        pass_all().await;
4080
        let all = db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap();
4081
        if let Some(p) = all.into_iter().find(|p| p.source_bookmark == "diffusion/deps/api" && p.state == "landed") {
4082
            landed = Some(p);
4083
            break;
4084
        }
4085
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4086
    }
4087
    let p = landed.expect("landed by itself once both halves were green");
4088
    assert!(p.body.contains("lands its bumps itself"), "{}", p.body);
a2ef53c5 Andy McCall ↶ 4089
    // The state is written a moment before the timeline's event: wait for it.
4090
    let mut events = vec![];
4091
    for _ in 0..100 {
4092
        events = db::proposals::events(&h.app.db, p.id).await.unwrap();
4093
        if events.iter().any(|e| e.event == "landed") {
4094
            break;
4095
        }
4096
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
4097
    }
f4d6ef41 Andy McCall ↶ 4098
    let landing = events.iter().find(|e| e.event == "landed").expect("a landing on the timeline");
4099
    assert_eq!(landing.actor, "diffusion");
4100
    assert!(landing.detail.contains("Diffusion, both halves green"), "{}", landing.detail);
4101
    // The game's main now pins api v2.
4102
    let mut behind = serde_json::Value::Null;
4103
    for _ in 0..100 {
4104
        let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
4105
        let list: Vec<serde_json::Value> = serde_json::from_str(&list).unwrap();
4106
        behind = list.iter().find(|c| c["name"] == "game").map(|c| c["behind"].clone()).unwrap_or_default();
4107
        if behind == 0 {
4108
            break;
4109
        }
4110
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4111
    }
4112
    assert_eq!(behind, 0, "main moved to the bump");
4113
4114
    // An upstream with no checks: its bump passes in the consumer, but
4115
    // amber never lands by itself, whatever the setting.
4116
    create(&h.app, "andy", "lib").await;
4117
    create(&h.app, "andy", "app").await;
4118
    let lib_work = tempfile::tempdir().unwrap();
4119
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
4120
    write(lib_work.path(), "lib.h", "v1\n");
4121
    lib.snapshot("t").unwrap();
4122
    lib.commit("lib v1", &[]).unwrap();
4123
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4124
    let app_work = tempfile::tempdir().unwrap();
4125
    let app = client(&format!("{}/andy/app", h.base), app_work.path());
4126
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
4127
    let modules = std::fs::read_to_string(app_work.path().join(".oxymodules")).unwrap();
4128
    write(app_work.path(), ".oxymodules", &format!("{modules}follow = green\nland = auto\n"));
4129
    write(app_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4130
    write(app_work.path(), "test.sh", "echo ok\n");
4131
    app.snapshot("t").unwrap();
4132
    app.commit("app on lib", &[]).unwrap();
4133
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
4134
    pass_all().await;
4135
    let app_row = db::repos::get(&h.app.db, "andy", "app").await.unwrap().unwrap();
4136
    for _ in 0..100 {
3b1bc27f Andy McCall 4137
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
f4d6ef41 Andy McCall ↶ 4138
            .bind(app_row.id)
4139
            .fetch_one(&h.app.db)
4140
            .await
4141
            .unwrap();
4142
        if n > 0 {
4143
            break;
4144
        }
4145
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4146
    }
4147
    write(lib_work.path(), "lib.c", "v2\n");
4148
    lib.snapshot("t").unwrap();
4149
    lib.commit("lib v2", &[]).unwrap();
4150
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4151
    let mut passed = false;
4152
    for _ in 0..100 {
4153
        pass_all().await;
4154
        let s: Option<String> = sqlx::query_scalar(
3b1bc27f Andy McCall 4155
            "SELECT status FROM flow_runs WHERE repo_id = $1 AND bookmark = 'diffusion/deps/lib' ORDER BY id DESC LIMIT 1",
f4d6ef41 Andy McCall ↶ 4156
        )
4157
        .bind(app_row.id)
4158
        .fetch_optional(&h.app.db)
4159
        .await
4160
        .unwrap();
4161
        if s.as_deref() == Some("passed") {
4162
            passed = true;
4163
            break;
4164
        }
4165
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4166
    }
4167
    assert!(passed, "the app's run on the bump passed");
4168
    assert_eq!(oxygenhub::diffusion::auto_land(&h.app, &app_row, "deps/lib").await, Err(oxygenhub::diffusion::Held::Unverified));
4169
    let open = db::proposals::list(&h.app.db, app_row.id, &["open"]).await.unwrap();
4170
    assert!(open.iter().any(|p| p.source_bookmark == "diffusion/deps/lib"), "amber waits for a person");
4171
}
e8fa5369 Andy McCall ↶ 4172
4173
/// oxygenflow#31: one finished job runs again in the same run, with the
4174
/// jobs that depend on it; what it depends on keeps its result, so a flaky
4175
/// test reruns without its build. Not while the run is live, and only a
4176
/// job the run has.
4177
#[tokio::test(flavor = "multi_thread")]
4178
async fn one_job_reruns_with_what_depends_on_it() {
4179
    let h = hub().await;
4180
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4181
    create(&h.app, "andy", "flaky").await;
4182
    let work = tempfile::tempdir().unwrap();
4183
    let c = client(&format!("{}/andy/flaky", h.base), work.path());
4184
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4185
    write(work.path(), "test.sh", "echo ok\n");
4186
    c.commit("Add a pipeline", &[]).unwrap();
4187
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4188
    let run = runs_of(&h.app, "andy", "flaky").await[0].clone();
4189
    // build and lint pass; test fails, as a flaky one does.
4190
    let (st, _) =
4191
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/test/rerun", run.number), Some("site"), None).await;
4192
    assert_eq!(st, StatusCode::CONFLICT, "not while the run is live");
4193
    while let Some(j) = claim(&h.app).await {
4194
        let id = j["job_id"].as_i64().unwrap();
4195
        let (name, ph) = (j["job"]["name"].as_str().unwrap().to_string(), j["pipeline_hash"].as_str().unwrap().to_string());
4196
        let exit = if name == "test" { 1 } else { 0 };
d9b3b846 Andy McCall ↶ 4197
        let log = serde_json::json!({ "records": [
4198
            { "t": 1, "stream": "out", "text": format!("{name} ran") },
4199
            { "t": 2, "stream": "out", "text": "::group::compile" },
4200
            { "t": 5, "stream": "out", "text": "cc a.c" },
4201
            { "t": 1502, "stream": "out", "text": "::endgroup::" },
4202
        ]});
e8fa5369 Andy McCall ↶ 4203
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(log.to_string())).await;
4204
        assert_eq!(
4205
            finish(&h.app, id, serde_json::json!({ "exit_code": exit, "duration_ms": 10, "receipt": receipt(&name, &ph, exit as u32) }))
4206
                .await,
4207
            StatusCode::NO_CONTENT
4208
        );
4209
    }
d9b3b846 Andy McCall ↶ 4210
    // Marked lines fold into a section, with how long it took (#31).
4211
    let (_, page) = call(&h.app, "GET", &format!("/andy/flaky/flow/{}", run.number), None, None).await;
4212
    assert!(page.contains(r#"<details class="log-group" data-from="2">"#), "{page}");
4213
    assert!(page.contains(r#"compile <span class="took">1.5s</span></summary>"#) && !page.contains("::endgroup::"), "{page}");
e8fa5369 Andy McCall ↶ 4214
    let status = |n: &'static str| {
4215
        let (app, run_id) = (h.app.clone(), run.id);
4216
        async move { db::flow::jobs(&app.db, run_id).await.unwrap().into_iter().find(|j| j.name == n).unwrap() }
4217
    };
4218
    assert_eq!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().status, "failed");
4219
    let failed_test = status("test").await;
4220
4221
    // The test again: build and lint keep their results.
4222
    let (st, body) =
4223
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/test/rerun", run.number), Some("site"), None).await;
4224
    assert_eq!(st, StatusCode::OK, "{body}");
4225
    assert!(body.contains(r#""queued":1"#), "{body}");
4226
    assert_eq!(
4227
        (status("build").await.status, status("lint").await.status, status("test").await.status),
4228
        ("passed".into(), "passed".into(), "queued".into())
4229
    );
4230
    assert!(db::flow::log(&h.app.db, failed_test.id, 0, 100).await.unwrap().is_empty(), "its old log is gone");
4231
    assert!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().live());
4232
    let checks = checks_when(&h.app, run.repo_id, &run.state, 3).await;
4233
    assert_eq!(checks.iter().find(|c| c.name == "flow/test").map(|c| c.status.as_str()), Some("queued"));
4234
    let j = claim(&h.app).await.expect("the test, queued again");
4235
    assert_eq!(j["job"]["name"], "test");
4236
    let ph = j["pipeline_hash"].as_str().unwrap().to_string();
4237
    let id = j["job_id"].as_i64().unwrap();
4238
    assert_eq!(
4239
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("test", &ph, 0) })).await,
4240
        StatusCode::NO_CONTENT
4241
    );
4242
    assert_eq!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().status, "passed", "the run is whole again");
bff9106e Andy McCall ↶ 4243
    // Andy owns it: told it failed, then that it is fixed (#183).
4244
    let andy_id = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap().id;
4245
    let kinds: Vec<String> = db::notify::inbox(&h.app.db, andy_id, 20).await.unwrap().into_iter().map(|n| n.kind).collect();
4246
    assert!(kinds.contains(&"flow.failed".to_string()) && kinds.contains(&"flow.fixed".to_string()), "{kinds:?}");
e8fa5369 Andy McCall ↶ 4247
4248
    // The build again brings the test that depends on it; lint stays.
4249
    let (_, body) =
4250
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/build/rerun", run.number), Some("site"), None).await;
4251
    assert!(body.contains(r#""queued":2"#), "{body}");
4252
    assert_eq!(
4253
        (status("build").await.status, status("lint").await.status, status("test").await.status),
4254
        ("queued".into(), "passed".into(), "queued".into())
4255
    );
4256
    let (st, _) =
4257
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/deploy/rerun", run.number), Some("site"), None).await;
4258
    assert_eq!(st, StatusCode::CONFLICT, "live again, and no such job either way");
4259
}
4a4400c5 Andy McCall ↶ 4260
4261
/// oxygenflow#30: a failed run tells its pusher and the repository's
4262
/// watchers; a runner whose last five jobs ended in infrastructure errors
4263
/// is drained and the administrators told, counting only since an
4264
/// administrator last made it active.
4265
#[tokio::test(flavor = "multi_thread")]
4266
async fn failed_runs_are_told_and_an_erroring_runner_is_drained() {
4267
    let h = hub().await;
4268
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4269
    let bob = db::accounts::create_account(&h.app.db, "bob", "[email protected]", "x", "salt", false).await.unwrap();
4270
    create(&h.app, "andy", "alerts").await;
4271
    let row = db::repos::get(&h.app.db, "andy", "alerts").await.unwrap().unwrap();
4272
    db::notify::set_watch(&h.app.db, bob.id, row.id, true).await.unwrap();
4273
    let work = tempfile::tempdir().unwrap();
4274
    let c = client(&format!("{}/andy/alerts", h.base), work.path());
4275
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4276
    write(work.path(), "test.sh", "exit 1\n");
4277
    c.commit("Add a pipeline", &[]).unwrap();
4278
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4279
    let run = runs_of(&h.app, "andy", "alerts").await[0].clone();
3b1bc27f Andy McCall 4280
    sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&h.app.db).await.unwrap();
4a4400c5 Andy McCall ↶ 4281
    while let Some(j) = claim(&h.app).await {
4282
        let id = j["job_id"].as_i64().unwrap();
4283
        let (name, ph) = (j["job"]["name"].as_str().unwrap().to_string(), j["pipeline_hash"].as_str().unwrap().to_string());
4284
        let exit = if name == "test" { 1 } else { 0 };
4285
        finish(&h.app, id, serde_json::json!({ "exit_code": exit, "duration_ms": 10, "receipt": receipt(&name, &ph, exit as u32) })).await;
4286
    }
4287
    let told = |id: i64| {
4288
        let db = h.app.db.clone();
4289
        async move { db::notify::inbox(&db, id, 20).await.unwrap().into_iter().filter(|n| n.kind == "flow.failed").collect::<Vec<_>>() }
4290
    };
4291
    let (for_andy, for_bob) = (told(andy.id).await, told(bob.id).await);
4292
    assert_eq!((for_andy.len(), for_bob.len()), (1, 1), "the pusher and a watcher");
4293
    assert!(for_andy[0].title.contains(&format!("run #{} on main failed (test)", run.number)), "{}", for_andy[0].title);
4294
    assert_eq!(for_andy[0].url, format!("/andy/alerts/flow/{}", run.number));
4295
4296
    // Five infrastructure errors in a row drain the runner.
4297
    let runner_id = || {
4298
        let db = h.app.db.clone();
4299
        async move { sqlx::query_scalar::<_, i64>("SELECT id FROM flow_runners WHERE name = 'test-1'").fetch_one(&db).await.unwrap() }
4300
    };
4301
    let mut errors = 0;
4302
    while errors < 5 {
4303
        let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/alerts/flow/runs", Some("site"), Some("{}".into())).await;
4304
        assert_eq!(st, StatusCode::CREATED);
4305
        while let Some(j) = claim(&h.app).await {
4306
            let id = j["job_id"].as_i64().unwrap();
4307
            let st = finish(
4308
                &h.app,
4309
                id,
4310
                serde_json::json!({ "exit_code": null, "duration_ms": 10, "error": "the microVM did not start: /dev/kvm busy" }),
4311
            )
4312
            .await;
4313
            assert_eq!(st, StatusCode::NO_CONTENT);
4314
            errors += 1;
4315
            if errors == 5 {
4316
                break;
4317
            }
4318
        }
4319
    }
4320
    let state = |id: i64| {
4321
        let db = h.app.db.clone();
4322
        async move { db::runners::get(&db, id).await.unwrap().unwrap().state }
4323
    };
4324
    let id = runner_id().await;
4325
    assert_eq!(state(id).await, "draining");
4326
    let drained: Vec<_> =
4327
        db::notify::inbox(&h.app.db, andy.id, 50).await.unwrap().into_iter().filter(|n| n.kind == "flow.runner_drained").collect();
4328
    assert_eq!(drained.len(), 1, "the administrator is told");
4329
    assert!(drained[0].title.contains("/dev/kvm busy"), "{}", drained[0].title);
4330
    assert!(
4331
        !told(bob.id).await.is_empty()
4332
            && db::notify::inbox(&h.app.db, bob.id, 50).await.unwrap().iter().all(|n| n.kind != "flow.runner_drained")
4333
    );
4334
    // Made active again, past errors no longer count.
4335
    db::runners::set_state(&h.app.db, id, "active").await.unwrap();
4336
    assert_eq!(db::runners::erroring(&h.app.db, id, 5).await.unwrap(), None);
f7bcee49 Andy McCall ↶ 4337
}
4338
4339
/// #197: landing a proposal moves its target as a push does, so the
4340
/// target's pipeline runs on the landed state.
4341
#[tokio::test(flavor = "multi_thread")]
4342
async fn a_landed_proposal_runs_its_targets_pipeline() {
4343
    let h = hub().await;
4344
    create(&h.app, "andy", "demo").await;
4345
    let url = format!("{}/andy/demo", h.base);
4346
    let work = tempfile::tempdir().unwrap();
4347
    let mut c = client(&url, work.path());
4348
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4349
    write(work.path(), "test.sh", "echo ok\n");
4350
    c.snapshot("test").unwrap();
4351
    c.commit("Add a pipeline", &[]).unwrap();
4352
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4353
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
4354
    c.bookmark_create("feature", None).unwrap();
4355
    c.bookmark_switch("feature", false).unwrap();
4356
    write(work.path(), "b.txt", "more\n");
4357
    c.snapshot("test").unwrap();
4358
    c.commit("More", &[]).unwrap();
4359
    assert!(c.push_bookmark("origin", "feature", false).unwrap().iter().all(|r| r.ok));
4360
    let runs_before =
4361
        db::flow::runs(&h.app.db, db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap().id, 10, None).await.unwrap().len();
4362
4363
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4364
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
4365
    db::proposals::create(
4366
        &h.app.db,
4367
        db::proposals::NewProposal {
4368
            repo_id: row.id,
4369
            title: "More",
4370
            body: "",
4371
            author_id: Some(andy.id),
4372
            author: "andy",
4373
            draft: false,
4374
            target: "main",
4375
            source_kind: "bookmark",
4376
            source_repo_id: Some(row.id),
4377
            source_bookmark: "feature",
4378
            source_changes: "",
4379
        },
4380
    )
4381
    .await
4382
    .unwrap();
4383
    let repo = RepoName::parse("andy/demo").unwrap();
2a8b6216 Andy McCall ↶ 4384
    let state = oxygenhub::web::proposals::land_as(&h.app, &repo, &row, &andy, 1, "web", false, None).await.ok().expect("landed");
f7bcee49 Andy McCall ↶ 4385
    let mut runs = vec![];
4386
    for _ in 0..100 {
4387
        runs = db::flow::runs(&h.app.db, row.id, 10, None).await.unwrap();
4388
        if runs.len() > runs_before {
4389
            break;
4390
        }
4391
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4392
    }
4393
    let landed = runs.iter().find(|r| r.bookmark == "main" && r.state == state).expect("a run of the landed state on main");
4394
    assert_eq!((landed.trigger.as_str(), landed.actor.as_str()), ("push", "andy"));
4a4400c5 Andy McCall ↶ 4395
}
1870e4fa Andy McCall ↶ 4396
4397
/// #225: an ordinary user turns Flow on for their repository on their own
4398
/// runner, and the site's runners never take its jobs.
4399
#[tokio::test(flavor = "multi_thread")]
4400
async fn owners_run_flow_on_their_own_runners_only() {
4401
    use oxy_core::identity::SecretKey;
4402
    let h = hub().await;
4403
    let register = |name: &'static str| {
4404
        let app = h.app.clone();
4405
        async move {
c8684d44 Andy McCall 4406
            let body = format!("username={name}&email={name}%40example.com&password=correct-horse-battery&setup=test-setup");
1870e4fa Andy McCall ↶ 4407
            let res = oxygenhub::router(app)
4408
                .oneshot(
4409
                    Request::post("/register")
4410
                        .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
4411
                        .body(Body::from(body))
4412
                        .unwrap(),
4413
                )
4414
                .await
4415
                .unwrap();
4416
            res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string()
4417
        }
4418
    };
4419
    register("andy").await; // the first account: the site's administrator
4420
    let bob = register("bob").await;
4421
    create(&h.app, "bob", "game").await;
4422
    let web = |method: &'static str, path: &str, body: Option<String>| {
4423
        let (app, cookie, path) = (h.app.clone(), bob.clone(), path.to_string());
4424
        async move {
c7067c7b Andy McCall 4425
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie.clone());
1870e4fa Andy McCall ↶ 4426
            if body.is_some() {
4427
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
4428
            }
c7067c7b Andy McCall 4429
            let req = req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap();
4430
            let mut res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
4431
            // A repository settings form returns to its page (#278).
4432
            let back =
4433
                res.headers().get(header::LOCATION).and_then(|v| v.to_str().ok()).filter(|l| l.contains("/settings/")).map(String::from);
4434
            if let Some(to) = back {
4435
                let req = Request::get(to).header(header::COOKIE, cookie).body(Body::empty()).unwrap();
4436
                res = oxygenhub::router(app).oneshot(req).await.unwrap();
4437
            }
1870e4fa Andy McCall ↶ 4438
            String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned()
4439
        }
4440
    };
4441
    let csrf_of = |page: &str| {
4442
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
4443
        page[i..].split('"').next().unwrap().to_string()
4444
    };
4445
    // No runner of his own yet: he is told how, and cannot switch it on.
c7067c7b Andy McCall 4446
    let page = web("GET", "/bob/game/settings/flow", None).await;
1870e4fa Andy McCall ↶ 4447
    assert!(page.contains("register a runner for this repository") && !page.contains("value=\"own\""), "{page}");
4448
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=own", csrf_of(&page)))).await;
4449
    assert!(page.contains("Register a runner for this repository"), "{page}");
4450
    // He registers one.
4451
    let page = web("GET", "/bob/game/settings", None).await;
4452
    let page = web("POST", "/bob/game/settings/runners/token", Some(format!("_csrf={}", csrf_of(&page)))).await;
4453
    let i = page.find("--token ").unwrap() + "--token ".len();
4454
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
4455
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
4456
    let identity = SecretKey::generate().identity("bobs", "", 1);
4457
    let reg = serde_json::json!({ "token": token, "name": "bobs", "identity": hex::encode(identity.encode()), "info": info });
4458
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
4459
    assert_eq!(st, StatusCode::OK, "{body}");
4460
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
4461
    // The site's runners stay a site administrator's to grant; his own he may choose.
c7067c7b Andy McCall 4462
    let page = web("GET", "/bob/game/settings/flow", None).await;
1870e4fa Andy McCall ↶ 4463
    assert!(page.contains("value=\"own\"") && !page.contains("value=\"on\""), "{page}");
4464
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=on", csrf_of(&page)))).await;
4465
    assert!(page.contains("Only site administrators let the site's runners"), "{page}");
4466
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=own", csrf_of(&page)))).await;
4467
    assert!(page.contains("value=\"own\" checked") && page.contains("start runs"), "{page}");
4468
    assert_eq!(db::repos::get(&h.app.db, "bob", "game").await.unwrap().unwrap().flow, "own");
4469
    // A push starts a run; the site's runner is not offered it, his is.
4470
    let work = tempfile::tempdir().unwrap();
4471
    let c = client(&format!("{}/bob/game", h.base), work.path());
4472
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4473
    write(work.path(), "test.sh", "echo ok\n");
4474
    c.snapshot("t").unwrap();
4475
    c.commit("A pipeline", &[]).unwrap();
4476
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4477
    assert_eq!(runs_of(&h.app, "bob", "game").await.len(), 1, "a run started");
4478
    assert!(claim(&h.app).await.is_none(), "the site's runner is not offered it");
4479
    let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
4480
    let (st, job) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(body)).await;
4481
    assert_eq!(st, StatusCode::OK, "{job}");
4482
    assert_eq!(serde_json::from_str::<serde_json::Value>(&job).unwrap()["repo"], "bob/game");
4483
}
cd437c4f Andy McCall ↶ 4484
4485
#[tokio::test(flavor = "multi_thread")]
4486
async fn a_job_takes_the_artifact_its_producer_kept() {
4487
    let h = hub().await;
4488
    create(&h.app, "andy", "demo").await;
4489
    let url = format!("{}/andy/demo", h.base);
4490
    let work = tempfile::tempdir().unwrap();
4491
    let c = client(&url, work.path());
4492
    write(
4493
        work.path(),
4494
        ".flow/pipeline.kdl",
4495
        &format!(
4496
            "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"
4497
        ),
4498
    );
4499
    c.snapshot("test").unwrap();
4500
    c.commit("Plan, then apply that plan", &[]).unwrap();
4501
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4502
4503
    // The plan job runs and keeps its plan, named by its receipt.
4504
    let runs = runs_of(&h.app, "andy", "demo").await;
4505
    assert_eq!(runs.len(), 1, "a run");
4506
    let jobs = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap();
4507
    assert!(!jobs.is_empty(), "jobs: {:?}", runs[0]);
4508
    let p = claim(&h.app)
4509
        .await
4510
        .unwrap_or_else(|| panic!("nothing to claim: {:?}", jobs.iter().map(|j| (&j.name, &j.status, &j.error)).collect::<Vec<_>>()));
4511
    assert_eq!(p["job"]["name"], "plan");
4512
    let plan_id = p["job_id"].as_i64().unwrap();
4513
    let plan = b"the reviewed plan".to_vec();
4514
    let (st, text) = upload(&h.app, plan_id, "tfplan", &plan).await;
4515
    assert_eq!(st, StatusCode::OK, "{text}");
4516
    let blob = oxy_core::repo::Repo::blob_ref(&plan).to_hex();
4517
    let mut r = receipt("plan", p["pipeline_hash"].as_str().unwrap(), 0);
4518
    r["outputs"] = serde_json::json!([blob]);
4519
    assert_eq!(
4520
        finish(&h.app, plan_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r })).await,
4521
        StatusCode::NO_CONTENT
4522
    );
4523
4524
    // The apply job is told what to take and the blob to expect, and the
4525
    // runner fetches exactly those bytes.
4526
    let a = claim(&h.app).await.unwrap();
4527
    assert_eq!(a["job"]["name"], "apply");
4528
    let apply_id = a["job_id"].as_i64().unwrap();
4529
    assert_eq!(
4530
        a["inputs"],
4531
        serde_json::json!([{ "artifact": "tfplan", "from": "plan", "path": "/src/tfplan", "blob": blob }]),
4532
        "the claim names the producer's blob"
4533
    );
4534
    let req = Request::get(format!("/api/v1/flow/jobs/{apply_id}/inputs/0")).header(header::AUTHORIZATION, "Bearer runner-secret");
4535
    let res = oxygenhub::router(h.app.clone()).oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
4536
    assert_eq!(res.status(), StatusCode::OK);
4537
    assert_eq!(res.into_body().collect().await.unwrap().to_bytes().to_vec(), plan);
4538
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{apply_id}/inputs/1"), Some("runner-secret"), None).await;
4539
    assert_eq!(st, StatusCode::NOT_FOUND, "no second input");
4540
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{apply_id}/inputs/0"), None, None).await;
4541
    assert_eq!(st, StatusCode::UNAUTHORIZED, "runners only");
4542
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{plan_id}/inputs/0"), Some("runner-secret"), None).await;
4543
    assert_eq!(st, StatusCode::CONFLICT, "only a running job's");
4544
}
417184c7 Andy McCall ↶ 4545
4546
#[tokio::test(flavor = "multi_thread")]
4547
async fn a_job_waits_for_approval_and_is_approved_rejected_or_expires() {
4548
    let h = hub().await;
4549
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4550
    let bob = db::accounts::create_account(&h.app.db, "bob", "[email protected]", "x", "salt", false).await.unwrap();
4551
    let carol = db::accounts::create_account(&h.app.db, "carol", "[email protected]", "x", "salt", true).await.unwrap();
4552
    create(&h.app, "andy", "gated").await;
4553
    let row = db::repos::get(&h.app.db, "andy", "gated").await.unwrap().unwrap();
4554
    let work = tempfile::tempdir().unwrap();
4555
    let c = client(&format!("{}/andy/gated", h.base), work.path());
4556
    write(
4557
        work.path(),
4558
        ".flow/pipeline.kdl",
4559
        &format!(
47e37402 Andy McCall ↶ 4560
            "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"
417184c7 Andy McCall ↶ 4561
        ),
4562
    );
4563
    let mut n = 0;
4564
    let mut push = || {
4565
        n += 1;
4566
        write(work.path(), "n.txt", &format!("{n}\n"));
4567
        c.snapshot("test").unwrap();
4568
        c.commit(&format!("Push {n}"), &[]).unwrap();
4569
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4570
    };
4571
    // Runs `plan` to a pass; returns the run, its actor set to andy.
4572
    let plan_passes = |number: i64| {
4573
        let app = h.app.clone();
4574
        let row = row.clone();
4575
        async move {
4576
            let mut run = None;
4577
            for _ in 0..100 {
4578
                if let Some(r) = db::flow::run(&app.db, row.id, number).await.unwrap() {
4579
                    run = Some(r);
4580
                    break;
4581
                }
4582
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4583
            }
4584
            let run = run.expect("the run");
3b1bc27f Andy McCall 4585
            sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&app.db).await.unwrap();
417184c7 Andy McCall ↶ 4586
            let j = claim(&app).await.expect("plan is claimed");
4587
            assert_eq!(j["job"]["name"], "plan");
4588
            let (id, ph) = (j["job_id"].as_i64().unwrap(), j["pipeline_hash"].as_str().unwrap().to_string());
4589
            finish(&app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("plan", &ph, 0) })).await;
4590
            db::flow::run(&app.db, row.id, number).await.unwrap().unwrap()
4591
        }
4592
    };
4593
4594
    // Run 1: apply waits; only someone with the role, other than the pusher, approves it.
4595
    push();
4596
    let run = runs_of(&h.app, "andy", "gated").await[0].clone();
7e01a766 Andy McCall ↶ 4597
    // Live pages hear of the push (oxygenhub#203).
33d98147 Andy McCall 4598
    let heard = |topic: String| match h.app.bus.live.since(0, &[topic]) {
7e01a766 Andy McCall ↶ 4599
        oxygenhub::events::Replay::Events(e) => e.into_iter().map(|e| e.kind).collect::<Vec<_>>(),
4600
        oxygenhub::events::Replay::Reload => vec!["reload".into()],
4601
    };
4602
    assert!(heard(oxygenhub::events::topic::repo(row.id)).contains(&"push".to_string()), "the push is on the repository's topic");
3b1bc27f Andy McCall 4603
    sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&h.app.db).await.unwrap();
05f1a85a Andy McCall ↶ 4604
    let early = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true, None).await.unwrap_err();
417184c7 Andy McCall ↶ 4605
    assert!(early.contains("waits for plan first"), "{early}");
4606
    let run = plan_passes(run.number).await;
4607
    assert!(claim(&h.app).await.is_none(), "apply waits for a person, so no runner gets it");
7e01a766 Andy McCall ↶ 4608
    assert!(heard(oxygenhub::events::topic::run(run.id)).contains(&"jobs".to_string()), "the run's topic hears its jobs");
dc59d1b5 Andy McCall ↶ 4609
    // Those who may approve are told, once; the pusher (others-only) and
4610
    // someone without the role are not.
4611
    let told = |id: i64| {
4612
        let db = h.app.db.clone();
4613
        async move { db::notify::inbox(&db, id, 20).await.unwrap().into_iter().filter(|n| n.kind == "flow.approval").count() }
4614
    };
4615
    assert_eq!((told(carol.id).await, told(andy.id).await, told(bob.id).await), (1, 0, 0));
417184c7 Andy McCall ↶ 4616
    let (_, page) = call(&h.app, "GET", &format!("/andy/gated/flow/{}", run.number), None, None).await;
4617
    assert!(page.contains("waits for approval by someone with the <em>maintain</em> role, other than andy"), "the run page says so");
05f1a85a Andy McCall ↶ 4618
    let own = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &andy, true, None).await.unwrap_err();
417184c7 Andy McCall ↶ 4619
    assert!(own.contains("someone other than andy"), "{own}");
05f1a85a Andy McCall ↶ 4620
    let no_role = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &bob, true, None).await.unwrap_err();
417184c7 Andy McCall ↶ 4621
    assert!(no_role.contains("takes the maintain role"), "{no_role}");
05f1a85a Andy McCall ↶ 4622
    assert_eq!(oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true, None).await.unwrap(), "apply: approved by carol");
dc59d1b5 Andy McCall ↶ 4623
    assert_eq!(told(carol.id).await, 1, "told once");
417184c7 Andy McCall ↶ 4624
    let j = claim(&h.app).await.expect("approved, it runs");
4625
    assert_eq!(j["job"]["name"], "apply");
b644e175 Andy McCall ↶ 4626
    // Approved, its identity token names the environment (oxygenflow#59).
4627
    let token =
4628
        j["secrets"].as_array().unwrap().iter().find(|s| s["path"] == "/run/secrets/cloud").unwrap()["value"].as_str().unwrap().to_string();
4629
    let claims = h.app.oidc().await.unwrap().verify(&token, "https://sts.example", db::now_ms()).expect("a valid token");
4630
    assert_eq!(claims["environment"], "prod");
417184c7 Andy McCall ↶ 4631
    let (id, ph) = (j["job_id"].as_i64().unwrap(), j["pipeline_hash"].as_str().unwrap().to_string());
4632
    finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("apply", &ph, 0) })).await;
4633
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
4634
    assert!(audit.iter().any(|r| r.action == "flow.approved" && r.actor == "carol" && r.target.ends_with("#1 apply")), "audited");
4635
    let (_, page) = call(&h.app, "GET", &format!("/andy/gated/flow/{}", run.number), None, None).await;
4636
    assert!(page.contains("approved by carol"), "the run says who");
b644e175 Andy McCall ↶ 4637
    let (_, page) = call(&h.app, "GET", "/andy/gated/deployments", None, None).await;
4638
    assert!(page.contains("<strong>prod</strong>") && page.contains(">#1</a>") && page.contains("<td>carol</td>"), "the Deployments page");
4639
    let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/gated/deployments", Some("site"), None).await;
4640
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
4641
    assert_eq!((list[0]["environment"].as_str(), list[0]["approved_by"].as_str()), (Some("prod"), Some("carol")));
417184c7 Andy McCall ↶ 4642
05f1a85a Andy McCall ↶ 4643
    // Run 2: rejected through the API with carol's agent token: the job
4644
    // ends cancelled, the run ends, and it says the agent did it
4645
    // (oxygenhub#229).
417184c7 Andy McCall ↶ 4646
    push();
4647
    let run = plan_passes(2).await;
05f1a85a Andy McCall ↶ 4648
    let (secret, hash) = oxygenhub::auth::new_token();
4649
    let tok = db::accounts::create_token(&h.app.db, carol.id, "claude-code", &hash, "repo:write", "", None).await.unwrap();
4650
    db::accounts::set_token_agent(&h.app.db, carol.id, tok.id, true).await.unwrap();
4a68f106 Andy McCall ↶ 4651
    // An agent's token decides a gate only where the repository allows it
4652
    // (#258).
05f1a85a Andy McCall ↶ 4653
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/gated/flow/runs/2/jobs/apply/reject", Some(&secret), Some("{}".into())).await;
4a68f106 Andy McCall ↶ 4654
    assert_eq!(st, StatusCode::CONFLICT, "{body}");
4655
    assert!(body.contains("decided by a person here") && body.contains("Settings › OxygenFlow"), "{body}");
4656
    let gated = db::repos::get(&h.app.db, "andy", "gated").await.unwrap().unwrap();
4657
    db::repos::set_agents_decide_gates(&h.app.db, gated.id, true).await.unwrap();
4658
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/gated/flow/runs/2/jobs/apply/reject", Some(&secret), Some("{}".into())).await;
05f1a85a Andy McCall ↶ 4659
    assert_eq!(st, StatusCode::OK, "{body}");
4660
    assert!(body.contains("rejected by carol via claude-code"), "{body}");
417184c7 Andy McCall ↶ 4661
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
4662
    let apply = jobs.iter().find(|j| j.name == "apply").unwrap();
05f1a85a Andy McCall ↶ 4663
    assert_eq!((apply.status.as_str(), apply.error.as_str()), ("cancelled", "rejected by carol via claude-code"));
4664
    assert_eq!((apply.approved_by.as_str(), apply.approved_via.as_str()), ("carol", "claude-code"));
4665
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
4666
    assert!(
4667
        audit.iter().any(|r| r.action == "flow.rejected" && r.actor == "carol" && r.detail.contains("via claude-code")),
4668
        "audited with the agent"
4669
    );
417184c7 Andy McCall ↶ 4670
    assert!(claim(&h.app).await.is_none());
4671
4672
    // Run 3: nobody decides in time.
4673
    push();
4674
    let run = plan_passes(3).await;
4675
    assert_eq!(oxygenhub::flow::expire_approvals(&h.app, db::now_ms() + 3_600_000).await.unwrap(), 0, "not yet");
4676
    assert_eq!(oxygenhub::flow::expire_approvals(&h.app, db::now_ms() + 25 * 3_600_000).await.unwrap(), 1);
4677
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
4678
    let apply = jobs.iter().find(|j| j.name == "apply").unwrap();
4679
    assert_eq!((apply.status.as_str(), apply.error.as_str()), ("cancelled", "no approval within 24h"));
4680
}
67be8ac0 Andy McCall ↶ 4681
4682
#[tokio::test(flavor = "multi_thread")]
4683
async fn live_streams_only_topics_the_viewer_may_hear_and_replays() {
4684
    let h = hub().await;
4685
    create(&h.app, "andy", "open").await;
4686
    h.app.repos.create(&RepoName::parse("andy/shut").unwrap(), None).unwrap();
4687
    db::repos::create(&h.app.db, "andy", "shut", "", hub_api::Visibility::Private).await.unwrap();
4688
    let open = db::repos::get(&h.app.db, "andy", "open").await.unwrap().unwrap();
4689
    let shut = db::repos::get(&h.app.db, "andy", "shut").await.unwrap().unwrap();
33d98147 Andy McCall 4690
    let live = &h.app.bus.live;
67be8ac0 Andy McCall ↶ 4691
    let first = live.publish(&oxygenhub::events::topic::repo(open.id), "push");
4692
    live.publish(&oxygenhub::events::topic::repo(shut.id), "push");
4693
    live.publish(&oxygenhub::events::topic::proposal(open.id, 3), "review");
4694
4695
    // The first bytes of a stream, within a moment.
4696
    let read = |path: String, last: Option<u64>| {
4697
        let app = h.app.clone();
4698
        async move {
4699
            let mut req = Request::get(&path);
4700
            if let Some(l) = last {
4701
                req = req.header("last-event-id", l.to_string());
4702
            }
4703
            let res = oxygenhub::router(app).oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
4704
            let status = res.status();
4705
            let mut body = res.into_body();
4706
            let mut text = String::new();
4707
            while let Ok(Some(Ok(frame))) = tokio::time::timeout(std::time::Duration::from_millis(300), body.frame()).await {
4708
                if let Some(d) = frame.data_ref() {
4709
                    text.push_str(&String::from_utf8_lossy(d));
4710
                }
4711
            }
4712
            (status, text)
4713
        }
4714
    };
4715
    let topics = format!("/live?topics=repo:{},repo:{}/proposal:3", open.id, open.id);
4716
    // From the first event on: what came after it on these topics only.
4717
    let (st, text) = read(topics.clone(), Some(first.id)).await;
4718
    assert_eq!(st, StatusCode::OK);
4719
    assert!(text.contains("event: change") && text.contains(&format!("\"topic\":\"repo:{}/proposal:3\"", open.id)), "{text}");
4720
    assert!(!text.contains(&format!("\"topic\":\"repo:{}\"", shut.id)), "never another topic: {text}");
4721
    assert!(!text.contains(&format!("id: {}\n", first.id)), "not what was already seen: {text}");
4722
    // A private repository's topic, or someone else's, is refused whole.
4723
    let (st, _) = read(format!("/live?topics=repo:{},repo:{}", open.id, shut.id), None).await;
4724
    assert_eq!(st, StatusCode::FORBIDDEN);
4725
    assert_eq!(read("/live?topics=user:1".into(), None).await.0, StatusCode::FORBIDDEN);
4726
    assert_eq!(read("/live?topics=nonsense".into(), None).await.0, StatusCode::BAD_REQUEST);
4727
    assert_eq!(read("/live?topics=".into(), None).await.0, StatusCode::BAD_REQUEST);
4728
    // Too far behind: told to reload.
4729
    for _ in 0..oxygenhub::events::REPLAY {
4730
        live.publish("repo:999999", "push");
4731
    }
4732
    let (_, text) = read(topics, Some(first.id)).await;
4733
    assert!(text.contains("event: reload"), "{text}");
4734
}
47e37402 Andy McCall ↶ 4735
4736
#[tokio::test(flavor = "multi_thread")]
4737
async fn a_sealed_approval_releases_exactly_the_reviewed_plan() {
4738
    use oxy_core::approval::{SignedApproval, Statement};
4739
    use oxy_core::hash::ObjectRef;
4740
    use oxy_core::identity::SecretKey;
4741
    let h = hub().await;
4742
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4743
    let carol = db::accounts::create_account(&h.app.db, "carol", "[email protected]", "x", "salt", true).await.unwrap();
4744
    let sk = SecretKey::generate();
4745
    let carol_id = sk.identity("Carol", "[email protected]", 1);
4746
    db::accounts::link_identity(&h.app.db, carol.id, &carol_id.hash().to_hex(), "Carol", "[email protected]", &carol_id.encode())
4747
        .await
4748
        .unwrap();
4749
    create(&h.app, "andy", "infra").await;
4750
    let row = db::repos::get(&h.app.db, "andy", "infra").await.unwrap().unwrap();
4751
    let work = tempfile::tempdir().unwrap();
4752
    let c = client(&format!("{}/andy/infra", h.base), work.path());
4753
    write(
4754
        work.path(),
4755
        ".flow/pipeline.kdl",
4756
        &format!(
4757
            "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"
4758
        ),
4759
    );
4760
    c.snapshot("test").unwrap();
4761
    c.commit("Plan, then apply", &[]).unwrap();
4762
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4763
    let run = runs_of(&h.app, "andy", "infra").await[0].clone();
4764
    let p = claim(&h.app).await.unwrap();
4765
    let plan_id = p["job_id"].as_i64().unwrap();
4766
    let plan = b"the reviewed plan".to_vec();
4767
    upload(&h.app, plan_id, "tfplan", &plan).await;
4768
    let mut r = receipt("plan", p["pipeline_hash"].as_str().unwrap(), 0);
4769
    r["outputs"] = serde_json::json!([oxy_core::repo::Repo::blob_ref(&plan).to_hex()]);
4770
    finish(&h.app, plan_id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": r })).await;
4771
    let run = db::flow::run(&h.app.db, row.id, run.number).await.unwrap().unwrap();
4772
4773
    // An environment's gate takes a sealed approval: pressing Approve is not enough.
05f1a85a Andy McCall ↶ 4774
    let plain = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true, None).await.unwrap_err();
47e37402 Andy McCall ↶ 4775
    assert!(plain.contains(&format!("oxy seal --flow {}/andy/infra/flow/{} --job apply", h.base, run.number)), "{plain}");
4776
    // What there is to sign.
4777
    let (st, body) =
4778
        call(&h.app, "GET", &format!("/api/v1/repos/andy/infra/flow/runs/{}/jobs/apply/approval", run.number), Some("site"), None).await;
4779
    assert_eq!(st, StatusCode::OK, "{body}");
4780
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
4781
    assert_eq!(v["environment"], "prod");
4782
    assert_eq!(v["inputs"], serde_json::json!([oxy_core::repo::Repo::blob_ref(&plan).to_hex()]), "the reviewed plan");
4783
    let mut repo = [0u8; 16];
4784
    repo.copy_from_slice(&hex::decode(v["repo"].as_str().unwrap()).unwrap());
4785
    let oref = |k: &str| ObjectRef::from_hex(v[k].as_str().unwrap()).unwrap();
4786
    let statement = Statement {
4787
        repo,
4788
        run: v["run"].as_str().unwrap().into(),
4789
        job: "apply".into(),
4790
        job_hash: oref("job_hash"),
4791
        state: oref("state"),
4792
        inputs: v["inputs"].as_array().unwrap().iter().map(|i| ObjectRef::from_hex(i.as_str().unwrap()).unwrap()).collect(),
4793
        environment: "prod".into(),
4794
        approve: true,
4795
    };
4796
    let seal = |s: &Statement, key: &SecretKey, id: &oxy_core::identity::Identity| {
4797
        let body = serde_json::json!({ "signed": hex::encode(SignedApproval::sign(s, id, key).encode()) }).to_string();
4798
        let app = h.app.clone();
4799
        let path = format!("/api/v1/repos/andy/infra/flow/runs/{}/jobs/apply/seal", run.number);
4800
        async move { call(&app, "POST", &path, Some("site"), Some(body)).await }
4801
    };
4802
    // Another plan, or a key linked to nobody (an agent's), is refused.
4803
    let other_plan = Statement { inputs: vec![ObjectRef([9; 32])], ..statement.clone() };
4804
    let (st, body) = seal(&other_plan, &sk, &carol_id).await;
4805
    assert!(st == StatusCode::CONFLICT && body.contains("approves something else"), "{st} {body}");
4806
    let agent = SecretKey::generate();
4807
    let agent_id = agent.identity("Claude Code", "[email protected]", 1);
4808
    let (st, body) = seal(&statement, &agent, &agent_id).await;
4809
    assert!(st == StatusCode::CONFLICT && body.contains("not linked to an account"), "{st} {body}");
4810
    assert!(claim(&h.app).await.is_none(), "still waiting");
4811
317d776c Andy McCall ↶ 4812
    // A key that claims Carol's as its predecessor but has other keys: refused.
4813
    let forged = oxy_core::identity::Identity { previous: Some(carol_id.hash()), ..agent_id.clone() };
4814
    let (st, body) = seal(&statement, &agent, &forged).await;
4815
    assert!(st == StatusCode::CONFLICT && body.contains("not linked"), "{st} {body}");
4816
4817
    // Carol's seal, by a renewal of her linked key never linked itself
4818
    // (oxygenhub#236), releases it and links it; it is kept in the
4819
    // repository; the token names her and it.
4820
    let renewed = carol_id.successor(vec![], None, 2);
4821
    let (st, body) = seal(&statement, &sk, &renewed).await;
47e37402 Andy McCall ↶ 4822
    assert_eq!(st, StatusCode::OK, "{body}");
317d776c Andy McCall ↶ 4823
    assert!(
4824
        db::accounts::identity_by_key(&h.app.db, &renewed.hash().to_hex()).await.unwrap().is_some_and(|l| l.account_id == carol.id),
4825
        "linked now"
4826
    );
47e37402 Andy McCall ↶ 4827
    assert!(body.contains("approved by carol, sealed"), "{body}");
4828
    let name = oxygenhub::repos::RepoName::parse("andy/infra").unwrap();
4829
    let state = statement.state;
4830
    let kept = h.app.repos.read(&name, move |r, _| Ok(r.store().approvals_for(&state)?)).await.unwrap();
4831
    assert_eq!(kept.len(), 1, "the approval is in the repository");
4832
    let j = claim(&h.app).await.expect("released");
4833
    assert_eq!(j["job"]["name"], "apply");
4834
    let token =
4835
        j["secrets"].as_array().unwrap().iter().find(|s| s["path"] == "/run/secrets/cloud").unwrap()["value"].as_str().unwrap().to_string();
4836
    let claims = h.app.oidc().await.unwrap().verify(&token, "https://sts.example", db::now_ms()).unwrap();
4837
    assert_eq!((claims["environment"].as_str(), claims["approved_by"].as_str()), (Some("prod"), Some("carol")));
4838
    assert_eq!(claims["approval"].as_str(), Some(kept[0].to_hex().as_str()));
4839
    let (_, page) = call(&h.app, "GET", &format!("/andy/infra/flow/{}", run.number), None, None).await;
4840
    assert!(page.contains("sealed with their key"), "the run page says so");
4841
}
55673c65 Andy McCall ↶ 4842
4843
/// Repositories take turns (oxygenhub#244): a repository with a job running
4844
/// waits behind one with none, so a burst can't hold up the rest.
4845
#[tokio::test(flavor = "multi_thread")]
4846
async fn repositories_take_turns_on_the_runners() {
4847
    let h = hub().await;
4848
    for name in ["busy", "quiet"] {
4849
        create(&h.app, "andy", name).await;
4850
        let work = tempfile::tempdir().unwrap();
4851
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
4852
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4853
        write(work.path(), "test.sh", "echo ok\n");
4854
        c.snapshot("test").unwrap();
4855
        c.commit("Add a pipeline", &[]).unwrap();
4856
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4857
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
4858
    }
4859
    // busy pushed first: its first job goes first; then quiet's turn, though
4860
    // busy's other independent job is older; then busy's again.
4861
    let order: Vec<String> = {
4862
        let mut out = Vec::new();
4863
        for _ in 0..3 {
4864
            let c = claim(&h.app).await.expect("a job to claim");
4865
            out.push(c["repo"].as_str().unwrap().to_string());
4866
        }
4867
        out
4868
    };
4869
    assert_eq!(order, ["andy/busy", "andy/quiet", "andy/busy"]);
4870
}
107eaba5 Andy McCall ↶ 4871
53a0fb2e Andy McCall ↶ 4872
/// A pipeline lowers its jobs, never raises them (oxygenhub#244): a
4873
/// repository whose pipeline says `priority "low"` waits for another's
4874
/// everyday jobs, even set high itself; the queue says why; an expedited
4875
/// run is still urgent.
4876
#[tokio::test(flavor = "multi_thread")]
4877
async fn a_pipeline_lowers_its_jobs_and_expediting_still_wins() {
4878
    let h = hub().await;
4879
    for (name, extra) in [("nightly", "priority \"low\"\n"), ("everyday", "")] {
4880
        create(&h.app, "andy", name).await;
4881
        let work = tempfile::tempdir().unwrap();
4882
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
4883
        write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
4884
        write(work.path(), "test.sh", "echo ok\n");
4885
        c.snapshot("test").unwrap();
4886
        c.commit("Add a pipeline", &[]).unwrap();
4887
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4888
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
4889
    }
4890
    let nightly = db::repos::get(&h.app.db, "andy", "nightly").await.unwrap().unwrap();
4891
    db::repos::set_flow_priority(&h.app.db, nightly.id, "high").await.unwrap();
4892
    let q = db::flow::queue(&h.app.db).await.unwrap();
4893
    assert!(
4894
        q.iter().filter(|e| e.name == "nightly").all(|e| e.priority() == "low" && e.priority_note == "pipeline: low"),
4895
        "{:?}",
4896
        q.iter().map(|e| (&e.name, e.priority(), &e.priority_note)).collect::<Vec<_>>()
4897
    );
4898
    let repo_of = |c: serde_json::Value| c["repo"].as_str().unwrap().to_string();
4899
    // nightly pushed first and its repository is high, but its pipeline
4900
    // says low: everyday's jobs go first.
4901
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/everyday");
4902
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/everyday");
4903
    let run = &runs_of(&h.app, "andy", "nightly").await[0];
4904
    assert!(db::flow::expedite(&h.app.db, run.id, "expedited by andy: needed now").await.unwrap());
4905
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/nightly", "an expedited run is urgent whatever its jobs say");
4906
}
4907
107eaba5 Andy McCall ↶ 4908
/// Priority comes before taking turns (oxygenhub#244): a low repository's
4909
/// jobs wait for a normal one's, and an expedited run goes first of all.
4910
#[tokio::test(flavor = "multi_thread")]
4911
async fn priority_then_turns_and_an_expedited_run_first() {
4912
    let h = hub().await;
4913
    for name in ["early", "later"] {
4914
        create(&h.app, "andy", name).await;
4915
        let work = tempfile::tempdir().unwrap();
4916
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
4917
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4918
        write(work.path(), "test.sh", "echo ok\n");
4919
        c.snapshot("test").unwrap();
4920
        c.commit("Add a pipeline", &[]).unwrap();
4921
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4922
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
4923
    }
4924
    let early = db::repos::get(&h.app.db, "andy", "early").await.unwrap().unwrap();
4925
    db::repos::set_flow_priority(&h.app.db, early.id, "low").await.unwrap();
4926
    // early pushed first, but it is low: later's jobs go first.
4927
    let repo_of = |c: serde_json::Value| c["repo"].as_str().unwrap().to_string();
4928
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/later");
4929
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/later");
4930
    // Expedited, early's run goes before anything else.
4931
    let run = &runs_of(&h.app, "andy", "early").await[0];
4932
    assert!(db::flow::expedite(&h.app.db, run.id, "expedited by andy: an incident").await.unwrap());
76f93eae Andy McCall ↶ 4933
    // What the cap on expedited runs counts: andy's live urgent runs.
4934
    assert_eq!(db::flow::expedited_live(&h.app.db, "andy").await.unwrap(), 1);
4935
    assert_eq!(db::flow::expedited_live(&h.app.db, "someone-else").await.unwrap(), 0);
107eaba5 Andy McCall ↶ 4936
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/early");
4937
    let q = db::flow::queue(&h.app.db).await.unwrap();
4938
    assert!(
4939
        q.iter().any(|e| e.name == "early" && e.priority() == "urgent" && e.priority_note.contains("an incident")),
4940
        "{:?}",
4941
        q.iter().map(|e| (&e.name, e.priority())).collect::<Vec<_>>()
4942
    );
4943
    // The site's level is the default for everyone else.
4944
    db::accounts::set_setting(&h.app.db, "flow_priority", "high").await.unwrap();
4945
    let q = db::flow::queue(&h.app.db).await.unwrap();
4946
    assert!(q.iter().filter(|e| e.name == "later").all(|e| e.priority() == "high"));
4947
}
026a76d2 Andy McCall ↶ 4948
4949
/// Keyless (oxygenhub#241): a running job's token gets a ten-minute
4950
/// certificate for a fresh key from the hub, signed with the hub's key and
4951
/// naming the job's repository and bookmark; a proof made for another
4952
/// credential, an OIDC token for another audience, and a finished job's
4953
/// token get nothing.
4954
#[tokio::test(flavor = "multi_thread")]
4955
async fn a_running_job_gets_a_short_certificate_for_a_fresh_key() {
4956
    use oxy_core::cert::{certify_challenge, SignedCertificate};
4957
    use oxy_core::identity::{Scope, SecretKey};
4958
    let h = hub().await;
4959
    create(&h.app, "andy", "demo").await;
4960
    let work = tempfile::tempdir().unwrap();
4961
    let c = client(&format!("{}/andy/demo", h.base), work.path());
4962
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4963
    write(work.path(), "test.sh", "echo ok\n");
4964
    c.snapshot("test").unwrap();
4965
    c.commit("Add a pipeline", &[]).unwrap();
4966
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4967
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
4968
    let job = claim(&h.app).await.expect("a job");
4969
    let token = job["token"].as_str().unwrap().to_string();
4970
    let job_id = job["job_id"].as_i64().unwrap();
4971
4972
    let sk = SecretKey::generate();
4973
    let id = sk.identity("job", "[email protected]", 1);
4974
    let ask = |credential: &str, signed_for: &str| {
4975
        let proof = sk.sign_challenge(&id.hash(), &certify_challenge(signed_for)).unwrap();
4976
        let body = serde_json::json!({
4977
            "identity": oxy_core::dsse::base64(&id.encode()),
4978
            "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
4979
            "scope": "changes,refs",
4980
        });
4981
        let (credential, app) = (credential.to_string(), h.app.clone());
4982
        async move { call(&app, "POST", "/api/v1/keyless/certify", Some(&credential), Some(body.to_string())).await }
4983
    };
4984
    let (st, body) = ask(&token, &token).await;
4985
    assert_eq!(st, StatusCode::OK, "{body}");
4986
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
4987
    let sc = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
4988
    assert!(sc.verify(&h.app.hub_key.identity).is_ok(), "signed with the hub's key");
4989
    assert_eq!(sc.cert.key_id(), id.hash());
4990
    assert_eq!(sc.cert.subject, "repo:andy/demo:bookmark:main");
4991
    assert_eq!(sc.cert.claim("repository"), Some("andy/demo"));
4992
    assert!(sc.cert.claim("job").is_some() && sc.cert.claim("run") == Some("1"));
4993
    assert_eq!(sc.cert.scope, Scope::CHANGES | Scope::REFS);
4994
    assert!(sc.cert.expires - sc.cert.not_before <= 10 * 60_000 + 30_000, "ten minutes");
4995
4996
    // A proof made for another credential is not this one's.
4997
    let (st, body) = ask(&token, "flowjob_someone_else").await;
4998
    assert_eq!(st, StatusCode::UNAUTHORIZED, "{body}");
4999
    assert!(body.contains("the proof does not show"), "{body}");
5000
5001
    // The hub's own OIDC token, for the keyless audience, works too; for
5002
    // another audience it does not.
5003
    let issuer = h.app.oidc().await.unwrap();
5004
    let now = oxygenhub::db::now_ms();
5005
    let aud = oxygenhub::keyless::audience(h.app.config.base_url());
5006
    let good = issuer.mint_for(h.app.config.base_url(), "agent:claude@andy", &aud, now, 600);
5007
    let (st, body) = ask(&good, &good).await;
5008
    assert_eq!(st, StatusCode::OK, "{body}");
5009
    assert!(body.contains("\"subject\":\"agent:claude@andy\""), "{body}");
5010
    let other = issuer.mint_for(h.app.config.base_url(), "agent:claude@andy", "sts.amazonaws.com", now, 600);
5011
    let (st, _) = ask(&other, &other).await;
5012
    assert_eq!(st, StatusCode::UNAUTHORIZED);
5013
5014
    // A job that has finished asks with a token that no longer counts.
5015
    sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE id = $1").bind(job_id).execute(&h.app.db).await.unwrap();
5016
    let (st, body) = ask(&token, &token).await;
5017
    assert_eq!(st, StatusCode::UNAUTHORIZED, "{body}");
5018
}
2c31915f Andy McCall ↶ 5019
5020
/// Keyless step 3 (oxygenhub#241): a job signs its receipt with a fresh
5021
/// key the hub certified for it, and the hub keeps the receipt without
5022
/// binding any runner key; a certificate for another job, or from another
5023
/// issuer, is not this job's.
5024
#[tokio::test(flavor = "multi_thread")]
5025
async fn a_receipt_signed_by_a_certified_key_is_kept() {
5026
    use oxy_core::cert::{certify_challenge, SignedCertificate};
5027
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
5028
    use oxy_core::identity::SecretKey;
5029
    use oxy_core::objects::StateObject;
5030
    use oxy_core::receipt::SignedReceipt;
5031
    let h = hub().await;
5032
    create(&h.app, "andy", "demo").await;
5033
    let url = format!("{}/andy/demo", h.base);
5034
    let work = tempfile::tempdir().unwrap();
5035
    let c = client(&url, work.path());
5036
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5037
    c.snapshot("test").unwrap();
5038
    c.commit("Add a pipeline", &[]).unwrap();
5039
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5040
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
5041
    let heads: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
5042
    let state = hash_object(ObjectType::State, &StateObject::new(heads.clone()).encode());
5043
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
5044
5045
    // Certify a fresh key with a job's token, as a runner does just before
5046
    // it signs the receipt.
5047
    let certify = |token: String| {
5048
        let app = h.app.clone();
5049
        async move {
5050
            let sk = SecretKey::generate();
5051
            let id = sk.identity("test-1 job", "", 1);
5052
            let proof = sk.sign_challenge(&id.hash(), &certify_challenge(&token)).unwrap();
5053
            let body = serde_json::json!({
5054
                "identity": oxy_core::dsse::base64(&id.encode()),
5055
                "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
5056
                "scope": "seal",
5057
            });
5058
            let (st, body) = call(&app, "POST", "/api/v1/keyless/certify", Some(&token), Some(body.to_string())).await;
5059
            assert_eq!(st, StatusCode::OK, "{body}");
5060
            let v: serde_json::Value = serde_json::from_str(&body).unwrap();
5061
            let cert = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
5062
            (sk, id, cert)
5063
        }
5064
    };
5065
    let sign = |r: &serde_json::Value,
5066
                sk: &SecretKey,
5067
                id: &oxy_core::identity::Identity,
5068
                cert: SignedCertificate,
5069
                issuer: oxy_core::identity::Identity| {
5070
        let r: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
5071
        let run_url = format!("{url}/flow/{}", run.number);
5072
        hex::encode(SignedReceipt::sign(r.to_oxy(), repo_id, state, &run_url, id, sk).with_certificate(cert, issuer).encode())
5073
    };
5074
    let hub_id = h.app.hub_key.identity.clone();
5075
5076
    let a = claim(&h.app).await.unwrap();
5077
    let b = claim(&h.app).await.unwrap();
5078
    let ph = a["pipeline_hash"].as_str().unwrap().to_string();
5079
    let (a_name, b_name) = (a["job"]["name"].as_str().unwrap().to_string(), b["job"]["name"].as_str().unwrap().to_string());
5080
    let (a_id, b_id) = (a["job_id"].as_i64().unwrap(), b["job_id"].as_i64().unwrap());
5081
    let (sk_a, id_a, cert_a) = certify(a["token"].as_str().unwrap().to_string()).await;
5082
5083
    // Job b's receipt signed with job a's certified key: another job's.
5084
    let rb = receipt(&b_name, &ph, 0);
5085
    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()) });
5086
    assert_eq!(finish(&h.app, b_id, body).await, StatusCode::NO_CONTENT);
5087
    // Job a's, with its own certificate: kept.
5088
    let ra = receipt(&a_name, &ph, 0);
5089
    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()) });
5090
    assert_eq!(finish(&h.app, a_id, body).await, StatusCode::NO_CONTENT);
5091
5092
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
5093
    let job = |n: &str| jobs.iter().find(|j| j.name == n).unwrap().clone();
5094
    assert_eq!(job(&a_name).receipt_attest.len(), 64, "{}", job(&a_name).receipt_note);
5095
    assert!(job(&a_name).receipt_signer.ends_with("(short-lived key)"), "{}", job(&a_name).receipt_signer);
5096
    assert!(job(&b_name).receipt_attest.is_empty());
5097
    assert!(job(&b_name).receipt_note.contains("another run or job"), "{}", job(&b_name).receipt_note);
5098
    // The kept receipt carries its certificate, and verifies on its own.
5099
    let kept = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().receipts(&heads).unwrap();
5100
    assert_eq!(kept.len(), 1);
5101
    assert!(kept[0].problem.is_none() && kept[0].signed.certificate.is_some());
5102
5103
    // A certificate from another issuer, for the third job: not this hub's.
5104
    let t = claim(&h.app).await.unwrap();
5105
    let t_name = t["job"]["name"].as_str().unwrap().to_string();
5106
    let fake_sk = SecretKey::generate();
5107
    let fake = fake_sk.identity("not the hub", "", 1);
5108
    let (sk_t, id_t, mut cert_t) = certify(t["token"].as_str().unwrap().to_string()).await;
5109
    cert_t.cert.issuer = fake.hash();
5110
    let cert_t = SignedCertificate::sign(cert_t.cert, &fake, &fake_sk);
5111
    let rt = receipt(&t_name, &ph, 0);
5112
    let body =
5113
        serde_json::json!({ "exit_code": 0, "duration_ms": 500, "receipt": rt, "signed_receipt": sign(&rt, &sk_t, &id_t, cert_t, fake) });
5114
    assert_eq!(finish(&h.app, t["job_id"].as_i64().unwrap(), body).await, StatusCode::NO_CONTENT);
5115
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
5116
    let t_job = jobs.iter().find(|j| j.name == t_name).unwrap();
5117
    assert!(t_job.receipt_note.contains("not issued by this hub"), "{}", t_job.receipt_note);
5118
}
3eb491e9 Andy McCall ↶ 5119
24472413 Andy McCall ↶ 5120
/// oxygenhub#241: a release asset whose receipt a short-lived key signed,
5121
/// certified by this hub for the job, is an attested build of a known
5122
/// signer on the release's trust report (it was "not one this hub's
5123
/// runners use" with 0.4.5).
5124
#[tokio::test(flavor = "multi_thread")]
5125
async fn a_release_built_by_a_certified_key_is_attested() {
5126
    use oxy_core::cert::{certify_challenge, SignedCertificate};
5127
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
5128
    use oxy_core::identity::SecretKey;
5129
    use oxy_core::objects::StateObject;
5130
    use oxy_core::receipt::SignedReceipt;
5131
    let h = hub().await;
5132
    create(&h.app, "andy", "demo").await;
5133
    let url = format!("{}/andy/demo", h.base);
5134
    let work = tempfile::tempdir().unwrap();
5135
    let mut c = client(&url, work.path());
5136
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5137
    write(
5138
        work.path(),
5139
        ".flow/pipeline.kdl",
5140
        &format!(
5141
            "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"
5142
        ),
5143
    );
5144
    c.snapshot("test").unwrap();
5145
    c.commit("Build a tool", &[]).unwrap();
5146
    let heads = c.bookmark_heads().unwrap();
5147
    c.tag_create("v1", &heads, "first").unwrap();
5148
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5149
5150
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
5151
    let a = claim(&h.app).await.unwrap();
5152
    let id = a["job_id"].as_i64().unwrap();
5153
    let token = a["token"].as_str().unwrap().to_string();
5154
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
5155
    let (_, text) = upload(&h.app, id, "tool", &body).await;
5156
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
5157
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
5158
    r["outputs"] = serde_json::json!([blob]);
5159
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
5160
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
5161
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
5162
    // The job's fresh key, certified with its token.
5163
    let sk = SecretKey::generate();
5164
    let key = sk.identity("test-1 job", "", 1);
5165
    let proof = sk.sign_challenge(&key.hash(), &certify_challenge(&token)).unwrap();
5166
    let ask = serde_json::json!({
5167
        "identity": oxy_core::dsse::base64(&key.encode()),
5168
        "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
5169
        "scope": "seal",
5170
    });
5171
    let (st, answer) = call(&h.app, "POST", "/api/v1/keyless/certify", Some(&token), Some(ask.to_string())).await;
5172
    assert_eq!(st, StatusCode::OK, "{answer}");
5173
    let v: serde_json::Value = serde_json::from_str(&answer).unwrap();
5174
    let cert = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
5175
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
5176
    let signed = hex::encode(
5177
        SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/{}", run.number), &key, &sk)
5178
            .with_certificate(cert, h.app.hub_key.identity.clone())
5179
            .encode(),
5180
    );
5181
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
5182
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
5183
5184
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
5185
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
5186
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
5187
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
5188
    assert_eq!(st, StatusCode::OK);
5189
    for want in [
5190
        "tool: signed receipt from run #1 build",
5191
        "a short-lived key this hub certified for repo:andy/demo:bookmark:main",
5192
        "1 of 1 assets built and attested by OxygenFlow",
5193
    ] {
5194
        assert!(page.contains(want), "missing {want:?}");
5195
    }
5196
    assert!(!page.contains("not one this hub"), "not an unknown key");
5197
}
5198
965b950f Andy McCall ↶ 5199
/// The transparency log (oxygenhub#238): a push's reference attestation,
5200
/// seal and policy become entries; the checkpoint is signed by the hub's
5201
/// key; the tiles and entry bundles served rebuild the checkpoint's root;
5202
/// and the `/log` page lists them.
5203
#[tokio::test(flavor = "multi_thread")]
5204
async fn a_push_is_logged_and_the_log_checks_out() {
5205
    use oxy_core::tlog::{self, Checkpoint, Entry, Hash, Note, Tile};
5206
    let h = hub().await;
5207
    create(&h.app, "andy", "demo").await;
5208
    let url = format!("{}/andy/demo", h.base);
5209
    let work = tempfile::tempdir().unwrap();
5210
    let mut c = client(&url, work.path());
5211
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5212
    write(work.path(), "a.txt", "a\n");
5213
    c.commit("a", &[]).unwrap();
5214
    c.policy_init().unwrap();
5215
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5216
    let host = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
5217
    let (attest, _) = host.latest_ref_attest("main").unwrap().unwrap();
5218
5219
    // Sign a checkpoint now rather than wait for the next tick.
5220
    let (_, sk) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
5221
    h.app.tlog.refresh_checkpoint(&h.app.hub_key.identity, &sk).unwrap();
5222
    let (st, note) = call(&h.app, "GET", "/log/checkpoint", None, None).await;
5223
    assert_eq!(st, StatusCode::OK, "{note}");
5224
    let origin = oxygenhub::tlog::origin_of(h.app.config.base_url());
5225
    let cp = Checkpoint::verify(&Note::parse(&note).unwrap(), &origin, &h.app.hub_key.identity).unwrap();
5226
    assert!(cp.size >= 3, "ref, seal and policy: {}", cp.size);
5227
5228
    // The entries, from the bundle beside the partial level-0 tile.
5229
    let bundle_path = Tile { level: 0, n: 0, width: cp.size as u32 }.entries_path();
5230
    let (st, _) = call(&h.app, "GET", &format!("/log/{bundle_path}"), None, None).await;
5231
    assert_eq!(st, StatusCode::OK);
5232
    let res =
5233
        oxygenhub::router(h.app.clone()).oneshot(Request::get(format!("/log/{bundle_path}")).body(Body::empty()).unwrap()).await.unwrap();
5234
    assert_eq!(res.headers()[header::CACHE_CONTROL], "public, max-age=5", "a partial tile changes");
5235
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
5236
    let entries: Vec<Entry> = tlog::decode_bundle(&bytes).unwrap().iter().map(|b| Entry::decode(b).unwrap()).collect();
5237
    let kinds: Vec<&str> = entries.iter().map(|e| e.kind.as_str()).collect();
5238
    assert!(kinds.contains(&"ref") && kinds.contains(&"seal") && kinds.contains(&"policy"), "{kinds:?}");
5239
    let r = entries.iter().find(|e| e.kind == "ref").unwrap();
5240
    assert_eq!(r.object, attest);
5241
    assert_eq!(r.repo, c.id().unwrap());
5242
5243
    // The leaves rebuild the checkpoint's root, and the hash tile served
5244
    // is what they make.
5245
    let mut stored: Vec<Hash> = Vec::new();
5246
    for (n, e) in entries.iter().enumerate() {
5247
        stored.extend(tlog::stored_hashes_for_leaf(n as u64, e.leaf_hash(), &stored).unwrap());
5248
    }
5249
    assert_eq!(tlog::tree_hash(cp.size, &stored).unwrap(), cp.root);
5250
    let t = Tile { level: 0, n: 0, width: cp.size as u32 };
5251
    let res =
5252
        oxygenhub::router(h.app.clone()).oneshot(Request::get(format!("/log/{}", t.path())).body(Body::empty()).unwrap()).await.unwrap();
5253
    assert_eq!(res.status(), StatusCode::OK);
5254
    let data = res.into_body().collect().await.unwrap().to_bytes();
5255
    assert_eq!(data.to_vec(), t.read_data(&stored).unwrap());
5256
    let (st, _) = call(&h.app, "GET", "/log/tile/0/000.p/200", None, None).await;
5257
    assert_eq!(st, StatusCode::NOT_FOUND, "not held yet");
5258
5259
    // Pushing the same again logs nothing new.
5260
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5261
    assert_eq!(h.app.tlog.size(), cp.size);
5262
    let (st, page) = call(&h.app, "GET", "/log", None, None).await;
5263
    assert_eq!(st, StatusCode::OK);
5264
    assert!(page.contains("Transparency log") && page.contains("andy/demo") && page.contains(&origin), "{page}");
5265
}
5266
e5b97ac3 Andy McCall ↶ 5267
/// Fetching checks the hub's log (oxygenhub#238, step A3): the checkpoint
5268
/// comes with the refs, each attestation with its entry and inclusion
5269
/// proof; a later checkpoint is proved to extend the one seen before, from
5270
/// the hub's tiles; an attestation not in a checkpoint yet is a note; and a
5271
/// log that does not extend what this user saw fails the fetch.
5272
#[tokio::test(flavor = "multi_thread")]
5273
async fn a_fetch_checks_the_hub_s_log_and_refuses_a_fork() {
5274
    use oxy_core::tlog::{Checkpoint, Note};
5275
    let h = hub().await;
5276
    create(&h.app, "andy", "demo").await;
5277
    let url = format!("{}/andy/demo", h.base);
5278
    let work = tempfile::tempdir().unwrap();
5279
    let mut a = client(&url, &work.path().join("a"));
5280
    a.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5281
    let (_, sk) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
5282
    let hub_id = h.app.hub_key.identity.clone();
5283
    let checkpoint = || h.app.tlog.refresh_checkpoint(&hub_id, &sk).unwrap();
5284
    let mut n = 0;
5285
    let mut push = |a: &Repo| {
5286
        n += 1;
5287
        write(&work.path().join("a"), "a.txt", &format!("{n}\n"));
5288
        a.commit(&format!("change {n}"), &[]).unwrap();
5289
        assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
5290
    };
5291
    push(&a);
5292
    checkpoint();
5293
5294
    let home = work.path().join("home-b");
5295
    let b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(home.clone());
5296
    let report = b.fetch("origin").unwrap();
5297
    assert!(report.log_notes.is_empty(), "{:?}", report.log_notes);
5298
    let pin = std::fs::read_dir(home.join("tlog")).unwrap().next().unwrap().unwrap().path();
5299
    let seen = |p: &std::path::Path| {
5300
        let t = std::fs::read_to_string(p).unwrap();
5301
        Checkpoint::parse(&Note::parse(t.split_once('\n').unwrap().1).unwrap().text).unwrap()
5302
    };
5303
    let first = seen(&pin);
5304
5305
    // A later checkpoint: proved to extend the first from the tiles.
5306
    push(&a);
5307
    checkpoint();
5308
    let report = b.fetch("origin").unwrap();
5309
    assert!(report.log_notes.is_empty(), "{:?}", report.log_notes);
5310
    assert!(seen(&pin).size > first.size);
5311
5312
    // Pushed after the last checkpoint: not provable yet, only a note.
5313
    push(&a);
5314
    let report = b.fetch("origin").unwrap();
5315
    assert!(report.log_notes.iter().any(|n| n.contains("not in its transparency log yet")), "{:?}", report.log_notes);
5316
7dbb41b0 Andy McCall ↶ 5317
    // A log key other than the one pinned (a hub given a new key, or a
5318
    // port reused by another hub): a note, and the new key pinned.
5319
    let text = std::fs::read_to_string(&pin).unwrap();
5320
    let other_sk = oxy_core::identity::SecretKey::generate();
5321
    let other = other_sk.identity("another hub", "[email protected]", 1);
5322
    let note = text.split_once('\n').unwrap().1;
5323
    std::fs::write(&pin, format!("{}\n{note}", oxy_core::dsse::base64(&other.encode()))).unwrap();
5324
    let report = b.fetch("origin").unwrap();
5325
    assert!(report.log_notes.iter().any(|n| n.contains("signed by another key")), "{:?}", report.log_notes);
5326
    let report = b.fetch("origin").unwrap();
5327
    assert!(!report.log_notes.iter().any(|n| n.contains("another key")), "pinned now: {:?}", report.log_notes);
5328
e5b97ac3 Andy McCall ↶ 5329
    // What this user saw replaced by another log of the same size, signed
5330
    // by the hub's own key: the hub's real log does not extend it.
5331
    let size = seen(&pin).size;
5332
    let forged = Checkpoint { origin: oxygenhub::tlog::origin_of(h.app.config.base_url()), size, root: [7; 32], extensions: vec![] };
5333
    let text = std::fs::read_to_string(&pin).unwrap();
5334
    let key = text.split_once('\n').unwrap().0;
5335
    std::fs::write(&pin, format!("{key}\n{}", forged.sign(&hub_id, &sk).unwrap().encode())).unwrap();
5336
    checkpoint();
5337
    let err = b.fetch("origin").unwrap_err().to_string();
5338
    assert!(err.contains("showed two histories") && err.contains("does not extend"), "{err}");
5339
}
5340
4f40eed0 Andy McCall ↶ 5341
/// Witnesses (oxygenhub#238, step A5): one hub cosigns another's
5342
/// checkpoints when each extends the last it cosigned, and the log serves
5343
/// the cosignatures with its checkpoint; the witness refuses a fork (422),
5344
/// tells a log that guessed its size wrong (409), and knows only the logs
5345
/// it was told to witness (404).
5346
#[tokio::test(flavor = "multi_thread")]
5347
async fn a_hub_witnesses_another_hub_s_log() {
5348
    use oxy_core::tlog::{AddCheckpoint, Checkpoint, Note};
5349
    let log = hub().await;
5350
    let witness = hub().await;
5351
    let origin = oxygenhub::tlog::origin_of(log.app.config.base_url());
5352
    witness.app.tlog.add_witness_for(&origin, log.app.hub_key.identity.clone());
5353
    let name = witness.app.tlog.witness_name().to_string();
5354
    log.app.tlog.set_witnesses(vec![oxygenhub::tlog::Peer {
5355
        name: name.clone(),
5356
        url: format!("{}/log/witness/add-checkpoint", witness.base),
5357
        identity: witness.app.hub_key.identity.clone(),
5358
    }]);
5359
    create(&log.app, "andy", "demo").await;
5360
    let work = tempfile::tempdir().unwrap();
5361
    let mut c = client(&format!("{}/andy/demo", log.base), work.path());
5362
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5363
    let (_, sk) = oxygenhub::keys::load_secret(&log.app.config.keys_dir()).unwrap();
5364
    let log_id = log.app.hub_key.identity.clone();
5365
    let wid = witness.app.hub_key.identity.clone();
5366
    for n in 0..2 {
5367
        write(work.path(), "a.txt", &format!("{n}\n"));
5368
        c.commit(&format!("change {n}"), &[]).unwrap();
5369
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5370
        log.app.tlog.refresh_checkpoint(&log_id, &sk).unwrap();
5371
        oxygenhub::tlog::collect(&log.app).await;
5372
        let note = Note::parse(&log.app.tlog.checkpoint().unwrap()).unwrap();
5373
        assert!(note.cosigned_by(&name, &wid).is_ok(), "round {n}: {}", note.encode());
5374
        // Served as such.
5375
        let (_, served) = call(&log.app, "GET", "/log/checkpoint", None, None).await;
5376
        assert!(Note::parse(&served).unwrap().cosigned_by(&name, &wid).is_ok());
5377
    }
5378
    let cp = Checkpoint::parse(&Note::parse(&log.app.tlog.checkpoint().unwrap()).unwrap().text).unwrap();
13b27cb2 Andy McCall ↶ 5379
5380
    // Trusted time (#240): the log lists its witnesses, and a fetch's refs
5381
    // carry, for a logged bookmark, the cosigned checkpoints that first held
5382
    // its entry, from which the client takes the integrated time.
5383
    let (_, listed) = call(&log.app, "GET", "/log/witnesses", None, None).await;
5384
    assert!(listed.starts_with(&format!("{name} ")), "{listed}");
5385
    let url = format!("{}/andy/demo", log.base);
5386
    let refs = tokio::task::spawn_blocking(move || {
5387
        let opts = RemoteOptions { token: Some("site".into()), ..Default::default() };
5388
        open_remote(&url, &opts).unwrap().refs().unwrap()
5389
    })
5390
    .await
5391
    .unwrap();
5392
    assert_eq!(refs.witnesses.len(), 1);
5393
    assert_eq!(refs.witnesses[0].0, name);
5394
    let main = refs.refs.iter().find(|r| r.name == "main").expect("main");
5395
    let logged = main.logged.as_ref().expect("logged");
5396
    assert!(!main.integration.is_empty(), "a witnessed checkpoint holds it");
5397
    let cosigned: Vec<(&str, &[[u8; 32]])> = main.integration.iter().map(|i| (i.note.as_str(), i.proof.as_slice())).collect();
5398
    let at = oxy_core::tlog::integrated_time(&logged.entry, logged.index, &cosigned, &origin, &log_id, &[(name.clone(), wid.clone())])
5399
        .expect("an integrated time");
5400
    assert_eq!(at.witness, name);
5401
    assert!(at.size > logged.index);
4f40eed0 Andy McCall ↶ 5402
5403
    let ask = |req: AddCheckpoint| {
5404
        let app = witness.app.clone();
5405
        async move { call(&app, "POST", "/log/witness/add-checkpoint", None, Some(req.encode())).await }
5406
    };
5407
    // Another log of the same size, signed by the log's own key: a fork.
5408
    let forked = Checkpoint { root: [7; 32], ..cp.clone() }.sign(&log_id, &sk).unwrap().encode();
5409
    let (st, body) = ask(AddCheckpoint { old_size: cp.size, proof: vec![], note: forked.clone() }).await;
5410
    assert_eq!(st, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
5411
    // A wrong idea of what the witness saw: its size, to try again from.
5412
    let (st, body) = ask(AddCheckpoint { old_size: 1, proof: vec![], note: forked }).await;
5413
    assert_eq!((st, body.trim()), (StatusCode::CONFLICT, cp.size.to_string().as_str()));
5414
    // A log it was not told to witness.
5415
    let stranger = oxy_core::identity::SecretKey::generate();
5416
    let sid = stranger.identity("elsewhere", "[email protected]", 1);
5417
    let other = Checkpoint { origin: "elsewhere.example/log".into(), ..cp.clone() }.sign(&sid, &stranger).unwrap().encode();
5418
    let (st, _) = ask(AddCheckpoint { old_size: 0, proof: vec![], note: other }).await;
5419
    assert_eq!(st, StatusCode::NOT_FOUND);
5420
}
5421
8dcaeeb8 Andy McCall ↶ 5422
/// Terraform state (oxygenhub#252): the HTTP backend's calls as
5423
/// Terraform and OpenTofu make them, with a running job's token as the
5424
/// Basic-auth password; the lock is honoured, versions are kept, the state
5425
/// is sealed at rest, and another repository's job is refused.
5426
#[tokio::test(flavor = "multi_thread")]
5427
async fn a_job_keeps_its_terraform_state_on_the_hub() {
5428
    let h = hub().await;
5429
    create(&h.app, "andy", "infra").await;
5430
    create(&h.app, "andy", "other").await;
5431
    let work = tempfile::tempdir().unwrap();
5432
    let c = client(&format!("{}/andy/infra", h.base), work.path());
5433
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5434
    write(work.path(), "test.sh", "echo ok\n");
5435
    c.snapshot("test").unwrap();
5436
    c.commit("Add a pipeline", &[]).unwrap();
5437
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5438
    assert_eq!(runs_of(&h.app, "andy", "infra").await.len(), 1);
5439
    let job = claim(&h.app).await.expect("a job");
5440
    let token = job["token"].as_str().unwrap().to_string();
5441
    let basic = format!("Basic {}", oxy_core::dsse::base64(format!("flow:{token}").as_bytes()));
5442
    let path = "/api/v1/repos/andy/infra/terraform/state/prod";
5443
    let send = |method: &str, uri: String, auth: Option<String>, body: &str| {
5444
        let mut req = Request::builder().method(method).uri(uri);
5445
        if let Some(a) = auth {
5446
            req = req.header(header::AUTHORIZATION, a);
5447
        }
5448
        let req = req.body(Body::from(body.to_string())).unwrap();
5449
        let app = h.app.clone();
5450
        async move {
5451
            let res = oxygenhub::router(app).oneshot(req).await.unwrap();
5452
            let st = res.status();
5453
            let b = res.into_body().collect().await.unwrap().to_bytes();
5454
            (st, String::from_utf8_lossy(&b).into_owned())
5455
        }
5456
    };
5457
    let lock = r#"{"ID":"lock-1","Operation":"OperationTypeApply","Who":"flow@runner","Version":"1.8.0"}"#;
5458
    // No state yet; no token, nothing.
5459
    assert_eq!(send("GET", path.into(), None, "").await.0, StatusCode::UNAUTHORIZED);
5460
    assert_eq!(send("GET", path.into(), Some(basic.clone()), "").await.0, StatusCode::NO_CONTENT);
5461
    // Lock, write under the lock, unlock.
5462
    let (st, body) = send("LOCK", path.into(), Some(basic.clone()), lock).await;
5463
    assert_eq!(st, StatusCode::OK, "{body}");
5464
    let other_lock = r#"{"ID":"lock-2","Operation":"OperationTypePlan"}"#;
5465
    let (st, held) = send("LOCK", path.into(), Some(basic.clone()), other_lock).await;
5466
    assert_eq!(st, StatusCode::LOCKED);
5467
    assert!(held.contains("lock-1"), "the holder's lock info: {held}");
5468
    let state1 = r#"{"version":4,"serial":1,"lineage":"l","resources":[{"secret":"hunter2"}]}"#;
5469
    assert_eq!(send("POST", path.into(), Some(basic.clone()), state1).await.0, StatusCode::LOCKED, "not under its lock");
5470
    assert_eq!(send("POST", format!("{path}?ID=lock-1"), Some(basic.clone()), state1).await.0, StatusCode::OK);
5471
    assert_eq!(send("UNLOCK", path.into(), Some(basic.clone()), other_lock).await.0, StatusCode::CONFLICT, "not its lock");
5472
    assert_eq!(send("UNLOCK", path.into(), Some(basic.clone()), lock).await.0, StatusCode::OK);
5473
    let (st, got) = send("GET", path.into(), Some(basic.clone()), "").await;
5474
    assert_eq!((st, got.as_str()), (StatusCode::OK, state1));
5475
    // A second write keeps the first as a version; the body is sealed.
5476
    let state2 = state1.replace("\"serial\":1", "\"serial\":2");
5477
    assert_eq!(send("POST", path.into(), Some(basic.clone()), &state2).await.0, StatusCode::OK);
5478
    let row = db::repos::get(&h.app.db, "andy", "infra").await.unwrap().unwrap();
5479
    assert_eq!(db::terraform::versions(&h.app.db, row.id, "prod").await.unwrap(), 1);
5480
    let kept = db::terraform::get(&h.app.db, row.id, "prod").await.unwrap().unwrap();
5481
    assert_eq!(kept.serial, 2);
5482
    assert!(!String::from_utf8_lossy(&kept.body).contains("hunter2"), "sealed at rest");
5483
    // Another repository's state is not this job's; a bad name is refused.
5484
    let (st, _) = send("GET", "/api/v1/repos/andy/other/terraform/state/prod".into(), Some(basic.clone()), "").await;
5485
    assert_eq!(st, StatusCode::FORBIDDEN);
5486
    assert_eq!(
5487
        send("GET", "/api/v1/repos/andy/infra/terraform/state/..x".into(), Some(basic.clone()), "").await.0,
5488
        StatusCode::BAD_REQUEST
5489
    );
bb018142 Andy McCall ↶ 5490
    // A stranger reads a public repository, but not its state: states hold
5491
    // secrets (#256), so reading one needs the write role, whatever the token.
5492
    let mallory = db::accounts::create_account(&h.app.db, "mallory", "[email protected]", "x", "salt", false).await.unwrap();
5493
    let (secret, hash) = oxygenhub::auth::new_token();
5494
    db::accounts::create_token(&h.app.db, mallory.id, "cli", &hash, "repo:write", "", None).await.unwrap();
5495
    let (st, got) = send("GET", path.into(), Some(format!("Bearer {secret}")), "").await;
5496
    assert_eq!(st, StatusCode::FORBIDDEN, "{got}");
5497
    assert!(!got.contains("hunter2"));
5498
    let (_, page) = call(&h.app, "GET", "/andy/infra/terraform", Some(&secret), None).await;
5499
    assert!(!page.contains("<strong>prod</strong>") && page.contains("shown to people who can write"), "{page}");
8dcaeeb8 Andy McCall ↶ 5500
    // The site token is no person's: refused.
5501
    let (st, _) = send("GET", path.into(), Some("Bearer site".into()), "").await;
5502
    assert_eq!(st, StatusCode::UNAUTHORIZED, "the site token is not a person's token");
5503
    // A job's identity token for the Terraform audience, as its pipeline's
5504
    // identity block mounts it: its own repository only, that audience only.
5505
    let issuer = h.app.oidc().await.unwrap();
5506
    let now = db::now_ms();
5507
    let aud = oxygenhub::terraform::audience(h.app.config.base_url());
5508
    let own = issuer.mint_for(h.app.config.base_url(), "repo:andy/infra:bookmark:main", &aud, now, 600);
5509
    let (st, got) = send("GET", path.into(), Some(format!("Bearer {own}")), "").await;
5510
    assert_eq!((st, got.contains("\"serial\":2")), (StatusCode::OK, true));
5511
    let other = issuer.mint_for(h.app.config.base_url(), "repo:andy/other:bookmark:main", &aud, now, 600);
5512
    assert_eq!(send("GET", path.into(), Some(format!("Bearer {other}")), "").await.0, StatusCode::FORBIDDEN);
5513
    let elsewhere = issuer.mint_for(h.app.config.base_url(), "repo:andy/infra:bookmark:main", "sts.amazonaws.com", now, 600);
5514
    assert_eq!(send("GET", path.into(), Some(format!("Bearer {elsewhere}")), "").await.0, StatusCode::UNAUTHORIZED);
16ee5d19 Andy McCall ↶ 5515
    // Its page under Artifacts (#254) lists the state and the backend block.
bb018142 Andy McCall ↶ 5516
    // Its owner, signed in, sees the states.
5517
    let res = oxygenhub::router(h.app.clone())
5518
        .oneshot(
5519
            Request::post("/register")
5520
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
5521
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
5522
                .unwrap(),
5523
        )
5524
        .await
5525
        .unwrap();
5526
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
5527
    let res = oxygenhub::router(h.app.clone())
67523e06 Andy McCall ↶ 5528
        .oneshot(Request::get("/andy/infra/terraform").header(header::COOKIE, cookie.clone()).body(Body::empty()).unwrap())
bb018142 Andy McCall ↶ 5529
        .await
5530
        .unwrap();
5531
    let st = res.status();
5532
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
16ee5d19 Andy McCall ↶ 5533
    assert_eq!(st, StatusCode::OK, "{page}");
5534
    assert!(page.contains("<strong>prod</strong>") && page.contains("/api/v1/repos/andy/infra/terraform/state/NAME"), "{page}");
5535
    assert!(page.contains("allow &quot;") || page.contains("allow \""), "the egress line names the hub");
67523e06 Andy McCall ↶ 5536
    assert!(page.contains("1 kept version") && page.contains(">restore</button>"), "its versions, restorable by its owner: {page}");
5537
5538
    // Versions (#255) through the API: listed and read with the write role,
5539
    // restored with the maintain role (never by a job, never under a lock),
5540
    // as a new serial, so nothing is lost and going forward again works.
5541
    let andy = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap();
5542
    let (pat, hash) = oxygenhub::auth::new_token();
5543
    db::accounts::create_token(&h.app.db, andy.id, "cli", &hash, "repo:write", "", None).await.unwrap();
5544
    let bearer = format!("Bearer {pat}");
5545
    let (st, list) = send("GET", format!("{path}/versions"), Some(bearer.clone()), "").await;
5546
    assert_eq!(st, StatusCode::OK, "{list}");
5547
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
5548
    assert_eq!((list.as_array().unwrap().len(), list[0]["serial"].as_i64()), (1, Some(1)), "{list}");
5549
    let first = list[0]["id"].as_i64().unwrap();
5550
    let (st, got) = send("GET", format!("{path}/versions/{first}"), Some(bearer.clone()), "").await;
5551
    assert_eq!((st, got.as_str()), (StatusCode::OK, state1));
5552
    assert_eq!(send("GET", format!("{path}/versions"), Some(format!("Bearer {secret}")), "").await.0, StatusCode::FORBIDDEN, "a stranger");
5553
    let restore = |id: i64, auth: String| send("POST", format!("{path}/versions/{id}/restore"), Some(auth), "");
5554
    assert_eq!(restore(first, basic.clone()).await.0, StatusCode::FORBIDDEN, "a job does not restore");
5555
    assert_eq!(restore(first, format!("Bearer {secret}")).await.0, StatusCode::FORBIDDEN, "nor a stranger");
5556
    assert_eq!(restore(9999, bearer.clone()).await.0, StatusCode::NOT_FOUND);
5557
    assert_eq!(send("LOCK", path.into(), Some(basic.clone()), lock).await.0, StatusCode::OK);
5558
    assert_eq!(restore(first, bearer.clone()).await.0, StatusCode::LOCKED, "not under someone's lock");
5559
    assert_eq!(send("UNLOCK", path.into(), Some(basic.clone()), lock).await.0, StatusCode::OK);
5560
    let (st, got) = restore(first, bearer.clone()).await;
5561
    assert_eq!((st, got.contains("\"serial\":3")), (StatusCode::OK, true), "{got}");
5562
    let (_, now) = send("GET", path.into(), Some(bearer.clone()), "").await;
5563
    let now: serde_json::Value = serde_json::from_str(&now).unwrap();
5564
    assert_eq!(
5565
        (now["serial"].as_i64(), now["lineage"].as_str(), now["resources"][0]["secret"].as_str()),
5566
        (Some(3), Some("l"), Some("hunter2"))
5567
    );
5568
    // Forward again: serial 2 is a kept version now.
5569
    let (_, list) = send("GET", format!("{path}/versions"), Some(bearer.clone()), "").await;
5570
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
5571
    let serials: Vec<i64> = list.as_array().unwrap().iter().map(|v| v["serial"].as_i64().unwrap()).collect();
5572
    assert_eq!(serials, vec![2, 1], "{list}");
5573
    let (st, got) = restore(list[0]["id"].as_i64().unwrap(), bearer.clone()).await;
5574
    assert_eq!((st, got.contains("\"serial\":4")), (StatusCode::OK, true), "{got}");
5575
5576
    // And from the page: download a version, restore one with the form.
5577
    let page_with = |req: axum::http::request::Builder, body: Body| {
5578
        let (app, cookie) = (h.app.clone(), cookie.clone());
5579
        async move {
5580
            let res = oxygenhub::router(app).oneshot(req.header(header::COOKIE, cookie).body(body).unwrap()).await.unwrap();
5581
            let st = res.status();
5582
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
5583
        }
5584
    };
5585
    let (st, file) = page_with(Request::get(format!("/andy/infra/terraform/prod/download?version={first}")), Body::empty()).await;
5586
    assert_eq!((st, file.as_str()), (StatusCode::OK, state1));
5587
    let (_, page) = page_with(Request::get("/andy/infra/terraform"), Body::empty()).await;
5588
    let csrf = page.split("name=\"_csrf\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
5589
    let (st, page) = page_with(
5590
        Request::post("/andy/infra/terraform/prod/restore").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"),
5591
        Body::from(format!("_csrf={csrf}&version={first}")),
5592
    )
5593
    .await;
5594
    assert_eq!(st, StatusCode::OK, "{page}");
5595
    assert!(page.contains("Restored prod: it is now serial 5."), "{page}");
5596
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
5597
    assert_eq!(audit.iter().filter(|r| r.action == "terraform.restored").count(), 3, "every restore audited");
8dcaeeb8 Andy McCall ↶ 5598
}
5599
5600
/// The real OpenTofu against the backend (oxygenhub#252): init, apply,
5601
/// a second apply that changes nothing, all through the hub's state with a
5602
/// job's token. Needs Docker and the `oxygenflow-tofu` image; run with
5603
/// `cargo test -p oxygenhub --test flow -- --ignored tofu_keeps`.
5604
#[tokio::test(flavor = "multi_thread")]
5605
#[ignore]
5606
async fn tofu_keeps_its_state_on_the_hub() {
5607
    let h = hub().await;
5608
    create(&h.app, "andy", "infra").await;
5609
    let work = tempfile::tempdir().unwrap();
5610
    let c = client(&format!("{}/andy/infra", h.base), work.path());
5611
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5612
    write(work.path(), "test.sh", "echo ok\n");
5613
    c.snapshot("test").unwrap();
5614
    c.commit("Add a pipeline", &[]).unwrap();
5615
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5616
    assert_eq!(runs_of(&h.app, "andy", "infra").await.len(), 1);
5617
    let job = claim(&h.app).await.expect("a job");
5618
    let token = job["token"].as_str().unwrap().to_string();
5619
    let tf = tempfile::tempdir().unwrap();
5620
    let address = format!("{}/api/v1/repos/andy/infra/terraform/state/prod", h.base);
5621
    std::fs::write(
5622
        tf.path().join("main.tf"),
5623
        format!(
5624
            "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"
5625
        ),
5626
    )
5627
    .unwrap();
5628
    let tofu = |args: &[&str]| {
5629
        let out = std::process::Command::new("docker")
5630
            .args(["run", "--rm", "--network", "host", "-v"])
5631
            .arg(format!("{}:/w", tf.path().display()))
5632
            .args(["-w", "/w", "-e"])
5633
            .arg(format!("TF_HTTP_PASSWORD={token}"))
5634
            .args(["--entrypoint", "tofu", "oxygenflow-tofu:latest"])
5635
            .args(args)
5636
            .output()
5637
            .expect("docker");
5638
        let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
5639
        assert!(out.status.success(), "tofu {args:?}: {text}");
5640
        text
5641
    };
5642
    tofu(&["init", "-input=false", "-no-color"]);
5643
    let applied = tofu(&["apply", "-auto-approve", "-input=false", "-no-color"]);
5644
    assert!(applied.contains("1 added"), "{applied}");
5645
    let again = tofu(&["apply", "-auto-approve", "-input=false", "-no-color"]);
5646
    assert!(again.contains("No changes"), "the state was kept: {again}");
5647
    let row = db::repos::get(&h.app.db, "andy", "infra").await.unwrap().unwrap();
5648
    let kept = db::terraform::get(&h.app.db, row.id, "prod").await.unwrap().unwrap();
5649
    assert!(kept.lock_id.is_empty(), "unlocked after each run");
5650
    assert!(kept.serial >= 1);
5651
}
5652
8a48dd83 Andy McCall ↶ 5653
/// `/metrics` (oxygenhub#212): off until a token is set, then served only
5654
/// to its bearer, in the Prometheus text format, with Flow's jobs counted.
5655
#[tokio::test(flavor = "multi_thread")]
5656
async fn metrics_are_private_and_count_flow_jobs() {
5657
    let h = hub().await;
5658
    let (st, _) = call(&h.app, "GET", "/metrics", None, None).await;
5659
    assert_eq!(st, StatusCode::NOT_FOUND, "off by default");
5660
    let text = oxygenhub::metrics::render(&h.app).await;
5661
    for want in [
5662
        "# TYPE oxyhub_uptime_seconds gauge",
5663
        "oxyhub_flow_jobs{state=\"queued\"} 0",
5664
        "oxyhub_bucket_requests_total{kind=\"list\"}",
5665
        "oxyhub_tlog_entries",
a6d824c5 Andy McCall ↶ 5666
        "oxyhub_db_connections{idle=\"true\"}",
5667
        "oxyhub_pushes_last_day{result=\"refused\"} 0",
5668
        "# TYPE oxyhub_backup_last_run_ok gauge",
2c47eecf Andy McCall ↶ 5669
        "# TYPE oxyhub_flow_runner_last_seen_seconds gauge",
5670
        "oxyhub_flow_runs_last_day{result=\"failed\"} 0",
5671
        "oxyhub_mail_total{result=\"sent\"}",
8a48dd83 Andy McCall ↶ 5672
    ] {
5673
        assert!(text.contains(want), "missing {want}:\n{text}");
5674
    }
5675
    create(&h.app, "andy", "demo").await;
5676
    let work = tempfile::tempdir().unwrap();
5677
    let c = client(&format!("{}/andy/demo", h.base), work.path());
5678
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5679
    write(work.path(), "test.sh", "echo ok\n");
5680
    c.snapshot("test").unwrap();
5681
    c.commit("Add a pipeline", &[]).unwrap();
5682
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5683
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
5684
    let text = oxygenhub::metrics::render(&h.app).await;
5685
    assert!(!text.contains("oxyhub_flow_jobs{state=\"queued\"} 0"), "the run's jobs are queued:\n{text}");
a6d824c5 Andy McCall ↶ 5686
    assert!(text.contains("oxyhub_pushes_last_day{result=\"accepted\"}"), "{text}");
85ec74fd Andy McCall ↶ 5687
    // The push's bytes are counted (other tests share the counters, so
5688
    // only that they are there and not nothing).
5689
    let pushed = text
5690
        .lines()
5691
        .find_map(|l| l.strip_prefix("oxyhub_protocol_bytes_total{endpoint=\"push\",direction=\"received\"} "))
5692
        .and_then(|v| v.parse::<f64>().ok())
5693
        .unwrap_or(0.0);
5694
    assert!(pushed > 0.0, "{text}");
b9b74d99 Andy McCall ↶ 5695
    // Requests through the router are counted by route class.
5696
    call(&h.app, "GET", "/andy/demo", None, None).await;
5697
    let text = oxygenhub::metrics::render(&h.app).await;
5698
    assert!(text.contains("oxyhub_http_requests_total{route=\"page:repository\",method=\"GET\",status=\"2xx\"}"), "{text}");
5699
    assert!(text.contains("oxyhub_http_request_duration_seconds_bucket{route=\"page:repository\",method=\"GET\",le=\"+Inf\"}"));
8a48dd83 Andy McCall ↶ 5700
}
5701
e97500b7 Andy McCall ↶ 5702
/// Insights (oxygenhub#257): a job is ready when it could run (queued, its
5703
/// dependencies passed), so its pickup time is from then to its claim; the
5704
/// repository's page charts its jobs, an owner's numbers are its own and
5705
/// the site's are the administrators'.
5706
#[tokio::test(flavor = "multi_thread")]
5707
async fn insights_chart_pickup_from_when_a_job_could_run() {
5708
    let h = hub().await;
5709
    create(&h.app, "andy", "demo").await;
5710
    let work = tempfile::tempdir().unwrap();
5711
    let c = client(&format!("{}/andy/demo", h.base), work.path());
5712
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5713
    write(work.path(), "test.sh", "echo ok\n");
5714
    c.snapshot("test").unwrap();
5715
    c.commit("Add a pipeline", &[]).unwrap();
5716
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5717
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
5718
    let mut finished = std::collections::HashMap::new();
5719
    for want in ["build", "lint", "test"] {
5720
        let j = claim(&h.app).await.expect("a job");
5721
        assert_eq!(j["job"]["name"].as_str(), Some(want));
5722
        let id = j["job_id"].as_i64().unwrap();
5723
        let row = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
5724
        let (queued, ready, started) = (row.queued_ms.unwrap(), row.ready_ms.unwrap(), row.started_ms.unwrap());
5725
        assert!(queued <= ready && ready <= started, "{want}: {queued} {ready} {started}");
5726
        if want == "test" {
5727
            assert_eq!(Some(ready), finished["build"], "ready when build passed, not when it was queued");
5728
        }
5729
        let ph = j["pipeline_hash"].as_str().unwrap();
5730
        let st = finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt(want, ph, 0) })).await;
5731
        assert_eq!(st, StatusCode::NO_CONTENT);
5732
        finished.insert(want, db::flow::job(&h.app.db, id).await.unwrap().unwrap().finished_ms);
5733
    }
5734
    let (st, page) = call(&h.app, "GET", "/andy/demo/insights", None, None).await;
5735
    assert_eq!(st, StatusCode::OK, "{page}");
5736
    assert!(page.contains("<span class=\"kpi-v\">3</span><span class=\"kpi-l\">jobs finished"), "{page}");
5737
    assert!(page.contains("100% passed"), "{page}");
5738
    assert_eq!(page.matches("<svg class=\"chart\"").count(), 5, "five charts");
5739
    assert!(page.contains("class=\"bar s-ok\""), "the passed jobs drawn");
5740
    assert!(page.contains("data-refresh=\"30\" data-fragment=\"insights\""), "it refreshes itself");
5741
    assert!(page.contains("<summary class=\"on\">More</summary>"), "the bar's More menu holds it");
5742
    let (_, wall) = call(&h.app, "GET", "/andy/demo/insights?range=7d&wall=1", None, None).await;
5743
    assert!(wall.contains("<body class=\"wall\"") && wall.contains("the last 7 days") && wall.contains("leave the wall view"), "{wall}");
5744
    // An owner's numbers are not anyone's; the site's are administrators'.
5745
    assert_eq!(call(&h.app, "GET", "/insights/andy", None, None).await.0, StatusCode::NOT_FOUND);
5746
    assert_eq!(call(&h.app, "GET", "/admin/insights", None, None).await.0, StatusCode::NOT_FOUND);
5747
    let res = oxygenhub::router(h.app.clone())
5748
        .oneshot(
5749
            Request::post("/register")
5750
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
5751
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
5752
                .unwrap(),
5753
        )
5754
        .await
5755
        .unwrap();
5756
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
5757
    let andy = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap();
5758
    db::accounts::set_admin(&h.app.db, andy.id, true).await.unwrap();
5759
    for path in ["/insights/andy", "/admin/insights?runner=test-1&range=1h"] {
5760
        let res = oxygenhub::router(h.app.clone())
5761
            .oneshot(Request::get(path).header(header::COOKIE, cookie.clone()).body(Body::empty()).unwrap())
5762
            .await
5763
            .unwrap();
5764
        let st = res.status();
5765
        let body = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
5766
        assert_eq!(st, StatusCode::OK, "{path}: {body}");
5767
        assert!(body.contains("<svg class=\"chart\""), "{path}");
5768
    }
5769
}
5770
7c06f5b2 Andy McCall ↶ 5771
/// Readers never wait (oxygenhub#249): a page, the API and a fetch's refs
5772
/// answer while a writer (a push, a gc) holds the repository; writers take
5773
/// turns; deleting or moving it waits for everyone and holds off newcomers.
5774
#[tokio::test(flavor = "multi_thread")]
5775
async fn reads_do_not_wait_for_a_writer() {
5776
    use std::time::Duration;
5777
    let h = hub().await;
5778
    create(&h.app, "andy", "demo").await;
5779
    let work = tempfile::tempdir().unwrap();
5780
    let c = client(&format!("{}/andy/demo", h.base), work.path());
5781
    write(work.path(), "a.txt", "a\n");
5782
    c.commit("A change", &[]).unwrap();
5783
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5784
    let name = RepoName::parse("andy/demo").unwrap();
5785
    let writer = h.app.repos.write_guard(&name).await;
5786
    for path in ["/andy/demo", "/andy/demo/changes/main", "/api/v1/repos/andy/demo/bookmarks"] {
5787
        let (st, body) = tokio::time::timeout(Duration::from_secs(10), call(&h.app, "GET", path, None, None))
5788
            .await
5789
            .unwrap_or_else(|_| panic!("{path} waited for the writer"));
5790
        assert_eq!(st, StatusCode::OK, "{path}: {body}");
5791
    }
5792
    let refs = tokio::time::timeout(Duration::from_secs(10), call(&h.app, "POST", "/andy/demo/oxy/v1/refs", Some("site"), None)).await;
5793
    assert!(refs.is_ok(), "a fetch's refs waited for the writer");
5794
    assert!(tokio::time::timeout(Duration::from_millis(300), h.app.repos.write_guard(&name)).await.is_err(), "writers take turns");
5795
    assert!(tokio::time::timeout(Duration::from_millis(300), h.app.repos.exclusive_guard(&name)).await.is_err(), "a delete waits");
5796
    drop(writer);
5797
    let all = tokio::time::timeout(Duration::from_secs(5), h.app.repos.exclusive_guard(&name)).await.expect("then it runs");
5798
    assert!(
5799
        tokio::time::timeout(Duration::from_millis(300), h.app.repos.read_guard(&name)).await.is_err(),
5800
        "nothing reads a repository being deleted"
5801
    );
5802
    drop(all);
5803
}
5804
a10446c6 Andy McCall ↶ 5805
/// Live L5 (docs/live.md, oxygenhub#207): the issue page's timeline
5806
/// listens on the issue's topic and the repository's, the overview's latest
5807
/// change and bookmarks on the repository's, and its Diffusion card and the
5808
/// Diffusion tab on the repository's Diffusion topic.
5809
#[tokio::test(flavor = "multi_thread")]
5810
async fn the_issue_overview_and_diffusion_pages_listen_on_their_topics() {
5811
    let h = hub().await;
5812
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
5813
    create(&h.app, "andy", "demo").await;
5814
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
5815
    let work = tempfile::tempdir().unwrap();
5816
    let c = client(&format!("{}/andy/demo", h.base), work.path());
5817
    write(work.path(), "a.txt", "a\n");
5818
    c.snapshot("t").unwrap();
5819
    c.commit("a", &[]).unwrap();
5820
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5821
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/issues", Some("site"), Some(r#"{"title":"Broken"}"#.into())).await;
5822
    assert!(st.is_success(), "{st} {body}");
5823
    let repo = format!("repo:{}", row.id);
5824
    let (_, issue) = call(&h.app, "GET", "/andy/demo/issue/1", None, None).await;
5825
    assert!(issue.contains(&format!("data-live=\"{repo}/issue:1 {repo}\" data-fragment=\"timeline\"")), "the issue's timeline");
5826
    let (_, overview) = call(&h.app, "GET", "/andy/demo", None, None).await;
5827
    assert!(overview.contains(&format!("data-live=\"{repo}\" data-fragment=\"latest\"")), "the latest change");
5828
    assert!(overview.contains(&format!("data-live=\"{repo}\" data-fragment=\"bookmarks\"")), "the bookmarks");
5829
    let (_, diffusion) = call(&h.app, "GET", "/andy/demo/diffusion", None, None).await;
5830
    assert!(diffusion.contains(&format!("data-live=\"diffusion:{} {repo}\" data-fragment=\"diffusion\"", row.id)), "the Diffusion tab");
5831
}
5832
3eb491e9 Andy McCall ↶ 5833
/// Keyless step 4c (oxygenhub#241): when a key the hub certified moves a
5834
/// bookmark, the hub signs when it accepted the update and serves that
5835
/// with the bookmark, so a fetch checks the certificate at the hub's time
5836
/// rather than the time the key claimed.
5837
#[tokio::test(flavor = "multi_thread")]
5838
async fn the_hub_countersigns_an_update_by_a_key_it_certified() {
5839
    use oxy_core::attest::AttestBody;
5840
    use oxy_core::cert::{Certificate, SignedCertificate};
5841
    use oxy_core::identity::Scope;
5842
    use oxy_core::repo::IdentityScope;
5843
    let h = hub().await;
5844
    create(&h.app, "andy", "demo").await;
5845
    let url = format!("{}/andy/demo", h.base);
5846
    let work = tempfile::tempdir().unwrap();
5847
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
5848
    a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
5849
    write(&work.path().join("a"), "a.txt", "a\n");
5850
    a.commit("a", &[]).unwrap();
5851
    a.policy_init().unwrap();
5852
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
5853
    let hub_id = h.app.hub_key.identity.clone();
5854
    a.policy_grant_subject("agent:claude@andy", hub_id.clone(), Scope::CHANGES | Scope::REFS, None).unwrap();
5855
    assert!(a.push("origin", false).unwrap().iter().any(|r| r.name == "policy" && r.ok));
5856
5857
    // An agent whose fresh key the hub certified pushes.
5858
    let mut b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(work.path().join("home-b"));
5859
    b.config.set("remote.origin.token", "site").unwrap();
5860
    b.save_config().unwrap();
5861
    let (_, key) = b.create_identity("claude", "[email protected]", IdentityScope::User).unwrap();
5862
    let (_, secret) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
5863
    let now = db::now_ms() as u64;
5864
    let cert = SignedCertificate::sign(
5865
        Certificate {
5866
            key,
5867
            issuer: hub_id.hash(),
5868
            subject: "agent:claude@andy".into(),
5869
            claims: vec![],
5870
            scope: Scope::CHANGES | Scope::REFS,
5871
            not_before: now - 60_000,
5872
            expires: now + 600_000,
8aa5ef38 Andy McCall ↶ 5873
            grant: None,
3eb491e9 Andy McCall ↶ 5874
        },
5875
        &hub_id,
5876
        &secret,
5877
    );
5878
    b.store().put_identity(&hub_id).unwrap();
5879
    b.store().put_certificate(&cert).unwrap();
5880
    write(&work.path().join("b"), "b.txt", "agent work\n");
5881
    b.commit("work", &[]).unwrap();
5882
    let r = b.push("origin", false).unwrap();
5883
    assert!(r.iter().all(|x| x.ok), "{r:?}");
5884
5885
    // The hub serves its acceptance of that update, signed by its key.
5886
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
5887
    let main = refs.refs.iter().find(|r| r.name == "main").unwrap();
5888
    let (attest, acc) = (main.attestation.clone().unwrap(), main.accepted.clone().expect("an acceptance"));
5889
    assert!(matches!(acc.attest.body, AttestBody::Accepted { attest: r } if r == attest.attest.hash()));
5890
    assert_eq!(acc.sigs[0].key, hub_id.hash());
5891
    assert!(acc.attest.hlc.wall_ms >= now);
5892
    // An update signed by a long-lived key gets none.
5893
    a.pull("origin").unwrap();
5894
    write(&work.path().join("a"), "a.txt", "again\n");
5895
    a.commit("again", &[]).unwrap();
5896
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
5897
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
5898
    assert!(refs.refs.iter().find(|r| r.name == "main").unwrap().accepted.is_none());
5899
}
8aa5ef38 Andy McCall ↶ 5900
b5c199bd Andy McCall ↶ 5901
/// A keyless agent's release tag (oxygen#129): a key the hub certified
5902
/// creates a tag and pushes it under the policy's subject grant; the hub
5903
/// accepts it, countersigns when, logs both and serves them with the tag,
5904
/// and a fresh clone fetches it at the hub's time rather than the tag's.
5905
#[tokio::test(flavor = "multi_thread")]
5906
async fn a_tag_by_a_key_the_hub_certified_is_accepted_and_fetched() {
5907
    use oxy_core::attest::AttestBody;
5908
    use oxy_core::cert::{Certificate, SignedCertificate};
5909
    use oxy_core::identity::Scope;
5910
    use oxy_core::repo::IdentityScope;
5911
    use oxy_core::tlog::Entry;
5912
    let h = hub().await;
5913
    create(&h.app, "andy", "demo").await;
5914
    let url = format!("{}/andy/demo", h.base);
5915
    let work = tempfile::tempdir().unwrap();
5916
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
5917
    a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
5918
    write(&work.path().join("a"), "a.txt", "a\n");
5919
    a.commit("a", &[]).unwrap();
5920
    a.policy_init().unwrap();
5921
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
5922
    let hub_id = h.app.hub_key.identity.clone();
5923
    a.policy_grant_subject("agent:claude@andy", hub_id.clone(), Scope::CHANGES | Scope::REFS, None).unwrap();
5924
    assert!(a.push("origin", false).unwrap().iter().any(|r| r.name == "policy" && r.ok));
5925
5926
    // An agent whose fresh key the hub certified tags what it fetched.
5927
    let mut b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(work.path().join("home-b"));
5928
    b.config.set("remote.origin.token", "site").unwrap();
5929
    b.save_config().unwrap();
5930
    let (_, key) = b.create_identity("claude", "[email protected]", IdentityScope::User).unwrap();
5931
    let (_, secret) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
5932
    let now = db::now_ms() as u64;
5933
    let cert = SignedCertificate::sign(
5934
        Certificate {
5935
            key,
5936
            issuer: hub_id.hash(),
5937
            subject: "agent:claude@andy".into(),
5938
            claims: vec![],
5939
            scope: Scope::CHANGES | Scope::REFS,
5940
            not_before: now - 60_000,
5941
            expires: now + 600_000,
5942
            grant: None,
5943
        },
5944
        &hub_id,
5945
        &secret,
5946
    );
5947
    b.store().put_identity(&hub_id).unwrap();
5948
    b.store().put_certificate(&cert).unwrap();
5949
    let heads = b.bookmark_heads().unwrap();
5950
    b.tag_create("v0.2.0", &heads, "OxygenFlow 0.2.0").unwrap();
5951
    let r = b.push("origin", false).unwrap();
5952
    assert!(r.iter().any(|x| x.name == "tags/v0.2.0" && x.ok), "{r:?}");
5953
5954
    // The hub serves its acceptance of the tag, signed by its key, and
5955
    // logs both.
5956
    h.app.tlog.refresh_checkpoint(&hub_id, &secret).unwrap();
5957
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
5958
    let tag = refs.tags.iter().find(|t| t.name == "v0.2.0").expect("the tag");
5959
    let (attest, acc) = (tag.attestation.clone().unwrap(), tag.accepted.clone().expect("an acceptance"));
5960
    assert!(matches!(acc.attest.body, AttestBody::Accepted { attest: r } if r == attest.attest.hash()));
5961
    assert_eq!(acc.sigs[0].key, hub_id.hash());
5962
    assert!(acc.attest.hlc.wall_ms >= now);
5963
    let logged = tag.logged.as_ref().expect("the tag's place in the log");
5964
    let entry = Entry::decode(&logged.entry).unwrap();
5965
    assert_eq!((entry.kind.as_str(), entry.object), ("tag", attest.attest.hash()));
5966
    let logged_acceptance = db::tlog::entry_of(&h.app.db, &acc.attest.hash().to_hex(), "accepted").await.unwrap();
5967
    assert!(logged_acceptance.is_some(), "the acceptance is logged too");
5968
5969
    // A fresh clone takes the tag at the hub's time.
5970
    let c = Repo::clone(&url, &work.path().join("c")).unwrap().with_home(work.path().join("home-c"));
5971
    assert_eq!(c.tag_heads("v0.2.0").unwrap(), Some(heads));
5972
    let report = c.fetch("origin").unwrap();
5973
    assert!(report.skipped.is_empty(), "{:?}", report.skipped);
5974
    // Andy's checkout too, the tag signed by the agent's key.
5975
    a.pull("origin").unwrap();
5976
    let t = a.tags().unwrap().into_iter().find(|t| t.name == "v0.2.0").expect("pulled");
5977
    assert_eq!(t.signer.as_deref(), Some("claude"));
a0a1601e Andy McCall ↶ 5978
5979
    // oxy 0.5.0 and older, which send no `Oxy-Features`, refuse a tag only a
5980
    // certificate authorizes and, with it, the whole clone (oxygen#131): the
5981
    // hub leaves it out of their refs answer, and Andy's own tag in.
5982
    a.tag_create("v0.1.0", &a.bookmark_heads().unwrap(), "by Andy").unwrap();
5983
    assert!(a.push("origin", false).unwrap().iter().any(|r| r.name == "tags/v0.1.0" && r.ok));
5984
    let bare = oxy_core::protocol::http_get(&format!("{url}/oxy/v1/refs"), &RemoteOptions::default()).unwrap();
5985
    let (_, old) = oxy_core::protocol::wire::decode_refs(&bare).unwrap();
5986
    let names: Vec<String> = old.tags.into_iter().map(|t| t.name).collect();
5987
    assert_eq!(names, ["v0.1.0"], "no Oxy-Features header");
5988
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
5989
    let mut names: Vec<String> = refs.tags.into_iter().map(|t| t.name).collect();
5990
    names.sort();
5991
    assert_eq!(names, ["v0.1.0", "v0.2.0"], "a current client declares certified-tags");
b5c199bd Andy McCall ↶ 5992
}
5993
8aa5ef38 Andy McCall ↶ 5994
/// Keyless step 5 (oxygenhub#241): Andy grants an agent with his own key;
5995
/// the agent, holding only the grant token, commits and pushes in Andy's
5996
/// name with fresh keys the hub certifies under the grant. A grant by a
5997
/// key not linked to the account, or for another account's agent, is
5998
/// refused; a revoked grant certifies no more.
5999
#[tokio::test(flavor = "multi_thread")]
6000
async fn an_agent_with_a_grant_pushes_in_its_owner_s_name() {
6001
    use oxy_core::cert::{Grant, SignedGrant};
6002
    use oxy_core::identity::{Identity, Scope, SecretKey};
6003
    use oxy_core::repo::{IdentityScope, SignatureStatus};
6004
    let h = hub().await;
6005
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
6006
    let (pat, pat_hash) = oxygenhub::auth::new_token();
6007
    db::accounts::create_token(&h.app.db, andy.id, "cli", &pat_hash, "repo:write", "", None).await.unwrap();
6008
    create(&h.app, "andy", "demo").await;
6009
    let url = format!("{}/andy/demo", h.base);
6010
    let work = tempfile::tempdir().unwrap();
6011
    // Andy's checkout, its policy granting the agent's subject.
6012
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
6013
    let (andy_key, andy_id) = a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
6014
    db::accounts::link_identity(&h.app.db, andy.id, &andy_key.to_hex(), "Andy", "[email protected]", &andy_id.encode()).await.unwrap();
6015
    write(&work.path().join("a"), "a.txt", "a\n");
6016
    a.commit("a", &[]).unwrap();
6017
    a.policy_init().unwrap();
6018
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6019
    let hub_id = h.app.hub_key.identity.clone();
6020
    a.policy_grant_subject("agent:claude@andy", hub_id.clone(), Scope::CHANGES | Scope::REFS, None).unwrap();
6021
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6022
6023
    // Andy grants the agent, as `oh agent grant claude` does.
6024
    let (_, andy_sk) = a.secret_key().unwrap().unwrap();
6025
    let now = db::now_ms() as u64;
6026
    let grant = |by: &Identity, sk: &SecretKey, subject: &str| {
6027
        SignedGrant::sign(
6028
            Grant {
6029
                grantor: by.hash(),
6030
                subject: subject.into(),
6031
                issuer: hub_id.hash(),
6032
                scope: Scope::CHANGES | Scope::SEAL | Scope::REFS,
6033
                not_before: now - 60_000,
6034
                expires: now + 86_400_000,
6035
            },
6036
            by,
6037
            sk,
6038
        )
6039
    };
6040
    let post = |g: SignedGrant| {
6041
        let (app, pat) = (h.app.clone(), pat.clone());
6042
        let body = serde_json::json!({ "grant": oxy_core::dsse::base64(&g.encode()) }).to_string();
6043
        async move { call(&app, "POST", "/api/v1/agents/grants", Some(&pat), Some(body)).await }
6044
    };
6045
    let stray_sk = SecretKey::generate();
6046
    let stray = stray_sk.identity("stray", "[email protected]", 1);
6047
    let (st, body) = post(grant(&stray, &stray_sk, "agent:claude@andy")).await;
6048
    assert_eq!(st, StatusCode::FORBIDDEN, "a key not linked to the account: {body}");
6049
    let (st, body) = post(grant(&andy_id, &andy_sk, "agent:claude@mallory")).await;
6050
    assert_eq!(st, StatusCode::BAD_REQUEST, "another account's agent: {body}");
6051
    let (st, body) = post(grant(&andy_id, &andy_sk, "agent:claude@andy")).await;
6052
    assert_eq!(st, StatusCode::CREATED, "{body}");
6053
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
6054
    let token = v["token"].as_str().unwrap().to_string();
6055
    assert!(token.starts_with("oxyagent_"));
6056
    let grant_id = v["id"].as_i64().unwrap();
205d8f86 Andy McCall ↶ 6057
    // The grant token works for the API too, as its owner's agent
6058
    // (#253), but cannot manage grants.
6059
    let (st, me) = call(&h.app, "GET", "/api/v1/user", Some(&token), None).await;
6060
    assert!(st == StatusCode::OK && me.contains("\"andy\""), "{st} {me}");
6061
    let (st, _) = call(&h.app, "GET", "/api/v1/agents/grants", Some(&token), None).await;
6062
    assert_eq!(st, StatusCode::FORBIDDEN, "an agent does not manage grants");
d4a0043f Andy McCall ↶ 6063
    // What the agent does through the API is told to its owner, as an
6064
    // agent token's is (#183).
6065
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
6066
    db::notify::set_watch(&h.app.db, andy.id, repo.id, true).await.unwrap();
6067
    let body = serde_json::json!({ "title": "Filed by the agent", "body": "" }).to_string();
6068
    let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/demo/issues", Some(&token), Some(body)).await;
6069
    assert_eq!(st, StatusCode::CREATED, "{out}");
6070
    let actor: String = sqlx::query_scalar("SELECT actor FROM notifications WHERE account_id = $1 AND title LIKE '%Filed by the agent%'")
6071
        .bind(andy.id)
6072
        .fetch_one(&h.app.db)
6073
        .await
6074
        .expect("told of the agent's issue");
6075
    assert!(actor.starts_with("andy (agent token "), "{actor}");
8aa5ef38 Andy McCall ↶ 6076
6077
    // The agent: a home holding only the grant token, Andy the author.
6078
    let agent_home = work.path().join("home-claude");
6079
    oxy_core::credentials::Credentials::at(&agent_home).save_grant(&h.base, &token).unwrap();
6080
    let agent = || {
6081
        let n = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
6082
        let dir = work.path().join(format!("claude-{n}"));
6083
        let mut r = Repo::clone(&url, &dir).unwrap().with_home(agent_home.clone());
559c3920 Andy McCall ↶ 6084
        // The grant token is its only credential: it pushes with it too.
6085
        r.config.set("remote.origin.token", &token).unwrap();
8aa5ef38 Andy McCall ↶ 6086
        r.save_config().unwrap();
6087
        r.set_user_config("author.key", &andy_key.to_hex()).unwrap();
6088
        r.set_user_config("author.signer", "keyless").unwrap();
6089
        (r, dir)
6090
    };
6091
    let (claude, dir) = agent();
6092
    assert!(!agent_home.join("keys").exists(), "no key on disk");
6093
    write(&dir, "work.txt", "agent work\n");
6094
    let change = claude.commit("Agent work", &[]).unwrap();
6095
    let r = claude.push("origin", false).unwrap();
6096
    assert!(r.iter().all(|x| x.ok), "{r:?}");
6097
    let signer = claude.signing_key().expect("a certified key");
6098
    assert_ne!(signer, andy_key);
6099
    assert!(!agent_home.join("keys").exists(), "still no key on disk");
6100
6101
    // The hub holds it in Andy's name, sealed by the certified key, and
6102
    // countersigned when it accepted the update.
6103
    let host = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
6104
    assert_eq!(host.store().get_change_meta(&change).unwrap().author, andy_key);
6105
    assert!(matches!(
6106
        host.authenticate_change(&change).unwrap(),
6107
        SignatureStatus::Valid { key, sealed: true, .. } if key == signer
6108
    ));
6109
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
6110
    assert!(refs.refs.iter().find(|r| r.name == "main").unwrap().accepted.is_some());
6111
    a.pull("origin").unwrap();
6112
    assert!(matches!(a.authenticate_change(&change).unwrap(), SignatureStatus::Valid { .. }));
6113
6114
    // Revoked: the next command gets no certificate.
6115
    let (st, _) = call(&h.app, "DELETE", &format!("/api/v1/agents/grants/{grant_id}"), Some(&pat), None).await;
6116
    assert_eq!(st, StatusCode::NO_CONTENT);
6117
    let (late, dir) = agent();
6118
    write(&dir, "late.txt", "after the revocation\n");
6119
    late.commit("Late", &[]).unwrap();
6120
    let err = late.push("origin", false).unwrap_err().to_string();
559c3920 Andy McCall ↶ 6121
    assert!(err.contains("not valid") || err.contains("would not certify"), "{err}");
6122
    // The hub recorded the push as the agent's, for its owner.
6123
    let by_agent: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM pushes WHERE via = 'claude'").fetch_one(&h.app.db).await.unwrap();
6124
    assert!(by_agent >= 1, "recorded as via the agent");
8aa5ef38 Andy McCall ↶ 6125
    let (_, body) = call(&h.app, "GET", "/api/v1/agents/grants", Some(&pat), None).await;
6126
    let list: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
6127
    assert!(list[0]["revoked_ms"].is_i64() && list[0].get("token").is_none(), "{body}");
6128
}
a9f1c0bf Andy McCall ↶ 6129
6130
/// oxygenhub#267, newest run wins: a proposal's new run supersedes its
6131
/// older runs still live, as a push run does its bookmark's; a repository
6132
/// that keeps running runs has only the queued ones cancelled; manual
6133
/// runs and reruns supersede nothing and nothing supersedes them.
6134
#[tokio::test(flavor = "multi_thread")]
6135
async fn newest_run_wins() {
6136
    use oxy_core::hash::ChangeHash;
6137
    let h = hub().await;
6138
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
6139
    create(&h.app, "andy", "newest").await;
6140
    let url = format!("{}/andy/newest", h.base);
6141
    let work = tempfile::tempdir().unwrap();
6142
    let c = client(&url, work.path());
6143
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
6144
    write(work.path(), "test.sh", "echo ok\n");
6145
    c.commit("Start", &[]).unwrap();
6146
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6147
    let pushed = runs_of(&h.app, "andy", "newest").await[0].clone();
6148
    assert_eq!((pushed.number, pushed.trigger.as_str()), (1, "push"));
6149
    let heads: Vec<ChangeHash> = pushed.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
6150
    let start = |row: db::repos::RepoRow, bookmark: &'static str, trigger: &'static str| {
6151
        let (app, state, heads) = (h.app.clone(), pushed.state.clone(), heads.clone());
6152
        async move {
6153
            oxygenhub::flow::start_run_scoped(&app, &row, bookmark, &state, &heads, "andy", trigger, None).await.unwrap().expect("a run")
6154
        }
6155
    };
6156
    let row = db::repos::get(&h.app.db, "andy", "newest").await.unwrap().unwrap();
6157
    let run = |n: i64| {
6158
        let (app, id) = (h.app.clone(), row.id);
6159
        async move { db::flow::run(&app.db, id, n).await.unwrap().unwrap() }
6160
    };
6161
    let superseded_by = |n: i64, by: i64| {
6162
        let app = h.app.clone();
6163
        let run = run(n);
6164
        async move {
6165
            let r = run.await;
6166
            assert_eq!(r.status, "cancelled", "run #{n} is superseded");
6167
            let jobs = db::flow::jobs(&app.db, r.id).await.unwrap();
6168
            let why = format!("superseded by run #{by}");
6169
            assert!(jobs.iter().all(|j| j.status == "cancelled" && j.error == why), "{jobs:?}");
6170
        }
6171
    };
6172
6173
    // A proposal's new run supersedes its older one, not another
6174
    // proposal's, nor the push run of a bookmark.
6175
    assert_eq!(start(row.clone(), "proposal/7", "proposal").await, 2);
6176
    assert_eq!(start(row.clone(), "proposal/7", "proposal").await, 3);
6177
    superseded_by(2, 3).await;
6178
    assert_eq!(start(row.clone(), "proposal/8", "proposal").await, 4);
6179
    assert!(run(3).await.live(), "another proposal's run is not superseded");
6180
    assert!(run(1).await.live(), "a proposal's run leaves push runs alone");
6181
6182
    // Manual runs and reruns supersede nothing, and a push supersedes
6183
    // only push runs.
6184
    assert_eq!(start(row.clone(), "main", "manual").await, 5);
6185
    assert_eq!(start(row.clone(), "main", "rerun:1:push").await, 6);
6186
    assert!(run(1).await.live(), "a manual run or a rerun supersedes nothing");
6187
    assert_eq!(start(row.clone(), "main", "push").await, 7);
6188
    superseded_by(1, 7).await;
6189
    assert!(run(5).await.live() && run(6).await.live(), "a push leaves manual runs and reruns alone");
6190
6191
    // Kept running: a superseded run already running finishes; queued
6192
    // ones are still cancelled.
6193
    db::repos::set_flow_keep_running(&h.app.db, row.id, true).await.unwrap();
6194
    let kept = db::repos::get(&h.app.db, "andy", "newest").await.unwrap().unwrap();
6195
    assert!(kept.flow_keep_running);
6196
    let three = run(3).await;
6197
    sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = $1").bind(three.id).execute(&h.app.db).await.unwrap();
6198
    sqlx::query("UPDATE flow_jobs SET status = 'running' WHERE run_id = $1 AND name = 'build'")
6199
        .bind(three.id)
6200
        .execute(&h.app.db)
6201
        .await
6202
        .unwrap();
6203
    assert_eq!(start(kept.clone(), "proposal/7", "proposal").await, 8);
6204
    assert_eq!(start(kept.clone(), "proposal/7", "proposal").await, 9);
6205
    assert_eq!(run(3).await.status, "running", "a running run is kept");
6206
    superseded_by(8, 9).await;
6207
    // The default again: running runs are cancelled too.
6208
    db::repos::set_flow_keep_running(&h.app.db, row.id, false).await.unwrap();
6209
    let row = db::repos::get(&h.app.db, "andy", "newest").await.unwrap().unwrap();
6210
    assert_eq!(start(row.clone(), "proposal/7", "proposal").await, 10);
6211
    superseded_by(3, 10).await;
6212
    superseded_by(9, 10).await;
6213
}