OXYGENHUB
◆ v0.9.24 oxygenhub / crates / hub / tests / flow.rs
435.1 KiB · Rust · last changed A push no longer stops the default bookmark's running run (closes #369) 1 day 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()));
3d086bc3 Andy McCall ↶ 613
    // Both, newest first, across andy's repositories with their jobs (oxygenhub-android#26).
614
    let (st, body) = call(&h.app, "GET", "/api/v1/user/flow/runs", Some("site"), None).await;
615
    assert_eq!(st, StatusCode::OK, "{body}");
616
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
617
    assert_eq!(v.as_array().unwrap().len(), 2, "{v}");
618
    assert_eq!(
619
        (v[0]["repository"].as_str(), v[0]["number"].as_i64(), v[1]["number"].as_i64()),
620
        (Some("andy/demo"), Some(2), Some(1)),
621
        "{v}"
622
    );
623
    assert!(!v[0]["jobs"].as_array().unwrap().is_empty(), "with its jobs: {v}");
624
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/user/flow/runs?before={}", v[0]["created_ms"]), Some("site"), None).await;
625
    let older: serde_json::Value = serde_json::from_str(&body).unwrap();
626
    assert!(older.as_array().unwrap().iter().all(|r| r["number"] != 2), "before pages back: {older}");
627
    assert_eq!(call(&h.app, "GET", "/api/v1/user/flow/runs", None, None).await.0, StatusCode::UNAUTHORIZED);
1edac4b6 Andy McCall ↶ 628
    assert_eq!(db::flow::jobs(&h.app.db, second.id).await.unwrap().len(), 3);
629
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/2", None, None).await;
630
    assert!(page.contains("started by andy"), "the run page says what started it");
631
4f692533 Andy McCall ↶ 632
    // Run pipeline on one change: its state, with no bookmark.
633
    let head = first[0].head_list()[0].to_string();
634
    let (st, body) =
635
        call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(format!(r#"{{"change":"{head}"}}"#))).await;
636
    assert_eq!(st, StatusCode::CREATED, "{body}");
637
    let on_change = db::flow::run(&h.app.db, first[0].repo_id, 3).await.unwrap().unwrap();
638
    assert_eq!(
639
        (on_change.bookmark.as_str(), on_change.heads.as_str(), on_change.state.as_str()),
640
        ("", head.as_str(), first[0].state.as_str())
641
    );
642
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/3", None, None).await;
643
    assert!(page.contains("title=\"Run on one change, not a bookmark\">change</span>"), "run page");
644
    let (st, body) =
645
        call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(format!(r#"{{"change":"{}"}}"#, "ab".repeat(32))))
646
            .await;
647
    assert!(st == StatusCode::CONFLICT && body.contains("no change"), "{st} {body}");
648
    // Viewers who cannot start runs are told why, and get no button.
649
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
650
    assert!(page.contains("Sign in with write access to run the pipeline.") && !page.contains("primary-btn"));
651
    let (_, page) = call(&h.app, "GET", "/andy/demo/bookmarks", None, None).await;
652
    assert!(!page.contains("/flow/start"), "no run buttons for anonymous viewers");
653
1edac4b6 Andy McCall ↶ 654
    // A live run is not re-run; unknown bookmarks and runs are refused.
655
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/1/rerun", Some("site"), None).await;
656
    assert!(st == StatusCode::CONFLICT && body.contains("still queued"), "{st} {body}");
657
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"bookmark":"nope"}"#.into())).await;
658
    assert_eq!(st, StatusCode::CONFLICT);
659
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/99/rerun", Some("site"), None).await;
660
    assert_eq!(st, StatusCode::NOT_FOUND);
661
    // Anonymous callers cannot start runs.
662
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", None, Some("{}".into())).await;
663
    assert_ne!(st, StatusCode::CREATED);
664
665
    // A finished run re-runs as a new run of the same state.
666
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
667
    for r in [&first[0], &second] {
668
        for j in db::flow::jobs(&h.app.db, r.id).await.unwrap() {
3b1bc27f Andy McCall 669
            sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE id = $1").bind(j.id).execute(&h.app.db).await.unwrap();
1edac4b6 Andy McCall ↶ 670
        }
3b1bc27f Andy McCall 671
        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 ↶ 672
    }
673
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/1/rerun", Some("site"), None).await;
674
    assert_eq!(st, StatusCode::CREATED, "{body}");
4f692533 Andy McCall ↶ 675
    let third = db::flow::run(&h.app.db, row.id, 4).await.unwrap().unwrap();
348f8c4b Andy McCall ↶ 676
    assert_eq!(
677
        (third.trigger_label().as_str(), third.status.as_str(), third.state.as_str()),
678
        ("rerun:1", "queued", first[0].state.as_str())
679
    );
c889911b Andy McCall ↶ 680
    assert_eq!(third.trigger, "rerun:1:push", "a rerun keeps the event it repeats");
1edac4b6 Andy McCall ↶ 681
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, &third.state).await.unwrap();
682
    assert!(
4f692533 Andy McCall ↶ 683
        checks.iter().all(|c| c.status == "queued" && c.url.ends_with("/flow/4")),
1edac4b6 Andy McCall ↶ 684
        "the re-run's checks replace the old ones: {checks:?}"
685
    );
4f692533 Andy McCall ↶ 686
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/4", None, None).await;
1edac4b6 Andy McCall ↶ 687
    assert!(page.contains("re-run of #1 by andy"));
688
    assert!(!page.contains("RE-RUN"), "anonymous viewers get no button");
689
0650d94e Andy McCall ↶ 690
    // oxygenhub#130: one job, with what it depends on; an unknown one is
691
    // refused, naming the jobs a manual run can start.
692
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"jobs":["test"]}"#.into())).await;
693
    assert_eq!(st, StatusCode::CREATED, "{body}");
694
    let n = serde_json::from_str::<serde_json::Value>(&body).unwrap()["number"].as_i64().unwrap();
695
    let only = db::flow::run(&h.app.db, first[0].repo_id, n).await.unwrap().unwrap();
696
    let mut names: Vec<String> = db::flow::jobs(&h.app.db, only.id).await.unwrap().into_iter().map(|j| j.name).collect();
697
    names.sort();
698
    assert_eq!(names, ["build", "test"], "test and the job it depends on, not lint");
699
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"jobs":["deploy"]}"#.into())).await;
700
    assert!(st == StatusCode::CONFLICT && body.contains("not in the pipeline") && body.contains("build, lint, test"), "{st} {body}");
701
1edac4b6 Andy McCall ↶ 702
    // With Flow off, nothing starts.
703
    db::repos::set_flow(&h.app.db, row.id, "off").await.unwrap();
704
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
705
    assert!(st == StatusCode::CONFLICT && body.contains("not enabled"), "{body}");
4f692533 Andy McCall ↶ 706
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
707
    assert!(page.contains("Flow is off for this repository"), "and the Flow tab says so");
90326c96 Andy McCall ↶ 708
}
709
710
/// The Flow API (hub spec §13.2): runs, a run with its jobs, a job's log,
711
/// checks by the heads a client has, and JSON for unknown API routes.
712
#[tokio::test(flavor = "multi_thread")]
713
async fn runs_jobs_and_logs_are_in_the_api() {
714
    let h = hub().await;
715
    create(&h.app, "andy", "demo").await;
716
    let url = format!("{}/andy/demo", h.base);
717
    let work = tempfile::tempdir().unwrap();
718
    let c = client(&url, work.path());
719
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
720
    write(work.path(), "test.sh", "echo ok\n");
721
    let head = c.commit("Add a pipeline", &[]).unwrap();
722
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
723
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
724
725
    // A job runs and logs.
726
    let a = claim(&h.app).await.unwrap();
727
    let id = a["job_id"].as_i64().unwrap();
728
    let recs =
729
        serde_json::json!({ "records": [{ "t": 1, "stream": "stdout", "text": "one" }, { "t": 3, "stream": "stderr", "text": "three" }] });
730
    let (st, _) = call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(recs.to_string())).await;
731
    assert!(st.is_success(), "{st}");
732
733
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs", None, None).await;
734
    assert_eq!(st, StatusCode::OK, "{body}");
735
    let runs: Vec<hub_api::FlowRun> = serde_json::from_str(&body).unwrap();
736
    assert_eq!(runs.len(), 1);
737
    assert_eq!((runs[0].number, runs[0].state.as_str(), runs[0].trigger.as_str()), (1, run.state.as_str(), "push"));
738
    assert!(runs[0].url.ends_with("/andy/demo/flow/1") && runs[0].jobs.is_empty());
739
740
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", None, None).await;
741
    let one: hub_api::FlowRun = serde_json::from_str(&body).unwrap();
742
    let names: Vec<(&str, &str)> = one.jobs.iter().map(|j| (j.name.as_str(), j.status.as_str())).collect();
743
    assert_eq!(names.len(), 3);
744
    let running = one.jobs.iter().find(|j| j.status == "running").unwrap();
745
    assert_eq!(running.name, a["job"]["name"].as_str().unwrap());
746
    assert!(one.jobs.iter().any(|j| j.name == "test" && j.depends_on == ["build"]));
747
748
    let job = running.name.clone();
749
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/1/jobs/{job}/log"), None, None).await;
750
    assert_eq!(st, StatusCode::OK, "{body}");
751
    let lines: Vec<hub_api::FlowLogLine> = serde_json::from_str(&body).unwrap();
752
    assert!(lines.iter().any(|l| l.text == "three"), "{body}");
753
    let last = lines.last().unwrap().seq;
754
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/1/jobs/{job}/log?after={last}"), None, None).await;
755
    assert_eq!(body, "[]", "nothing after the last line");
756
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/9", None, None).await.0, StatusCode::NOT_FOUND);
757
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1/jobs/nope/log", None, None).await.0, StatusCode::NOT_FOUND);
758
759
    // Checks by the state hash, by the head `oxy log` shows, and by bookmark.
760
    let by = |key: String| {
761
        let app = h.app.clone();
762
        async move {
763
            let (st, body) = call(&app, "GET", &format!("/api/v1/repos/andy/demo/checks/{key}"), None, None).await;
764
            assert_eq!(st, StatusCode::OK, "{key}: {body}");
765
            serde_json::from_str::<Vec<hub_api::Check>>(&body).unwrap().len()
766
        }
767
    };
768
    checks_when(&h.app, run.repo_id, &run.state, 3).await;
769
    assert_eq!(by(run.state.clone()).await, 3);
770
    assert_eq!(by(head.to_hex()).await, 3, "a single head names its state");
771
    assert_eq!(by("main".into()).await, 3);
772
    let (st, _) = call(&h.app, "GET", "/api/v1/repos/andy/demo/checks/no-such-bookmark", None, None).await;
773
    assert_eq!(st, StatusCode::NOT_FOUND);
774
775
    // An unknown API route answers with a problem document.
776
    let (st, body) = call(&h.app, "GET", "/api/v1/users/andy/repos", None, None).await;
777
    assert_eq!(st, StatusCode::NOT_FOUND);
778
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
779
    assert_eq!(v["status"], 404, "{body}");
1edac4b6 Andy McCall ↶ 780
}
cc19697f Andy McCall ↶ 781
782
async fn get_bytes(app: &Shared, path: &str) -> (StatusCode, Vec<u8>) {
783
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(path).body(Body::empty()).unwrap()).await.unwrap();
784
    let status = res.status();
785
    (status, res.into_body().collect().await.unwrap().to_bytes().to_vec())
786
}
787
788
#[tokio::test(flavor = "multi_thread")]
789
async fn signed_receipts_are_checked_kept_and_shown() {
790
    use oxy_core::hash::{hash_object, ChangeHash, ObjectRef, ObjectType};
791
    use oxy_core::identity::SecretKey;
792
    use oxy_core::objects::StateObject;
793
    use oxy_core::receipt::SignedReceipt;
794
    let h = hub().await;
795
    create(&h.app, "andy", "demo").await;
796
    let url = format!("{}/andy/demo", h.base);
797
    let work = tempfile::tempdir().unwrap();
798
    let c = client(&url, work.path());
799
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
800
    c.snapshot("test").unwrap();
801
    c.commit("Add a pipeline", &[]).unwrap();
802
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
803
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
804
    let heads: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
805
    let state = hash_object(ObjectType::State, &StateObject::new(heads.clone()).encode());
806
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
807
    let sk = SecretKey::generate();
808
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
809
    let sign = |r: &serde_json::Value, state: ObjectRef, sk: &SecretKey, id: &oxy_core::identity::Identity| {
810
        let r: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
811
        let run_url = format!("{url}/flow/{}", run.number);
812
        hex::encode(SignedReceipt::sign(r.to_oxy(), repo_id, state, &run_url, id, sk).encode())
813
    };
814
815
    let a = claim(&h.app).await.unwrap();
816
    let b = claim(&h.app).await.unwrap();
817
    let ph = a["pipeline_hash"].as_str().unwrap().to_string();
818
    let (a_id, b_id) = (a["job_id"].as_i64().unwrap(), b["job_id"].as_i64().unwrap());
819
    // The first signed receipt binds the runner token to its key, and is kept.
820
    let rb = receipt("build", &ph, 0);
821
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": rb, "signed_receipt": sign(&rb, state, &sk, &runner) });
822
    assert_eq!(finish(&h.app, a_id, body).await, StatusCode::NO_CONTENT);
823
    // Another key under the same token: the result counts, the receipt is not kept.
824
    let other = SecretKey::generate();
825
    let rl = receipt("lint", &ph, 0);
826
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 300, "receipt": rl,
827
        "signed_receipt": sign(&rl, state, &other, &other.identity("mallory", "", 1)) });
828
    assert_eq!(finish(&h.app, b_id, body).await, StatusCode::NO_CONTENT);
829
    // The right key, but for another state.
830
    let t = claim(&h.app).await.unwrap();
831
    let rt = receipt("test", &ph, 0);
832
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 500, "receipt": rt,
833
        "signed_receipt": sign(&rt, ObjectRef([9; 32]), &sk, &runner) });
834
    assert_eq!(finish(&h.app, t["job_id"].as_i64().unwrap(), body).await, StatusCode::NO_CONTENT);
835
836
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
837
    let job = |n: &str| jobs.iter().find(|j| j.name == n).unwrap().clone();
838
    assert_eq!(job("build").status, "passed");
839
    assert_eq!((job("build").receipt_attest.len(), job("build").receipt_signer.as_str()), (64, "test-1 (OxygenFlow runner)"));
840
    assert_eq!(job("lint").status, "passed", "the job's result stands");
841
    assert!(job("lint").receipt_attest.is_empty());
842
    assert!(job("lint").receipt_note.contains("not the key this runner signs with"), "{}", job("lint").receipt_note);
843
    assert!(job("test").receipt_note.contains("another state"), "{}", job("test").receipt_note);
844
845
    // The repository keeps it, and anyone who can read the repository can
846
    // download it and check it on their own.
847
    let kept = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().receipts(&heads).unwrap();
848
    assert_eq!(kept.len(), 1);
849
    let attest = job("build").receipt_attest;
850
    let (st, bytes) = get_bytes(&h.app, &format!("/andy/demo/receipts/{attest}")).await;
851
    assert_eq!(st, StatusCode::OK);
852
    let sr = SignedReceipt::decode(&bytes).unwrap();
853
    sr.verify().unwrap();
854
    assert_eq!((sr.state(), sr.receipt.job_name.as_str()), (state, "build"));
855
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/receipts/{}", "0".repeat(64))).await.0, StatusCode::NOT_FOUND);
856
857
    // Pages: the run names the signer or why a receipt was not kept; the
858
    // change whose state it is lists it.
859
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
860
    assert!(page.contains("signed receipt</a> by test-1"), "run page");
861
    assert!(page.contains("receipt not kept"), "run page");
862
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/change/{}", heads[0].to_hex()), None, None).await;
863
    assert!(page.contains("<dt>Receipts</dt>") && page.contains(&format!("/andy/demo/receipts/{attest}")), "change page");
864
}
a3c8288b Andy McCall ↶ 865
866
async fn upload(app: &Shared, job: i64, name: &str, bytes: &[u8]) -> (StatusCode, String) {
867
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/artifacts/{name}"))
868
        .header(header::AUTHORIZATION, "Bearer runner-secret")
869
        .header(header::CONTENT_TYPE, "application/octet-stream")
870
        .body(Body::from(bytes.to_vec()))
871
        .unwrap();
872
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
873
    let status = res.status();
874
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
875
}
876
877
#[tokio::test(flavor = "multi_thread")]
878
async fn artifacts_are_kept_named_by_the_receipt_and_served() {
879
    let h = hub().await;
880
    create(&h.app, "andy", "demo").await;
881
    let url = format!("{}/andy/demo", h.base);
882
    let work = tempfile::tempdir().unwrap();
883
    let c = client(&url, work.path());
884
    write(
885
        work.path(),
886
        ".flow/pipeline.kdl",
887
        &format!(
888
            "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"
889
        ),
890
    );
891
    c.snapshot("test").unwrap();
892
    c.commit("Build a tool", &[]).unwrap();
893
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
894
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
895
    let a = claim(&h.app).await.unwrap();
896
    assert_eq!(a["job"]["outputs"], serde_json::json!([{ "name": "tool", "path": "/src/out/tool" }]), "the runner is told");
897
    let id = a["job_id"].as_i64().unwrap();
898
899
    let body: Vec<u8> = (0..300_000u32).map(|i| (i % 253) as u8).collect();
900
    let (st, text) = upload(&h.app, id, "other", &body).await;
901
    assert_eq!(st, StatusCode::BAD_REQUEST, "an undeclared artifact: {text}");
902
    let (st, text) = upload(&h.app, id, "tool", &body).await;
903
    assert_eq!(st, StatusCode::OK, "{text}");
904
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
905
    assert_eq!(blob, oxy_core::repo::Repo::blob_ref(&body).to_hex(), "the same blob the runner computes");
906
907
    // The receipt must name exactly the uploaded artifacts.
908
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
909
    assert_eq!(
910
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r.clone() })).await,
911
        StatusCode::BAD_REQUEST
912
    );
913
    r["outputs"] = serde_json::json!([blob]);
914
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r })).await, StatusCode::NO_CONTENT);
915
916
    // The run page lists it; anyone who can read the repository downloads it.
917
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
918
    let link = format!("/andy/demo/flow/{}/artifacts/build/tool", run.number);
919
    assert!(page.contains(&link), "run page lists the artifact");
16ee5d19 Andy McCall ↶ 920
    // So does the repository's Build artifacts page (#254), and the bar's
921
    // Artifacts menu leads there.
922
    let (_, list) = call(&h.app, "GET", "/andy/demo/artifacts", None, None).await;
923
    assert!(list.contains(&link) && list.contains(&format!("#{}</a>", run.number)), "{list}");
924
    assert!(list.contains("<summary class=\"on\">Artifacts</summary>") && list.contains("href=\"/andy/demo/images\""), "{list}");
a3c8288b Andy McCall ↶ 925
    let (st, got) = get_bytes(&h.app, &link).await;
926
    assert_eq!((st, got == body), (StatusCode::OK, true));
927
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/flow/{}/artifacts/build/none", run.number)).await.0, StatusCode::NOT_FOUND);
076c7a7c Andy McCall ↶ 928
    // Provenance (#239): only for a job whose signed receipt the hub kept;
929
    // then an in-toto statement in a DSSE envelope the hub's key verifies.
930
    let prov = format!("{link}/provenance");
931
    assert_eq!(get_bytes(&h.app, &prov).await.0, StatusCode::BAD_REQUEST, "no kept receipt, no provenance");
932
    sqlx::query("UPDATE flow_jobs SET receipt_attest = 'a1b2', receipt_signer = 'test-1 runner' WHERE id = $1")
933
        .bind(id)
934
        .execute(&h.app.db)
935
        .await
936
        .unwrap();
937
    let (st, env) = get_bytes(&h.app, &prov).await;
938
    assert_eq!(st, StatusCode::OK);
939
    let env: serde_json::Value = serde_json::from_slice(&env).unwrap();
940
    assert_eq!(env["payloadType"], "application/vnd.in-toto+json");
681db69e Andy McCall ↶ 941
    let unb64 = |t: &str| oxy_core::dsse::base64_decode(t).expect("base64");
076c7a7c Andy McCall ↶ 942
    let payload = unb64(env["payload"].as_str().unwrap());
943
    let sig = unb64(env["signatures"][0]["sig"].as_str().unwrap());
944
    let signed = oxygenhub::provenance::pae("application/vnd.in-toto+json", &payload);
945
    ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, h.app.hub_key.identity.ed25519_pk)
946
        .verify(&signed, &sig)
947
        .expect("the hub's key signed the envelope");
948
    let statement: serde_json::Value = serde_json::from_slice(&payload).unwrap();
949
    use sha2::Digest;
950
    assert_eq!(statement["subject"][0]["digest"]["sha256"], hex::encode(sha2::Sha256::digest(&body)));
951
    assert_eq!(statement["predicateType"], "https://slsa.dev/provenance/v1");
952
    assert_eq!(statement["predicate"]["buildDefinition"]["externalParameters"]["job"], "build");
953
    assert_eq!(statement["predicate"]["runDetails"]["byproducts"][0]["digest"]["oxygen-attestation"], "a1b2");
954
    let (_, pem) = get_bytes(&h.app, "/.well-known/oxyhub-signing.pem").await;
955
    let pem = String::from_utf8(pem).unwrap();
956
    let der = unb64(pem.lines().filter(|l| !l.starts_with("-----")).collect::<String>().as_str());
957
    assert_eq!(&der[der.len() - 32..], &h.app.hub_key.identity.ed25519_pk[..], "the PEM holds the hub's key");
958
    sqlx::query("UPDATE flow_jobs SET receipt_attest = '', receipt_signer = '' WHERE id = $1").bind(id).execute(&h.app.db).await.unwrap();
10708ab8 Andy McCall ↶ 959
45977501 Andy McCall ↶ 960
    // The nightly gc keeps it (#126): only the database names it, so with
961
    // no grace period a gc that did not root it would prune it at once.
962
    {
963
        let name = RepoName::parse("andy/demo").unwrap();
964
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
965
        hosted.config.set("core.gc-grace", "0").unwrap();
966
        hosted.save_config().unwrap();
967
    }
968
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
969
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
970
    let (st, got) = get_bytes(&h.app, &link).await;
971
    assert_eq!((st, got == body), (StatusCode::OK, true), "the artifact survives gc");
972
10708ab8 Andy McCall ↶ 973
    // A writer attaches the artifact to a release from the run page; the
974
    // release then names the run and job that built it, as does the API.
975
    let form = |f: String| {
976
        Request::post("/register").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(Body::from(f)).unwrap()
977
    };
978
    let res = oxygenhub::router(h.app.clone())
c8684d44 Andy McCall 979
        .oneshot(form("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup".into()))
10708ab8 Andy McCall ↶ 980
        .await
981
        .unwrap();
982
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
983
    let with_cookie = |method: &str, path: &str, body: Option<String>| {
984
        let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie.clone());
985
        if body.is_some() {
986
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
987
        }
988
        req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()
989
    };
990
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
991
    db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
992
    let res = oxygenhub::router(h.app.clone()).oneshot(with_cookie("GET", &format!("/andy/demo/flow/{}", run.number), None)).await.unwrap();
993
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
994
    let attach = format!("/andy/demo/flow/{}/artifacts/build/tool/attach", run.number);
995
    assert!(page.contains(&attach), "a writer is offered the release");
996
    let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
997
    let csrf = page[i..].split('"').next().unwrap().to_string();
998
    let release_id = db::releases::list(&h.app.db, row.id).await.unwrap()[0].id;
999
    let res = oxygenhub::router(h.app.clone())
1000
        .oneshot(with_cookie("POST", &attach, Some(format!("_csrf={csrf}&release={release_id}"))))
1001
        .await
1002
        .unwrap();
1003
    assert_eq!(res.status(), StatusCode::SEE_OTHER);
1004
    let (_, page) = call(&h.app, "GET", "/andy/demo/releases/tag/v1", None, None).await;
1005
    assert!(
1006
        page.contains(">tool</a>") && page.contains(&format!("built by <a href=\"/andy/demo/flow/{0}\">run #{0}</a> build", run.number)),
1007
        "{page}"
1008
    );
1009
    let (_, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases", None, None).await;
1010
    let api: serde_json::Value = serde_json::from_str(&api).unwrap();
1011
    let asset = &api[0]["assets"][0];
1012
    assert_eq!(
1013
        (asset["name"].as_str(), asset["built_by"]["run"].as_i64(), asset["built_by"]["job"].as_str()),
1014
        (Some("tool"), Some(run.number), Some("build"))
1015
    );
1016
    assert!(asset["built_by"]["receipt"].is_null(), "that receipt was not signed");
97fc47fe Andy McCall ↶ 1017
    assert!(asset["built_by"]["provenance_url"].is_null(), "no signed receipt, no provenance");
1018
1019
    // With a kept signed receipt, the asset links its provenance (#239).
1020
    sqlx::query("UPDATE flow_jobs SET receipt_attest = 'a1b2', receipt_signer = 'earth-1' WHERE run_id = $1 AND name = 'build'")
1021
        .bind(run.id)
1022
        .execute(&h.app.db)
1023
        .await
1024
        .unwrap();
1025
    let want = format!("/andy/demo/flow/{}/artifacts/build/tool/provenance", run.number);
1026
    let (_, page) = call(&h.app, "GET", "/andy/demo/releases/tag/v1", None, None).await;
1027
    assert!(page.contains(&format!("href=\"{want}\"")), "{page}");
1028
    let (_, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases", None, None).await;
1029
    let api: serde_json::Value = serde_json::from_str(&api).unwrap();
1030
    assert!(api[0]["assets"][0]["built_by"]["provenance_url"].as_str().unwrap().ends_with(&want));
a3c8288b Andy McCall ↶ 1031
}
df940d75 Andy McCall ↶ 1032
d29070fa Andy McCall ↶ 1033
/// oxygenflow#37: a failing job keeps a `when "always"` artifact; its
1034
/// receipt names none, and the run page says the file is outside it.
a36bab6b Andy McCall ↶ 1035
async fn upload_report_file(app: &Shared, job: i64, name: &str, path: &str, bytes: &[u8]) -> (StatusCode, String) {
1036
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/reports/{name}/files"))
1037
        .header(header::AUTHORIZATION, "Bearer runner-secret")
1038
        .header(header::CONTENT_TYPE, "application/octet-stream")
1039
        .header("X-Flow-Report-Path", path)
1040
        .body(Body::from(bytes.to_vec()))
1041
        .unwrap();
1042
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
1043
    let status = res.status();
1044
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1045
}
1046
1047
/// #127: a report's files arrive one by one, then its manifest as the
1048
/// report's artifact; the hub indexes the declaration, metrics and files,
1049
/// and gc keeps every file.
1050
#[tokio::test(flavor = "multi_thread")]
1051
async fn reports_are_kept_file_by_file_and_indexed() {
1052
    let h = hub().await;
1053
    create(&h.app, "andy", "demo").await;
1054
    let url = format!("{}/andy/demo", h.base);
1055
    let work = tempfile::tempdir().unwrap();
1056
    let c = client(&url, work.path());
1057
    write(
1058
        work.path(),
1059
        ".flow/pipeline.kdl",
1060
        &format!(
1061
            "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"
1062
        ),
1063
    );
1064
    c.snapshot("test").unwrap();
1065
    c.commit("Measure frames", &[]).unwrap();
1066
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1067
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1068
    let a = claim(&h.app).await.unwrap();
1069
    let id = a["job_id"].as_i64().unwrap();
1070
1071
    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";
1072
    let page = b"<p>frames</p>".to_vec();
1073
    let data: Vec<u8> = (0..100_000u32).map(|i| (i % 241) as u8).collect();
c8df33a6 Andy McCall ↶ 1074
    let (page_bytes, data_bytes) = (page.clone(), data.clone());
a36bab6b Andy McCall ↶ 1075
    let files: [(&str, &[u8]); 3] = [("data/frames.csv", &data), ("index.html", &page), ("report.toml", toml)];
1076
1077
    assert_eq!(upload_report_file(&h.app, id, "tool", "report.toml", toml).await.0, StatusCode::BAD_REQUEST, "not a report");
1078
    assert_eq!(upload_report_file(&h.app, id, "frame-timing", "../x", toml).await.0, StatusCode::BAD_REQUEST, "not a clean path");
1079
    let mut listed = vec![];
1080
    for (path, bytes) in files {
1081
        let (st, text) = upload_report_file(&h.app, id, "frame-timing", path, bytes).await;
1082
        assert_eq!(st, StatusCode::OK, "{text}");
1083
        let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1084
        assert_eq!(blob, oxy_core::repo::Repo::blob_ref(bytes).to_hex());
1085
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1086
    }
1087
    let mut missing = listed.clone();
1088
    missing.push(serde_json::json!({ "path": "assets/x.js", "blob": "ab".repeat(32), "size": 1 }));
1089
    let (st, text) =
1090
        upload(&h.app, id, "frame-timing", &serde_json::to_vec(&serde_json::json!({ "version": 1, "files": missing })).unwrap()).await;
1091
    assert_eq!(st, StatusCode::BAD_REQUEST, "a file never uploaded: {text}");
1092
    assert!(text.contains("assets/x.js"), "{text}");
1093
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed })).unwrap();
1094
    let (st, text) = upload(&h.app, id, "frame-timing", &manifest).await;
1095
    assert_eq!(st, StatusCode::OK, "{text}");
1096
1097
    let (kind, title, summary, files_n, bytes): (String, String, String, i64, i64) =
3b1bc27f Andy McCall 1098
        sqlx::query_as("SELECT kind, title, summary, files, bytes FROM reports WHERE job_id = $1 AND name = 'frame-timing'")
a36bab6b Andy McCall ↶ 1099
            .bind(id)
1100
            .fetch_one(&h.app.db)
1101
            .await
1102
            .unwrap();
1103
    assert_eq!((kind.as_str(), title.as_str(), summary.as_str()), ("performance", "Frame timing", "Median 16.4 ms"));
1104
    assert_eq!((files_n, bytes), (3, (data.len() + page.len() + toml.len()) as i64));
3b1bc27f Andy McCall 1105
    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 ↶ 1106
    let m = oxygenhub::reports::metrics(&h.app.db, rid).await.unwrap();
1107
    assert_eq!((m[0].key.as_str(), m[0].value, m[0].fail_above), ("median_ms", 16.4, Some(20.0)));
1108
    let log = db::flow::log(&h.app.db, id, 0, 1000).await.unwrap();
1109
    assert!(log.iter().any(|r| r.text.contains("report frame-timing: performance \"Frame timing\", 1 metric")), "{log:?}");
c8df33a6 Andy McCall ↶ 1110
1111
    // The threshold is a check on the run's state, passing at 16.4.
1112
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
1113
    let c = checks.iter().find(|c| c.name == "report/frame-timing/median_ms").expect("a check per threshold");
1114
    assert_eq!(c.status, "passed", "{c:?}");
1115
    assert!(c.summary.contains("16.4 ms") && c.url.contains("/reports/frame-timing?id="), "{c:?}");
1116
1117
    // The Reports tab, the report's page, and its own page in a sandbox.
1118
    let (_, page) = call(&h.app, "GET", "/andy/demo", None, None).await;
1119
    assert!(page.contains(">Reports</a>"), "the tab");
1120
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports", None, None).await;
1121
    assert!(st == StatusCode::OK && page.contains("Frame timing") && page.contains("median_ms"), "{st}");
1122
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1123
    assert!(st == StatusCode::OK && page.contains("fails above 20") && page.contains("sandbox=\"allow-scripts\""), "{st}");
1124
    let src = page.split("class=\"rep-frame\" src=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
1125
    assert!(src.ends_with("/index.html"), "{src}");
1126
    let res = oxygenhub::router(h.app.clone()).oneshot(Request::get(&src).body(Body::empty()).unwrap()).await.unwrap();
1127
    assert_eq!(res.status(), StatusCode::OK);
1128
    let csp = res.headers()[header::CONTENT_SECURITY_POLICY].to_str().unwrap().to_string();
1129
    assert!(csp.starts_with("sandbox allow-scripts;") && csp.contains("default-src 'none'"), "{csp}");
d74ce22f Andy McCall ↶ 1130
    // The site's own policy and frame refusal stay off it: report frames are framed (#222).
1131
    assert!(
1132
        res.headers().get(header::X_FRAME_OPTIONS).is_none() && res.headers().get(header::CONTENT_SECURITY_POLICY_REPORT_ONLY).is_none()
1133
    );
1134
    assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
c8df33a6 Andy McCall ↶ 1135
    assert_eq!(res.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*");
f3e5e2bc Andy McCall ↶ 1136
    // The page as kept, with the frame script that sizes the frame added.
1137
    let served = res.into_body().collect().await.unwrap().to_bytes().to_vec();
1138
    assert!(served.starts_with(&page_bytes), "the report's page");
1139
    assert!(String::from_utf8_lossy(&served).contains("/static/report-frame.js"), "with the frame script");
1140
    let (st, _) = get_bytes(&h.app, "/static/report.css").await;
1141
    assert_eq!(st, StatusCode::OK, "the stylesheet a report may link");
c8df33a6 Andy McCall ↶ 1142
    let data = src.replace("/index.html", "/data/frames.csv");
1143
    assert_eq!(get_bytes(&h.app, &data).await, (StatusCode::OK, data_bytes.clone()));
1144
    // A link with another report's MAC, or a file it lacks, finds nothing.
95b525b0 Andy McCall ↶ 1145
    // A second run of the report: the timeline has two stops, and the
1146
    // first can be compared with it (RP4).
1147
    let first: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE name = 'frame-timing'").fetch_one(&h.app.db).await.unwrap();
1148
    let second: i64 = sqlx::query_scalar(
1149
        "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 1150
         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 ↶ 1151
    )
1152
    .bind(first)
1153
    .fetch_one(&h.app.db)
1154
    .await
1155
    .unwrap();
1156
    sqlx::query(
3b1bc27f Andy McCall 1157
        "INSERT INTO report_metrics (report_id, key, value, unit, better, fail_above) VALUES ($1, 'median_ms', 18.0, 'ms', 'lower', 20)",
95b525b0 Andy McCall ↶ 1158
    )
1159
    .bind(second)
1160
    .execute(&h.app.db)
1161
    .await
1162
    .unwrap();
1163
    let (_, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1164
    assert_eq!(page.matches("data-tl-stop").count(), 2, "a stop per run");
1165
    assert!(page.contains("Median 18.0 ms"), "the newest run is shown");
1166
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/frame-timing?id={first}&compare={second}&play=3"), None, None).await;
1167
    assert!(page.contains("This run against run #2") && page.contains("-1.6"), "every metric against the other run");
1168
    let stop = page.split("data-tl-stop").next().unwrap_or("").rsplit("href=").next().unwrap_or("").to_string();
1169
    assert!(page.contains("data-play=\"3\""), "playing");
1170
    assert!(stop.contains("play") && stop.contains('3'), "playing carries on from stop to stop: {stop}");
1171
    assert!(page.contains("data-report-runs="), "the frame interface knows the runs");
fac6853c Andy McCall ↶ 1172
1173
    // The same over the API (#348): the job's report with its files, one
1174
    // file as published, the newest of each, one by id, and plain 404s.
1175
    let n = run.number;
1176
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/{n}/jobs/perf/report"), None, None).await;
1177
    assert_eq!(st, StatusCode::OK, "{body}");
1178
    let r: serde_json::Value = serde_json::from_str(&body).unwrap();
1179
    assert_eq!((r["id"].as_i64(), r["name"].as_str(), r["kind"].as_str()), (Some(first), Some("frame-timing"), Some("performance")));
1180
    assert_eq!((r["metrics"][0]["key"].as_str(), r["metrics"][0]["fail_above"].as_f64()), (Some("median_ms"), Some(20.0)));
1181
    assert_eq!(r["context"]["target_fps"], 30);
1182
    let paths: Vec<&str> = r["manifest"].as_array().unwrap().iter().map(|f| f["path"].as_str().unwrap()).collect();
1183
    assert_eq!(paths, ["data/frames.csv", "index.html", "report.toml"]);
1184
    assert!(r["url"].as_str().unwrap().ends_with(&format!("/andy/demo/reports/frame-timing?id={first}")));
1185
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/{n}/jobs/perf/reports"), None, None).await;
1186
    assert!(st == StatusCode::OK && body.contains("\"frame-timing\"") && !body.contains("manifest"), "{st} {body}");
1187
    let res = oxygenhub::router(h.app.clone())
1188
        .oneshot(
1189
            Request::get(format!("/api/v1/repos/andy/demo/flow/runs/{n}/jobs/perf/report/data/frames.csv")).body(Body::empty()).unwrap(),
1190
        )
1191
        .await
1192
        .unwrap();
1193
    assert_eq!(res.status(), StatusCode::OK);
1194
    assert_eq!(res.headers()[header::CONTENT_TYPE], "text/csv; charset=utf-8");
1195
    assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], "sandbox; default-src 'none'", "a page in it runs nothing on the hub");
1196
    assert_eq!(res.into_body().collect().await.unwrap().to_bytes().to_vec(), data_bytes);
1197
    let toml_path = format!("/api/v1/repos/andy/demo/flow/runs/{n}/jobs/perf/report/report.toml?name=frame-timing");
1198
    assert_eq!(get_bytes(&h.app, &toml_path).await, (StatusCode::OK, toml.to_vec()));
1199
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/{n}/jobs/perf/report/nope.csv"), None, None).await;
1200
    assert!(st == StatusCode::NOT_FOUND && body.contains("has no file nope.csv") && body.contains("report.toml"), "{st} {body}");
1201
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/{n}/jobs/perf/report?name=other"), None, None).await;
1202
    assert!(st == StatusCode::NOT_FOUND && body.contains("it published frame-timing"), "{st} {body}");
1203
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/{n}/jobs/nojob/report"), None, None).await;
1204
    assert!(st == StatusCode::NOT_FOUND && body.contains("its jobs: perf"), "{st} {body}");
1205
    // The newest of each is the second run; ?id= reaches the first.
1206
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/reports", None, None).await;
1207
    let latest: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
1208
    assert_eq!((latest.len(), latest[0]["id"].as_i64(), latest[0]["run"].as_i64()), (1, Some(second), Some(2)));
1209
    assert_eq!(latest[0]["metrics"][0]["value"].as_f64(), Some(18.0));
1210
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/reports/frame-timing", None, None).await;
1211
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["id"].as_i64(), Some(second), "newest on its bookmark");
1212
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/reports/frame-timing?id={first}"), None, None).await;
1213
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["summary"], "Median 16.4 ms");
1214
    let page_path = format!("/api/v1/repos/andy/demo/reports/frame-timing/files/index.html?id={first}");
1215
    assert_eq!(get_bytes(&h.app, &page_path).await, (StatusCode::OK, page_bytes.clone()), "as published, no frame script");
1216
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/reports/frame-timing?bookmark=elsewhere", None, None).await;
1217
    assert!(st == StatusCode::NOT_FOUND && body.contains("never ran on elsewhere"), "{st} {body}");
1218
    let (st, _) = call(&h.app, "GET", "/api/v1/repos/andy/demo/reports/nothing", None, None).await;
1219
    assert_eq!(st, StatusCode::NOT_FOUND);
1220
    // A run's jobs carry their timings, phases in the order taken.
1221
    let phases = std::collections::BTreeMap::from([("run".to_string(), 1200u64), ("image".to_string(), 300)]);
1222
    db::flow::set_phases(&h.app.db, id, &phases).await.unwrap();
1223
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/{n}"), None, None).await;
1224
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
1225
    assert!(v["jobs"][0]["queued_ms"].as_i64().is_some(), "{body}");
1226
    assert_eq!(v["jobs"][0]["phases"], serde_json::json!([{ "name": "image", "ms": 300 }, { "name": "run", "ms": 1200 }]));
c8df33a6 Andy McCall ↶ 1227
    let forged = src.replacen("/files/", "/files/9", 1);
1228
    assert_eq!(get_bytes(&h.app, &forged).await.0, StatusCode::NOT_FOUND);
1229
    assert_eq!(get_bytes(&h.app, &src.replace("/index.html", "/secret.txt")).await.0, StatusCode::NOT_FOUND);
a36bab6b Andy McCall ↶ 1230
    let _ = run;
1231
1232
    // gc keeps every file: only the database names them.
1233
    {
1234
        let name = RepoName::parse("andy/demo").unwrap();
1235
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
1236
        hosted.config.set("core.gc-grace", "0").unwrap();
1237
        hosted.save_config().unwrap();
1238
    }
1239
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
1240
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
1241
    let hosted = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
1242
    for (path, bytes) in files {
1243
        assert_eq!(hosted.read_blob(&oxy_core::repo::Repo::blob_ref(bytes)).unwrap(), bytes, "{path} survives gc");
1244
    }
1245
}
1246
d29070fa Andy McCall ↶ 1247
#[tokio::test(flavor = "multi_thread")]
1248
async fn a_failing_job_keeps_an_artifact_outside_its_receipt() {
1249
    let h = hub().await;
1250
    create(&h.app, "andy", "demo").await;
1251
    let url = format!("{}/andy/demo", h.base);
1252
    let work = tempfile::tempdir().unwrap();
1253
    let c = client(&url, work.path());
1254
    write(
1255
        work.path(),
1256
        ".flow/pipeline.kdl",
1257
        &format!(
336c953a Andy McCall ↶ 1258
            "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 ↶ 1259
        ),
1260
    );
1261
    c.snapshot("test").unwrap();
1262
    c.commit("Test", &[]).unwrap();
1263
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1264
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1265
    let a = claim(&h.app).await.unwrap();
336c953a Andy McCall ↶ 1266
    assert_eq!(a["job"]["outputs"][0]["always"], true, "the runner is told to keep it from a failing job");
d29070fa Andy McCall ↶ 1267
    let id = a["job_id"].as_i64().unwrap();
0b203bbf Andy McCall ↶ 1268
    // A JUnit report (#114): parsed on upload, counted, failures listed.
1269
    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>"#;
1270
    let (st, text) = upload(&h.app, id, "junit", xml).await;
d29070fa Andy McCall ↶ 1271
    assert_eq!(st, StatusCode::OK, "{text}");
1272
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1273
    let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), 1);
1274
    r["outputs"] = serde_json::json!([blob]);
1275
    assert_eq!(
1276
        finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r.clone() })).await,
1277
        StatusCode::BAD_REQUEST,
1278
        "a failing receipt names no outputs"
1279
    );
1280
    r["outputs"] = serde_json::json!([]);
04683947 Andy McCall ↶ 1281
    // oxygenflow#35: where its time went, as the runner reports it.
1282
    let phases = serde_json::json!({ "image": 9000, "prepare": 1200, "run": 3400, "finish": 500 });
1283
    assert_eq!(
1284
        finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r, "phases": phases })).await,
1285
        StatusCode::NO_CONTENT
1286
    );
d29070fa Andy McCall ↶ 1287
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
04683947 Andy McCall ↶ 1288
    let at = page.find("Where its time went: ").expect("the job's phases");
1289
    let line = &page[at..at + 120];
1290
    let order: Vec<usize> = ["image", "prepare", "run", "finish"].iter().map(|p| line.find(p).expect(p)).collect();
1291
    assert!(order.windows(2).all(|w| w[0] < w[1]), "in the order they happened: {line}");
d29070fa Andy McCall ↶ 1292
    assert!(page.contains(&format!("/andy/demo/flow/{}/artifacts/test/junit", run.number)), "listed");
1293
    assert!(page.contains("not in its receipt"), "marked");
0b203bbf Andy McCall ↶ 1294
    assert!(page.contains("2 tests: 1 failed"), "counts beside the job");
1295
    assert!(page.contains("tests.test_io::test_write") && page.contains("disk full") && page.contains("OSError"), "the failure");
1296
    assert!(page.contains("tests: 2 tests: 1 failed in 2.0 s"), "said in the job's log");
d29070fa Andy McCall ↶ 1297
}
1298
df940d75 Andy McCall ↶ 1299
/// A release's trust report (hub spec §9.1): a signed tag, an asset built
1300
/// by a job with a signed receipt from the tagged state, and one uploaded
1301
/// by hand; the page, its JSON export and the API.
1302
#[tokio::test(flavor = "multi_thread")]
1303
async fn a_release_is_audited_from_authors_to_receipts() {
1304
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
1305
    use oxy_core::identity::SecretKey;
1306
    use oxy_core::objects::StateObject;
1307
    use oxy_core::receipt::SignedReceipt;
1308
    let h = hub().await;
1309
    create(&h.app, "andy", "demo").await;
1310
    let url = format!("{}/andy/demo", h.base);
1311
    let work = tempfile::tempdir().unwrap();
1312
    let mut c = client(&url, work.path());
1313
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
1314
    write(
1315
        work.path(),
1316
        ".flow/pipeline.kdl",
1317
        &format!(
1318
            "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"
1319
        ),
1320
    );
1321
    c.snapshot("test").unwrap();
1322
    c.commit("Build a tool", &[]).unwrap();
1323
    let heads = c.bookmark_heads().unwrap();
1324
    c.tag_create("v1", &heads, "first").unwrap();
1325
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1326
1327
    // The runner builds, uploads the artifact and signs its receipt.
1328
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1329
    let a = claim(&h.app).await.unwrap();
1330
    let id = a["job_id"].as_i64().unwrap();
1331
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
1332
    let (_, text) = upload(&h.app, id, "tool", &body).await;
1333
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1334
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
1335
    r["outputs"] = serde_json::json!([blob]);
1336
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
1337
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
1338
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
1339
    let sk = SecretKey::generate();
1340
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
1341
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
1342
    let signed = hex::encode(SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/1"), &runner, &sk).encode());
1343
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
1344
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
1345
1346
    // A release with the built asset and a file uploaded by hand.
1347
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1348
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
1349
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
1350
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "notes.txt", "", b"by hand\n").await.unwrap();
1351
1352
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
1353
    assert_eq!(st, StatusCode::OK);
1354
    for want in [
1355
        "Tag v1 is signed",
1356
        "The one change in the release is authenticated",
1357
        "tool: signed receipt from run #1 build",
1358
        "a runner key of this hub",
edcef275 Andy McCall ↶ 1359
        "The tagged state is one change",
df940d75 Andy McCall ↶ 1360
        "tool: built from the tagged state",
1361
        "tool: pinned environment",
1362
        "notes.txt: no build found",
1363
        "<svg class=\"trust-graph\"",
bf5101d3 Andy McCall ↶ 1364
        // oxygenhub#79: a summary of badges, badges in the graph, and the
1365
        // graph drawn at its own size rather than stretched to the page.
1366
        "Tag signed by",
1367
        "1 of 1 changes signed or sealed",
1368
        "1 of 2 assets built and attested by OxygenFlow",
1369
        "attested build",
1370
        "uploaded by hand",
1371
        "receipt verified",
1372
        "class=\"shackle\"",
1373
        "<title>notes.txt:",
df940d75 Andy McCall ↶ 1374
    ] {
1375
        assert!(page.contains(want), "missing {want:?}");
1376
    }
bf5101d3 Andy McCall ↶ 1377
    let svg = &page[page.find("<svg class=\"trust-graph\"").unwrap()..];
1378
    assert!(svg[..200].contains(" width=\"") && svg[..200].contains(" height=\""), "the graph has its own size: {}", &svg[..200]);
df940d75 Andy McCall ↶ 1379
    let (_, releases) = call(&h.app, "GET", "/andy/demo/releases", None, None).await;
1380
    assert!(releases.contains("/andy/demo/releases/trust/v1"), "the release links its audit");
1381
1382
    // The export carries the signed receipt, which checks on its own.
1383
    let (st, json) = call(&h.app, "GET", "/andy/demo/releases/trust/v1?format=json", None, None).await;
1384
    assert_eq!(st, StatusCode::OK);
1385
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
1386
    assert_eq!((t["tag"].as_str(), t["tag_signature"].as_str(), t["changes"].as_i64()), (Some("v1"), Some("valid"), Some(1)));
1387
    assert_eq!(t["authors"][0]["who"]["name"], "Andy");
1388
    let tool = t["assets"].as_array().unwrap().iter().find(|a| a["name"] == "tool").unwrap();
1389
    let hex_receipt = tool["build"]["signed_receipt"].as_str().unwrap();
1390
    let sr = SignedReceipt::decode(&hex::decode(hex_receipt).unwrap()).unwrap();
1391
    sr.verify().unwrap();
1392
    assert_eq!(sr.receipt.outputs[0].to_hex(), blob);
1393
    let audit = t["audit"].as_array().unwrap();
1394
    assert!(audit.iter().any(|c| c["verdict"] == "warn" && c["title"].as_str().unwrap().starts_with("notes.txt")));
1395
    assert!(!audit.iter().any(|c| c["verdict"] == "fail"), "{audit:?}");
1396
    // The API gives the same report; an unknown release is a 404.
1397
    let (st, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v1", None, None).await;
1398
    assert_eq!(st, StatusCode::OK);
1399
    assert_eq!(serde_json::from_str::<serde_json::Value>(&api).unwrap()["assets"].as_array().unwrap().len(), 2);
1400
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1401
    assert_eq!(call(&h.app, "GET", "/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1402
}
b6b7e4cf Andy McCall ↶ 1403
1404
/// Runners (hub spec §13.2): an administrator makes a registration token,
1405
/// a runner registers with it (binding its key), claims, shows on Admin →
1406
/// Runners with its history, and is drained, disabled and removed.
1407
#[tokio::test(flavor = "multi_thread")]
1408
async fn runners_register_show_their_history_and_are_drained_and_removed() {
1409
    use oxy_core::identity::SecretKey;
1410
    let h = hub().await;
1411
    create(&h.app, "andy", "demo").await;
1412
    // A signed-in site administrator.
1413
    let res = oxygenhub::router(h.app.clone())
1414
        .oneshot(
1415
            Request::post("/register")
1416
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
c8684d44 Andy McCall 1417
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
b6b7e4cf Andy McCall ↶ 1418
                .unwrap(),
1419
        )
1420
        .await
1421
        .unwrap();
1422
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1423
    let admin = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
1424
    db::accounts::set_admin(&h.app.db, admin.id, true).await.unwrap();
1425
    let web = |method: &'static str, path: String, body: Option<String>| {
1426
        let (app, cookie) = (h.app.clone(), cookie.clone());
1427
        async move {
1428
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1429
            if body.is_some() {
1430
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1431
            }
1432
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1433
            let st = res.status();
1434
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1435
        }
1436
    };
1437
    let csrf_of = |page: &str| {
1438
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1439
        page[i..].split('"').next().unwrap().to_string()
1440
    };
1441
    let (st, page) = web("GET", "/admin/runners".into(), None).await;
1442
    assert_eq!(st, StatusCode::OK);
1443
    assert!(page.contains("No runners yet"));
1444
    assert_eq!(call(&h.app, "GET", "/admin/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1445
1446
    // A one-time registration token, shown once with the command.
1447
    let (_, page) = web("POST", "/admin/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1448
    let i = page.find("--token ").unwrap() + "--token ".len();
1449
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1450
    assert!(token.starts_with("flowreg_"), "{token}");
1451
1452
    // The runner registers, binding its key; the token then is spent.
1453
    let sk = SecretKey::generate();
1454
    let identity = sk.identity("plex (OxygenFlow runner)", "", 1);
1455
    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 });
1456
    let reg = serde_json::json!({ "token": token, "name": "plex", "identity": hex::encode(identity.encode()), "info": info });
1457
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1458
    assert_eq!(st, StatusCode::OK, "{body}");
1459
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1460
    assert!(credential.starts_with("flowrunner_"));
1461
    assert_eq!(
1462
        call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0,
1463
        StatusCode::FORBIDDEN,
1464
        "used once"
1465
    );
1466
1467
    // It claims with its credential; the hub.toml runner shows too.
1468
    let claim_as = |who: String| {
1469
        let app = h.app.clone();
1470
        let info = info.clone();
1471
        async move {
1472
            let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
1473
            call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await
1474
        }
1475
    };
1476
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "nothing queued");
1477
    assert_eq!(claim(&h.app).await, None);
1478
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1479
    assert!(
1480
        page.contains(">plex</strong>") && page.contains("st-online") && page.contains("x86_64 · linux") && page.contains("big-disk"),
1481
        "{page}"
1482
    );
1483
    assert!(page.contains(">test-1</strong>") && page.contains("hub.toml"), "the configured runner, by its claimed name");
1484
    let plex = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1485
    assert_eq!(plex.key, identity.hash().to_hex(), "bound at registration");
1486
1487
    // A run: plex takes a job, and its history shows it.
1488
    let url = format!("{}/andy/demo", h.base);
1489
    let work = tempfile::tempdir().unwrap();
1490
    let c = client(&url, work.path());
1491
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1492
    c.snapshot("test").unwrap();
1493
    c.commit("Add a pipeline", &[]).unwrap();
1494
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1495
    runs_of(&h.app, "andy", "demo").await;
1496
    let (st, body) = claim_as(credential.clone()).await;
1497
    assert_eq!(st, StatusCode::OK, "{body}");
1498
    let job: serde_json::Value = serde_json::from_str(&body).unwrap();
1ec29691 Andy McCall ↶ 1499
    // The build it ran on is kept with the job, for waves of updates (oxygenflow#84).
1500
    let kept: String =
1501
        sqlx::query_scalar("SELECT runner_version FROM flow_jobs WHERE runner_id = $1").bind(plex.id).fetch_one(&h.app.db).await.unwrap();
1502
    assert_eq!(kept, "0.1.0");
b6b7e4cf Andy McCall ↶ 1503
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1504
    assert!(
1505
        page.contains("andy/demo") && page.contains(job["job"]["name"].as_str().unwrap()) && page.contains("Running now</dt><dd>1 job"),
1506
        "{page}"
1507
    );
b66e70b7 Andy McCall ↶ 1508
    // The queue on Admin → Runners and through the API (#41, part 4).
1509
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
e9b9619c Andy McCall ↶ 1510
    assert!(page.contains("id=\"queue\"") && page.contains(">plex</a></td>"), "{page}");
1511
    // Connectivity and what it is doing, kept apart (#243); its status
1512
    // opens the queue filtered to it, and the filters keep and drop jobs.
1513
    assert!(page.contains("running 1 of ") && page.contains("/admin/runners?runner=plex#queue"), "{page}");
1514
    let (_, only) = web("GET", "/admin/runners?runner=plex".into(), None).await;
1515
    assert!(only.contains(">plex</a></td>") && only.contains(" of ") && only.contains(">all</a>"), "{only}");
1516
    let (_, none) = web("GET", "/admin/runners?runner=nobody&status=running".into(), None).await;
1517
    assert!(none.contains("Nothing matches."), "{none}");
1518
    // A busy runner claims nothing; its heartbeat keeps it online.
1519
    sqlx::query("UPDATE flow_runners SET last_seen_ms = 0 WHERE id = $1").bind(plex.id).execute(&h.app.db).await.unwrap();
1520
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1521
    assert!(page.contains("st-offline"), "quiet for long: offline");
1522
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/heartbeat", Some(&credential), None).await.0, StatusCode::NO_CONTENT);
1523
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/heartbeat", Some("flowrunner_nope"), None).await.0, StatusCode::UNAUTHORIZED);
1524
    let plex_now = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1525
    assert_eq!(plex_now.connectivity(), "online");
b66e70b7 Andy McCall ↶ 1526
    let (_, tokens) = web("GET", "/settings/tokens".into(), None).await;
1527
    let (_, made) = web("POST", "/settings/tokens".into(), Some(format!("_csrf={}&name=admin&scopes=user%3Aread", csrf_of(&tokens)))).await;
1528
    let i = made.find("oxyhub_").unwrap();
1529
    let admin_token: String = made[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
1530
    let (st, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1531
    assert_eq!(st, StatusCode::OK, "{body}");
1532
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1533
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1534
    assert_eq!((plex_row["running"].as_i64(), plex_row["arch"].as_str()), (Some(1), Some("x86_64")));
7f5f6c05 Andy McCall ↶ 1535
    // A runner's own labels and time limit from its page (#98).
1536
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1537
    let (st, _) = web(
1538
        "POST",
1539
        format!("/admin/runners/{}/limits", plex.id),
1540
        Some(format!("_csrf={}&labels=gpu%2C+plex&timeout_minutes=5", csrf_of(&page))),
1541
    )
1542
    .await;
1543
    assert_eq!(st, StatusCode::SEE_OTHER);
1544
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1545
    assert!(page.contains(">gpu<") && page.contains("5 min for its jobs"), "{page}");
1546
    let (_, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1547
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1548
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1549
    assert!(plex_row["labels"].as_array().unwrap().iter().any(|l| l == "gpu"), "{plex_row}");
1550
    let (st, _) = web(
1551
        "POST",
1552
        format!("/admin/runners/{}/limits", plex.id),
1553
        Some(format!("_csrf={}&labels=bad%20label%21&timeout_minutes=", csrf_of(&page))),
1554
    )
1555
    .await;
1556
    assert_eq!(st, StatusCode::BAD_REQUEST, "a label with a space or punctuation is refused");
b66e70b7 Andy McCall ↶ 1557
    let (_, body) = call(&h.app, "GET", "/api/v1/runners/queue", Some(&admin_token), None).await;
1558
    let queue: serde_json::Value = serde_json::from_str(&body).unwrap();
1559
    assert!(queue.as_array().unwrap().iter().any(|q| q["status"] == "running" && q["runner"] == "plex"), "{queue}");
1560
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/runners/{}/jobs", plex.id), Some(&admin_token), None).await;
1561
    let jobs: serde_json::Value = serde_json::from_str(&body).unwrap();
1562
    assert_eq!(jobs[0]["repo"], "andy/demo", "{jobs}");
1563
    assert_eq!(call(&h.app, "GET", "/api/v1/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
b6b7e4cf Andy McCall ↶ 1564
1565
    // Draining: no new work; removing while busy is refused.
1566
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1567
    let csrf = csrf_of(&page);
1568
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=draining"))).await;
1569
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "a draining runner takes nothing");
1570
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1571
    assert!(page.contains("is running jobs: drain it first"), "{page}");
1572
    // Its job finishes; disabled, it is refused; removed, its credential is dead.
1573
    let id = job["job_id"].as_i64().unwrap();
1574
    let done = call(
1575
        &h.app,
1576
        "POST",
1577
        &format!("/api/v1/flow/jobs/{id}/finish"),
1578
        Some(&credential),
1579
        Some(r#"{"exit_code":0,"duration_ms":5}"#.into()),
1580
    )
1581
    .await;
1582
    assert_eq!(done.0, StatusCode::NO_CONTENT);
1583
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=disabled"))).await;
1584
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::FORBIDDEN);
1585
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1586
    assert!(page.contains("Removed plex."), "{page}");
1587
    assert_eq!(claim_as(credential).await.0, StatusCode::UNAUTHORIZED);
1588
}
74be9796 Andy McCall ↶ 1589
1590
/// Runner scopes (oxygenhub#41): a runner registered for one repository, or
1591
/// one owner, takes only those jobs; a site runner takes any.
1592
#[tokio::test(flavor = "multi_thread")]
1593
async fn scoped_runners_take_only_their_scope() {
1594
    use oxy_core::identity::SecretKey;
1595
    let h = hub().await;
1596
    create(&h.app, "andy", "demo").await;
1597
    create(&h.app, "andy", "other").await;
1598
    let register = |scope: db::runners::Scope, name: &'static str| {
1599
        let app = h.app.clone();
1600
        async move {
1601
            let token = format!("flowreg_{name}");
1602
            db::runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &scope).await.unwrap();
1603
            let identity = SecretKey::generate().identity(name, "", 1);
1604
            let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1605
            let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
1606
            let (st, body) = call(&app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1607
            assert_eq!(st, StatusCode::OK, "{body}");
1608
            serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string()
1609
        }
1610
    };
1611
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1612
    let only_demo = register(db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) }, "demo-runner").await;
1613
    let carols = register(db::runners::Scope { owner: "carol".into(), repo_id: None }, "carol-runner").await;
1614
    let andys = register(db::runners::Scope { owner: "andy".into(), repo_id: None }, "andy-runner").await;
1615
    let claim_as = |who: String| {
1616
        let app = h.app.clone();
1617
        async move {
1618
            let body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"] }).to_string();
1619
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await;
1620
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["repo"].as_str().unwrap().to_string())
1621
        }
1622
    };
1623
    // Jobs queued in andy/other only.
1624
    let work = tempfile::tempdir().unwrap();
1625
    let c = client(&format!("{}/andy/other", h.base), work.path());
1626
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1627
    c.snapshot("t").unwrap();
1628
    c.commit("pipeline", &[]).unwrap();
1629
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1630
    assert!(!runs_of(&h.app, "andy", "other").await.is_empty());
1631
    assert_eq!(claim_as(only_demo.clone()).await, None, "nothing of andy/demo is queued");
1632
    assert_eq!(claim_as(carols).await, None, "nothing of carol's");
1633
    assert_eq!(claim_as(andys).await.as_deref(), Some("andy/other"), "the owner's runner takes its repositories' jobs");
1634
    // The site runner (hub.toml) takes any.
1635
    assert_eq!(claim(&h.app).await.unwrap()["repo"], "andy/other");
1636
    assert_eq!(claim_as(only_demo).await, None, "still nothing of its own");
1637
}
7974adb0 Andy McCall ↶ 1638
5714347a Andy McCall ↶ 1639
/// oxygenhub-android#8: an app asks for a registration token for its
1640
/// user's own repositories; the runner it registers takes their jobs and
1641
/// no one else's.
1642
#[tokio::test(flavor = "multi_thread")]
1643
async fn a_user_registers_a_runner_for_their_own_repositories() {
1644
    use oxy_core::identity::SecretKey;
1645
    let h = hub().await;
1646
    create(&h.app, "andy", "demo").await;
1647
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "", "salt", false).await.unwrap();
1648
    let pat = "oxyhub_phone_test_token";
1649
    db::accounts::create_token(&h.app.db, andy.id, "phone", &oxygenhub::auth::token_hash(pat), "repo:read,repo:write", "", None)
1650
        .await
1651
        .unwrap();
1652
    let read_only = "oxyhub_read_only_token";
1653
    db::accounts::create_token(&h.app.db, andy.id, "ro", &oxygenhub::auth::token_hash(read_only), "repo:read", "", None).await.unwrap();
1654
    assert_eq!(call(&h.app, "POST", "/api/v1/user/runner-token", Some(read_only), None).await.0, StatusCode::FORBIDDEN);
1655
    assert_eq!(call(&h.app, "POST", "/api/v1/user/runner-token", None, None).await.0, StatusCode::UNAUTHORIZED);
1656
    let (st, body) = call(&h.app, "POST", "/api/v1/user/runner-token", Some(pat), None).await;
1657
    assert_eq!(st, StatusCode::CREATED, "{body}");
1658
    let got: serde_json::Value = serde_json::from_str(&body).unwrap();
1659
    let token = got["token"].as_str().unwrap().to_string();
1660
    assert!(token.starts_with("flowreg_") && got["owner"] == "andy", "{body}");
1661
    let identity = SecretKey::generate().identity("andy's phone", "", 1);
1662
    let info = serde_json::json!({ "arch": "aarch64", "os": "android", "version": "0.3.1", "labels": ["android"], "max_jobs": 1 });
1663
    let reg = serde_json::json!({ "token": token, "name": "pixel", "identity": hex::encode(identity.encode()), "info": info });
1664
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1665
    assert_eq!(st, StatusCode::OK, "{body}");
1666
    let phone = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "pixel").unwrap();
1667
    assert_eq!((phone.scope_owner.as_str(), phone.scope_repo_id), ("andy", None), "andy's repositories, all of them, and no one else's");
1668
}
1669
7974adb0 Andy McCall ↶ 1670
/// Settings → Runners (oxygenhub#41, part 2b): a repository's admin adds a
1671
/// runner for that repository alone, sees which runners serve it, and
1672
/// removes only its own.
1673
#[tokio::test(flavor = "multi_thread")]
1674
async fn repository_admins_add_and_remove_their_own_runners() {
1675
    use oxy_core::identity::SecretKey;
1676
    let h = hub().await;
1677
    let res = oxygenhub::router(h.app.clone())
1678
        .oneshot(
1679
            Request::post("/register")
1680
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
c8684d44 Andy McCall 1681
                .body(Body::from("username=andy&email=andy%40example.com&password=correct-horse-battery&setup=test-setup"))
7974adb0 Andy McCall ↶ 1682
                .unwrap(),
1683
        )
1684
        .await
1685
        .unwrap();
1686
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1687
    create(&h.app, "andy", "demo").await;
1688
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1689
    let web = |method: &'static str, path: String, body: Option<String>| {
1690
        let (app, cookie) = (h.app.clone(), cookie.clone());
1691
        async move {
1692
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1693
            if body.is_some() {
1694
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1695
            }
1696
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1697
            let st = res.status();
1698
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1699
        }
1700
    };
1701
    let csrf_of = |page: &str| {
1702
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1703
        page[i..].split('"').next().unwrap().to_string()
1704
    };
c7067c7b Andy McCall 1705
    let (st, page) = web("GET", "/andy/demo/settings/runners".into(), None).await;
7974adb0 Andy McCall ↶ 1706
    assert_eq!(st, StatusCode::OK);
c7067c7b Andy McCall 1707
    assert!(page.contains("<h2>Runners</h2>"), "the owner sees the page");
7974adb0 Andy McCall ↶ 1708
    let (_, page) = web("POST", "/andy/demo/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1709
    let i = page.find("--token ").unwrap() + "--token ".len();
1710
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1711
    let identity = SecretKey::generate().identity("mine", "", 1);
1712
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1713
    let reg = serde_json::json!({ "token": token, "name": "mine", "identity": hex::encode(identity.encode()), "info": info });
1714
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1715
    assert_eq!(st, StatusCode::OK, "{body}");
1716
    let mine = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "mine").unwrap();
1717
    assert_eq!(mine.scope(), db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) });
1718
    // The site's runner (hub.toml, from its first claim) serves it too, but is not the owner's to remove.
1719
    claim(&h.app).await;
1720
    let site = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "test-1").unwrap();
c7067c7b Andy McCall 1721
    let (_, page) = web("GET", "/andy/demo/settings/runners".into(), None).await;
7974adb0 Andy McCall ↶ 1722
    assert!(page.contains("<strong>mine</strong>") && page.contains("this repository"), "{page}");
1723
    assert!(page.contains("<strong>test-1</strong>") && page.contains("the whole site"), "{page}");
1724
    let csrf = csrf_of(&page);
1725
    let (st, _) = web("POST", format!("/andy/demo/settings/runners/{}/remove", site.id), Some(format!("_csrf={csrf}"))).await;
1726
    assert_eq!(st, StatusCode::NOT_FOUND, "not the repository's own");
c7067c7b Andy McCall 1727
    let (st, _) = web("POST", format!("/andy/demo/settings/runners/{}/remove", mine.id), Some(format!("_csrf={csrf}"))).await;
1728
    assert_eq!(st, StatusCode::SEE_OTHER, "back to the Runners page");
1729
    let (_, page) = web("GET", "/andy/demo/settings/runners?notice=x".into(), None).await;
1730
    assert!(!page.contains("<strong>mine</strong>"), "{page}");
7974adb0 Andy McCall ↶ 1731
    assert!(db::runners::get(&h.app.db, mine.id).await.unwrap().is_none());
1732
1733
    // The same for an organisation's owner.
1734
    let (_, page) = web("GET", "/orgs/new".into(), None).await;
1735
    web("POST", "/orgs/new".into(), Some(format!("_csrf={}&name=acme&display_name=Acme", csrf_of(&page)))).await;
1736
    let (st, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1737
    assert_eq!(st, StatusCode::OK);
1738
    let (_, page) = web("POST", "/orgs/acme/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1739
    let i = page.find("--token ").unwrap() + "--token ".len();
1740
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1741
    let identity = SecretKey::generate().identity("acme-runner", "", 1);
1742
    let reg = serde_json::json!({ "token": token, "name": "acme-runner", "identity": hex::encode(identity.encode()), "info": info });
1743
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0, StatusCode::OK);
1744
    let acme = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "acme-runner").unwrap();
1745
    assert_eq!(acme.scope(), db::runners::Scope { owner: "acme".into(), repo_id: None });
1746
    let (_, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1747
    assert!(page.contains("<strong>acme-runner</strong>") && page.contains("the organisation's repositories"), "{page}");
1748
    let (_, page) = web("POST", format!("/orgs/acme/settings/runners/{}/remove", acme.id), Some(format!("_csrf={}", csrf_of(&page)))).await;
1749
    assert!(page.contains("acme-runner removed"), "{page}");
1750
}
c4c87f48 Andy McCall ↶ 1751
1752
/// runs-on (oxygenhub#41, part 3): a job that asks for a label goes only to
1753
/// a runner that has it, and waits for one otherwise.
1754
#[tokio::test(flavor = "multi_thread")]
1755
async fn jobs_that_ask_for_labels_wait_for_a_runner_with_them() {
1756
    use oxy_core::identity::SecretKey;
1757
    let h = hub().await;
1758
    create(&h.app, "andy", "demo").await;
1759
    let work = tempfile::tempdir().unwrap();
1760
    let c = client(&format!("{}/andy/demo", h.base), work.path());
1761
    let cross = "job \"cross\" {\n    sandbox \"alpine\"\n    runs-on \"riscv64\"\n    exec \"true\"\n}\n";
1762
    write(work.path(), ".flow/pipeline.kdl", &pipeline(cross));
1763
    c.snapshot("t").unwrap();
1764
    c.commit("pipeline", &[]).unwrap();
1765
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1766
    assert!(!runs_of(&h.app, "andy", "demo").await.is_empty());
1767
    // The site runner has no labels: it takes the others, never cross.
1768
    let mut taken = Vec::new();
1769
    while let Some(j) = claim(&h.app).await {
1770
        taken.push(j["job"]["name"].as_str().unwrap().to_string());
1771
    }
1772
    assert!(!taken.contains(&"cross".to_string()) && taken.contains(&"lint".to_string()), "{taken:?}");
1773
    let queue = db::flow::queue(&h.app.db).await.unwrap();
1774
    let waiting = queue.iter().find(|q| q.job == "cross").unwrap();
1775
    assert_eq!((waiting.status.as_str(), waiting.needs()), ("queued", vec!["riscv64".to_string()]));
1776
    // A runner registered with the label takes it.
1777
    let token = "flowreg_riscv";
1778
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
1779
    let identity = SecretKey::generate().identity("visionfive", "", 1);
1780
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": ["riscv64"], "max_jobs": 1 });
1781
    let reg = serde_json::json!({ "token": token, "name": "visionfive", "identity": hex::encode(identity.encode()), "info": info });
1782
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1783
    assert_eq!(st, StatusCode::OK, "{body}");
1784
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1785
    let claim_body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"], "info": info }).to_string();
1786
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(claim_body)).await;
1787
    assert_eq!(st, StatusCode::OK, "{body}");
1788
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"], "cross");
1789
}
070a7b64 Andy McCall ↶ 1790
1791
/// oxygenhub#71: a job its runner stopped reporting (restarted, or lost
1792
/// the hub as the job ended) is ended once it has run past the time limit
1793
/// and a grace: an error with the reason, its dependents skipped and its
1794
/// run settled, as if the runner had reported the error.
1795
#[tokio::test(flavor = "multi_thread")]
1796
async fn a_job_no_runner_reports_is_ended_after_the_time_limit() {
1797
    let h = hub().await;
1798
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1799
    create(&h.app, "andy", "lost").await;
1800
    let url = format!("{}/andy/lost", h.base);
1801
    let work = tempfile::tempdir().unwrap();
1802
    let c = client(&url, work.path());
1803
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1804
    write(work.path(), "test.sh", "echo ok\n");
1805
    c.commit("Add a pipeline", &[]).unwrap();
1806
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1807
    assert_eq!(runs_of(&h.app, "andy", "lost").await.len(), 1);
1808
    let job = claim(&h.app).await.expect("a job to claim");
1809
    let id = job["job_id"].as_i64().unwrap();
1810
1811
    // Running, but well within the limit: left alone.
1812
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 0);
1813
    // Started long ago and never reported: ended.
1814
    let old = db::now_ms() - 24 * 3600 * 1000;
3b1bc27f Andy McCall 1815
    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 ↶ 1816
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 1);
1817
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1818
    assert_eq!(j.status, "error");
1819
    assert!(j.error.starts_with("lost:"), "{}", j.error);
1820
    let run = &runs_of(&h.app, "andy", "lost").await[0];
1821
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
1822
    assert!(jobs.iter().all(|j| j.status != "running"), "nothing left running");
1823
    // A late report, should one come, does not overwrite the ending.
1824
    assert_ne!(finish(&h.app, id, serde_json::json!({ "exit_code": 0 })).await, StatusCode::NO_CONTENT);
1825
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "error");
1826
}
b0612e7d Andy McCall ↶ 1827
1828
/// oxygenhub#73: a runner that lists the images it holds is offered only
1829
/// the jobs whose rootfs is among them; one that does not say gets any.
1830
#[tokio::test(flavor = "multi_thread")]
1831
async fn a_runner_is_offered_only_jobs_whose_image_it_holds() {
1832
    let h = hub().await;
1833
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1834
    create(&h.app, "andy", "images").await;
1835
    let url = format!("{}/andy/images", h.base);
1836
    let work = tempfile::tempdir().unwrap();
1837
    let c = client(&url, work.path());
1838
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1839
    write(work.path(), "test.sh", "echo ok\n");
1840
    c.commit("Add a pipeline", &[]).unwrap();
1841
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1842
    assert_eq!(runs_of(&h.app, "andy", "images").await.len(), 1);
1843
    let claim_with = |images: Vec<String>| {
1844
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "images": images }).to_string();
1845
        let app = h.app.clone();
1846
        async move {
1847
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await;
1848
            (st, body)
1849
        }
1850
    };
1851
    let (st, _) = claim_with(vec!["ab".repeat(32)]).await;
1852
    assert_eq!(st, StatusCode::NO_CONTENT, "no job for a runner without the image");
1853
    let jobs = db::flow::jobs(&h.app.db, runs_of(&h.app, "andy", "images").await[0].id).await.unwrap();
1854
    let rootfs: serde_json::Value = serde_json::from_str(&jobs[0].sandbox).unwrap();
1855
    let rootfs = rootfs["rootfs"].as_str().unwrap().to_string();
1856
    let (st, body) = claim_with(vec!["ab".repeat(32), rootfs]).await;
1857
    assert_eq!(st, StatusCode::OK, "{body}");
1858
}
eef677c4 Andy McCall ↶ 1859
1860
/// oxygenhub#71: a runner that lists the jobs it holds has the others it
1861
/// was given ended at once (it restarted, or never received them), not at
1862
/// the time limit; a held job is left alone.
1863
#[tokio::test(flavor = "multi_thread")]
1864
async fn a_job_its_runner_no_longer_holds_is_ended_at_its_next_claim() {
1865
    let h = hub().await;
1866
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1867
    create(&h.app, "andy", "held").await;
1868
    let url = format!("{}/andy/held", h.base);
1869
    let work = tempfile::tempdir().unwrap();
1870
    let c = client(&url, work.path());
1871
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1872
    write(work.path(), "test.sh", "echo ok\n");
1873
    c.commit("Add a pipeline", &[]).unwrap();
1874
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1875
    assert_eq!(runs_of(&h.app, "andy", "held").await.len(), 1);
1876
    let id = claim(&h.app).await.expect("a job to claim")["job_id"].as_i64().unwrap();
1877
    let claim_holding = |holding: Vec<i64>| {
1878
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "holding": holding }).to_string();
1879
        let app = h.app.clone();
1880
        async move { call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await.0 }
1881
    };
1882
    claim_holding(vec![id]).await;
1883
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "running", "a held job stays");
1884
    claim_holding(vec![]).await;
1885
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1886
    assert_eq!(j.status, "error");
1887
    assert!(j.error.starts_with("lost:") && j.error.contains("no longer holds"), "{}", j.error);
1888
    let run = &runs_of(&h.app, "andy", "held").await[0];
1889
    assert!(db::flow::jobs(&h.app.db, run.id).await.unwrap().iter().all(|j| j.status != "running"), "the run settles");
1890
}
d7ce41ac Andy McCall ↶ 1891
1892
/// oxygen#59: a job with a `scope` runs on a push only when the push's
1893
/// changes touch a path it names (a release job, when Cargo.toml's version
1894
/// moves); a bookmark's first run and manual runs have every job.
1895
#[tokio::test(flavor = "multi_thread")]
1896
async fn a_scoped_job_runs_only_when_a_push_touches_its_paths() {
1897
    let h = hub().await;
1898
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1899
    create(&h.app, "andy", "scoped").await;
1900
    let url = format!("{}/andy/scoped", h.base);
1901
    let work = tempfile::tempdir().unwrap();
1902
    let c = client(&url, work.path());
1903
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\" \"packaging/**\"\n    exec \"true\"\n}\n";
1904
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1905
    write(work.path(), "test.sh", "echo ok\n");
1906
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1907
    c.commit("Start", &[]).unwrap();
1908
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1909
    let names = |app: Shared, n: usize| async move {
1910
        let mut runs = Vec::new();
1911
        for _ in 0..100 {
1912
            runs = runs_of(&app, "andy", "scoped").await;
1913
            if runs.len() >= n {
1914
                break;
1915
            }
1916
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1917
        }
1918
        assert_eq!(runs.len(), n, "runs");
1919
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1920
        j.sort();
745d225d Andy McCall ↶ 1921
        // Passed, so the next push is scoped against it, not superseding it.
3b1bc27f Andy McCall 1922
        sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(runs[0].id).execute(&app.db).await.unwrap();
d7ce41ac Andy McCall ↶ 1923
        j
1924
    };
1925
    assert_eq!(names(h.app.clone(), 1).await, ["build", "dist", "lint", "test"], "the first run has every job");
1926
    write(work.path(), "test.sh", "echo still ok\n");
1927
    c.commit("Edit the test", &[]).unwrap();
1928
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1929
    assert_eq!(names(h.app.clone(), 2).await, ["build", "lint", "test"], "dist is out of scope");
1930
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1931
    c.commit("Release 0.1.1", &[]).unwrap();
1932
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1933
    assert_eq!(names(h.app.clone(), 3).await, ["build", "dist", "lint", "test"], "a version bump runs dist");
1934
}
5dead1f4 Andy McCall ↶ 1935
367f34b8 Andy McCall ↶ 1936
/// oxygenhub#284: a push whose newest change says `[skip ci]` records a
1937
/// skipped run with no jobs; the next run's scope still covers what it
1938
/// brought; and a repository can refuse skips on its default bookmark.
1939
#[tokio::test(flavor = "multi_thread")]
1940
async fn a_push_can_skip_its_run() {
1941
    let h = hub().await;
1942
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1943
    create(&h.app, "andy", "skip").await;
1944
    let url = format!("{}/andy/skip", h.base);
1945
    let work = tempfile::tempdir().unwrap();
1946
    let c = client(&url, work.path());
1947
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\"\n    exec \"true\"\n}\n";
1948
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1949
    write(work.path(), "test.sh", "echo ok\n");
1950
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1951
    c.commit("Start", &[]).unwrap();
1952
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1953
    let newest = |app: Shared, n: usize| async move {
1954
        for _ in 0..100 {
1955
            let runs = runs_of(&app, "andy", "skip").await;
1956
            if runs.len() >= n {
1957
                assert_eq!(runs.len(), n, "runs");
1958
                let r = runs[0].clone();
1959
                let mut jobs: Vec<String> = db::flow::jobs(&app.db, r.id).await.unwrap().into_iter().map(|j| j.name).collect();
1960
                jobs.sort();
1961
                if r.status != "skipped" {
1962
                    sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(r.id).execute(&app.db).await.unwrap();
1963
                }
1964
                return (r, jobs);
1965
            }
1966
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1967
        }
1968
        panic!("no run {n}");
1969
    };
1970
    assert_eq!(newest(h.app.clone(), 1).await.1, ["build", "dist", "lint", "test"]);
1971
1972
    // Skipped: recorded, finished, no jobs, saying which change and who.
1973
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1974
    c.commit("Bump the version [Skip CI]", &[]).unwrap();
1975
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1976
    let (run, jobs) = newest(h.app.clone(), 2).await;
1977
    assert_eq!(run.status, "skipped");
1978
    assert!(jobs.is_empty(), "{jobs:?}");
1979
    assert!(run.error.starts_with("[skip ci] in change ") && run.error.contains(", pushed by "), "{}", run.error);
1980
    assert!(run.finished_ms.is_some());
1981
    let (_, page) = call(&h.app, "GET", "/andy/skip/flow/2", None, None).await;
1982
    assert!(page.contains("the push asked to skip this run"), "{page}");
1983
1984
    // The next run is scoped against run 1, so it still runs dist for the
1985
    // version the skipped push brought.
1986
    write(work.path(), "test.sh", "echo still ok\n");
1987
    c.commit("Edit the test", &[]).unwrap();
1988
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1989
    assert_eq!(newest(h.app.clone(), 3).await.1, ["build", "dist", "lint", "test"], "the skipped bump still runs dist");
1990
1991
    // Not on the default bookmark: the marker is ignored there.
1992
    let row = db::repos::get(&h.app.db, "andy", "skip").await.unwrap().unwrap();
1993
    db::repos::set_flow_skip(&h.app.db, row.id, "others").await.unwrap();
1994
    write(work.path(), "test.sh", "echo ok again\n");
1995
    c.commit("Docs only [skip flow]", &[]).unwrap();
1996
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1997
    let (run, jobs) = newest(h.app.clone(), 4).await;
1998
    assert_ne!(run.status, "skipped");
1999
    assert_eq!(jobs, ["build", "lint", "test"]);
2000
    let row = db::repos::get(&h.app.db, "andy", "skip").await.unwrap().unwrap();
2001
    assert!(oxygenhub::flow::skip_allowed(&row, "feature") && !oxygenhub::flow::skip_allowed(&row, "main"));
2002
    db::repos::set_flow_skip(&h.app.db, row.id, "never").await.unwrap();
2003
    let row = db::repos::get(&h.app.db, "andy", "skip").await.unwrap().unwrap();
2004
    assert!(!oxygenhub::flow::skip_allowed(&row, "feature"));
2005
}
2006
5588bb36 Andy McCall ↶ 2007
/// oxygenhub#265: a push run on a state whose jobs already passed reuses
2008
/// those passes (same spec and sandbox), except a job behind a gate; a
2009
/// repository can turn reuse off.
2010
#[tokio::test(flavor = "multi_thread")]
2011
async fn a_push_reuses_a_pass_on_the_same_state() {
2012
    let h = hub().await;
2013
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2014
    create(&h.app, "andy", "reuse").await;
2015
    let url = format!("{}/andy/reuse", h.base);
2016
    let work = tempfile::tempdir().unwrap();
2017
    let c = client(&url, work.path());
2018
    let gated = "job \"deploy\" {\n    sandbox \"alpine\"\n    depends-on \"test\"\n    approval {\n        by \"maintain\"\n    }\n    exec \"true\"\n}\n";
2019
    write(work.path(), ".flow/pipeline.kdl", &pipeline(gated));
2020
    write(work.path(), "test.sh", "echo ok\n");
2021
    c.commit("Start", &[]).unwrap();
2022
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2023
    let first = runs_of(&h.app, "andy", "reuse").await.remove(0);
2024
    // Its jobs pass, the gated one too, each with a receipt.
2025
    sqlx::query("UPDATE flow_jobs SET status = 'passed', exit_code = 0, receipt_hash = 'r-' || name WHERE run_id = $1")
2026
        .bind(first.id)
2027
        .execute(&h.app.db)
2028
        .await
2029
        .unwrap();
2030
    sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(first.id).execute(&h.app.db).await.unwrap();
2031
    let heads: Vec<oxy_core::hash::ChangeHash> = first.head_list().into_iter().filter_map(oxy_core::hash::ChangeHash::from_hex).collect();
2032
    let row = db::repos::get(&h.app.db, "andy", "reuse").await.unwrap().unwrap();
2033
    assert!(row.flow_reuse, "on by default");
2034
    let again = |row: db::repos::RepoRow| {
2035
        let (app, state, heads) = (h.app.clone(), first.state.clone(), heads.clone());
2036
        async move {
2037
            let n =
2038
                oxygenhub::flow::start_run_scoped(&app, &row, "main", &state, &heads, "andy", "push", None).await.unwrap().expect("a run");
2039
            let run = db::flow::run(&app.db, row.id, n).await.unwrap().unwrap();
2040
            let jobs = db::flow::jobs(&app.db, run.id).await.unwrap();
2041
            (run, jobs)
2042
        }
2043
    };
2044
    let (run, jobs) = again(row.clone()).await;
2045
    let by = |name: &str| jobs.iter().find(|j| j.name == name).unwrap().clone();
2046
    for name in ["build", "test", "lint"] {
2047
        let j = by(name);
2048
        assert_eq!((j.status.as_str(), j.reused_from()), ("passed", Some(first.number)), "{name}: {j:?}");
2049
        assert_eq!(j.receipt_hash, format!("r-{name}"), "the pass's receipt stands for it");
2050
    }
2051
    let deploy = by("deploy");
2052
    assert!(deploy.status == "queued" && deploy.reused_from().is_none(), "a gated job runs again: {deploy:?}");
2053
    assert_eq!(run.status, "queued", "the run waits for the gated job");
2054
    let (_, page) = call(&h.app, "GET", &format!("/andy/reuse/flow/{}", run.number), None, None).await;
2055
    assert!(page.contains("data-reused") && page.contains(&format!("/andy/reuse/flow/{}", first.number)), "{page}");
2056
2057
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, &first.state).await.unwrap();
2058
    assert!(
2059
        checks.iter().any(|c| c.name == "flow/build" && c.status == "passed" && c.summary.contains("reused")),
2060
        "a reused pass reports its check: {checks:?}"
2061
    );
2062
2063
    // Turned off: every job runs.
2064
    db::repos::set_flow_reuse(&h.app.db, row.id, false).await.unwrap();
2065
    let row = db::repos::get(&h.app.db, "andy", "reuse").await.unwrap().unwrap();
2066
    let (_, jobs) = again(row).await;
2067
    assert!(jobs.iter().all(|j| j.status == "queued" && j.reused_from().is_none()), "{jobs:?}");
2068
}
2069
42cd46c9 Andy McCall ↶ 2070
/// oxygenhub#296: a fork starts green where upstream proved the same state:
2071
/// its push reuses upstream's passes, says whose, and links to them; never
2072
/// a private upstream's when the fork has another owner.
2073
#[tokio::test(flavor = "multi_thread")]
2074
async fn a_fork_reuses_what_upstream_proved() {
2075
    let h = hub().await;
2076
    for who in ["andy", "bob"] {
2077
        db::accounts::create_account(&h.app.db, who, &format!("{who}@example.com"), "x", "salt", true).await.unwrap();
2078
    }
2079
    create(&h.app, "andy", "game").await;
2080
    create(&h.app, "bob", "game").await;
2081
    let up = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
2082
    let fork = db::repos::get(&h.app.db, "bob", "game").await.unwrap().unwrap();
2083
    db::repos::set_forked_from(&h.app.db, fork.id, up.id).await.unwrap();
2084
    // Flow on for the fork (the test hub allows andy's repositories only).
2085
    sqlx::query("UPDATE repositories SET flow = 'on' WHERE id = $1").bind(fork.id).execute(&h.app.db).await.unwrap();
2086
    let work = tempfile::tempdir().unwrap();
2087
    let mut c = client(&format!("{}/andy/game", h.base), work.path());
2088
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2089
    write(work.path(), "test.sh", "echo ok\n");
2090
    c.commit("Start", &[]).unwrap();
2091
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2092
    let first = runs_of(&h.app, "andy", "game").await.remove(0);
06b75635 Andy McCall ↶ 2093
    // Upstream's jobs pass on a runner, each with its signed receipt, which
2094
    // the hub checks against the runner's key and keeps (#296's C2).
2095
    {
2096
        use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
2097
        use oxy_core::identity::SecretKey;
2098
        use oxy_core::objects::StateObject;
2099
        use oxy_core::receipt::SignedReceipt;
2100
        let heads: Vec<ChangeHash> = first.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
2101
        let state = hash_object(ObjectType::State, &StateObject::new(heads).encode());
2102
        let repo_id = h.app.repos.open(&RepoName::parse("andy/game").unwrap()).unwrap().id().unwrap();
2103
        let sk = SecretKey::generate();
2104
        let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
2105
        let run_url = format!("{}/andy/game/flow/{}", h.base, first.number);
2106
        while let Some(j) = claim(&h.app).await {
2107
            let r = receipt(j["job"]["name"].as_str().unwrap(), j["pipeline_hash"].as_str().unwrap(), 0);
2108
            let parsed: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
2109
            let signed = hex::encode(SignedReceipt::sign(parsed.to_oxy(), repo_id, state, &run_url, &runner, &sk).encode());
2110
            let body = serde_json::json!({ "exit_code": 0, "duration_ms": 5, "receipt": r, "signed_receipt": signed });
2111
            assert_eq!(finish(&h.app, j["job_id"].as_i64().unwrap(), body).await, StatusCode::NO_CONTENT);
2112
        }
2113
    }
2114
    let up_jobs = db::flow::jobs(&h.app.db, first.id).await.unwrap();
2115
    assert!(up_jobs.iter().all(|j| j.status == "passed" && j.receipt_attest.len() == 64), "{up_jobs:?}");
42cd46c9 Andy McCall ↶ 2116
    // The same changes pushed to the fork: the same state.
2117
    c.config.set("remote.origin.url", &format!("{}/bob/game", h.base)).unwrap();
2118
    c.save_config().unwrap();
2119
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2120
    let run = runs_of(&h.app, "bob", "game").await.remove(0);
2121
    assert_eq!(run.state, first.state);
2122
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
2123
    for j in &jobs {
2124
        assert_eq!((j.status.as_str(), j.reused_from(), j.reused_repo()), ("passed", Some(first.number), Some("andy/game")), "{j:?}");
06b75635 Andy McCall ↶ 2125
        let from = up_jobs.iter().find(|u| u.name == j.name).unwrap();
2126
        assert_eq!(j.receipt_attest, from.receipt_attest, "upstream's signed receipt stands for it");
42cd46c9 Andy McCall ↶ 2127
    }
2128
    let (_, page) = call(&h.app, "GET", &format!("/bob/game/flow/{}", run.number), None, None).await;
2129
    assert!(page.contains(&format!("href=\"/andy/game/flow/{}\">andy/game run #{}</a>", first.number, first.number)), "{page}");
2130
    let checks = db::hooks::checks_for_state(&h.app.db, fork.id, &run.state).await.unwrap();
2131
    assert!(checks.iter().any(|c| c.summary.contains("passed in andy/game run #")), "{checks:?}");
06b75635 Andy McCall ↶ 2132
2133
    // A pass whose receipt does not hold (here, one the store never kept)
2134
    // is not taken: that job runs in the fork; the others are reused.
2135
    let lint = up_jobs.iter().find(|j| j.name == "lint").unwrap();
2136
    sqlx::query("UPDATE flow_jobs SET receipt_attest = $1 WHERE id = $2")
2137
        .bind("ab".repeat(32))
2138
        .bind(lint.id)
2139
        .execute(&h.app.db)
2140
        .await
2141
        .unwrap();
2142
    create(&h.app, "bob", "game2").await;
2143
    let fork2 = db::repos::get(&h.app.db, "bob", "game2").await.unwrap().unwrap();
2144
    db::repos::set_forked_from(&h.app.db, fork2.id, up.id).await.unwrap();
2145
    sqlx::query("UPDATE repositories SET flow = 'on' WHERE id = $1").bind(fork2.id).execute(&h.app.db).await.unwrap();
2146
    c.config.set("remote.origin.url", &format!("{}/bob/game2", h.base)).unwrap();
2147
    c.save_config().unwrap();
2148
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2149
    let jobs2 = db::flow::jobs(&h.app.db, runs_of(&h.app, "bob", "game2").await.remove(0).id).await.unwrap();
2150
    let status = |name: &str| jobs2.iter().find(|j| j.name == name).map(|j| (j.status.clone(), j.reused_repo().map(String::from))).unwrap();
2151
    assert_eq!(status("lint"), ("queued".to_string(), None), "{jobs2:?}");
2152
    assert_eq!(status("build"), ("passed".to_string(), Some("andy/game".to_string())), "{jobs2:?}");
2153
    sqlx::query("UPDATE flow_jobs SET receipt_attest = $1 WHERE id = $2")
2154
        .bind(&lint.receipt_attest)
2155
        .bind(lint.id)
2156
        .execute(&h.app.db)
2157
        .await
2158
        .unwrap();
42cd46c9 Andy McCall ↶ 2159
91c306aa Andy McCall ↶ 2160
    // Any repository on the hub holding the same state, not only forks:
2161
    // carol's, which no one forked, starts green from a public pass.
2162
    for who in ["carol"] {
2163
        db::accounts::create_account(&h.app.db, who, &format!("{who}@example.com"), "x", "salt", false).await.unwrap();
2164
    }
2165
    let push_to = |owner: &'static str, name: &'static str| {
2166
        let (app, base) = (h.app.clone(), h.base.clone());
2167
        let path = work.path().to_path_buf();
2168
        async move {
2169
            create(&app, owner, name).await;
2170
            let r = db::repos::get(&app.db, owner, name).await.unwrap().unwrap();
2171
            sqlx::query("UPDATE repositories SET flow = 'on' WHERE id = $1").bind(r.id).execute(&app.db).await.unwrap();
2172
            let mut c = Repo::open(&path).unwrap();
2173
            c.config.set("remote.origin.url", &format!("{base}/{owner}/{name}")).unwrap();
2174
            c.save_config().unwrap();
2175
            assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2176
            let run = runs_of(&app, owner, name).await.remove(0);
2177
            db::flow::jobs(&app.db, run.id).await.unwrap()
2178
        }
2179
    };
2180
    let jobs = push_to("carol", "tetris-clone").await;
2181
    assert!(jobs.iter().all(|j| j.status == "passed" && j.reused_repo().is_some()), "{jobs:?}");
2182
2183
    // Every repository holding those passes private, and none of them
2184
    // carol's: her next repository runs its own.
2185
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE owner IN ('andy', 'bob')").execute(&h.app.db).await.unwrap();
2186
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE owner = 'carol'").execute(&h.app.db).await.unwrap();
2187
    sqlx::query("DELETE FROM flow_jobs WHERE run_id IN (SELECT id FROM flow_runs WHERE repo_id IN (SELECT id FROM repositories WHERE owner = 'carol'))")
2188
        .execute(&h.app.db)
2189
        .await
2190
        .unwrap();
2191
    let jobs = push_to("carol", "another").await;
42cd46c9 Andy McCall ↶ 2192
    assert!(jobs.iter().all(|j| j.status == "queued" && j.reused_from().is_none()), "{jobs:?}");
2193
}
2194
367f34b8 Andy McCall ↶ 2195
#[test]
2196
fn skip_markers_are_the_forges_spellings_in_any_case() {
2197
    use oxygenhub::flow::skip_marker;
2198
    assert_eq!(skip_marker("Fix typo [skip flow]"), Some("[skip flow]"));
2199
    assert_eq!(skip_marker("[CI SKIP] docs"), Some("[ci skip]"));
2200
    assert_eq!(skip_marker("Docs\n\n[Skip CI]"), Some("[skip ci]"));
2201
    assert_eq!(skip_marker("skip ci without brackets"), None);
3b3a51af Andy McCall ↶ 2202
    // Mentioned in code, not asked for (F1 of #284's follow-up).
2203
    assert_eq!(skip_marker("Document the `[skip flow]` marker"), None);
2204
    assert_eq!(skip_marker("Example:\n\n```\ngit commit -m 'x [skip ci]'\n```\n"), None);
2205
    assert_eq!(skip_marker("`code` then [skip ci]"), Some("[skip ci]"));
2206
    assert_eq!(skip_marker("an odd ` backtick [skip ci]"), Some("[skip ci]"));
367f34b8 Andy McCall ↶ 2207
}
2208
745d225d Andy McCall ↶ 2209
/// oxygenflow#32: a run still going is cancelled from the API, the web or
2210
/// by a newer push to its bookmark; its runner is refused from then on,
2211
/// and the next push is scoped past the cancelled run.
2212
#[tokio::test(flavor = "multi_thread")]
2213
async fn runs_are_cancelled_by_hand_or_by_a_newer_push() {
2214
    let h = hub().await;
2215
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2216
    create(&h.app, "andy", "stop").await;
50928fab Andy McCall ↶ 2217
    // main is not the default bookmark here: the default's running push
2218
    // runs always finish (#369), and this is about the others.
2219
    let stop = db::repos::get(&h.app.db, "andy", "stop").await.unwrap().unwrap();
2220
    db::repos::set_default_bookmark(&h.app.db, stop.id, "trunk").await.unwrap();
745d225d Andy McCall ↶ 2221
    let url = format!("{}/andy/stop", h.base);
2222
    let work = tempfile::tempdir().unwrap();
2223
    let c = client(&url, work.path());
2224
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\"\n    exec \"true\"\n}\n";
2225
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
2226
    write(work.path(), "test.sh", "echo ok\n");
2227
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
2228
    c.commit("Start", &[]).unwrap();
2229
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2230
    let wait_runs = |app: Shared, n: usize| async move {
2231
        for _ in 0..100 {
2232
            let runs = runs_of(&app, "andy", "stop").await;
2233
            if runs.len() >= n {
2234
                return runs;
2235
            }
2236
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2237
        }
2238
        panic!("no run {n}");
2239
    };
2240
    let first = wait_runs(h.app.clone(), 1).await;
3b1bc27f Andy McCall 2241
    sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = $1").bind(first[0].id).execute(&h.app.db).await.unwrap();
2242
    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 ↶ 2243
2244
    // Run 2 (a version bump) has a job running when run 3 is pushed.
2245
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
2246
    c.commit("Release 0.1.1", &[]).unwrap();
2247
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2248
    wait_runs(h.app.clone(), 2).await;
2249
    let job = claim(&h.app).await.expect("a job of run 2");
2250
    let id = job["job_id"].as_i64().unwrap();
2251
    write(work.path(), "test.sh", "echo still ok\n");
2252
    c.commit("Edit the test", &[]).unwrap();
2253
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2254
    let runs = wait_runs(h.app.clone(), 3).await;
2255
    let third = &runs[0];
2256
    let mut second = runs[1].clone();
2257
    for _ in 0..100 {
2258
        second = db::flow::run_by_id(&h.app.db, runs[1].id).await.unwrap().unwrap();
2259
        if !second.live() {
2260
            break;
2261
        }
2262
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2263
    }
2264
    assert_eq!(second.status, "cancelled", "a newer push supersedes a run still going");
2265
    let jobs = db::flow::jobs(&h.app.db, second.id).await.unwrap();
2266
    assert!(jobs.iter().all(|j| j.status == "cancelled" && j.error == "superseded by run #3"), "{jobs:?}");
2267
    let mut names: Vec<String> = db::flow::jobs(&h.app.db, third.id).await.unwrap().into_iter().map(|j| j.name).collect();
2268
    names.sort();
2269
    assert_eq!(names, ["build", "dist", "lint", "test"], "run 3 also checks what run 2 would have: the version bump");
2270
    let mut checks = vec![];
2271
    for _ in 0..100 {
2272
        checks = db::hooks::checks_for_state(&h.app.db, second.repo_id, &second.state).await.unwrap();
2273
        if checks.iter().all(|c| c.status == "cancelled") {
2274
            break;
2275
        }
2276
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2277
    }
2278
    assert!(checks.iter().all(|c| c.status == "cancelled"), "{checks:?}");
2279
    // The runner of the cancelled job is refused, so it stops the job.
2280
    let (st, _) =
2281
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(r#"{"records":[]}"#.into())).await;
2282
    assert_eq!(st, StatusCode::CONFLICT);
2283
2284
    // By hand: the API, then a run already ended is refused.
2285
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
2286
    assert_eq!(st, StatusCode::OK, "{body}");
2287
    let third = db::flow::run_by_id(&h.app.db, third.id).await.unwrap().unwrap();
2288
    assert_eq!(third.status, "cancelled");
2289
    assert!(db::flow::jobs(&h.app.db, third.id).await.unwrap().iter().all(|j| j.error == "cancelled by andy"));
2290
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
2291
    assert!(st == StatusCode::CONFLICT && body.contains("already cancelled"), "{st} {body}");
2292
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", None, None).await;
2293
    assert_ne!(st, StatusCode::OK, "anonymous callers cannot cancel");
2294
    let (_, page) = call(&h.app, "GET", "/andy/stop/flow/3", None, None).await;
2295
    assert!(page.contains("⊘") && !page.contains("CANCEL</button>"), "a cancelled run shows so, with no button");
2296
}
2297
5dead1f4 Andy McCall ↶ 2298
/// oxygenflow#23 and oxygenhub#89: a job runs under its pipeline's
2299
/// timeout, capped at the site's maximum, else the site's default; and the
2300
/// hub gives a job up only past its own limit.
2301
#[tokio::test(flavor = "multi_thread")]
2302
async fn a_job_runs_under_its_own_time_limit_within_the_sites() {
2303
    let h = hub().await;
2304
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2305
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_DEFAULT, "30").await.unwrap();
2306
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_MAX, "120").await.unwrap();
2307
    create(&h.app, "andy", "limits").await;
2308
    let url = format!("{}/andy/limits", h.base);
2309
    let work = tempfile::tempdir().unwrap();
2310
    let c = client(&url, work.path());
2311
    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";
2312
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
2313
    write(work.path(), "test.sh", "echo ok\n");
2314
    c.commit("Add a pipeline", &[]).unwrap();
2315
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2316
    assert_eq!(runs_of(&h.app, "andy", "limits").await.len(), 1);
2317
    let mut limits = std::collections::HashMap::new();
2318
    let mut ids = std::collections::HashMap::new();
2319
    while let Some(j) = claim(&h.app).await {
2320
        let name = j["job"]["name"].as_str().unwrap().to_string();
2321
        limits.insert(name.clone(), j["timeout_s"].as_u64().unwrap());
2322
        ids.insert(name, j["job_id"].as_i64().unwrap());
2323
    }
2324
    assert_eq!(limits["slow"], 5400, "its own");
2325
    assert_eq!(limits["huge"], 7200, "cut to the site's maximum");
2326
    assert_eq!(limits["build"], 1800, "the site's default");
2327
    // 40 minutes in: past the default and its grace, within slow's limit.
2328
    let started = db::now_ms() - 40 * 60 * 1000;
3b1bc27f Andy McCall 2329
    sqlx::query("UPDATE flow_jobs SET started_ms = $1").bind(started).execute(&h.app.db).await.unwrap();
5dead1f4 Andy McCall ↶ 2330
    oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap();
2331
    let status = |id: i64| {
2332
        let app = h.app.clone();
2333
        async move { db::flow::job(&app.db, id).await.unwrap().unwrap().status }
2334
    };
2335
    assert_eq!(status(ids["build"]).await, "error", "past its 30 minutes");
2336
    assert_eq!(status(ids["slow"]).await, "running", "within its 90");
2337
    assert_eq!(status(ids["huge"]).await, "running", "within its 120");
2338
}
c889911b Andy McCall ↶ 2339
2340
/// oxygenflow#24: a job's `on` decides which events start it: a pushed
2341
/// tag runs only the jobs that name it; a push to a bookmark the pipeline
2342
/// does not name starts no run; a rerun repeats its run's event.
2343
#[tokio::test(flavor = "multi_thread")]
2344
async fn on_decides_which_events_start_a_job() {
2345
    let h = hub().await;
2346
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2347
    create(&h.app, "andy", "events").await;
2348
    let url = format!("{}/andy/events", h.base);
2349
    let work = tempfile::tempdir().unwrap();
2350
    let c = client(&url, work.path());
2351
    let text = format!(
2352
        "on {{\n    push \"main\"\n    manual\n}}\n{}job \"dist\" {{\n    sandbox \"alpine\"\n    on {{\n        tag \"v*\"\n    }}\n    exec \"true\"\n}}\n",
2353
        pipeline("")
2354
    );
2355
    // `on` must come after schema-version; pipeline() starts with it.
2356
    let text = text.replacen(
2357
        "on {\n    push \"main\"\n    manual\n}\nschema-version 1\n",
2358
        "schema-version 1\non {\n    push \"main\"\n    manual\n}\n",
2359
        1,
2360
    );
2361
    write(work.path(), ".flow/pipeline.kdl", &text);
2362
    write(work.path(), "test.sh", "echo ok\n");
2363
    c.commit("Start", &[]).unwrap();
2364
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2365
    let jobs_of_latest = |app: Shared, n: usize| async move {
2366
        let mut runs = Vec::new();
2367
        for _ in 0..100 {
2368
            runs = runs_of(&app, "andy", "events").await;
2369
            if runs.len() >= n {
2370
                break;
2371
            }
2372
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2373
        }
2374
        assert_eq!(runs.len(), n, "runs");
2375
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
2376
        j.sort();
2377
        (runs[0].clone(), j)
2378
    };
2379
    let (_, j) = jobs_of_latest(h.app.clone(), 1).await;
2380
    assert_eq!(j, ["build", "lint", "test"], "a push to main: no dist");
2381
    // A tag: only dist.
2382
    let heads = c.bookmark_heads().unwrap();
2383
    c.tag_create("v1.0.0", &heads, "first").unwrap();
2384
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2385
    let (run, j) = jobs_of_latest(h.app.clone(), 2).await;
2386
    assert_eq!(j, ["dist"], "a tag runs only what names it");
2387
    assert_eq!(run.trigger, "tag:v1.0.0");
2388
    // A rerun repeats the tag's event.
2389
    let row = db::repos::get(&h.app.db, "andy", "events").await.unwrap().unwrap();
2390
    db::flow::finish(
2391
        &h.app.db,
2392
        db::flow::jobs(&h.app.db, run.id).await.unwrap()[0].id,
2393
        db::flow::Outcome { status: "passed", exit_code: Some(0), error: "", receipt: "", receipt_hash: "" },
2394
    )
2395
    .await
2396
    .unwrap();
2397
    let run = db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap();
2398
    oxygenhub::flow::rerun(&h.app, &row, &run, "andy").await.unwrap();
2399
    let (_, j) = jobs_of_latest(h.app.clone(), 3).await;
2400
    assert_eq!(j, ["dist"], "the rerun is the tag's run again");
2401
    // A bookmark the pipeline does not name starts nothing.
2402
    c.bookmark_create("develop", None).unwrap();
2403
    assert!(c.push_bookmark("origin", "develop", false).unwrap().iter().all(|r| r.ok));
2404
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
2405
    assert_eq!(runs_of(&h.app, "andy", "events").await.len(), 3, "no run for develop");
348f8c4b Andy McCall ↶ 2406
}
2407
2408
/// oxygenflow#24: a job with a `schedule` line runs on the default
2409
/// bookmark when the line comes due, and only then; other jobs stay out.
2410
#[tokio::test(flavor = "multi_thread")]
2411
async fn scheduled_jobs_run_when_due() {
2412
    let h = hub().await;
2413
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2414
    create(&h.app, "andy", "nightly").await;
2415
    let url = format!("{}/andy/nightly", h.base);
2416
    let work = tempfile::tempdir().unwrap();
2417
    let c = client(&url, work.path());
2418
    // An odd minute, so the hub's own ticker cannot fire it during the test.
2419
    let extra = "job \"nightly\" {\n    sandbox \"alpine\"\n    on {\n        schedule \"17 4 29 2 *\"\n    }\n    exec \"true\"\n}\n";
2420
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
2421
    write(work.path(), "test.sh", "echo ok\n");
2422
    c.commit("Start", &[]).unwrap();
2423
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2424
    assert_eq!(runs_of(&h.app, "andy", "nightly").await.len(), 1);
2425
    let first = runs_of(&h.app, "andy", "nightly").await;
2426
    let names: Vec<String> = db::flow::jobs(&h.app.db, first[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
2427
    assert!(!names.contains(&"nightly".to_string()), "a push does not run a scheduled job");
2428
    use flow_core::pipeline::When;
2429
    let not_yet = When { minute: 16, hour: 4, day: 29, month: 2, weekday: 4 };
2430
    assert_eq!(oxygenhub::flow::run_due(&h.app, not_yet).await, 0);
2431
    let due = When { minute: 17, ..not_yet };
2432
    assert_eq!(oxygenhub::flow::run_due(&h.app, due).await, 1);
2433
    let runs = runs_of(&h.app, "andy", "nightly").await;
2434
    assert_eq!(runs.len(), 2);
2435
    assert_eq!(runs[0].trigger, "schedule");
2436
    let names: Vec<String> = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
2437
    assert_eq!(names, ["nightly"]);
2438
    assert_eq!(runs[0].bookmark, "main", "on the default bookmark");
5f3fa151 Andy McCall ↶ 2439
    // #321: a pipeline that does not parse fails its push's run once, and
2440
    // the scheduler records nothing for it, minute after minute.
2441
    write(work.path(), ".flow/pipeline.kdl", "schema-version 1\n");
2442
    c.commit("No jobs", &[]).unwrap();
2443
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
f87a74ff Andy McCall ↶ 2444
    // The push's run is recorded in the background: wait for it, as long as
2445
    // a loaded machine needs (#354), rather than a fixed moment.
2446
    let mut runs = runs_of(&h.app, "andy", "nightly").await;
2447
    for _ in 0..150 {
2448
        if runs.len() == 3 {
2449
            break;
2450
        }
2451
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2452
        runs = runs_of(&h.app, "andy", "nightly").await;
2453
    }
5f3fa151 Andy McCall ↶ 2454
    assert_eq!(runs.len(), 3);
2455
    assert!(runs[0].error.contains("at least one job"), "{}", runs[0].error);
2456
    assert_eq!(oxygenhub::flow::run_due(&h.app, due).await, 0);
2457
    assert_eq!(oxygenhub::flow::run_due(&h.app, not_yet).await, 0);
2458
    assert_eq!(runs_of(&h.app, "andy", "nightly").await.len(), 3, "no scheduled runs of a broken pipeline");
c889911b Andy McCall ↶ 2459
}
2a83f530 Andy McCall ↶ 2460
2461
#[tokio::test(flavor = "multi_thread")]
2462
async fn variables_from_three_levels_reach_a_job_inner_overriding_outer() {
2463
    use oxygenhub::levels::Scope;
2464
    use oxygenhub::variables;
2465
    let h = hub().await;
2466
    let app = &h.app;
2467
    // Andy, the site's administrator, owns the acme organisation.
2468
    let res = oxygenhub::router(app.clone())
2469
        .oneshot(
2470
            Request::post("/register")
2471
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
c8684d44 Andy McCall 2472
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
2a83f530 Andy McCall ↶ 2473
                .unwrap(),
2474
        )
2475
        .await
2476
        .unwrap();
2477
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
2478
    let andy = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
2479
    db::accounts::create_org(&app.db, "acme", "Acme", andy.id).await.unwrap();
2480
    create(app, "acme", "app").await;
2481
    let page = |path: &str, form: Option<String>| {
2482
        let mut req =
2483
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2484
        if form.is_some() {
2485
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2486
        }
2487
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
c7067c7b Andy McCall 2488
        let (app, cookie) = (app.clone(), cookie.clone());
2a83f530 Andy McCall ↶ 2489
        async move {
c7067c7b Andy McCall 2490
            let mut res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
2491
            // A repository settings form returns to its page (#278).
2492
            let back =
2493
                res.headers().get(header::LOCATION).and_then(|v| v.to_str().ok()).filter(|l| l.contains("/settings/")).map(String::from);
2494
            if let Some(to) = back {
2495
                let req = Request::get(to).header(header::COOKIE, cookie).body(Body::empty()).unwrap();
2496
                res = oxygenhub::router(app).oneshot(req).await.unwrap();
2497
            }
2a83f530 Andy McCall ↶ 2498
            let status = res.status();
2499
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2500
            (status, body)
2501
        }
2502
    };
2503
    let csrf_of = |page: &str| {
2504
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2505
        page[i..].split('"').next().unwrap().to_string()
2506
    };
2507
2508
    // The site sets CC and LANG, the organisation its own CC, the
2509
    // repository RUST_LOG from its settings page.
2510
    variables::set(&app.db, Scope::Site, "CC", "gcc").await.unwrap();
2511
    variables::set(&app.db, Scope::Site, "LANG", "C").await.unwrap();
2512
    let org = db::accounts::org_by_name(&app.db, "acme").await.unwrap().unwrap();
2513
    variables::set(&app.db, Scope::Org(org.id), "CC", "clang").await.unwrap();
c7067c7b Andy McCall 2514
    let (st, settings) = page("/acme/app/settings/variables", None).await;
2a83f530 Andy McCall ↶ 2515
    assert_eq!(st, StatusCode::OK, "{settings}");
2516
    assert!(settings.contains("Inherited") && settings.contains("the acme organisation") && settings.contains("overridden"), "{settings}");
2517
    let csrf = csrf_of(&settings);
2518
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=RUST_LOG&value=debug"))).await;
2519
    assert!(body.contains("RUST_LOG set.") && body.contains("<code>debug</code>"), "{body}");
2520
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=FLOW_REPO&value=x"))).await;
2521
    assert!(body.contains("not FLOW_"), "{body}");
2522
    let repo = db::repos::get(&app.db, "acme", "app").await.unwrap().unwrap();
2523
    db::repos::set_flow(&app.db, repo.id, "on").await.unwrap();
2524
    let env = variables::env_for_repo(&app.db, &repo).await.unwrap();
2525
    assert_eq!(
2526
        env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect::<Vec<_>>(),
2527
        [("CC", "clang"), ("LANG", "C"), ("RUST_LOG", "debug")],
2528
        "the organisation's CC wins over the site's"
2529
    );
2530
2531
    // A claim carries them.
2532
    let url = format!("{}/acme/app", h.base);
2533
    let work = tempfile::tempdir().unwrap();
2534
    let c = client(&url, work.path());
2535
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2536
    write(work.path(), "test.sh", "echo ok\n");
2537
    c.snapshot("test").unwrap();
2538
    c.commit("Add a pipeline", &[]).unwrap();
2539
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2540
    let runs = runs_of(app, "acme", "app").await;
2541
    assert_eq!(runs.len(), 1, "{runs:?}");
2542
    let got = claim(app).await.unwrap_or_else(|| panic!("a job: {:?}", runs[0]));
2543
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "LANG": "C", "RUST_LOG": "debug" }), "{got}");
2544
2545
    // Removing a site variable from the admin page takes effect at the next claim.
737de0fa Andy McCall ↶ 2546
    let (_, admin) = page("/admin/variables", None).await;
2a83f530 Andy McCall ↶ 2547
    assert!(admin.contains("Variables") && admin.contains("<code>gcc</code>"), "{admin}");
2548
    let (_, body) = page("/admin/variables", Some(format!("_csrf={}&action=delete&name=LANG", csrf_of(&admin)))).await;
2549
    assert!(body.contains("LANG removed."), "{body}");
2550
    let got = claim(app).await.expect("another job");
2551
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "RUST_LOG": "debug" }), "{got}");
2552
}
4ac01a73 Andy McCall ↶ 2553
2554
#[tokio::test(flavor = "multi_thread")]
2555
async fn secrets_a_job_declares_come_with_the_claim_and_never_reach_the_log() {
2556
    let h = hub().await;
2557
    let app = &h.app;
2558
    let res = oxygenhub::router(app.clone())
2559
        .oneshot(
2560
            Request::post("/register")
2561
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
c8684d44 Andy McCall 2562
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
4ac01a73 Andy McCall ↶ 2563
                .unwrap(),
2564
        )
2565
        .await
2566
        .unwrap();
2567
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
2568
    let page = |path: &str, form: Option<String>| {
2569
        let mut req =
2570
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2571
        if form.is_some() {
2572
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2573
        }
2574
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
c7067c7b Andy McCall 2575
        let (app, cookie) = (app.clone(), cookie.clone());
4ac01a73 Andy McCall ↶ 2576
        async move {
c7067c7b Andy McCall 2577
            let mut res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
2578
            // A repository settings form returns to its page (#278).
2579
            let back =
2580
                res.headers().get(header::LOCATION).and_then(|v| v.to_str().ok()).filter(|l| l.contains("/settings/")).map(String::from);
2581
            if let Some(to) = back {
2582
                let req = Request::get(to).header(header::COOKIE, cookie).body(Body::empty()).unwrap();
2583
                res = oxygenhub::router(app).oneshot(req).await.unwrap();
2584
            }
4ac01a73 Andy McCall ↶ 2585
            let status = res.status();
2586
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2587
            (status, body)
2588
        }
2589
    };
2590
    let csrf_of = |page: &str| {
2591
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2592
        page[i..].split('"').next().unwrap().to_string()
2593
    };
2594
    create(app, "andy", "demo").await;
2595
    // The site sets deploy-token; the repository overrides it. Neither
2596
    // page shows a value, only that it is set.
2597
    let (_, admin) = page("/admin", None).await;
2598
    let csrf = csrf_of(&admin);
2599
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=deploy-token&value=site-level-value"))).await;
2600
    assert!(body.contains("deploy-token set.") && !body.contains("site-level-value"), "{body}");
2601
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=bad+name&value=x"))).await;
2602
    assert!(body.contains("name is 1 to 64 of"), "{body}");
c7067c7b Andy McCall 2603
    let (_, settings) = page("/andy/demo/settings/secrets", None).await;
4ac01a73 Andy McCall ↶ 2604
    assert!(
2605
        settings.contains("Secrets") && settings.contains("<code>deploy-token</code>") && settings.contains("the site</td>"),
2606
        "{settings}"
2607
    );
2608
    let csrf_r = csrf_of(&settings);
2609
    let (_, body) =
2610
        page("/andy/demo/settings/secrets", Some(format!("_csrf={csrf_r}&action=set&name=deploy-token&value=hunter22-repo-value"))).await;
2611
    assert!(body.contains("deploy-token set.") && body.contains("overridden") && !body.contains("hunter22"), "{body}");
2612
    let repo = db::repos::get(&app.db, "andy", "demo").await.unwrap().unwrap();
2613
    assert!(
2614
        !String::from_utf8_lossy(&oxygenhub::secrets::list(&app.db, oxygenhub::levels::Scope::Repo(repo.id)).await.unwrap()[0].value)
2615
            .contains("hunter22"),
2616
        "sealed at rest"
2617
    );
2618
2619
    // A job that declares the secret, and one the levels do not hold.
2620
    let url = format!("{}/andy/demo", h.base);
2621
    let work = tempfile::tempdir().unwrap();
2622
    let c = client(&url, work.path());
2623
    write(
2624
        work.path(),
2625
        ".flow/pipeline.kdl",
2626
        &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"),
2627
    );
2628
    write(work.path(), "test.sh", "echo ok\n");
2629
    c.snapshot("test").unwrap();
2630
    c.commit("Add a pipeline", &[]).unwrap();
2631
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2632
    let runs = runs_of(app, "andy", "demo").await;
2633
    let jobs = match runs.first() {
2634
        Some(r) => db::flow::jobs(&app.db, r.id).await.unwrap().iter().map(|j| format!("{}:{}", j.name, j.status)).collect::<Vec<_>>(),
2635
        None => vec![],
2636
    };
2637
    let mut deploy = None;
2638
    for _ in 0..50 {
2639
        let Some(got) = claim(app).await else {
2640
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2641
            continue;
2642
        };
2643
        if got["job"]["name"] == "deploy" {
2644
            deploy = Some(got);
2645
            break;
2646
        }
2647
        assert_eq!(got["secrets"], serde_json::Value::Null, "{got}");
2648
    }
2649
    let got = deploy.unwrap_or_else(|| panic!("the deploy job: runs {runs:?} jobs {jobs:?}"));
2650
    assert_eq!(
2651
        got["secrets"],
2652
        serde_json::json!([{ "name": "deploy-token", "path": "/run/secrets/token", "value": "hunter22-repo-value" }]),
2653
        "the repository's value, the missing one left out: {got}"
2654
    );
2655
    let id = got["job_id"].as_i64().unwrap();
2656
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2657
    assert!(log.iter().any(|l| l.stream == "flow" && l.text.contains("secret \"missing\" is not set")), "{log:?}");
2658
2659
    // The value never reaches the stored log, plain or base64.
2660
    let records = serde_json::json!({ "records": [
2661
        { "t": 1, "stream": "out", "text": "token=hunter22-repo-value" },
2662
        { "t": 2, "stream": "err", "text": "b64 aHVudGVyMjItcmVwby12YWx1ZQ== end" },
2663
    ] });
2664
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2665
    assert_eq!(st, StatusCode::NO_CONTENT);
2666
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2667
    let texts: Vec<&str> = log.iter().map(|l| l.text.as_str()).collect();
2668
    assert!(texts.contains(&"token=***") && texts.contains(&"b64 *** end"), "{texts:?}");
2669
    assert!(!texts.iter().any(|t| t.contains("hunter22")), "{texts:?}");
2670
}
d1727c57 Andy McCall ↶ 2671
2672
#[tokio::test(flavor = "multi_thread")]
2673
async fn a_job_s_identity_is_a_signed_token_the_discovery_document_lets_anyone_verify() {
2674
    let h = hub().await;
2675
    let app = &h.app;
2676
    let (st, disc) = call(app, "GET", "/.well-known/openid-configuration", None, None).await;
2677
    assert_eq!(st, StatusCode::OK, "{disc}");
2678
    let disc: serde_json::Value = serde_json::from_str(&disc).unwrap();
2679
    assert_eq!(disc["issuer"], h.base.as_str());
2680
    assert_eq!(disc["jwks_uri"], format!("{}/.well-known/jwks.json", h.base));
2681
    let (st, jwks) = call(app, "GET", "/.well-known/jwks.json", None, None).await;
2682
    assert_eq!(st, StatusCode::OK, "{jwks}");
2683
    let jwks: serde_json::Value = serde_json::from_str(&jwks).unwrap();
2684
    assert_eq!(jwks["keys"][0]["alg"], "RS256");
2685
    let kid = jwks["keys"][0]["kid"].as_str().unwrap().to_string();
2686
2687
    create(app, "andy", "demo").await;
2688
    let url = format!("{}/andy/demo", h.base);
2689
    let work = tempfile::tempdir().unwrap();
2690
    let c = client(&url, work.path());
2691
    write(
2692
        work.path(),
2693
        ".flow/pipeline.kdl",
2694
        &pipeline("job \"deploy\" {\n    sandbox \"alpine\"\n    identity \"sts.amazonaws.com\" {\n        mount-path \"/run/secrets/aws-token\"\n    }\n    exec \"deploy\"\n}\n"),
2695
    );
2696
    write(work.path(), "test.sh", "echo ok\n");
2697
    c.snapshot("test").unwrap();
2698
    c.commit("Add a pipeline", &[]).unwrap();
2699
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2700
    let mut deploy = None;
2701
    for _ in 0..50 {
2702
        let Some(got) = claim(app).await else {
2703
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2704
            continue;
2705
        };
2706
        if got["job"]["name"] == "deploy" {
2707
            deploy = Some(got);
2708
            break;
2709
        }
2710
    }
2711
    let got = deploy.expect("the deploy job");
2712
    let secrets = got["secrets"].as_array().expect("secrets");
2713
    assert_eq!(secrets.len(), 1);
2714
    assert_eq!(
2715
        (secrets[0]["name"].as_str(), secrets[0]["path"].as_str()),
2716
        (Some("identity:sts.amazonaws.com"), Some("/run/secrets/aws-token"))
2717
    );
2718
    let token = secrets[0]["value"].as_str().unwrap().to_string();
2719
    let issuer = app.oidc().await.unwrap();
2720
    assert_eq!(issuer.kid, kid, "the key the JWKS publishes signed it");
2721
    let claims = issuer.verify(&token, "sts.amazonaws.com", db::now_ms()).expect("verifies");
2722
    assert_eq!(claims["sub"], "repo:andy/demo:bookmark:main");
2723
    assert_eq!(claims["repository"], "andy/demo");
2724
    assert_eq!(claims["job"], "deploy");
2725
    assert_eq!(claims["run_number"], 1);
2726
    assert_eq!(claims["runner"], "test-1");
2727
    assert_eq!(claims["iss"], h.base.as_str());
2728
    assert!(claims["state"].as_str().unwrap().len() == 64);
2729
    // A job that prints its token leaves *** in the log.
2730
    let id = got["job_id"].as_i64().unwrap();
2731
    let records = serde_json::json!({ "records": [{ "t": 1, "stream": "out", "text": format!("TOKEN={token} end") }] });
2732
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2733
    assert_eq!(st, StatusCode::NO_CONTENT);
2734
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2735
    assert!(log.iter().any(|l| l.text == "TOKEN=*** end"), "{log:?}");
2736
}
efd29a00 Andy McCall ↶ 2737
2738
#[tokio::test(flavor = "multi_thread")]
2739
async fn jobs_are_offered_only_to_runners_of_their_architecture() {
2740
    let h = hub().await;
2741
    let app = &h.app;
2742
    create(app, "andy", "demo").await;
2743
    let url = format!("{}/andy/demo", h.base);
2744
    let work = tempfile::tempdir().unwrap();
2745
    let c = client(&url, work.path());
2746
    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)));
2747
    write(work.path(), "test.sh", "echo ok\n");
2748
    c.snapshot("test").unwrap();
2749
    c.commit("Add a pipeline", &[]).unwrap();
2750
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2751
    let claim_as = |arch: &'static str, archs: serde_json::Value| {
2752
        let app = app.clone();
2753
        async move {
2754
            let body = serde_json::json!({
2755
                "runner": format!("{arch}-1"), "runtimes": ["microvm"],
2756
                "info": { "arch": arch, "os": "linux", "version": "t", "labels": [], "max_jobs": 1 },
2757
                "image_archs": archs,
2758
            });
2759
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
2760
            match st {
2761
                StatusCode::NO_CONTENT => None,
2762
                StatusCode::OK => {
2763
                    Some(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"].as_str().unwrap().to_string())
2764
                }
2765
                other => panic!("claim: {other} {body}"),
2766
            }
2767
        }
2768
    };
2769
    // An x86_64 runner that says the alpine image is x86_64: it takes the
2770
    // alpine jobs, never the one that asks for riscv64.
2771
    let rootfs = pipeline("").split("cas://blob/").nth(1).unwrap()[..64].to_string();
2772
    for _ in 0..50 {
2773
        if !runs_of(app, "andy", "demo").await.is_empty() {
2774
            break;
2775
        }
2776
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2777
    }
2778
    let runs = runs_of(app, "andy", "demo").await;
2779
    assert_eq!(runs.len(), 1, "{runs:?}");
2780
    let mut taken = vec![];
2781
    while let Some(j) = claim_as("x86_64", serde_json::json!({ rootfs.clone(): "x86_64" })).await {
2782
        taken.push(j);
2783
    }
2784
    assert_eq!(taken, ["build", "lint"], "test waits for build; flash is for riscv64");
2785
    // A riscv64 runner: the alpine image is known to be x86_64, so only flash.
2786
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await.as_deref(), Some("flash"));
2787
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await, None);
2788
    let (_, queue) = call(app, "GET", "/admin/runners", None, None).await;
2789
    let _ = queue;
2790
}
4d2e44d7 Andy McCall ↶ 2791
2792
/// OxygenFlow spec §11.5: a runner hands back a job it cannot run. The
2793
/// job is queued again and not offered to that runner again, the decline
2794
/// shows on the run's page and is kept for the runner's, and once three
2795
/// runners have declined it the job ends as unplaceable with their reasons.
2796
#[tokio::test(flavor = "multi_thread")]
2797
async fn a_declined_job_goes_to_another_runner_or_ends_unplaceable() {
2798
    let h = hub().await;
2799
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2800
    create(&h.app, "andy", "declines").await;
2801
    let url = format!("{}/andy/declines", h.base);
2802
    let work = tempfile::tempdir().unwrap();
2803
    let c = client(&url, work.path());
2804
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2805
    write(work.path(), "test.sh", "echo ok\n");
2806
    c.commit("Add a pipeline", &[]).unwrap();
2807
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2808
    let run = runs_of(&h.app, "andy", "declines").await[0].clone();
2809
    let claim_as = |token: &'static str, name: &'static str| {
2810
        let app = h.app.clone();
2811
        async move {
2812
            let body = serde_json::json!({ "runner": name, "runtimes": ["microvm"] }).to_string();
2813
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(token), Some(body)).await;
2814
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap())
2815
        }
2816
    };
2817
    let decline = |token: &'static str, id: i64, reason: &'static str| {
2818
        let app = h.app.clone();
2819
        async move {
2820
            let body = serde_json::json!({ "reason": reason }).to_string();
2821
            call(&app, "POST", &format!("/api/v1/flow/jobs/{id}/decline"), Some(token), Some(body)).await.0
2822
        }
2823
    };
2824
    let job = claim_as("runner-secret", "earth-1").await.expect("a job");
2825
    // The other runners are known to the hub before they decline anything.
2826
    assert_eq!(decline("runner-two", job, "not mine").await, StatusCode::CONFLICT, "only the runner it runs on may decline it");
2827
    assert_eq!(decline("runner-secret", job, "the MicroVM tier needs /dev/kvm").await, StatusCode::NO_CONTENT);
2828
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2829
    assert_eq!((j.status.as_str(), j.runner.as_str()), ("queued", ""));
2830
    assert_eq!(j.waiting, "declined by earth-1: the MicroVM tier needs /dev/kvm; waiting for another runner");
2831
    // earth-1 is offered the other ready job, not this one, while it stays the same.
2832
    let next = claim_as("runner-secret", "earth-1").await.expect("the other ready job");
2833
    assert_ne!(next, job);
2834
    let page = call(&h.app, "GET", &format!("/andy/declines/flow/{}", run.number), None, None).await.1;
2835
    assert!(page.contains("Waiting: declined by earth-1: the MicroVM tier needs /dev/kvm"), "{page}");
2836
    assert_eq!(claim_as("runner-two", "plex-1").await, Some(job), "another runner takes it");
2837
    assert_eq!(decline("runner-two", job, "rootfs 36fc4e323804 is not on this runner").await, StatusCode::NO_CONTENT);
2838
    assert_eq!(claim_as("runner-three", "narvi").await, Some(job));
2839
    assert_eq!(decline("runner-three", job, "rootfs 36fc4e323804 is for x86_64; this runner is riscv64").await, StatusCode::NO_CONTENT);
2840
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2841
    assert_eq!(j.status, "error");
2842
    assert_eq!(
2843
        j.error,
2844
        "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"
2845
    );
2846
    let r = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex-1").unwrap();
2847
    let declined = db::flow::declines_of_runner(&h.app.db, r.id, 10).await.unwrap();
2848
    assert_eq!(declined.len(), 1);
2849
    assert_eq!((declined[0].job_id, declined[0].reason.as_str()), (job, "rootfs 36fc4e323804 is not on this runner"));
2850
    assert_eq!(r.tier_list(), vec!["microvm"]);
2851
}
554ccacf Andy McCall ↶ 2852
ab4df6aa Andy McCall ↶ 2853
/// oxygenflow#76, #312: a draining runner hands back a job it holds. It is
2854
/// queued again ahead of new work (even a job of lower priority), its log
2855
/// says why and goes on with the next attempt, and it is no decline. A
2856
/// runner the hub stops hearing from has its jobs handed back the same way.
2857
#[tokio::test(flavor = "multi_thread")]
2858
async fn a_drained_job_goes_back_ahead_of_new_work() {
2859
    let h = hub().await;
2860
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2861
    create(&h.app, "andy", "drains").await;
2862
    let url = format!("{}/andy/drains", h.base);
2863
    let work = tempfile::tempdir().unwrap();
2864
    let c = client(&url, work.path());
e4203e14 Andy McCall ↶ 2865
    let bulk = "job \"bulk\" {\n    sandbox \"alpine\"\n    priority \"low\"\n    checkpoint \"/src/state\"\n    exec \"true\"\n}\n";
ab4df6aa Andy McCall ↶ 2866
    write(work.path(), ".flow/pipeline.kdl", &pipeline(bulk));
2867
    write(work.path(), "test.sh", "echo ok\n");
2868
    c.commit("Add a pipeline", &[]).unwrap();
2869
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2870
    runs_of(&h.app, "andy", "drains").await;
2871
    let claim_as = |token: &'static str, name: &'static str| {
2872
        let app = h.app.clone();
2873
        async move {
2874
            let body = serde_json::json!({ "runner": name, "runtimes": ["microvm"] }).to_string();
2875
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(token), Some(body)).await;
2876
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap())
2877
        }
2878
    };
2879
    let release = |token: &'static str, id: i64, reason: &'static str| {
2880
        let app = h.app.clone();
2881
        async move {
2882
            let body = serde_json::json!({ "reason": reason }).to_string();
2883
            call(&app, "POST", &format!("/api/v1/flow/jobs/{id}/release"), Some(token), Some(body)).await.0
2884
        }
2885
    };
2886
    let name_of = |id: i64| {
2887
        let app = h.app.clone();
2888
        async move { db::flow::job(&app.db, id).await.unwrap().unwrap().name }
2889
    };
2890
    let build = claim_as("runner-secret", "earth-1").await.unwrap();
2891
    let lint = claim_as("runner-two", "plex-1").await.unwrap();
2892
    let low = claim_as("runner-three", "phone").await.unwrap();
2893
    assert_eq!((name_of(build).await, name_of(lint).await, name_of(low).await), ("build".into(), "lint".into(), "bulk".into()));
2894
    // The low-priority job logs a line, then its runner leaves.
2895
    let line = serde_json::json!({ "records": [{ "t": 1200, "stream": "stdout", "text": "step 1 of 30" }] }).to_string();
2896
    call(&h.app, "POST", &format!("/api/v1/flow/jobs/{low}/log"), Some("runner-three"), Some(line)).await;
2897
    assert_eq!(finish(&h.app, build, serde_json::json!({ "exit_code": 0, "duration_ms": 700 })).await, StatusCode::NO_CONTENT);
e4203e14 Andy McCall ↶ 2898
    // It keeps its checkpoint first (oxygenflow#77), a job's own only.
2899
    let (st, body) = call(&h.app, "POST", &format!("/api/v1/flow/jobs/{lint}/checkpoint"), Some("runner-two"), Some("x".into())).await;
2900
    assert_eq!(st, StatusCode::BAD_REQUEST, "lint declares no checkpoint: {body}");
2901
    let (st, body) =
2902
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{low}/checkpoint"), Some("runner-three"), Some("step 32".into())).await;
2903
    assert_eq!(st, StatusCode::OK, "{body}");
2904
    let saved = serde_json::from_str::<serde_json::Value>(&body).unwrap()["blob"].as_str().unwrap().to_string();
ab4df6aa Andy McCall ↶ 2905
    assert_eq!(release("runner-two", low, "off Wi-Fi").await, StatusCode::CONFLICT, "only the runner that holds it");
2906
    assert_eq!(release("runner-three", low, "off Wi-Fi").await, StatusCode::NO_CONTENT);
2907
    let j = db::flow::job(&h.app.db, low).await.unwrap().unwrap();
2908
    assert_eq!((j.status.as_str(), j.runner.as_str(), j.handbacks), ("queued", "", 1));
2909
    let log: Vec<String> = db::flow::log(&h.app.db, low, 0, 50).await.unwrap().into_iter().map(|l| l.text).collect();
2910
    assert_eq!(log, ["step 1 of 30", "── handed back by phone: off Wi-Fi; queued again ahead of new work"]);
2911
    assert!(db::flow::declines_of_job(&h.app.db, low).await.unwrap().is_empty(), "not a decline");
2912
    // `test` became ready when `build` passed, and is of higher priority:
2913
    // the handed-back job still goes first, to any runner, its own too.
e4203e14 Andy McCall ↶ 2914
    let body = serde_json::json!({ "runner": "phone", "runtimes": ["microvm"] }).to_string();
2915
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-three"), Some(body)).await;
2916
    assert_eq!(st, StatusCode::OK, "{body}");
2917
    let again: serde_json::Value = serde_json::from_str(&body).unwrap();
2918
    assert_eq!((again["job_id"].as_i64(), again["checkpoint"].as_str()), (Some(low), Some(saved.as_str())), "it resumes: {again}");
2919
    let (st, bytes) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{low}/checkpoint"), Some("runner-three"), None).await;
2920
    assert_eq!((st, bytes.as_str()), (StatusCode::OK, "step 32"));
2921
    assert!(db::flow::artifacts(&h.app.db, low).await.unwrap().is_empty(), "a checkpoint is no artifact of the job");
ab4df6aa Andy McCall ↶ 2922
    assert_eq!(claim_as("runner-secret", "earth-1").await.map(|id| id != low), Some(true), "then new work");
2923
2924
    // The phone goes quiet: once its lease lapses the job is handed back.
2925
    let phone = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "phone").unwrap();
2926
    sqlx::query("UPDATE flow_runners SET last_seen_ms = $1 WHERE id = $2")
2927
        .bind(db::now_ms() - oxygenhub::flow::LEASE_MS - 1000)
2928
        .bind(phone.id)
2929
        .execute(&h.app.db)
2930
        .await
2931
        .unwrap();
2932
    assert_eq!(oxygenhub::flow::requeue_lapsed(&h.app).await.unwrap(), 1);
2933
    let j = db::flow::job(&h.app.db, low).await.unwrap().unwrap();
2934
    assert_eq!((j.status.as_str(), j.handbacks), ("queued", 2));
2935
    let log: Vec<String> = db::flow::log(&h.app.db, low, 0, 50).await.unwrap().into_iter().map(|l| l.text).collect();
2936
    assert_eq!(log.last().unwrap(), "── the runner phone has not been heard from for 3 minutes; queued again ahead of new work");
2937
    assert_eq!(claim_as("runner-two", "plex-1").await, Some(low), "another runner takes it");
2938
}
2939
3b650652 Andy McCall ↶ 2940
/// oxygenflow#76: a claim says how long the job is expected to take, once
2941
/// it has passed: the median of its recent passing runs in the repository,
2942
/// so a runner leaving with notice can tell whether to finish it.
2943
#[tokio::test(flavor = "multi_thread")]
2944
async fn a_claim_carries_the_job_s_expected_time() {
2945
    let h = hub().await;
2946
    create(&h.app, "andy", "eta").await;
2947
    let url = format!("{}/andy/eta", h.base);
2948
    let work = tempfile::tempdir().unwrap();
2949
    let c = client(&url, work.path());
2950
    let one = "schema-version 1\nsandbox \"alpine\" {\n    rootfs \"cas://blob/ROOTFS\"\n}\njob \"build\" {\n    sandbox \"alpine\"\n    exec \"make\"\n}\n".replace("ROOTFS", ROOTFS);
2951
    write(work.path(), ".flow/pipeline.kdl", &one);
2952
    c.commit("One job", &[]).unwrap();
2953
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2954
    runs_of(&h.app, "andy", "eta").await;
2955
    let first = claim(&h.app).await.expect("a job");
2956
    assert!(first.get("expected_ms").is_none(), "never passed: no estimate, {first}");
2957
    let id = first["job_id"].as_i64().unwrap();
2958
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700 })).await, StatusCode::NO_CONTENT);
2959
    // It took 42 s from its claim.
2960
    sqlx::query("UPDATE flow_jobs SET started_ms = finished_ms - 42000 WHERE id = $1").bind(id).execute(&h.app.db).await.unwrap();
2961
    write(work.path(), "README", "again\n");
2962
    c.commit("Again", &[]).unwrap();
2963
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2964
    let mut next = None;
2965
    for _ in 0..100 {
2966
        if let Some(j) = claim(&h.app).await {
2967
            next = Some(j);
2968
            break;
2969
        }
2970
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2971
    }
2972
    let next = next.expect("the second run's job");
2973
    assert_eq!(next["expected_ms"], 42_000, "{next}");
2974
}
2975
554ccacf Andy McCall ↶ 2976
/// oxygenhub#113: a job's artifact named `coverage` (LCOV) is read when
2977
/// it is uploaded. The job's log says what it found; the Coverage tab,
2978
/// the file view, the badge and the run page show it.
2979
#[tokio::test(flavor = "multi_thread")]
2980
async fn a_coverage_artifact_becomes_a_coverage_report() {
2981
    let h = hub().await;
2982
    create(&h.app, "andy", "cov").await;
2983
    let url = format!("{}/andy/cov", h.base);
2984
    let work = tempfile::tempdir().unwrap();
2985
    let c = client(&url, work.path());
2986
    write(
2987
        work.path(),
2988
        ".flow/pipeline.kdl",
2989
        &format!(
2990
            "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"
2991
        ),
2992
    );
2993
    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");
2994
    c.snapshot("test").unwrap();
2995
    c.commit("Code and coverage", &[]).unwrap();
2996
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2997
    let run = runs_of(&h.app, "andy", "cov").await.remove(0);
c8df33a6 Andy McCall ↶ 2998
    assert!(!call(&h.app, "GET", "/andy/cov", None, None).await.1.contains(">Reports</a>"), "no tab before a report");
554ccacf Andy McCall ↶ 2999
    let id = claim(&h.app).await.unwrap()["job_id"].as_i64().unwrap();
3000
3001
    let (st, text) = upload(&h.app, id, "coverage", b"this is not a report").await;
3002
    assert_eq!(st, StatusCode::OK, "a bad report never fails the upload: {text}");
3003
    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\
3004
SF:/src/src/gone.rs\nDA:1,1\nend_of_record\nSF:/usr/lib/rustlib/x.rs\nDA:1,1\nend_of_record\n";
3005
    let (st, text) = upload(&h.app, id, "coverage", lcov.as_bytes()).await;
3006
    assert_eq!(st, StatusCode::OK, "{text}");
3007
    let log: Vec<String> = db::flow::log(&h.app.db, id, 0, 50).await.unwrap().into_iter().map(|l| l.text).collect();
3008
    assert!(log.iter().any(|l| l.contains("coverage: this is not an LCOV report")), "{log:?}");
3009
    assert!(
3010
        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)"),
3011
        "{log:?}"
3012
    );
3013
3014
    let (st, page) = call(&h.app, "GET", "/andy/cov/coverage", None, None).await;
3015
    assert_eq!(st, StatusCode::OK);
c987c865 Andy McCall ↶ 3016
    assert!(
c8df33a6 Andy McCall ↶ 3017
        page.contains(">Reports</a>")
c987c865 Andy McCall ↶ 3018
            && page.contains("50.0%")
3019
            && page.contains("<strong>2</strong> of <strong>4</strong> relevant lines covered"),
3020
        "{page}"
3021
    );
554ccacf Andy McCall ↶ 3022
    assert!(page.contains("1 of 2") && page.contains("/andy/cov/coverage/") && page.contains("/file/src/lib.rs"), "{page}");
3023
    let report = crate_report(&h.app, run.id).await;
3024
    let (st, file) = call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/lib.rs"), None, None).await;
3025
    assert_eq!(st, StatusCode::OK, "{file}");
3026
    assert_eq!(file.matches("class=\"cov-hit\"").count(), 2, "{file}");
3027
    assert_eq!(file.matches("class=\"cov-miss\"").count(), 2, "{file}");
3028
    assert!(file.contains("3×"), "{file}");
3029
    assert_eq!(call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/gone.rs"), None, None).await.0, StatusCode::NOT_FOUND);
3030
    let (_, badge) = call(&h.app, "GET", "/andy/cov/coverage/badge.svg", None, None).await;
3031
    assert!(badge.contains("coverage: 50.0%"), "{badge}");
3032
    let (_, run_page) = call(&h.app, "GET", &format!("/andy/cov/flow/{}", run.number), None, None).await;
3033
    assert!(run_page.contains("coverage 50.0%"), "{run_page}");
617c2840 Andy McCall ↶ 3034
    // The API (#113).
3035
    let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/cov/coverage", None, None).await;
3036
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
3037
    assert_eq!((list[0]["percent"].as_f64(), list[0]["format"].as_str()), (Some(50.0), Some("lcov")), "{list}");
3038
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/cov/coverage/{report}"), None, None).await;
3039
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
3040
    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 ↶ 3041
3042
    // The `coverage` check on the run's state: it reports, and with a
3043
    // minimum the repository sets, it fails below it.
3044
    let row = db::repos::get(&h.app.db, "andy", "cov").await.unwrap().unwrap();
3045
    let check = |checks: Vec<db::hooks::Check>| checks.into_iter().find(|c| c.name == "coverage").expect("a coverage check");
3046
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
3047
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "50.0%"));
3048
    assert!(c.url.ends_with(&format!("/andy/cov/coverage?report={report}")), "{}", c.url);
3049
    oxygenhub::coverage::set_rules(&h.app.db, row.id, oxygenhub::coverage::Rules { min: Some(60.0), max_drop: None }).await.unwrap();
3050
    assert_eq!(upload(&h.app, id, "coverage", lcov.as_bytes()).await.0, StatusCode::OK);
3051
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
3052
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "50.0%: below the minimum of 60%"));
554ccacf Andy McCall ↶ 3053
}
3054
3055
async fn crate_report(app: &Shared, run_id: i64) -> i64 {
3056
    oxygenhub::coverage::for_run(&app.db, run_id).await.unwrap()[0].id
3057
}
36e5a9c1 Andy McCall ↶ 3058
3059
/// The Tests tab (#114): three runs' JUnit reports on a bookmark; a test
3060
/// breaks in the second and is fixed in the third.
3061
#[tokio::test(flavor = "multi_thread")]
3062
async fn junit_reports_make_a_tests_tab() {
3063
    let h = hub().await;
3064
    create(&h.app, "andy", "t").await;
3065
    let url = format!("{}/andy/t", h.base);
3066
    let work = tempfile::tempdir().unwrap();
3067
    let c = client(&url, work.path());
3068
    write(
3069
        work.path(),
3070
        ".flow/pipeline.kdl",
3071
        &format!(
3072
            "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"
3073
        ),
3074
    );
c8df33a6 Andy McCall ↶ 3075
    assert!(!call(&h.app, "GET", "/andy/t", None, None).await.1.contains(">Reports</a>"));
36e5a9c1 Andy McCall ↶ 3076
    let case = |name: &str, ok: bool, secs: &str| {
3077
        if ok {
3078
            format!(r#"<testcase classname="t.suite" name="{name}" time="{secs}"/>"#)
3079
        } else {
3080
            format!(
3081
                r#"<testcase classname="t.suite" name="{name}" time="{secs}"><failure message="{name} broke">AssertionError</failure></testcase>"#
3082
            )
3083
        }
3084
    };
3085
    let runs = [
3086
        vec![case("a", true, "0.1"), case("b", true, "2.5"), case("c", true, "0.2")],
3087
        vec![case("a", true, "0.1"), case("b", false, "2.6"), case("c", true, "0.2"), case("d", true, "0.3")],
3088
        vec![case("a", true, "0.1"), case("b", true, "2.4"), case("c", true, "0.2"), case("d", true, "0.3")],
3089
    ];
3090
    for (i, cases) in runs.iter().enumerate() {
3091
        write(work.path(), "n.txt", &i.to_string());
3092
        c.snapshot("test").unwrap();
3093
        c.commit(&format!("Run {i}"), &[]).unwrap();
3094
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3095
        // The run is made after the push answers.
3096
        let mut a = None;
3097
        for _ in 0..100 {
3098
            a = claim(&h.app).await;
3099
            if a.is_some() {
3100
                break;
3101
            }
3102
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3103
        }
3104
        let a = a.expect("a job to claim");
3105
        let id = a["job_id"].as_i64().unwrap();
3106
        let xml = format!("<testsuites><testsuite name=\"t\">{}</testsuite></testsuites>", cases.concat());
3107
        assert_eq!(upload(&h.app, id, "junit", xml.as_bytes()).await.0, StatusCode::OK);
3108
        let failed = cases.iter().any(|c| c.contains("<failure"));
3109
        let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), failed as u32);
3110
        if !failed {
3111
            r["outputs"] = serde_json::json!([oxy_core::repo::Repo::blob_ref(xml.as_bytes()).to_hex()]);
3112
        }
3113
        let code = failed as i32;
3114
        assert_eq!(
3115
            finish(&h.app, id, serde_json::json!({ "exit_code": code, "duration_ms": 700, "receipt": r })).await,
3116
            StatusCode::NO_CONTENT
3117
        );
3118
    }
3119
    let (st, page) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
3120
    assert_eq!(st, StatusCode::OK, "{page}");
3121
    if let Some(out) = std::env::var_os("OXYHUB_DUMP_TESTS_PAGE") {
3122
        std::fs::write(out, &page).unwrap();
3123
    }
c8df33a6 Andy McCall ↶ 3124
    assert!(page.contains(">Reports</a>"), "the tab");
36e5a9c1 Andy McCall ↶ 3125
    assert!(page.contains("100%") && page.contains("of 4 tests passed"), "the latest run passes");
3126
    assert!(page.contains("1 fixed") && page.contains("t.suite::b"), "b fixed against the run before");
3127
    assert!(page.contains("1 ✕") && page.contains("2 ✓"), "b is flaky: {page}");
3128
    assert!(page.contains("<svg class=\"cov-chart\""), "charts");
3129
    // The slowest first.
3130
    let slow = page.find("Slowest tests").unwrap();
3131
    assert!(page[slow..].find("t.suite::b").unwrap() < page[slow..].find("t.suite::d").unwrap());
3132
    // The second run, picked: b newly failing, its failure listed.
3133
    let row = db::repos::get(&h.app.db, "andy", "t").await.unwrap().unwrap();
3134
    let second = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap()[1].id;
3135
    let (_, page) = call(&h.app, "GET", &format!("/andy/t/tests?report={second}"), None, None).await;
3136
    assert!(page.contains("1 failing") && page.contains("Newly failing") && page.contains("b broke"), "{page}");
3137
    assert!(page.contains("1 new tests"), "d is new");
617c2840 Andy McCall ↶ 3138
3139
    // The API (#114): the bookmark's reports newest first, and one with
3140
    // its failed cases.
3141
    let (st, list) = call(&h.app, "GET", "/api/v1/repos/andy/t/tests", None, None).await;
3142
    assert_eq!(st, StatusCode::OK, "{list}");
3143
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
3144
    assert_eq!(list.as_array().unwrap().len(), 3);
3145
    assert_eq!((list[0]["tests"].as_i64(), list[1]["failed"].as_i64()), (Some(4), Some(1)));
3146
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}?status=failed"), None, None).await;
3147
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
3148
    assert_eq!(one["cases"].as_array().unwrap().len(), 1);
3149
    assert_eq!((one["cases"][0]["name"].as_str(), one["cases"][0]["message"].as_str()), (Some("b"), Some("b broke")));
3150
    let (_, all) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}"), None, None).await;
3151
    assert_eq!(serde_json::from_str::<serde_json::Value>(&all).unwrap()["cases"].as_array().unwrap().len(), 4);
3152
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/t/tests/99999", None, None).await.0, StatusCode::NOT_FOUND);
3d5c825a Andy McCall ↶ 3153
3154
    // The `tests` check names what broke against main.
3155
    let reports = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap();
3156
    let check = |state: String| {
3157
        let app = h.app.clone();
3158
        async move { db::hooks::checks_for_state(&app.db, row.id, &state).await.unwrap().into_iter().find(|c| c.name == "tests").unwrap() }
3159
    };
3160
    let c = check(reports[1].state.clone()).await;
3161
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "1 failing; 1 new against main: t.suite::b"));
3162
    let c = check(reports[0].state.clone()).await;
3163
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "4 passed"));
3164
3165
    // One test's history: b passed, failed, passed.
3166
    let (_, tab) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
3167
    assert!(
3168
        tab.contains("/andy/t/tests/case?classname=t.suite&amp;name=b") || tab.contains("/andy/t/tests/case?classname=t.suite&name=b"),
3169
        "linked"
3170
    );
3171
    let (st, hist) = call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=b", None, None).await;
3172
    assert_eq!(st, StatusCode::OK, "{hist}");
3173
    assert!(hist.contains("2 passed") && hist.contains("1 failed") && hist.contains("b broke"), "{hist}");
3174
    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 ↶ 3175
}
67040b15 Andy McCall ↶ 3176
3177
/// oxygenhub#28: a queued job no runner can take says why, in the API, on
3178
/// the run page (its panel open) and in its check.
3179
#[tokio::test(flavor = "multi_thread")]
3180
async fn a_job_no_runner_can_take_says_why() {
3181
    let h = hub().await;
3182
    create(&h.app, "andy", "demo").await;
3183
    let url = format!("{}/andy/demo", h.base);
3184
    let work = tempfile::tempdir().unwrap();
3185
    let c = client(&url, work.path());
3186
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3187
    write(work.path(), "test.sh", "echo ok\n");
3188
    c.commit("Add a pipeline", &[]).unwrap();
3189
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3190
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
3191
3192
    // One runner, online, holding another image only.
3193
    let r = db::runners::configured(&h.app.db, &blake3::hash(b"elsewhere").to_hex(), "earth-9").await.unwrap();
3194
    db::runners::seen(&h.app.db, r.id, None, None).await.unwrap();
3195
    let other = "ab".repeat(32);
92a797b2 Andy McCall ↶ 3196
    db::runners::set_offer(&h.app.db, r.id, &["microvm".to_string()], Some(&[other]), false, "p").await.unwrap();
67040b15 Andy McCall ↶ 3197
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3198
3199
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
3200
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
3201
    let build = v["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "build").unwrap().clone();
3202
    let why = build["waiting"].as_str().unwrap_or_default().to_string();
3203
    assert!(why.contains("earth-9 does not hold image") && why.contains(&ROOTFS[..12]), "{body}");
3204
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/1", None, None).await;
3205
    assert!(page.contains("data-waiting") && page.contains("does not hold image"), "the run page says it");
13b27cb2 Andy McCall ↶ 3206
    // The check says it too. The hub's own placement pass runs beside this
3207
    // test's: if it lands a reading from before the runner's offer, the
3208
    // next pass puts it right.
3209
    let mut summary = String::new();
3210
    for _ in 0..40 {
3211
        let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
3212
        summary = checks.iter().find(|c| c.name == "flow/build").unwrap().summary.clone();
3213
        if summary.contains("does not hold image") {
3214
            break;
3215
        }
3216
        let build = db::flow::jobs(&h.app.db, run.id).await.unwrap().into_iter().find(|j| j.name == "build").unwrap();
3217
        db::flow::set_waiting(&h.app.db, build.id, "").await.unwrap();
3218
        oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3219
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3220
    }
3221
    assert!(summary.contains("does not hold image"), "{summary}");
67040b15 Andy McCall ↶ 3222
}
92a797b2 Andy McCall ↶ 3223
58cbf424 Andy McCall ↶ 3224
/// A job a runner could take but that still waits says why (#259): the
3225
/// runners that can take it are busy, or have a free slot without the room
3226
/// for it; and how many ready jobs come first.
3227
#[tokio::test(flavor = "multi_thread")]
3228
async fn a_job_waiting_for_a_busy_runner_says_so() {
3229
    let h = hub().await;
3230
    create(&h.app, "andy", "demo").await;
3231
    let url = format!("{}/andy/demo", h.base);
3232
    let work = tempfile::tempdir().unwrap();
3233
    let c = client(&url, work.path());
3234
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3235
    write(work.path(), "test.sh", "echo ok\n");
3236
    c.commit("Add a pipeline", &[]).unwrap();
3237
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3238
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
3239
    // One runner holding the image, its one slot taken by lint.
3240
    let r = db::runners::configured(&h.app.db, &blake3::hash(b"busy").to_hex(), "earth-9").await.unwrap();
3241
    db::runners::seen(&h.app.db, r.id, None, None).await.unwrap();
3242
    db::runners::set_offer(&h.app.db, r.id, &["microvm".to_string()], Some(&[ROOTFS.to_string()]), false, "p").await.unwrap();
3243
    sqlx::query(
3244
        "UPDATE flow_jobs SET status = 'running', runner_id = $1, runner = 'earth-9', started_ms = $2 WHERE run_id = $3 AND name = 'lint'",
3245
    )
3246
    .bind(r.id)
3247
    .bind(db::now_ms())
3248
    .bind(run.id)
3249
    .execute(&h.app.db)
3250
    .await
3251
    .unwrap();
3252
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3253
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
3254
    let build = jobs.iter().find(|j| j.name == "build").unwrap();
3255
    assert!(build.waiting.contains("the runners that can take it are busy: earth-9 busy (1 of 1)"), "{}", build.waiting);
3256
    // A second slot it hasn't used: free, but not the room for this job.
3257
    sqlx::query("UPDATE flow_runners SET max_jobs = 2 WHERE id = $1").bind(r.id).execute(&h.app.db).await.unwrap();
3258
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3259
    let build = db::flow::jobs(&h.app.db, run.id).await.unwrap().into_iter().find(|j| j.name == "build").unwrap();
5d66f27c Andy McCall ↶ 3260
    assert!(build.waiting.contains("earth-9 has a free slot (1 of 2) but not the memory, CPUs or disk for it now"), "{}", build.waiting);
58cbf424 Andy McCall ↶ 3261
}
3262
794ff94f Andy McCall ↶ 3263
/// #291: expediting a run places the queue again at once, and a job it
3264
/// moved down says which expedited run went before it.
3265
#[tokio::test(flavor = "multi_thread")]
3266
async fn an_expedited_run_moves_the_queue_at_once() {
3267
    let h = hub().await;
3268
    for name in ["first", "urgent"] {
3269
        create(&h.app, "andy", name).await;
3270
        let work = tempfile::tempdir().unwrap();
3271
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
3272
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3273
        write(work.path(), "test.sh", "echo ok\n");
3274
        c.commit("Add a pipeline", &[]).unwrap();
3275
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3276
        // In order: the second run is the newer.
3277
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
3278
    }
3279
    // One runner holding the image, busy with something else.
3280
    let r = db::runners::configured(&h.app.db, &blake3::hash(b"busy").to_hex(), "earth-9").await.unwrap();
3281
    db::runners::seen(&h.app.db, r.id, None, None).await.unwrap();
3282
    db::runners::set_offer(&h.app.db, r.id, &["microvm".to_string()], Some(&[ROOTFS.to_string()]), false, "p").await.unwrap();
3283
    let first = runs_of(&h.app, "andy", "first").await.remove(0);
3284
    sqlx::query(
3285
        "UPDATE flow_jobs SET status = 'running', runner_id = $1, runner = 'earth-9', started_ms = $2 WHERE run_id = $3 AND name = 'lint'",
3286
    )
3287
    .bind(r.id)
3288
    .bind(db::now_ms())
3289
    .bind(first.id)
3290
    .execute(&h.app.db)
3291
    .await
3292
    .unwrap();
3293
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3294
    let db = h.app.db.clone();
3295
    let build = |run: i64| {
3296
        let db = db.clone();
3297
        async move { db::flow::jobs(&db, run).await.unwrap().into_iter().find(|j| j.name == "build").unwrap() }
3298
    };
3299
    let urgent = runs_of(&h.app, "andy", "urgent").await.remove(0);
3300
    assert!(build(urgent.id).await.waiting.contains("1 ready job comes first"), "{}", build(urgent.id).await.waiting);
3301
3302
    // Expedited from its page: the places change before any pass runs.
3303
    let res = oxygenhub::router(h.app.clone())
3304
        .oneshot(
3305
            Request::post("/register")
3306
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
3307
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
3308
                .unwrap(),
3309
        )
3310
        .await
3311
        .unwrap();
3312
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
3313
    let page = oxygenhub::router(h.app.clone())
3314
        .oneshot(Request::get("/andy/urgent/flow/1").header(header::COOKIE, cookie.clone()).body(Body::empty()).unwrap())
3315
        .await
3316
        .unwrap();
3317
    let page = String::from_utf8_lossy(&page.into_body().collect().await.unwrap().to_bytes()).into_owned();
3318
    let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
3319
    let csrf = page[i..].split('"').next().unwrap().to_string();
3320
    let res = oxygenhub::router(h.app.clone())
3321
        .oneshot(
3322
            Request::post("/andy/urgent/flow/1/expedite")
3323
                .header(header::COOKIE, cookie.clone())
3324
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
3325
                .body(Body::from(format!("_csrf={csrf}&reason=incident")))
3326
                .unwrap(),
3327
        )
3328
        .await
3329
        .unwrap();
3330
    assert!(res.status().is_redirection(), "{}", res.status());
3331
    assert!(!build(urgent.id).await.waiting.contains("come"), "first now: {}", build(urgent.id).await.waiting);
3332
    let w = build(first.id).await.waiting;
3333
    assert!(w.contains("2 ready jobs come first (after expedited run andy/urgent #1)"), "{w}");
b1860d60 Andy McCall ↶ 3334
3335
    // And over the API (oxygenhub-android#5): a reason is needed; then the
3336
    // first run is urgent too, within the cap of two.
3337
    let andy = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap();
3338
    let (token, hash) = oxygenhub::auth::new_token();
3339
    db::accounts::create_token(&h.app.db, andy.id, "phone", &hash, "repo:read,repo:write", "", None).await.unwrap();
3340
    let url = format!("/api/v1/repos/andy/first/flow/runs/{}/expedite", first.number);
3341
    let (st, body) = call(&h.app, "POST", &url, Some(&token), Some(r#"{"reason":"  "}"#.into())).await;
3342
    assert_eq!(st, StatusCode::CONFLICT, "{body}");
3343
    assert!(body.contains("Say why the run is urgent."), "{body}");
3344
    let (st, body) = call(&h.app, "POST", &url, Some(&token), Some(r#"{"reason":"the fix for the outage"}"#.into())).await;
3345
    assert_eq!(st, StatusCode::OK, "{body}");
3346
    let run = db::flow::run(&h.app.db, first.repo_id, first.number).await.unwrap().unwrap();
3347
    assert!(
3348
        run.priority == "urgent" && run.priority_note.contains("expedited by andy: the fix for the outage"),
3349
        "{} {}",
3350
        run.priority,
3351
        run.priority_note
3352
    );
794ff94f Andy McCall ↶ 3353
}
3354
92a797b2 Andy McCall ↶ 3355
async fn put_bytes(app: &Shared, path: &str, bearer: &str, bytes: Vec<u8>) -> (StatusCode, String) {
3356
    let req = Request::put(path)
3357
        .header(header::AUTHORIZATION, format!("Bearer {bearer}"))
3358
        .header(header::CONTENT_TYPE, "application/octet-stream")
3359
        .body(Body::from(bytes))
3360
        .unwrap();
3361
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
3362
    let st = res.status();
3363
    (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
3364
}
3365
3366
/// oxygenflow#39: an image is sent as the chunks the hub lacks and then its
3367
/// manifest, checked against its hash; runners fetch it; and a job whose
3368
/// image only the hub holds is offered to a runner that fetches, not to one
3369
/// that does not.
951aed50 Andy McCall ↶ 3370
/// oxygenflow#94, #342: a runner sends the manifest of an image it holds
3371
/// that the hub lacks; the hub keeps it as held by runners only (no chunks,
3372
/// announce says it is no seed) until the image is pushed whole.
92a797b2 Andy McCall ↶ 3373
#[tokio::test(flavor = "multi_thread")]
951aed50 Andy McCall ↶ 3374
async fn a_runner_offers_the_manifest_of_an_image_the_hub_lacks() {
3375
    let h = hub().await;
3376
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3377
    let image: Vec<u8> = (0..300_000u32).map(|i| (i % 241) as u8).collect();
3378
    let mut chunks = std::collections::HashMap::new();
3379
    let m = jet::images::scan(&image[..], Some("x86_64".into()), |c, b| {
3380
        chunks.insert(c.hash().to_string(), b.to_vec());
3381
        Ok(())
3382
    })
3383
    .unwrap();
3384
    let hash = m.hash.clone();
3385
    // Asked which of its images the hub lacks: this one.
3386
    let held = serde_json::json!({ "images": [hash.clone(), "not-a-hash"] }).to_string();
3387
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/images/held", Some("runner-secret"), Some(held.clone())).await;
3388
    assert_eq!(st, StatusCode::OK, "{body}");
3389
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["wanted"], serde_json::json!([hash.clone()]));
3390
    // Only runners may say so.
3391
    assert_ne!(call(&h.app, "POST", "/api/v1/flow/images/held", Some("site"), Some(held.clone())).await.0, StatusCode::OK);
3392
    // A manifest filed under another hash is refused; its own is kept as peer-held.
3393
    let manifest = serde_json::to_string(&m).unwrap();
3394
    let wrong = format!("/api/v1/flow/images/{}/held", "ab".repeat(32));
3395
    assert_eq!(call(&h.app, "PUT", &wrong, Some("runner-secret"), Some(manifest.clone())).await.0, StatusCode::BAD_REQUEST);
3396
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}/held"), Some("runner-secret"), Some(manifest.clone())).await;
3397
    assert_eq!(st, StatusCode::CREATED, "{body}");
3398
    let kept = oxygenhub::images::kept(&h.app.db).await.unwrap();
3399
    let row = kept.iter().find(|k| k.hash == hash).expect("recorded");
3400
    assert_eq!(row.source, "peer");
3401
    let (_, body) = call(&h.app, "POST", "/api/v1/flow/images/held", Some("runner-secret"), Some(held)).await;
3402
    assert!(body.contains("\"wanted\":[]"), "{body}");
3403
    // Runners fetch its manifest; the hub has none of its chunks.
3404
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), Some("runner-secret"), None).await;
3405
    assert_eq!(st, StatusCode::OK);
3406
    let first = m.needed()[0].to_string();
3407
    assert_ne!(call(&h.app, "GET", &format!("/api/v1/flow/images/chunks/{first}"), Some("runner-secret"), None).await.0, StatusCode::OK);
3408
    let reach = oxygenhub::images::reach(&h.app).await.unwrap();
3409
    assert!(reach.peer_only(&hash));
3410
    // Pushed whole, it becomes the hub's.
3411
    for c in m.needed() {
3412
        let (st, body) = put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
3413
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
3414
    }
3415
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest)).await;
3416
    assert_eq!(st, StatusCode::CREATED, "{body}");
3417
    let kept = oxygenhub::images::kept(&h.app.db).await.unwrap();
3418
    assert_eq!(kept.iter().find(|k| k.hash == hash).unwrap().source, "hub");
3419
    assert!(!oxygenhub::images::reach(&h.app).await.unwrap().peer_only(&hash));
3420
}
3421
3422
#[tokio::test(flavor = "multi_thread")]
92a797b2 Andy McCall ↶ 3423
async fn images_are_sent_by_chunk_and_offered_to_runners_that_fetch() {
3424
    let h = hub().await;
3425
    // The site token acts as the first site administrator.
3426
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3427
    // An image: bytes, a run of zeros, more bytes.
3428
    let mut image: Vec<u8> = (0..400_000u32).map(|i| (i % 251) as u8).collect();
3429
    image.extend(std::iter::repeat_n(0u8, 2 << 20));
3430
    image.extend((0..100_000u32).map(|i| (i % 239) as u8));
3431
    let mut chunks = std::collections::HashMap::new();
3432
    let m = jet::images::scan(&image[..], Some("x86_64".into()), |c, b| {
3433
        chunks.insert(c.hash().to_string(), b.to_vec());
3434
        Ok(())
3435
    })
3436
    .unwrap();
3437
    let hash = m.hash.clone();
3438
3439
    // Which chunks the hub lacks: every one but zeros; a manifest before them is refused.
3440
    let ask = serde_json::json!({ "chunks": m.needed() }).to_string();
3441
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask.clone())).await;
3442
    assert_eq!(st, StatusCode::OK, "{body}");
3443
    let missing: Vec<String> = serde_json::from_str::<serde_json::Value>(&body).unwrap()["missing"]
3444
        .as_array()
3445
        .unwrap()
3446
        .iter()
3447
        .map(|v| v.as_str().unwrap().to_string())
3448
        .collect();
3449
    assert_eq!(missing.len(), m.needed().len());
3450
    let manifest = serde_json::to_string(&m).unwrap();
3451
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest.clone())).await;
3452
    assert!(st == StatusCode::CONFLICT && body.contains("was not sent"), "{st} {body}");
3453
    // A chunk is checked against its name; a runner token may not send.
3454
    let first = &missing[0];
3455
    assert_eq!(put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "site", vec![1, 2, 3]).await.0, StatusCode::BAD_REQUEST);
3456
    assert_ne!(
3457
        put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "runner-secret", chunks[first].clone()).await.0,
3458
        StatusCode::NO_CONTENT
3459
    );
3460
    for c in &missing {
3461
        let (st, body) = put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
3462
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
3463
    }
3464
    let (_, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask)).await;
3465
    assert!(body.contains("\"missing\":[]"), "{body}");
750579ec Andy McCall ↶ 3466
    // A large image's question fits (#147): 60,000 names, ~4 MB of JSON.
3467
    let many: Vec<String> = (0..60_000u32).map(|i| blake3::hash(&i.to_le_bytes()).to_hex().to_string()).collect();
3468
    let (st, body) =
3469
        call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(serde_json::json!({ "chunks": many }).to_string())).await;
3470
    assert_eq!(st, StatusCode::OK, "{}", &body[..body.len().min(200)]);
3471
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["missing"].as_array().unwrap().len(), 60_000);
92a797b2 Andy McCall ↶ 3472
    // A manifest naming another hash is refused; the right one is kept.
3473
    let mut wrong = m.clone();
3474
    wrong.hash = "ab".repeat(32);
3475
    let (st, _) =
3476
        call(&h.app, "PUT", &format!("/api/v1/flow/images/{}", wrong.hash), Some("site"), Some(serde_json::to_string(&wrong).unwrap()))
3477
            .await;
3478
    assert_eq!(st, StatusCode::CONFLICT, "chunks that make another image");
d9d0d314 Andy McCall ↶ 3479
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest.clone())).await;
3480
    assert_eq!(st, StatusCode::CREATED, "{body}");
3481
    // #341: a sender that gave up during the check left the manifest kept
3482
    // but no row; sending it again records it without reading the image
3483
    // again (a chunk gone from disk would fail a second check).
3484
    sqlx::query("DELETE FROM jet_images").execute(&h.app.db).await.unwrap();
3485
    let gone = h.app.config.data.join("images/chunks").join(&missing[0][..2]).join(&missing[0]);
3486
    let kept = std::fs::read(&gone).unwrap();
3487
    std::fs::remove_file(&gone).unwrap();
92a797b2 Andy McCall ↶ 3488
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest)).await;
3489
    assert_eq!(st, StatusCode::CREATED, "{body}");
d9d0d314 Andy McCall ↶ 3490
    assert!(oxygenhub::images::held(&h.app.db).await.unwrap().contains(&hash));
3491
    std::fs::write(&gone, kept).unwrap();
92a797b2 Andy McCall ↶ 3492
3493
    // A runner fetches the manifest and the chunks, and the image comes back whole.
3494
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), Some("runner-secret"), None).await;
3495
    assert_eq!(st, StatusCode::OK, "{body}");
3496
    let got: jet::images::Manifest = serde_json::from_str(&body).unwrap();
3497
    assert_eq!(got, m);
3498
    let dir = tempfile::tempdir().unwrap();
3499
    let out = dir.path().join("img.ext4");
3500
    let mut fetched = Vec::new();
3501
    for c in got.needed() {
3502
        let req = Request::get(format!("/api/v1/flow/images/chunks/{c}"))
3503
            .header(header::AUTHORIZATION, "Bearer runner-secret")
3504
            .body(Body::empty())
3505
            .unwrap();
3506
        let res = oxygenhub::router(h.app.clone()).oneshot(req).await.unwrap();
3507
        assert_eq!(res.status(), StatusCode::OK);
3508
        let bytes = res.into_body().collect().await.unwrap().to_bytes().to_vec();
3509
        fetched.push((c.to_string(), bytes));
3510
    }
3511
    jet::images::assemble(&got, &out, |c| Ok(fetched.iter().find(|(h, _)| h == c.hash()).unwrap().1.clone())).unwrap();
3512
    assert_eq!(std::fs::read(&out).unwrap(), image);
3513
    assert_eq!(
3514
        call(&h.app, "GET", &format!("/api/v1/flow/images/{}", "cd".repeat(32)), Some("runner-secret"), None).await.0,
3515
        StatusCode::NOT_FOUND
3516
    );
3517
    assert_ne!(call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), None, None).await.0, StatusCode::OK, "not anonymous");
3518
3519
    // A job on that image: a runner holding no images and not fetching
3520
    // is offered nothing; one that fetches is offered it.
3521
    create(&h.app, "andy", "demo").await;
3522
    let url = format!("{}/andy/demo", h.base);
3523
    let work = tempfile::tempdir().unwrap();
3524
    let c = client(&url, work.path());
3525
    write(
3526
        work.path(),
3527
        ".flow/pipeline.kdl",
3528
        &format!("schema-version 1\nsandbox \"img\" {{\n    rootfs \"cas://blob/{hash}\"\n}}\njob \"build\" {{\n    sandbox \"img\"\n    exec \"make\"\n}}\n"),
3529
    );
3530
    c.commit("Build on the image", &[]).unwrap();
3531
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3532
    runs_of(&h.app, "andy", "demo").await;
1c8276b9 Andy McCall ↶ 3533
    // #137: the run's images are held (by the hub), so no images check.
3534
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
3535
    let run1 = db::flow::run(&h.app.db, row.id, 1).await.unwrap().unwrap();
3536
    let checks = checks_when(&h.app, row.id, &run1.state, 1).await;
3537
    assert!(checks.iter().all(|c| c.name != "pipeline/images"), "{checks:?}");
92a797b2 Andy McCall ↶ 3538
    let ask = |fetches: bool| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":[],"fetches_images":{fetches}}}"#);
3539
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(false))).await;
3540
    assert_eq!(st, StatusCode::NO_CONTENT, "it lacks the image and does not fetch");
3541
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3542
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
3543
    assert!(body.contains("does not hold image"), "{body}");
3544
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(true))).await;
3545
    assert_eq!(st, StatusCode::OK, "it fetches, and the hub holds the image: {body}");
7829b7c7 Andy McCall ↶ 3546
    // oxygenhub#135: once claimed, the old waiting reason is gone.
3547
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
3548
    assert!(!body.contains("waiting"), "a running job keeps no waiting reason: {body}");
92a797b2 Andy McCall ↶ 3549
}
40dd3f86 Andy McCall ↶ 3550
3551
/// oxygenhub#136: coverage measured on a workstation is uploaded for a
3552
/// bookmark's state, kept as uploaded by its account, shown so, and sets
3553
/// no check.
3554
#[tokio::test(flavor = "multi_thread")]
3555
async fn coverage_uploaded_from_a_workstation_says_so() {
3556
    let h = hub().await;
3557
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3558
    create(&h.app, "andy", "vk").await;
3559
    let url = format!("{}/andy/vk", h.base);
3560
    let work = tempfile::tempdir().unwrap();
3561
    let c = client(&url, work.path());
3562
    write(work.path(), "src/game.c", "int a;\nint b;\nint c;\nint d;\n");
3563
    c.commit("Game", &[]).unwrap();
3564
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3565
3566
    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";
3567
    let body = serde_json::json!({ "bookmark": "main", "content": lcov }).to_string();
3568
    let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", Some("site"), Some(body)).await;
3569
    assert_eq!(st, StatusCode::CREATED, "{out}");
3570
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
3571
    assert_eq!((v["uploaded_by"].as_str(), v["lines_hit"].as_i64(), v["lines_found"].as_i64()), (Some("andy"), Some(3), Some(4)));
3572
    assert_eq!(v["dropped"], 1, "a file outside the state is left out");
3573
    assert_eq!(v["bookmark"], "main");
3574
3575
    let (_, page) = call(&h.app, "GET", "/andy/vk/coverage", None, None).await;
3576
    assert!(page.contains("uploaded by andy") && page.contains("75.0%"), "the Coverage page says where it came from");
3577
    let (_, page) = call(&h.app, "GET", "/andy/vk/reports", None, None).await;
3578
    assert!(page.contains("uploaded by andy"), "and the Reports card");
3579
    let row = db::repos::get(&h.app.db, "andy", "vk").await.unwrap().unwrap();
3580
    let state = v["state"].as_str().unwrap();
3581
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, state).await.unwrap();
3582
    assert!(checks.iter().all(|c| c.name != "coverage"), "an upload sets no check: {checks:?}");
3583
3584
    // Readers cannot upload; bad reports and bookmarks are refused.
3585
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", None, Some(r#"{"content":"x"}"#.into())).await;
3586
    assert_ne!(st, StatusCode::CREATED);
3587
    let (st, _) = call(
3588
        &h.app,
3589
        "POST",
3590
        "/api/v1/repos/andy/vk/coverage",
3591
        Some("site"),
3592
        Some(r#"{"bookmark":"nope","content":"SF:a\nend_of_record\n"}"#.into()),
3593
    )
3594
    .await;
3595
    assert_eq!(st, StatusCode::BAD_REQUEST);
3596
}
2fb70d01 Andy McCall ↶ 3597
3598
/// oxygenflow#40: what a runner measured at its claim is kept and shown.
3599
#[tokio::test(flavor = "multi_thread")]
3600
async fn a_runners_facts_are_kept_from_its_claim() {
3601
    let h = hub().await;
3602
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3603
    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"}}"#;
3604
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.into())).await;
3605
    assert_eq!(st, StatusCode::NO_CONTENT, "nothing to run, but the facts are kept");
3606
    let (st, out) = call(&h.app, "GET", "/api/v1/runners", Some("site"), None).await;
3607
    assert_eq!(st, StatusCode::OK, "{out}");
3608
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
3609
    let r = &v[0];
3610
    assert_eq!(
3611
        (r["speed"].as_i64(), r["speed_class"].as_i64(), r["free_disk_mib"].as_i64(), r["load_x100"].as_i64()),
3612
        (Some(100), Some(3), Some(42000), Some(112))
3613
    );
3614
    let row = db::runners::list(&h.app.db).await.unwrap().remove(0);
3615
    assert_eq!(row.facts_line(), "speed 100 (class 3) · load 1.12 · 41 GiB free");
3616
}
44a3d2eb Andy McCall ↶ 3617
3618
/// oxygenflow#41: a job's peaks set what its next run needs; a runner
3619
/// without that much free disk is not offered it, and the reason says so.
3620
#[tokio::test(flavor = "multi_thread")]
3621
async fn a_jobs_next_run_needs_the_disk_its_last_took() {
3622
    let h = hub().await;
3623
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3624
    create(&h.app, "andy", "demo").await;
3625
    let url = format!("{}/andy/demo", h.base);
3626
    let work = tempfile::tempdir().unwrap();
3627
    let c = client(&url, work.path());
3628
    write(
3629
        work.path(),
3630
        ".flow/pipeline.kdl",
3631
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
3632
    );
3633
    c.commit("Build", &[]).unwrap();
3634
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3635
    runs_of(&h.app, "andy", "demo").await;
3636
    let claim_with = |free: u64| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"facts":{{"free_disk_mib":{free}}}}}"#);
3637
3638
    // The first run has nothing to learn from: any runner takes it.
3639
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(500))).await;
3640
    assert_eq!(st, StatusCode::OK, "{body}");
3641
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
3642
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 10, "peak_disk_mib": 8000, "peak_memory_mib": 900 });
3643
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
3644
    let job = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
3645
    assert_eq!((job.peak_disk_mib, job.peak_memory_mib), (Some(8000), Some(900)));
3646
3647
    // The next run needs 8000 MiB and a quarter more.
3648
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
3649
    assert_eq!(st, StatusCode::CREATED);
3650
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
3651
    let run2 = db::flow::run(&h.app.db, repo.id, 2).await.unwrap().unwrap();
3652
    let next = db::flow::jobs(&h.app.db, run2.id).await.unwrap().remove(0);
3653
    assert_eq!(next.need_disk_mib, Some(8000 + 2000 + 64));
3654
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(9000))).await;
3655
    assert_eq!(st, StatusCode::NO_CONTENT, "9000 MiB free is not enough");
3656
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
3657
    let waiting = db::flow::job(&h.app.db, next.id).await.unwrap().unwrap().waiting;
3658
    assert!(waiting.contains("8.8 GiB free; the job needs ~9.8 GiB"), "{waiting}");
3659
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(20_000))).await;
3660
    assert_eq!(st, StatusCode::OK, "a roomier runner takes it: {body}");
3661
}
501d8b26 Andy McCall ↶ 3662
3663
/// oxygenflow#42: a job another free runner would do better (it holds the
3664
/// image) is held from a runner that would fetch it, the better runner
3665
/// takes it, and the job says why it ran there.
3666
#[tokio::test(flavor = "multi_thread")]
3667
async fn a_job_waits_briefly_for_a_runner_that_holds_its_image() {
3668
    let h = hub().await;
3669
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3670
    // A second runner, with a token of its own.
3671
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
3672
    let ask = |images: &str| {
3673
        format!(
3674
            r#"{{"runner":"r","runtimes":["microvm"],"images":[{images}],"fetches_images":true,"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
3675
        )
3676
    };
3677
    let holder = ask(&format!("\"{ROOTFS}\""));
3678
    // earth-9 holds the image and is polling; nothing is queued yet.
3679
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder.clone())).await;
3680
    assert_eq!(st, StatusCode::NO_CONTENT);
3681
    // The hub holds the image too, so test-1 could fetch it.
3b1bc27f Andy McCall 3682
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES ($1, 1, 'x86_64', 1, 'andy', 0)")
501d8b26 Andy McCall ↶ 3683
        .bind(ROOTFS)
3684
        .execute(&h.app.db)
3685
        .await
3686
        .unwrap();
3687
3688
    create(&h.app, "andy", "demo").await;
3689
    let url = format!("{}/andy/demo", h.base);
3690
    let work = tempfile::tempdir().unwrap();
3691
    let c = client(&url, work.path());
3692
    write(
3693
        work.path(),
3694
        ".flow/pipeline.kdl",
3695
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
3696
    );
3697
    c.commit("Build", &[]).unwrap();
3698
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3699
    runs_of(&h.app, "andy", "demo").await;
3700
3701
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
3702
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner that holds the image");
3703
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
3704
    assert_eq!(st, StatusCode::OK, "{body}");
3705
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
3706
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
3707
    assert!(placed.starts_with("holds the image, idle, speed 100 (class 3)"), "{placed}");
3708
    assert!(placed.contains("held for a better runner"), "{placed}");
3709
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
3710
    assert!(body.contains("\"placed\":\"holds the image"), "{body}");
3711
}
20b8fe85 Andy McCall ↶ 3712
4fa0da12 Andy McCall ↶ 3713
/// oxygenflow#51: a job waits briefly for the runner holding its build
3714
/// cache, even when the other one holds its image too.
3715
#[tokio::test(flavor = "multi_thread")]
3716
async fn a_job_waits_briefly_for_the_runner_holding_its_build_cache() {
3717
    let h = hub().await;
3718
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3719
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
3720
    let slot = flow_core::api::cache_slot("andy/demo", "build");
3721
    let ask = |caches: &str| {
3722
        format!(
3723
            r#"{{"runner":"r","runtimes":["microvm"],"images":["{ROOTFS}"],"fetches_images":true,"caches":[{caches}],"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
3724
        )
3725
    };
3726
    let holder = ask(&format!("\"{slot}\""));
3727
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder.clone())).await;
3728
    assert_eq!(st, StatusCode::NO_CONTENT);
3729
3730
    create(&h.app, "andy", "demo").await;
3731
    let url = format!("{}/andy/demo", h.base);
3732
    let work = tempfile::tempdir().unwrap();
3733
    let c = client(&url, work.path());
3734
    write(
3735
        work.path(),
3736
        ".flow/pipeline.kdl",
3737
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
3738
    );
3739
    c.commit("Build", &[]).unwrap();
3740
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3741
    runs_of(&h.app, "andy", "demo").await;
3742
3743
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
3744
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner holding the build cache");
3745
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
3746
    assert_eq!(st, StatusCode::OK, "{body}");
3747
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
3748
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
3749
    assert!(placed.starts_with("holds its build cache, holds the image"), "{placed}");
3750
}
3751
c2be148c Andy McCall ↶ 3752
/// oxygenflow#54: when both runners hold a job's build cache, the job waits
3753
/// briefly for the one whose copy is fresher.
3754
#[tokio::test(flavor = "multi_thread")]
3755
async fn a_job_waits_briefly_for_the_fresher_build_cache() {
3756
    let h = hub().await;
3757
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3758
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
3759
    let slot = flow_core::api::cache_slot("andy/demo", "build");
3760
    let now = db::now_ms();
3761
    let ask = |kept: i64| {
3762
        format!(
3763
            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}}}}"#
3764
        )
3765
    };
3766
    // earth-9 kept its copy a minute ago; the other runner's is a day old.
3767
    let fresh = ask(now - 60_000);
3768
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(fresh.clone())).await;
3769
    assert_eq!(st, StatusCode::NO_CONTENT);
3770
3771
    create(&h.app, "andy", "demo").await;
3772
    let url = format!("{}/andy/demo", h.base);
3773
    let work = tempfile::tempdir().unwrap();
3774
    let c = client(&url, work.path());
3775
    write(
3776
        work.path(),
3777
        ".flow/pipeline.kdl",
3778
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
3779
    );
3780
    c.commit("Build", &[]).unwrap();
3781
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3782
    runs_of(&h.app, "andy", "demo").await;
3783
3784
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(now - 86_400_000))).await;
3785
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the fresher copy");
3786
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(fresh)).await;
3787
    assert_eq!(st, StatusCode::OK, "{body}");
3788
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
3789
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
3790
    assert!(placed.starts_with("holds its build cache (kept 1 min ago), holds the image"), "{placed}");
3791
}
3792
20b8fe85 Andy McCall ↶ 3793
/// oxygenhub#127 §3.3: report files expire beyond the newest 50 runs of a
3794
/// report on a bookmark other than the default; the default keeps all,
3795
/// and an expired report keeps its metrics.
3796
#[tokio::test(flavor = "multi_thread")]
3797
async fn report_files_expire_under_retention() {
3798
    let h = hub().await;
3799
    create(&h.app, "andy", "demo").await;
3800
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
3801
    let add = |bookmark: &'static str, at: i64| {
3802
        let db = h.app.db.clone();
3803
        async move {
3804
            let id: i64 = sqlx::query_scalar(
3805
                "INSERT INTO reports (repo_id, name, kind, title, summary, context, job, bookmark, state, files, bytes, created_ms) \
3b1bc27f Andy McCall 3806
                 VALUES ($1, 'perf', 'performance', 'Perf', '', '{}', 'perf', $2, 's', 1, 1, $3) RETURNING id",
20b8fe85 Andy McCall ↶ 3807
            )
3808
            .bind(repo.id)
3809
            .bind(bookmark)
3810
            .bind(at)
3811
            .fetch_one(&db)
3812
            .await
3813
            .unwrap();
3b1bc27f Andy McCall 3814
            sqlx::query("INSERT INTO report_files (report_id, path, blob, size) VALUES ($1, 'report.toml', $2, 1)")
20b8fe85 Andy McCall ↶ 3815
                .bind(id)
3816
                .bind(format!("{:064x}", id))
3817
                .execute(&db)
3818
                .await
3819
                .unwrap();
3b1bc27f Andy McCall 3820
            sqlx::query("INSERT INTO report_metrics (report_id, key, value, unit, better) VALUES ($1, 'ms', 1, '', '')")
20b8fe85 Andy McCall ↶ 3821
                .bind(id)
3822
                .execute(&db)
3823
                .await
3824
                .unwrap();
3825
            id
3826
        }
3827
    };
3828
    let main_old = add("main", 1).await;
3829
    add("main", 2).await;
3830
    let mut feature = Vec::new();
3831
    for at in 0..52 {
3832
        feature.push(add("feature", 10 + at).await);
3833
    }
3834
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 2, "the two oldest feature runs");
3835
    let files = |id: i64| {
3836
        let db = h.app.db.clone();
3837
        async move {
3b1bc27f Andy McCall 3838
            sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM report_files WHERE report_id = $1").bind(id).fetch_one(&db).await.unwrap()
20b8fe85 Andy McCall ↶ 3839
        }
3840
    };
3841
    assert_eq!((files(feature[0]).await, files(feature[1]).await, files(feature[2]).await), (0, 0, 1));
3842
    assert_eq!(files(main_old).await, 1, "the default bookmark keeps every run");
3843
    assert_eq!(oxygenhub::reports::metrics(&h.app.db, feature[0]).await.unwrap().len(), 1, "metrics are kept");
3844
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 0, "once");
3845
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/perf?id={}", feature[0]), None, None).await;
3846
    assert!(page.contains("files have expired"), "the page says so");
1c8276b9 Andy McCall ↶ 3847
}
3848
3849
/// #137: a run pinning an image neither the hub nor any runner holds sets a
3850
/// failing `pipeline/images` check saying how to send it; once it is held,
3851
/// a run of the same state turns the check to passed.
3852
#[tokio::test(flavor = "multi_thread")]
3853
async fn a_pipeline_pinning_an_image_nobody_holds_fails_a_check() {
3854
    let h = hub().await;
3855
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3856
    // The one runner reports holding no images.
3857
    let none = r#"{"runner":"test-1","runtimes":["microvm"],"images":[]}"#;
3858
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(none.into())).await;
3859
    assert_eq!(st, StatusCode::NO_CONTENT);
3860
    create(&h.app, "andy", "demo").await;
3861
    let url = format!("{}/andy/demo", h.base);
3862
    let work = tempfile::tempdir().unwrap();
3863
    let c = client(&url, work.path());
3864
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3865
    write(work.path(), "test.sh", "echo ok\n");
3866
    c.commit("Add a pipeline", &[]).unwrap();
3867
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3868
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
3869
    let checks = checks_when(&h.app, run.repo_id, &run.state, 4).await;
3870
    let check = checks.iter().find(|c| c.name == "pipeline/images").expect("an images check");
3871
    assert!(check.status == "failed" && check.summary.contains(&ROOTFS[..12]) && check.summary.contains("flow rootfs push"), "{check:?}");
3872
    // Once a runner holds it, a run of the state passes the check.
3873
    let holds = format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":["{ROOTFS}"]}}"#);
3874
    call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(holds)).await;
3875
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
3876
    assert_eq!(st, StatusCode::CREATED);
3877
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
3878
    let check = checks.iter().find(|c| c.name == "pipeline/images").unwrap();
3879
    assert_eq!(check.status, "passed", "{check:?}");
20b8fe85 Andy McCall ↶ 3880
}
a46d15e7 Andy McCall ↶ 3881
3882
/// The swarm's tracker (#144): a fetching runner is given the peers in its
3883
/// site that hold the image or are fetching it, and a ticket signed with
3884
/// the hub key; a runner not in a swarm is told how to join one.
3885
#[tokio::test(flavor = "multi_thread")]
3886
async fn the_tracker_names_peers_in_the_same_site_and_signs_a_ticket() {
3887
    let h = hub().await;
3888
    let app = &h.app;
3889
    let image = "ab".repeat(32);
3890
    let claim_as = |token: &'static str, name: &'static str, body: serde_json::Value| async move {
3891
        let mut b = serde_json::json!({ "runner": name, "runtimes": ["microvm"] });
3892
        b.as_object_mut().unwrap().extend(body.as_object().unwrap().clone());
3893
        let (st, out) = call(app, "POST", "/api/v1/flow/claim", Some(token), Some(b.to_string())).await;
3894
        assert_eq!(st, StatusCode::NO_CONTENT, "{out}");
3895
    };
3896
    let announce = |token: &'static str, state: &'static str| {
3897
        let body = serde_json::json!({ "image": image, "state": state }).to_string();
3898
        async move { call(app, "POST", "/api/v1/flow/swarm/announce", Some(token), Some(body)).await }
3899
    };
3900
    // A holds the image; B and C hold nothing; all three are in site "lab".
6adcd68b Andy McCall ↶ 3901
    claim_as(
3902
        "runner-secret",
3903
        "a",
3904
        serde_json::json!({ "images": [image], "swarm": { "addr": "10.0.0.1:7401", "site": "lab", "cert": "11".repeat(32) } }),
3905
    )
3906
    .await;
3907
    claim_as(
3908
        "runner-two",
3909
        "b",
3910
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.2:7401", "site": "lab", "cert": "22".repeat(32) } }),
3911
    )
3912
    .await;
3913
    claim_as(
3914
        "runner-three",
3915
        "c",
3916
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.3:7401", "site": "lab", "cert": "33".repeat(32) } }),
3917
    )
3918
    .await;
a46d15e7 Andy McCall ↶ 3919
3920
    let (st, body) = announce("runner-two", "fetching").await;
3921
    assert_eq!(st, StatusCode::OK, "{body}");
3922
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3923
    let names: Vec<(&str, bool)> = a.peers.iter().map(|p| (p.addr.as_str(), p.complete)).collect();
3924
    assert_eq!(names, vec![("10.0.0.1:7401", true)], "only A holds it so far");
6adcd68b Andy McCall ↶ 3925
    assert_eq!(a.peers[0].cert, "11".repeat(32), "with the fingerprint peers check it by");
a46d15e7 Andy McCall ↶ 3926
    let t = jet::swarm::Ticket::open(&a.ticket, &app.hub_key.identity, oxygenhub::db::now_ms() as u64).unwrap();
3927
    assert_eq!((t.name.as_str(), t.site.as_str()), ("b", "lab"));
3928
3929
    // C, fetching too, is told of A (whole) and B (fetching).
3930
    let (_, body) = announce("runner-three", "fetching").await;
3931
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3932
    let mut peers: Vec<(&str, bool)> = a.peers.iter().map(|p| (p.addr.as_str(), p.complete)).collect();
3933
    peers.sort();
3934
    assert_eq!(peers, vec![("10.0.0.1:7401", true), ("10.0.0.2:7401", false)]);
3935
3936
    // B is done: no longer offered as fetching. C moves site: no peers.
3937
    announce("runner-two", "done").await;
6adcd68b Andy McCall ↶ 3938
    claim_as(
3939
        "runner-three",
3940
        "c",
3941
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.3:7401", "site": "elsewhere", "cert": "33".repeat(32) } }),
3942
    )
3943
    .await;
a46d15e7 Andy McCall ↶ 3944
    let (_, body) = announce("runner-three", "fetching").await;
3945
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3946
    assert!(a.peers.is_empty(), "{:?}", a.peers);
6adcd68b Andy McCall ↶ 3947
3948
    // A runner without a certificate (an older flow) is not in the swarm.
3949
    claim_as("runner-secret", "a", serde_json::json!({ "images": [image], "swarm": { "addr": "10.0.0.1:7401", "site": "elsewhere" } }))
3950
        .await;
3951
    let (st, _) = announce("runner-secret", "fetching").await;
3952
    assert_eq!(st, StatusCode::CONFLICT);
a46d15e7 Andy McCall ↶ 3953
3954
    // A runner that left the swarm is told how to join; nonsense is refused.
3955
    claim_as("runner-two", "b", serde_json::json!({ "images": [] })).await;
3956
    let (st, body) = announce("runner-two", "fetching").await;
3957
    assert_eq!(st, StatusCode::CONFLICT);
3958
    assert!(body.contains("[runner.swarm]"), "{body}");
3959
    let (st, _) =
3960
        call(app, "POST", "/api/v1/flow/swarm/announce", Some("runner-secret"), Some(r#"{"image":"nope","state":"fetching"}"#.into()))
3961
            .await;
3962
    assert_eq!(st, StatusCode::BAD_REQUEST);
3963
    let (st, _) = call(
3964
        app,
3965
        "POST",
3966
        "/api/v1/flow/swarm/announce",
3967
        None,
3968
        Some(serde_json::json!({ "image": image, "state": "fetching" }).to_string()),
3969
    )
3970
    .await;
3971
    assert_eq!(st, StatusCode::UNAUTHORIZED);
3972
}
6ca0b971 Andy McCall ↶ 3973
3974
/// Admin › Runners › Images (C0): each image, where it is and what uses it.
3975
#[tokio::test(flavor = "multi_thread")]
3976
async fn the_images_page_says_where_each_image_is_and_what_uses_it() {
3977
    let h = hub().await;
3978
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3979
    create(&h.app, "andy", "demo").await;
3980
    let work = tempfile::tempdir().unwrap();
3981
    let c = client(&format!("{}/andy/demo", h.base), work.path());
3982
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3983
    write(work.path(), "test.sh", "echo ok\n");
3984
    c.commit("Add a pipeline", &[]).unwrap();
3985
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3986
    // A runner holds another image and shares it; the hub keeps a third.
3987
    let held = "cd".repeat(32);
3988
    let kept = "ef".repeat(32);
3989
    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) } });
3990
    let (st, out) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
3991
    assert!(st == StatusCode::NO_CONTENT || st == StatusCode::OK, "{st} {out}");
3b1bc27f Andy McCall 3992
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES ($1, 1048576, 'x86_64', 9, 'andy', 1)")
6ca0b971 Andy McCall ↶ 3993
        .bind(&kept)
3994
        .execute(&h.app.db)
3995
        .await
3996
        .unwrap();
3997
3998
    let res = oxygenhub::router(h.app.clone())
3999
        .oneshot(
4000
            Request::post("/register")
4001
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
c8684d44 Andy McCall 4002
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
6ca0b971 Andy McCall ↶ 4003
                .unwrap(),
4004
        )
4005
        .await
4006
        .unwrap();
4007
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
4008
    let carol = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
4009
    db::accounts::set_admin(&h.app.db, carol.id, true).await.unwrap();
5d66f27c Andy McCall ↶ 4010
    // An image only runners held (oxygenflow#94), and none holds it now.
4011
    let lost = jet::images::scan(&[7u8; 4096][..], Some("x86_64".into()), |_, _| Ok(())).unwrap();
4012
    oxygenhub::images::record_peer(&h.app.db, &lost, "mars-1").await.unwrap();
6ca0b971 Andy McCall ↶ 4013
    let res = oxygenhub::router(h.app.clone())
4014
        .oneshot(Request::get("/admin/runners/images").header(header::COOKIE, cookie).body(Body::empty()).unwrap())
4015
        .await
4016
        .unwrap();
4017
    assert_eq!(res.status(), StatusCode::OK);
4018
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
4019
    let row = |hash: &str| {
4020
        let at = page.find(&format!("title=\"{hash}\"")).unwrap_or_else(|| panic!("{hash} is not on the page"));
4021
        let end = page[at..].find("</tr>").unwrap();
4022
        page[at..at + end].to_string()
4023
    };
4024
    let pinned = row(ROOTFS);
4025
    assert!(pinned.contains("nowhere") && pinned.contains("andy/demo") && pinned.contains("3 jobs"), "{pinned}");
4026
    let on_runner = row(&held);
4027
    assert!(on_runner.contains("img-holds") && on_runner.contains("earth-1") && !on_runner.contains("nowhere"), "{on_runner}");
4028
    let on_hub = row(&kept);
4029
    assert!(on_hub.contains("img-hub") && on_hub.contains("1.0 MiB") && on_hub.contains("x86_64"), "{on_hub}");
5d66f27c Andy McCall ↶ 4030
    let peer_only = row(&lost.hash);
4031
    assert!(peer_only.contains("img-peer") && peer_only.contains("sent by mars-1") && peer_only.contains("nowhere"), "{peer_only}");
6ca0b971 Andy McCall ↶ 4032
    assert!(page.contains("earth-1 (home)"), "the swarm is named");
6246d1e5 Andy McCall ↶ 4033
    // The swarm backdrop (docs/backgrounds.md §2): the hub and the runners.
4034
    assert!(page.contains(r#"{"images":"#) && page.contains(r#""scene":"swarm""#) && page.contains(r#""earth-1""#), "the swarm's data");
6ca0b971 Andy McCall ↶ 4035
    assert_eq!(call(&h.app, "GET", "/admin/runners/images", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
4036
}
f677d627 Andy McCall ↶ 4037
4038
/// Diffusion D1 (#148): the reverse pin index. A repository that pins
4039
/// another as a subrepo is a consumer of it; the upstream's API and page
4040
/// say who, at which state, and how far behind its default bookmark.
4041
#[tokio::test(flavor = "multi_thread")]
4042
async fn consumers_of_a_subrepo_are_indexed_with_how_far_behind_they_are() {
4043
    let h = hub().await;
e7158350 Andy McCall ↶ 4044
    // The site token acts as the first site administrator.
4045
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
f677d627 Andy McCall ↶ 4046
    create(&h.app, "andy", "api").await;
4047
    create(&h.app, "andy", "game").await;
4048
    let api_work = tempfile::tempdir().unwrap();
4049
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
4050
    write(api_work.path(), "api.h", "v1\n");
4051
    api.snapshot("t").unwrap();
4052
    api.commit("api v1", &[]).unwrap();
4053
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4054
4055
    let game_work = tempfile::tempdir().unwrap();
4056
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
4057
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
4058
    write(game_work.path(), "game.c", "int main;\n");
4059
    game.snapshot("t").unwrap();
4060
    game.commit("game on api v1", &[]).unwrap();
4061
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
4062
4063
    let consumers = || async {
4064
        let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
4065
        assert_eq!(st, StatusCode::OK, "{body}");
4066
        serde_json::from_str::<Vec<serde_json::Value>>(&body).unwrap()
4067
    };
4068
    // The index is written by the push's after-work, a moment after the
4069
    // client hears the push succeeded.
4070
    let settle = |want: &'static (dyn Fn(&[serde_json::Value]) -> bool + Sync)| {
4071
        let consumers = &consumers;
4072
        async move {
4073
            for _ in 0..100 {
4074
                let list = consumers().await;
4075
                if want(&list) {
4076
                    return list;
4077
                }
4078
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4079
            }
4080
            consumers().await
4081
        }
4082
    };
4083
    let list = settle(&|l| !l.is_empty()).await;
4084
    assert_eq!(list.len(), 1, "{list:?}");
4085
    assert_eq!(
4086
        (list[0]["name"].as_str(), list[0]["path"].as_str(), list[0]["bookmark"].as_str()),
4087
        (Some("game"), Some("deps/api"), Some("main"))
4088
    );
4089
    assert_eq!(list[0]["behind"], 0);
4090
4091
    // The upstream moves on: the consumer is one change behind.
4092
    write(api_work.path(), "api.c", "v2\n");
4093
    api.snapshot("t").unwrap();
4094
    api.commit("api v2", &[]).unwrap();
4095
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4096
    assert_eq!(settle(&|l| l.first().is_some_and(|c| c["behind"] == 1)).await[0]["behind"], 1);
4097
    let (_, page) = call(&h.app, "GET", "/andy/api", None, None).await;
c9aacc0e Andy McCall ↶ 4098
    assert!(page.contains("Diffuses to") && page.contains("andy/game") && page.contains("1 behind"), "the page shows it");
f677d627 Andy McCall ↶ 4099
4100
    // A private consumer is not shown to someone who cannot read it.
4101
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'game'").execute(&h.app.db).await.unwrap();
4102
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", None, None).await;
4103
    assert_eq!(body.trim(), "[]");
4104
    let (_, page) = call(&h.app, "GET", "/andy/api", None, None).await;
4105
    assert!(!page.contains("andy/game"));
4106
    sqlx::query("UPDATE repositories SET visibility = 'public' WHERE name = 'game'").execute(&h.app.db).await.unwrap();
e7158350 Andy McCall ↶ 4107
1d634f69 Andy McCall ↶ 4108
    // A bump (DF3): one signed change on the target moving only the pin, on
4109
    // `diffusion/deps/api`; again with the same state, nothing new.
4110
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
4111
    let api_row = db::repos::get(&h.app.db, "andy", "api").await.unwrap().unwrap();
4112
    let api_heads = api.bookmark_heads().unwrap();
4113
    let bumped = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, api_heads.clone()).await.unwrap();
4114
    let oxygenhub::diffusion::Bumped::Moved { bookmark, heads, .. } = bumped else { panic!("{bumped:?}") };
4115
    assert_eq!(bookmark, "diffusion/deps/api");
4116
    game.fetch("origin").unwrap();
4117
    let bump_state = game.load_state(&heads).unwrap().materialize();
4118
    let pin = match &bump_state.files["deps/api"].content {
4119
        oxy_core::state::FileContent::Opaque { blobs } => oxy_core::subrepo::Pin::decode(&game.read_blob(&blobs[0]).unwrap()).unwrap(),
4120
        other => panic!("{other:?}"),
4121
    };
4122
    assert!(
4123
        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 }),
4124
        "{pin:?}"
4125
    );
4126
    assert!(bump_state.files.contains_key("game.c"), "the rest of the game is as it was");
9aaa88b2 Andy McCall ↶ 4127
    assert!(matches!(
1d634f69 Andy McCall ↶ 4128
        oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, api_heads.clone()).await.unwrap(),
9aaa88b2 Andy McCall ↶ 4129
        oxygenhub::diffusion::Bumped::Already { .. }
4130
    ));
7a14bdae Andy McCall ↶ 4131
    // A state lacking changes the pin has (as when the consumer pinned an
4132
    // upstream proposal not landed yet) is combined with the pin, never
4133
    // dropping what it relies on.
1d634f69 Andy McCall ↶ 4134
    write(api_work.path(), "other.c", "v3\n");
4135
    api.snapshot("t").unwrap();
4136
    let v3 = api.commit("api v3, on its own", &[]).unwrap();
4137
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4138
    let only_v3 = api.load_state(&[v3]).unwrap().heads().to_vec();
7a14bdae Andy McCall ↶ 4139
    let combined = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, only_v3).await.unwrap();
4140
    let oxygenhub::diffusion::Bumped::Moved { heads: ch, .. } = combined else { panic!("{combined:?}") };
4141
    game.fetch("origin").unwrap();
4142
    let st = game.load_state(&ch).unwrap().materialize();
4143
    let pin = match &st.files["deps/api"].content {
4144
        oxy_core::state::FileContent::Opaque { blobs } => oxy_core::subrepo::Pin::decode(&game.read_blob(&blobs[0]).unwrap()).unwrap(),
4145
        other => panic!("{other:?}"),
4146
    };
4147
    let oxy_core::subrepo::Pin::Oxy { heads: pinned, .. } = pin else { panic!() };
4148
    let all = api.load_state(&pinned).unwrap();
4149
    // The game's main still pins v1 alone; combined with v3, it is both.
4150
    assert!(all.contains(&v3) && all.len() == 2, "v1 and v3, {} changes", all.len());
1d634f69 Andy McCall ↶ 4151
    // The upstream moves again: the same bookmark moves.
4152
    let newer = api.bookmark_heads().unwrap();
4153
    let again = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, newer).await.unwrap();
4154
    assert!(matches!(again, oxygenhub::diffusion::Bumped::Moved { ref bookmark, .. } if bookmark == "diffusion/deps/api"), "{again:?}");
4155
e7158350 Andy McCall ↶ 4156
    // Following is off by default; owners turn it on (DF2).
4157
    let put =
4158
        |body: &'static str, who: Option<&'static str>| call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", who, Some(body.into()));
4159
    let (st, body) = put(r#"{"follow":"green"}"#, Some("site")).await;
4160
    assert_eq!(st, StatusCode::OK, "{body}");
4161
    assert!(body.contains("\"follow\":\"green\"") && body.contains("\"from\":\"setting\""), "{body}");
4162
    assert_eq!(put(r#"{"follow":"sometimes"}"#, Some("site")).await.0, StatusCode::BAD_REQUEST);
4163
    assert_ne!(put(r#"{"follow":"any"}"#, None).await.0, StatusCode::OK, "not without a token");
4164
    let (_, body) = put(r#"{"follow":"default"}"#, Some("site")).await;
4165
    assert!(body.contains("\"follow\":\"off\"") && body.contains("\"from\":\"site\""), "{body}");
f677d627 Andy McCall ↶ 4166
4167
    // Dropping the subrepo drops the consumer.
4168
    game.submodule_remove("deps/api").unwrap();
4169
    std::fs::remove_dir_all(game_work.path().join("deps/api")).unwrap();
4170
    game.snapshot("t").unwrap();
4171
    game.commit("game without api", &[]).unwrap();
4172
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
4173
    let left = settle(&|l| l.is_empty()).await;
4174
    assert!(left.is_empty(), "{left:?}");
4175
}
a7e6e8e6 Andy McCall ↶ 4176
4177
/// Diffusion D1 end to end (#148): a consumer that follows every move gets
4178
/// a bump proposal on a push; one that follows green gets it when the
4179
/// upstream's run passes. One proposal, kept up to date.
4180
#[tokio::test(flavor = "multi_thread")]
4181
async fn diffusion_proposes_a_bump_when_the_upstream_moves() {
4182
    let h = hub().await;
4183
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4184
    create(&h.app, "andy", "api").await;
4185
    create(&h.app, "andy", "game").await;
180dc43a Andy McCall ↶ 4186
    // Run every job of the upstream's newest run to a pass, keeping each claim.
4187
    let seen: std::sync::Mutex<Vec<serde_json::Value>> = std::sync::Mutex::new(Vec::new());
4188
    let seen = &seen;
4189
    let hub_app = &h.app;
4190
    let pass_all = move || async move {
4191
        let h_app = hub_app;
a7e6e8e6 Andy McCall ↶ 4192
        for _ in 0..20 {
180dc43a Andy McCall ↶ 4193
            let Some(a) = claim(h_app).await else {
a7e6e8e6 Andy McCall ↶ 4194
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
180dc43a Andy McCall ↶ 4195
                if !jobs_left(h_app).await {
a7e6e8e6 Andy McCall ↶ 4196
                    break;
4197
                }
4198
                continue;
4199
            };
180dc43a Andy McCall ↶ 4200
            seen.lock().unwrap().push(a.clone());
a7e6e8e6 Andy McCall ↶ 4201
            let id = a["job_id"].as_i64().unwrap();
4202
            let (name, ph) = (a["job"]["name"].as_str().unwrap().to_string(), a["pipeline_hash"].as_str().unwrap().to_string());
f7bcee49 Andy McCall ↶ 4203
            let st = finish(h_app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt(&name, &ph, 0) })).await;
4204
            // A run started in the background (a bump, a landing's run, #197)
4205
            // may supersede the one this job belongs to between its claim and
4206
            // its finish; then, and only then, the hub refuses the finish.
4207
            if st == StatusCode::CONFLICT {
4208
                let job = db::flow::job(&h_app.db, id).await.unwrap().unwrap();
4209
                assert_eq!(job.status, "cancelled", "refused only because a newer run cancelled it");
4210
                continue;
4211
            }
4212
            assert_eq!(st, StatusCode::NO_CONTENT);
a7e6e8e6 Andy McCall ↶ 4213
        }
4214
    };
4215
    let api_work = tempfile::tempdir().unwrap();
4216
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
4217
    write(api_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4218
    write(api_work.path(), "test.sh", "echo ok\n");
4219
    write(api_work.path(), "api.h", "v1\n");
4220
    api.snapshot("t").unwrap();
4221
    api.commit("api v1", &[]).unwrap();
4222
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4223
    pass_all().await;
4224
4225
    let game_work = tempfile::tempdir().unwrap();
4226
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
4227
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
4228
    write(game_work.path(), "game.c", "int main;\n");
f01cb865 Andy McCall ↶ 4229
    write(game_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4230
    write(game_work.path(), "test.sh", "echo ok\n");
a7e6e8e6 Andy McCall ↶ 4231
    game.snapshot("t").unwrap();
4232
    game.commit("game on api v1", &[]).unwrap();
4233
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
4234
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
4235
    let bump = || async {
4236
        for _ in 0..100 {
4237
            let open = db::proposals::list(&h.app.db, game_row.id, &["open"]).await.unwrap();
4238
            if let Some(p) = open.into_iter().find(|p| p.source_bookmark == "diffusion/deps/api") {
4239
                return Some(p);
4240
            }
4241
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4242
        }
4243
        None
4244
    };
4245
4246
    // Off by default: an upstream move proposes nothing.
4247
    write(api_work.path(), "a2.c", "v2\n");
4248
    api.snapshot("t").unwrap();
4249
    api.commit("api v2: faster sprites", &[]).unwrap();
4250
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4251
    pass_all().await;
4252
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
4253
    assert!(db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap().is_empty(), "off proposes nothing");
4254
3776b70d Andy McCall ↶ 4255
    // Turned on to follow every move: bumped at once to where the upstream
4256
    // is (v2), by the diffusion account; the next push updates it.
a7e6e8e6 Andy McCall ↶ 4257
    let put = |body: &'static str| call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(body.into()));
4258
    assert_eq!(put(r#"{"follow":"any"}"#).await.0, StatusCode::OK);
3776b70d Andy McCall ↶ 4259
    let first = bump().await.expect("caught up when turned on");
4260
    assert!(first.title.contains("1 change") && first.body.contains("api v2: faster sprites"), "{:?}", first.title);
f01cb865 Andy McCall ↶ 4261
    // The bump's pipeline runs, as a push of it would, so the proposal is tested.
4262
    let mut ran = false;
4263
    for _ in 0..100 {
4264
        if runs_of(&h.app, "andy", "game").await.iter().any(|r| r.bookmark == "diffusion/deps/api") {
4265
            ran = true;
4266
            break;
4267
        }
4268
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4269
    }
4270
    assert!(ran, "a run of the bump");
4271
    pass_all().await;
a7e6e8e6 Andy McCall ↶ 4272
    write(api_work.path(), "a3.c", "v3\n");
4273
    api.snapshot("t").unwrap();
4274
    api.commit("api v3: save slots past ten", &[]).unwrap();
4275
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3776b70d Andy McCall ↶ 4276
    let mut p = first.clone();
4277
    for _ in 0..100 {
4278
        p = bump().await.unwrap();
4279
        if p.body.contains("api v3") {
4280
            break;
4281
        }
4282
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4283
    }
4284
    assert_eq!(p.number, first.number, "the same proposal");
a7e6e8e6 Andy McCall ↶ 4285
    assert_eq!((p.author.as_str(), p.target.as_str()), ("diffusion", "main"));
4286
    assert!(p.title.contains("deps/api") && p.title.contains("andy/api") && p.title.contains("2 changes"), "{}", p.title);
4287
    assert!(p.body.contains("api v2: faster sprites") && p.body.contains("api v3: save slots past ten"), "{}", p.body);
4288
    let labels = db::issues::proposal_labels(&h.app.db, p.id).await.unwrap();
4289
    assert!(labels.iter().any(|l| l.name == "dependencies"));
4290
    pass_all().await;
4291
4292
    // Following green: a push alone does not move it; the passing run does,
4293
    // and the same proposal is brought up to date.
4294
    assert_eq!(put(r#"{"follow":"green"}"#).await.0, StatusCode::OK);
4295
    write(api_work.path(), "a4.c", "v4\n");
4296
    api.snapshot("t").unwrap();
4297
    api.commit("api v4: rsm_set cheaper", &[]).unwrap();
4298
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4299
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
4300
    assert!(!bump().await.unwrap().body.contains("api v4"), "not before its run passes");
4301
    pass_all().await;
4302
    let mut updated = None;
04683947 Andy McCall ↶ 4303
    // Up to 30 s: under the whole Postgres suite 5 s was not always enough.
4304
    for _ in 0..600 {
a7e6e8e6 Andy McCall ↶ 4305
        let p2 = bump().await.unwrap();
4306
        if p2.body.contains("api v4") {
4307
            updated = Some(p2);
4308
            break;
4309
        }
4310
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4311
    }
4312
    let p2 = updated.expect("brought up to date once the run passed");
4313
    assert_eq!(p2.number, p.number, "the same proposal");
4314
    assert!(p2.title.contains("3 changes"), "{}", p2.title);
4315
    assert_eq!(db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap().len(), 1, "never a pile of bumps");
3776b70d Andy McCall ↶ 4316
757195ad Andy McCall ↶ 4317
    // The views (#150): the upstream's Diffusion tab lists the game with its
4318
    // status; the game's tab and overview say what it follows.
4319
    pass_all().await;
4320
    let (st, page) = call(&h.app, "GET", "/andy/api/diffusion", None, None).await;
4321
    assert_eq!(st, StatusCode::OK);
c9aacc0e Andy McCall ↶ 4322
    assert!(page.contains("Diffuses to") && page.contains("andy/game") && page.contains(&format!("#{}", p2.number)), "the bump is listed");
757195ad Andy McCall ↶ 4323
    assert!(page.contains("df-green"), "a passing run of a checked upstream is green");
6246d1e5 Andy McCall ↶ 4324
    // The ripples backdrop: the page's own repositories and tones.
4325
    assert!(
4326
        page.contains(r#""scene":"ripples""#) && page.contains(r#"["andy/game","#) && page.contains(r#""repo":"andy/api""#),
4327
        "the ripples' data"
4328
    );
757195ad Andy McCall ↶ 4329
    let (_, page) = call(&h.app, "GET", "/andy/game/diffusion", None, None).await;
c9aacc0e Andy McCall ↶ 4330
    assert!(page.contains("Takes from") && page.contains("andy/api"));
757195ad Andy McCall ↶ 4331
    let (_, overview) = call(&h.app, "GET", "/andy/game", None, None).await;
c9aacc0e Andy McCall ↶ 4332
    assert!(overview.contains("Takes from") && overview.contains(">Diffusion</a>"), "the tab and the panel");
eb2a3502 Andy McCall ↶ 4333
    // Both directions through the API (#153), as the extension reads them.
4334
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/game/diffusion", Some("site"), None).await;
4335
    assert_eq!(st, StatusCode::OK, "{body}");
4336
    let d: hub_api::Diffusion = serde_json::from_str(&body).unwrap();
4337
    assert!(d.diffuses_to.is_empty(), "nothing pins the game");
4338
    let pin = d.takes_from.first().expect("the game takes from the api");
4339
    assert_eq!((pin.upstream.as_str(), pin.consumer.as_str()), ("andy/api", "andy/game"));
4340
    assert_eq!(pin.bump, Some(p2.number));
4341
    assert_eq!(pin.upstream_state.tone, "green", "{body}");
4342
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/diffusion", Some("site"), None).await;
4343
    let d: hub_api::Diffusion = serde_json::from_str(&body).unwrap();
4344
    assert!(d.takes_from.is_empty() && d.diffuses_to.iter().any(|p| p.consumer == "andy/game"), "{body}");
757195ad Andy McCall ↶ 4345
    let (st, _) = call(&h.app, "GET", "/admin/diffusion", None, None).await;
4346
    assert_eq!(st, StatusCode::NOT_FOUND, "administrators only");
4347
4348
    // Landing the bump on the hub moves the game's pin as a push would:
5d54cf74 Andy McCall ↶ 4349
    // the index follows, so it is no longer behind; even when the first
4350
    // write fails, as a busy database's would (#210: it is tried again).
4351
    let game = oxygenhub::db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
4352
    oxygenhub::diffusion::fail_next_records(&h.app, game.id, 1);
757195ad Andy McCall ↶ 4353
    let (st, body) =
4354
        call(&h.app, "POST", &format!("/api/v1/repos/andy/game/proposals/{}/land", p2.number), Some("site"), Some("{}".into())).await;
4355
    assert_eq!(st, StatusCode::OK, "{body}");
4356
    let mut behind = serde_json::Value::Null;
4357
    for _ in 0..100 {
4358
        let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
4359
        let list: Vec<serde_json::Value> = serde_json::from_str(&list).unwrap();
4360
        behind = list.iter().find(|c| c["name"] == "game").map(|c| c["behind"].clone()).unwrap_or_default();
4361
        if behind == 0 {
4362
            break;
4363
        }
4364
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4365
    }
4366
    assert_eq!(behind, 0, "the index followed the landing");
5d54cf74 Andy McCall ↶ 4367
    assert_eq!(oxygenhub::diffusion::forced_left(&h.app, game.id), 0, "the first write did fail");
0e04dfc2 Andy McCall ↶ 4368
    // The reconciler (#210): an index left behind its bookmark (as when
4369
    // both writes failed) is mended from the bookmark itself, and a pass
4370
    // with nothing to mend changes nothing.
4371
    let pins_of = || async {
3b1bc27f Andy McCall 4372
        sqlx::query_scalar::<_, String>("SELECT heads FROM diffusion_pins WHERE consumer_id = $1")
0e04dfc2 Andy McCall ↶ 4373
            .bind(game.id)
4374
            .fetch_one(&h.app.db)
4375
            .await
4376
            .unwrap()
4377
    };
4378
    let right = pins_of().await;
3b1bc27f Andy McCall 4379
    sqlx::query("UPDATE diffusion_pins SET heads = 'stale' WHERE consumer_id = $1").bind(game.id).execute(&h.app.db).await.unwrap();
4380
    sqlx::query("DELETE FROM diffusion_indexed WHERE consumer_id = $1").bind(game.id).execute(&h.app.db).await.unwrap();
0e04dfc2 Andy McCall ↶ 4381
    let r = oxygenhub::diffusion::reconcile(&h.app).await;
4382
    assert!(r.reindexed >= 1, "{r:?}");
4383
    assert_eq!(pins_of().await, right, "the pin read again from the game's bookmark");
4384
    assert_eq!(oxygenhub::diffusion::reconcile(&h.app).await.reindexed, 0, "nothing left to mend");
757195ad Andy McCall ↶ 4385
180dc43a Andy McCall ↶ 4386
    // A private upstream: the bump's run (started by the diffusion account,
4387
    // which cannot read it) still gets the subrepo it bumps.
4388
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'api'").execute(&h.app.db).await.unwrap();
4389
    seen.lock().unwrap().clear();
4390
    write(api_work.path(), "a6.c", "v6\n");
4391
    api.snapshot("t").unwrap();
4392
    api.commit("api v6", &[]).unwrap();
4393
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4fa0da12 Andy McCall ↶ 4394
    // The bump's run starts in the background: wait for its job, under a
4395
    // loaded test run as well as alone.
4396
    let mut bump_job = None;
4397
    for _ in 0..100 {
4398
        pass_all().await;
4399
        bump_job = seen.lock().unwrap().iter().find(|c| c["repo"] == "andy/game" && c["bookmark"] == "diffusion/deps/api").cloned();
4400
        if bump_job.is_some() {
4401
            break;
4402
        }
4403
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
4404
    }
4405
    let bump_job = bump_job.expect("the bump's job ran");
180dc43a Andy McCall ↶ 4406
    let subs: Vec<&str> = bump_job["subrepos"].as_array().unwrap().iter().filter_map(|s| s["path"].as_str()).collect();
4407
    assert_eq!(subs, vec!["deps/api"], "{bump_job}");
4408
3776b70d Andy McCall ↶ 4409
    // A consumer turning Diffusion on is bumped at once to the upstream's
4410
    // newest passing state, without waiting for it to move again.
4411
    create(&h.app, "andy", "game2").await;
4412
    let g2_work = tempfile::tempdir().unwrap();
4413
    let g2 = client(&format!("{}/andy/game2", h.base), g2_work.path());
4414
    g2.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
4415
    g2.snapshot("t").unwrap();
4416
    g2.commit("game2 on api", &[]).unwrap();
4417
    assert!(g2.push("origin", false).unwrap().iter().all(|r| r.ok));
4418
    // Its pin is api's newest state already: move api on, pass the run.
4419
    write(api_work.path(), "a5.c", "v5\n");
4420
    api.snapshot("t").unwrap();
4421
    api.commit("api v5", &[]).unwrap();
7e01a766 Andy McCall ↶ 4422
    let api_row = db::repos::get(&h.app.db, "andy", "api").await.unwrap().unwrap();
4423
    let runs_before = db::flow::runs(&h.app.db, api_row.id, 100, None).await.unwrap().len();
3776b70d Andy McCall ↶ 4424
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
7e01a766 Andy McCall ↶ 4425
    // The push's run is made in the background: wait for it, or pass_all
4426
    // can finish before it exists and v5 never passes (a flake under load).
4427
    for _ in 0..300 {
4428
        if db::flow::runs(&h.app.db, api_row.id, 100, None).await.unwrap().len() > runs_before {
4429
            break;
4430
        }
4431
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
4432
    }
3776b70d Andy McCall ↶ 4433
    pass_all().await;
4434
    let g2_row = db::repos::get(&h.app.db, "andy", "game2").await.unwrap().unwrap();
4435
    for _ in 0..100 {
3b1bc27f Andy McCall 4436
        if sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
3776b70d Andy McCall ↶ 4437
            .bind(g2_row.id)
4438
            .fetch_one(&h.app.db)
4439
            .await
4440
            .unwrap()
4441
            > 0
4442
        {
4443
            break;
4444
        }
4445
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4446
    }
4447
    assert!(db::proposals::list(&h.app.db, g2_row.id, &[]).await.unwrap().is_empty(), "off until turned on");
4448
    let (st, _) = call(&h.app, "PUT", "/api/v1/repos/andy/game2/diffusion", Some("site"), Some(r#"{"follow":"green"}"#.into())).await;
4449
    assert_eq!(st, StatusCode::OK);
4450
    let mut caught = None;
5d54cf74 Andy McCall ↶ 4451
    // Up to 15 s: under a full parallel test run the bump can take a while.
4452
    for _ in 0..300 {
3776b70d Andy McCall ↶ 4453
        if let Some(p) = db::proposals::list(&h.app.db, g2_row.id, &["open"]).await.unwrap().into_iter().next() {
4454
            caught = Some(p);
4455
            break;
4456
        }
4457
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4458
    }
4459
    let caught = caught.expect("bumped as soon as it was turned on");
4460
    assert!(caught.body.contains("api v5") && caught.title.contains("1 change"), "{:?} {:?}", caught.title, caught.body);
0e04dfc2 Andy McCall ↶ 4461
    // A bump someone closed is a "no": the reconciler does not open it again.
3b1bc27f Andy McCall 4462
    sqlx::query("UPDATE proposals SET state = 'closed' WHERE id = $1").bind(caught.id).execute(&h.app.db).await.unwrap();
62cdf34d Andy McCall ↶ 4463
    // (The bump's own runs finishing may still propose again, as Diffusion
4464
    // does on an upstream's moves; the reconciler itself opens nothing.)
0e04dfc2 Andy McCall ↶ 4465
    let r = oxygenhub::diffusion::reconcile(&h.app).await;
62cdf34d Andy McCall ↶ 4466
    assert_eq!(r.caught_up, 0, "the reconciler respects the closed bump: {r:?}");
a7e6e8e6 Andy McCall ↶ 4467
}
4468
4469
/// Whether any job is queued or running.
4470
async fn jobs_left(app: &Shared) -> bool {
4471
    sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM flow_jobs WHERE status IN ('queued', 'running')")
4472
        .fetch_one(&app.db)
4473
        .await
4474
        .unwrap_or(0)
4475
        > 0
9aaa88b2 Andy McCall ↶ 4476
}
4477
4478
/// An upstream with no checks never turns green: a consumer following green
4479
/// still gets its bumps, marked amber, `upstream unverified` (#148).
4480
#[tokio::test(flavor = "multi_thread")]
4481
async fn bumps_from_an_upstream_without_checks_are_marked_unverified() {
4482
    let h = hub().await;
4483
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4484
    create(&h.app, "andy", "lib").await;
4485
    create(&h.app, "andy", "app").await;
4486
    let lib_work = tempfile::tempdir().unwrap();
4487
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
4488
    write(lib_work.path(), "lib.h", "v1\n");
4489
    lib.snapshot("t").unwrap();
4490
    lib.commit("lib v1", &[]).unwrap();
4491
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4492
    let app_work = tempfile::tempdir().unwrap();
4493
    let app = client(&format!("{}/andy/app", h.base), app_work.path());
4494
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
c4e432da Andy McCall ↶ 4495
    // It watches lib.c: upstream changes touching it are flagged.
4496
    let modules = std::fs::read_to_string(app_work.path().join(".oxymodules")).unwrap();
4497
    write(app_work.path(), ".oxymodules", &format!("{modules}watch = lib.c\n"));
9aaa88b2 Andy McCall ↶ 4498
    app.snapshot("t").unwrap();
4499
    app.commit("app on lib", &[]).unwrap();
4500
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
4501
    let app_row = db::repos::get(&h.app.db, "andy", "app").await.unwrap().unwrap();
4502
    for _ in 0..100 {
3b1bc27f Andy McCall 4503
        if sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
9aaa88b2 Andy McCall ↶ 4504
            .bind(app_row.id)
4505
            .fetch_one(&h.app.db)
4506
            .await
4507
            .unwrap()
4508
            > 0
4509
        {
4510
            break;
4511
        }
4512
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4513
    }
4514
    let (st, _) = call(&h.app, "PUT", "/api/v1/repos/andy/app/diffusion", Some("site"), Some(r#"{"follow":"green"}"#.into())).await;
4515
    assert_eq!(st, StatusCode::OK);
4516
    write(lib_work.path(), "lib.c", "v2\n");
4517
    lib.snapshot("t").unwrap();
4518
    lib.commit("lib v2", &[]).unwrap();
4519
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4520
    let mut found = None;
4521
    for _ in 0..100 {
4522
        if let Some(p) = db::proposals::list(&h.app.db, app_row.id, &["open"]).await.unwrap().into_iter().next() {
4523
            found = Some(p);
4524
            break;
4525
        }
4526
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4527
    }
4528
    let p = found.expect("a bump although the upstream never goes green");
4529
    assert!(p.body.contains("Upstream unverified"), "{}", p.body);
c4e432da Andy McCall ↶ 4530
    assert!(p.body.contains("Touches what you watch") && p.body.contains("touches `lib.c`") && p.body.contains("⚑"), "{}", p.body);
9aaa88b2 Andy McCall ↶ 4531
    let mut labels = Vec::new();
4532
    for _ in 0..100 {
4533
        labels = db::issues::proposal_labels(&h.app.db, p.id).await.unwrap().into_iter().map(|l| l.name).collect::<Vec<String>>();
4534
        if labels.len() == 2 {
4535
            break;
4536
        }
4537
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4538
    }
4539
    assert!(labels.contains(&"upstream unverified".to_string()) && labels.contains(&"dependencies".to_string()), "{labels:?}");
a7e6e8e6 Andy McCall ↶ 4540
}
d943160d Andy McCall ↶ 4541
4542
/// #134: when a proposal's target moves, its projected state is new; the
4543
/// hub runs the pipeline on it, so its checks are never for an older one.
4544
#[tokio::test(flavor = "multi_thread")]
4545
async fn a_moved_target_runs_its_open_proposals_again() {
4546
    let h = hub().await;
4547
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4548
    create(&h.app, "andy", "demo").await;
4549
    let work = tempfile::tempdir().unwrap();
4550
    let mut c = client(&format!("{}/andy/demo", h.base), work.path());
4551
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4552
    write(work.path(), "test.sh", "echo ok\n");
4553
    c.snapshot("t").unwrap();
4554
    let base = c.commit("base", &[]).unwrap();
4555
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4556
    // Two proposals, each main plus one change.
4557
    for (b, file) in [("fix-a", "a.txt"), ("fix-b", "b.txt")] {
4558
        c.bookmark_create(b, Some(&[base])).unwrap();
4559
        c.bookmark_switch(b, true).unwrap();
4560
        write(work.path(), file, "x\n");
4561
        c.snapshot("t").unwrap();
4562
        c.commit(&format!("add {file}"), &[]).unwrap();
4563
        assert!(c.push_bookmark("origin", b, false).unwrap().iter().all(|r| r.ok));
4564
        let body = serde_json::json!({ "title": b, "target": "main", "source": b }).to_string();
4565
        let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/demo/proposals", Some("site"), Some(body)).await;
4566
        assert_eq!(st, StatusCode::CREATED, "{out}");
4567
    }
4568
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
4569
    let props = db::proposals::list(&h.app.db, row.id, &["open"]).await.unwrap();
4570
    let a = props.iter().find(|p| p.source_bookmark == "fix-a").unwrap().number;
4571
    let b = props.iter().find(|p| p.source_bookmark == "fix-b").unwrap().number;
4572
    // Landing fix-a moves main: fix-b's projected state gets a run.
4573
    let (st, out) = call(&h.app, "POST", &format!("/api/v1/repos/andy/demo/proposals/{a}/land"), Some("site"), Some("{}".into())).await;
4574
    assert_eq!(st, StatusCode::OK, "{out}");
4575
    let label = format!("proposal/{b}");
4576
    let mut found = None;
4577
    for _ in 0..100 {
4578
        if let Some(r) = runs_of(&h.app, "andy", "demo").await.into_iter().find(|r| r.bookmark == label) {
4579
            found = Some(r);
4580
            break;
4581
        }
4582
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4583
    }
4584
    let run = found.expect("a run of fix-b's new projected state");
4585
    let projected = db::proposals::get(&h.app.db, row.id, b).await.unwrap().unwrap();
4586
    assert_eq!((run.trigger.as_str(), run.state.as_str()), ("proposal", projected.projected_state.as_str()), "on its projected state");
4587
    // Moving main again by a push does it once more; the same state is not run twice.
4588
    let before = runs_of(&h.app, "andy", "demo").await.len();
4589
    oxygenhub::web::proposals::settle_after_push(&h.app, &row, "main", "andy").await;
4590
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), before, "not again for the same state");
4591
}
93501da2 Andy McCall ↶ 4592
4593
/// Send image bytes to the hub as their chunks and then a manifest that
4594
/// names no architecture; the manifest as the hub answers it.
4595
async fn send_image(app: &Shared, image: &[u8]) -> (String, serde_json::Value) {
4596
    let mut chunks = std::collections::HashMap::new();
4597
    let m = jet::images::scan(image, None, |c, b| {
4598
        chunks.insert(c.hash().to_string(), b.to_vec());
4599
        Ok(())
4600
    })
4601
    .unwrap();
4602
    for c in m.needed() {
4603
        let (st, body) = put_bytes(app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
4604
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
4605
    }
4606
    let (st, body) =
4607
        call(app, "PUT", &format!("/api/v1/flow/images/{}", m.hash), Some("site"), Some(serde_json::to_string(&m).unwrap())).await;
4608
    assert_eq!(st, StatusCode::CREATED, "{body}");
4609
    (m.hash.clone(), serde_json::from_str(&body).unwrap())
4610
}
4611
4612
/// oxygenhub#173 (OxygenFlow spec §11.2, Andy's "detect and learn"): an
4613
/// image sent with no architecture is read from its own files, so a
4614
/// riscv64 runner is never offered an x86_64 image's jobs; an image
4615
/// nobody can read takes the architecture its first pass ran on.
4616
#[tokio::test(flavor = "multi_thread")]
4617
async fn an_image_names_its_own_architecture_and_a_pass_teaches_the_rest() {
4618
    use oxy_core::identity::SecretKey;
4619
    let h = hub().await;
4620
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4621
    // An ext4 image whose shell is x86_64, as `flow rootfs import` makes one.
4622
    let dir = tempfile::tempdir().unwrap();
4623
    let tree = dir.path().join("tree");
4624
    std::fs::create_dir_all(tree.join("bin")).unwrap();
4625
    let mut elf = vec![0u8; 64];
4626
    elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
4627
    elf[18..20].copy_from_slice(&0x3Eu16.to_le_bytes());
4628
    std::fs::write(tree.join("bin/sh"), &elf).unwrap();
4629
    let img = dir.path().join("rootfs.ext4");
4630
    let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
4631
    if !made.is_ok_and(|s| s.success()) {
4632
        eprintln!("mkfs.ext4 not found: skipped");
4633
        return;
4634
    }
4635
    let (x86, answer) = send_image(&h.app, &std::fs::read(&img).unwrap()).await;
4636
    assert_eq!(answer["arch"], "x86_64", "read from its shell: {answer}");
4637
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{x86}"), Some("runner-secret"), None).await;
4638
    assert_eq!(serde_json::from_str::<jet::images::Manifest>(&body).unwrap().arch.as_deref(), Some("x86_64"), "runners fetch it named");
4639
    // One nobody can read: no ext4, no shell.
4640
    let blob: Vec<u8> = (0..300_000u32).map(|i| (i % 241) as u8).collect();
4641
    let (unread, answer) = send_image(&h.app, &blob).await;
4642
    assert!(answer["arch"].is_null(), "{answer}");
4643
    let archs = db::flow::image_archs(&h.app.db).await.unwrap();
4644
    assert_eq!((archs.get(&x86).map(String::as_str), archs.get(&unread)), (Some("x86_64"), None));
4645
    // Kept images with none are read once at start.
4646
    sqlx::query("UPDATE jet_images SET arch = ''").execute(&h.app.db).await.unwrap();
4647
    sqlx::query("DELETE FROM flow_images").execute(&h.app.db).await.unwrap();
4648
    assert_eq!(oxygenhub::images::learn_archs(&h.app).await.unwrap(), 1);
4649
    assert_eq!(db::flow::image_archs(&h.app.db).await.unwrap().get(&x86).map(String::as_str), Some("x86_64"));
4650
4651
    // A job on each image.
4652
    create(&h.app, "andy", "arch").await;
4653
    let work = tempfile::tempdir().unwrap();
4654
    let c = client(&format!("{}/andy/arch", h.base), work.path());
4655
    let kdl = format!(
4656
        "schema-version 1\nsandbox \"unread\" {{\n    rootfs \"cas://blob/{unread}\"\n}}\nsandbox \"x86\" {{\n    rootfs \"cas://blob/{x86}\"\n}}\n\
4657
         job \"first\" {{\n    sandbox \"unread\"\n    exec \"make\"\n}}\njob \"second\" {{\n    sandbox \"x86\"\n    exec \"make\"\n    depends-on \"first\"\n}}\n\
4658
         job \"third\" {{\n    sandbox \"unread\"\n    exec \"make\"\n    depends-on \"first\"\n}}\n"
4659
    );
4660
    write(work.path(), ".flow/pipeline.kdl", &kdl);
4661
    c.commit("Jobs on two images", &[]).unwrap();
4662
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4663
    runs_of(&h.app, "andy", "arch").await;
4664
4665
    // The x86_64 runner passes the first job: its image is x86_64 now.
4666
    let x86_info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
4667
    let x86_claim =
4668
        serde_json::json!({ "runner": "earth", "runtimes": ["microvm"], "images": [], "fetches_images": true, "info": x86_info });
4669
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(x86_claim.to_string())).await;
4670
    assert_eq!(st, StatusCode::OK, "{body}");
4671
    let first: serde_json::Value = serde_json::from_str(&body).unwrap();
4672
    assert_eq!(first["job"]["name"], "first");
4673
    let ph = first["pipeline_hash"].as_str().unwrap();
4674
    let id = first["job_id"].as_i64().unwrap();
4675
    assert_eq!(
4676
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("first", ph, 0) })).await,
4677
        StatusCode::NO_CONTENT
4678
    );
4679
    assert_eq!(db::flow::image_archs(&h.app.db).await.unwrap().get(&unread).map(String::as_str), Some("x86_64"), "learned");
4680
4681
    // A riscv64 runner is offered neither: one read, one learned.
4682
    let token = "flowreg_narvi";
4683
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
4684
    let identity = SecretKey::generate().identity("narvi", "", 1);
4685
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
4686
    let reg = serde_json::json!({ "token": token, "name": "narvi", "identity": hex::encode(identity.encode()), "info": info });
4687
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
4688
    assert_eq!(st, StatusCode::OK, "{body}");
4689
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
4690
    let narvi =
4691
        serde_json::json!({ "runner": "narvi", "runtimes": ["microvm"], "images": [], "fetches_images": true, "info": info }).to_string();
4692
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(narvi)).await;
4693
    assert_eq!(st, StatusCode::NO_CONTENT, "the second job's image is x86_64 and the third's learned so: {body}");
4694
    for _ in 0..2 {
4695
        let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(x86_claim.to_string())).await;
4696
        assert_eq!(st, StatusCode::OK, "both go to x86_64: {body}");
4697
    }
4698
}
f4d6ef41 Andy McCall ↶ 4699
4700
/// Diffusion auto-land (docs/diffusion.md §4.2; Andy chose "opt-in, per
4701
/// repository", 2026-10-13): a consumer that chose `land = auto` has a bump
4702
/// landed by itself, as the diffusion account, once both halves are green;
4703
/// a bump from an upstream with no checks (amber) always waits.
4704
#[tokio::test(flavor = "multi_thread")]
4705
async fn a_consumer_that_chose_auto_lands_green_bumps_itself() {
4706
    let h = hub().await;
4707
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4708
    create(&h.app, "andy", "api").await;
4709
    create(&h.app, "andy", "game").await;
4710
    let hub_app = &h.app;
4711
    // Run every queued job to a pass.
4712
    let pass_all = move || async move {
4713
        for _ in 0..20 {
4714
            let Some(a) = claim(hub_app).await else {
4715
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4716
                if !jobs_left(hub_app).await {
4717
                    break;
4718
                }
4719
                continue;
4720
            };
4721
            let id = a["job_id"].as_i64().unwrap();
4722
            let (name, ph) = (a["job"]["name"].as_str().unwrap().to_string(), a["pipeline_hash"].as_str().unwrap().to_string());
4723
            assert_eq!(
4724
                finish(hub_app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt(&name, &ph, 0) })).await,
4725
                StatusCode::NO_CONTENT
4726
            );
4727
        }
4728
    };
4729
    let api_work = tempfile::tempdir().unwrap();
4730
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
4731
    write(api_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4732
    write(api_work.path(), "test.sh", "echo ok\n");
4733
    api.snapshot("t").unwrap();
4734
    api.commit("api v1", &[]).unwrap();
4735
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4736
    pass_all().await;
4737
    let game_work = tempfile::tempdir().unwrap();
4738
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
4739
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
4740
    write(game_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4741
    write(game_work.path(), "test.sh", "echo ok\n");
4742
    game.snapshot("t").unwrap();
4743
    game.commit("game on api v1", &[]).unwrap();
4744
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
4745
    pass_all().await;
4746
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
4747
    for _ in 0..100 {
3b1bc27f Andy McCall 4748
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
f4d6ef41 Andy McCall ↶ 4749
            .bind(game_row.id)
4750
            .fetch_one(&h.app.db)
4751
            .await
4752
            .unwrap();
4753
        if n > 0 {
4754
            break;
4755
        }
4756
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4757
    }
4758
    let (st, body) =
4759
        call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(r#"{"follow":"green","land":"auto"}"#.into())).await;
4760
    assert_eq!(st, StatusCode::OK, "{body}");
4761
    assert!(body.contains(r#""land":"auto""#), "{body}");
4762
    let (st, _) =
4763
        call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(r#"{"follow":"green","land":"soon"}"#.into())).await;
4764
    assert_eq!(st, StatusCode::BAD_REQUEST);
4765
4766
    // The upstream moves and passes: the bump is proposed, its run passes,
4767
    // and it lands by itself.
4768
    write(api_work.path(), "a2.c", "v2\n");
4769
    api.snapshot("t").unwrap();
4770
    api.commit("api v2: faster sprites", &[]).unwrap();
4771
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
4772
    let mut landed = None;
4773
    for _ in 0..100 {
4774
        pass_all().await;
4775
        let all = db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap();
4776
        if let Some(p) = all.into_iter().find(|p| p.source_bookmark == "diffusion/deps/api" && p.state == "landed") {
4777
            landed = Some(p);
4778
            break;
4779
        }
4780
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4781
    }
4782
    let p = landed.expect("landed by itself once both halves were green");
4783
    assert!(p.body.contains("lands its bumps itself"), "{}", p.body);
a2ef53c5 Andy McCall ↶ 4784
    // The state is written a moment before the timeline's event: wait for it.
4785
    let mut events = vec![];
4786
    for _ in 0..100 {
4787
        events = db::proposals::events(&h.app.db, p.id).await.unwrap();
4788
        if events.iter().any(|e| e.event == "landed") {
4789
            break;
4790
        }
4791
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
4792
    }
f4d6ef41 Andy McCall ↶ 4793
    let landing = events.iter().find(|e| e.event == "landed").expect("a landing on the timeline");
4794
    assert_eq!(landing.actor, "diffusion");
4795
    assert!(landing.detail.contains("Diffusion, both halves green"), "{}", landing.detail);
4796
    // The game's main now pins api v2.
4797
    let mut behind = serde_json::Value::Null;
4798
    for _ in 0..100 {
4799
        let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
4800
        let list: Vec<serde_json::Value> = serde_json::from_str(&list).unwrap();
4801
        behind = list.iter().find(|c| c["name"] == "game").map(|c| c["behind"].clone()).unwrap_or_default();
4802
        if behind == 0 {
4803
            break;
4804
        }
4805
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4806
    }
4807
    assert_eq!(behind, 0, "main moved to the bump");
4808
4809
    // An upstream with no checks: its bump passes in the consumer, but
4810
    // amber never lands by itself, whatever the setting.
4811
    create(&h.app, "andy", "lib").await;
4812
    create(&h.app, "andy", "app").await;
4813
    let lib_work = tempfile::tempdir().unwrap();
4814
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
4815
    write(lib_work.path(), "lib.h", "v1\n");
4816
    lib.snapshot("t").unwrap();
4817
    lib.commit("lib v1", &[]).unwrap();
4818
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4819
    let app_work = tempfile::tempdir().unwrap();
4820
    let app = client(&format!("{}/andy/app", h.base), app_work.path());
4821
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
4822
    let modules = std::fs::read_to_string(app_work.path().join(".oxymodules")).unwrap();
4823
    write(app_work.path(), ".oxymodules", &format!("{modules}follow = green\nland = auto\n"));
4824
    write(app_work.path(), ".flow/pipeline.kdl", &pipeline(""));
4825
    write(app_work.path(), "test.sh", "echo ok\n");
4826
    app.snapshot("t").unwrap();
4827
    app.commit("app on lib", &[]).unwrap();
4828
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
4829
    pass_all().await;
4830
    let app_row = db::repos::get(&h.app.db, "andy", "app").await.unwrap().unwrap();
4831
    for _ in 0..100 {
3b1bc27f Andy McCall 4832
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = $1")
f4d6ef41 Andy McCall ↶ 4833
            .bind(app_row.id)
4834
            .fetch_one(&h.app.db)
4835
            .await
4836
            .unwrap();
4837
        if n > 0 {
4838
            break;
4839
        }
4840
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4841
    }
4842
    write(lib_work.path(), "lib.c", "v2\n");
4843
    lib.snapshot("t").unwrap();
4844
    lib.commit("lib v2", &[]).unwrap();
4845
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
4846
    let mut passed = false;
4847
    for _ in 0..100 {
4848
        pass_all().await;
4849
        let s: Option<String> = sqlx::query_scalar(
3b1bc27f Andy McCall 4850
            "SELECT status FROM flow_runs WHERE repo_id = $1 AND bookmark = 'diffusion/deps/lib' ORDER BY id DESC LIMIT 1",
f4d6ef41 Andy McCall ↶ 4851
        )
4852
        .bind(app_row.id)
4853
        .fetch_optional(&h.app.db)
4854
        .await
4855
        .unwrap();
4856
        if s.as_deref() == Some("passed") {
4857
            passed = true;
4858
            break;
4859
        }
4860
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
4861
    }
4862
    assert!(passed, "the app's run on the bump passed");
4863
    assert_eq!(oxygenhub::diffusion::auto_land(&h.app, &app_row, "deps/lib").await, Err(oxygenhub::diffusion::Held::Unverified));
4864
    let open = db::proposals::list(&h.app.db, app_row.id, &["open"]).await.unwrap();
4865
    assert!(open.iter().any(|p| p.source_bookmark == "diffusion/deps/lib"), "amber waits for a person");
4866
}
e8fa5369 Andy McCall ↶ 4867
4868
/// oxygenflow#31: one finished job runs again in the same run, with the
4869
/// jobs that depend on it; what it depends on keeps its result, so a flaky
4870
/// test reruns without its build. Not while the run is live, and only a
4871
/// job the run has.
4872
#[tokio::test(flavor = "multi_thread")]
4873
async fn one_job_reruns_with_what_depends_on_it() {
4874
    let h = hub().await;
4875
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4876
    create(&h.app, "andy", "flaky").await;
4877
    let work = tempfile::tempdir().unwrap();
4878
    let c = client(&format!("{}/andy/flaky", h.base), work.path());
4879
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4880
    write(work.path(), "test.sh", "echo ok\n");
4881
    c.commit("Add a pipeline", &[]).unwrap();
4882
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4883
    let run = runs_of(&h.app, "andy", "flaky").await[0].clone();
4884
    // build and lint pass; test fails, as a flaky one does.
4885
    let (st, _) =
4886
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/test/rerun", run.number), Some("site"), None).await;
4887
    assert_eq!(st, StatusCode::CONFLICT, "not while the run is live");
4888
    while let Some(j) = claim(&h.app).await {
4889
        let id = j["job_id"].as_i64().unwrap();
4890
        let (name, ph) = (j["job"]["name"].as_str().unwrap().to_string(), j["pipeline_hash"].as_str().unwrap().to_string());
4891
        let exit = if name == "test" { 1 } else { 0 };
d9b3b846 Andy McCall ↶ 4892
        let log = serde_json::json!({ "records": [
4893
            { "t": 1, "stream": "out", "text": format!("{name} ran") },
4894
            { "t": 2, "stream": "out", "text": "::group::compile" },
4895
            { "t": 5, "stream": "out", "text": "cc a.c" },
4896
            { "t": 1502, "stream": "out", "text": "::endgroup::" },
4897
        ]});
e8fa5369 Andy McCall ↶ 4898
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(log.to_string())).await;
4899
        assert_eq!(
4900
            finish(&h.app, id, serde_json::json!({ "exit_code": exit, "duration_ms": 10, "receipt": receipt(&name, &ph, exit as u32) }))
4901
                .await,
4902
            StatusCode::NO_CONTENT
4903
        );
4904
    }
d9b3b846 Andy McCall ↶ 4905
    // Marked lines fold into a section, with how long it took (#31).
4906
    let (_, page) = call(&h.app, "GET", &format!("/andy/flaky/flow/{}", run.number), None, None).await;
4907
    assert!(page.contains(r#"<details class="log-group" data-from="2">"#), "{page}");
4908
    assert!(page.contains(r#"compile <span class="took">1.5s</span></summary>"#) && !page.contains("::endgroup::"), "{page}");
e8fa5369 Andy McCall ↶ 4909
    let status = |n: &'static str| {
4910
        let (app, run_id) = (h.app.clone(), run.id);
4911
        async move { db::flow::jobs(&app.db, run_id).await.unwrap().into_iter().find(|j| j.name == n).unwrap() }
4912
    };
4913
    assert_eq!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().status, "failed");
4914
    let failed_test = status("test").await;
4915
4916
    // The test again: build and lint keep their results.
4917
    let (st, body) =
4918
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/test/rerun", run.number), Some("site"), None).await;
4919
    assert_eq!(st, StatusCode::OK, "{body}");
4920
    assert!(body.contains(r#""queued":1"#), "{body}");
4921
    assert_eq!(
4922
        (status("build").await.status, status("lint").await.status, status("test").await.status),
4923
        ("passed".into(), "passed".into(), "queued".into())
4924
    );
4925
    assert!(db::flow::log(&h.app.db, failed_test.id, 0, 100).await.unwrap().is_empty(), "its old log is gone");
4926
    assert!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().live());
4927
    let checks = checks_when(&h.app, run.repo_id, &run.state, 3).await;
4928
    assert_eq!(checks.iter().find(|c| c.name == "flow/test").map(|c| c.status.as_str()), Some("queued"));
4929
    let j = claim(&h.app).await.expect("the test, queued again");
4930
    assert_eq!(j["job"]["name"], "test");
4931
    let ph = j["pipeline_hash"].as_str().unwrap().to_string();
4932
    let id = j["job_id"].as_i64().unwrap();
4933
    assert_eq!(
4934
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("test", &ph, 0) })).await,
4935
        StatusCode::NO_CONTENT
4936
    );
4937
    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 ↶ 4938
    // Andy owns it: told it failed, then that it is fixed (#183).
4939
    let andy_id = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap().id;
4940
    let kinds: Vec<String> = db::notify::inbox(&h.app.db, andy_id, 20).await.unwrap().into_iter().map(|n| n.kind).collect();
4941
    assert!(kinds.contains(&"flow.failed".to_string()) && kinds.contains(&"flow.fixed".to_string()), "{kinds:?}");
e8fa5369 Andy McCall ↶ 4942
4943
    // The build again brings the test that depends on it; lint stays.
4944
    let (_, body) =
4945
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/build/rerun", run.number), Some("site"), None).await;
4946
    assert!(body.contains(r#""queued":2"#), "{body}");
4947
    assert_eq!(
4948
        (status("build").await.status, status("lint").await.status, status("test").await.status),
4949
        ("queued".into(), "passed".into(), "queued".into())
4950
    );
4951
    let (st, _) =
4952
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/deploy/rerun", run.number), Some("site"), None).await;
4953
    assert_eq!(st, StatusCode::CONFLICT, "live again, and no such job either way");
4954
}
4a4400c5 Andy McCall ↶ 4955
4956
/// oxygenflow#30: a failed run tells its pusher and the repository's
4957
/// watchers; a runner whose last five jobs ended in infrastructure errors
4958
/// is drained and the administrators told, counting only since an
4959
/// administrator last made it active.
4960
#[tokio::test(flavor = "multi_thread")]
4961
async fn failed_runs_are_told_and_an_erroring_runner_is_drained() {
4962
    let h = hub().await;
4963
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4964
    let bob = db::accounts::create_account(&h.app.db, "bob", "[email protected]", "x", "salt", false).await.unwrap();
4965
    create(&h.app, "andy", "alerts").await;
4966
    let row = db::repos::get(&h.app.db, "andy", "alerts").await.unwrap().unwrap();
4967
    db::notify::set_watch(&h.app.db, bob.id, row.id, true).await.unwrap();
4968
    let work = tempfile::tempdir().unwrap();
4969
    let c = client(&format!("{}/andy/alerts", h.base), work.path());
4970
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4971
    write(work.path(), "test.sh", "exit 1\n");
4972
    c.commit("Add a pipeline", &[]).unwrap();
4973
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4974
    let run = runs_of(&h.app, "andy", "alerts").await[0].clone();
3b1bc27f Andy McCall 4975
    sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&h.app.db).await.unwrap();
4a4400c5 Andy McCall ↶ 4976
    while let Some(j) = claim(&h.app).await {
4977
        let id = j["job_id"].as_i64().unwrap();
4978
        let (name, ph) = (j["job"]["name"].as_str().unwrap().to_string(), j["pipeline_hash"].as_str().unwrap().to_string());
4979
        let exit = if name == "test" { 1 } else { 0 };
4980
        finish(&h.app, id, serde_json::json!({ "exit_code": exit, "duration_ms": 10, "receipt": receipt(&name, &ph, exit as u32) })).await;
4981
    }
4982
    let told = |id: i64| {
4983
        let db = h.app.db.clone();
4984
        async move { db::notify::inbox(&db, id, 20).await.unwrap().into_iter().filter(|n| n.kind == "flow.failed").collect::<Vec<_>>() }
4985
    };
4986
    let (for_andy, for_bob) = (told(andy.id).await, told(bob.id).await);
4987
    assert_eq!((for_andy.len(), for_bob.len()), (1, 1), "the pusher and a watcher");
4988
    assert!(for_andy[0].title.contains(&format!("run #{} on main failed (test)", run.number)), "{}", for_andy[0].title);
4989
    assert_eq!(for_andy[0].url, format!("/andy/alerts/flow/{}", run.number));
4990
4991
    // Five infrastructure errors in a row drain the runner.
4992
    let runner_id = || {
4993
        let db = h.app.db.clone();
4994
        async move { sqlx::query_scalar::<_, i64>("SELECT id FROM flow_runners WHERE name = 'test-1'").fetch_one(&db).await.unwrap() }
4995
    };
4996
    let mut errors = 0;
4997
    while errors < 5 {
4998
        let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/alerts/flow/runs", Some("site"), Some("{}".into())).await;
4999
        assert_eq!(st, StatusCode::CREATED);
5000
        while let Some(j) = claim(&h.app).await {
5001
            let id = j["job_id"].as_i64().unwrap();
5002
            let st = finish(
5003
                &h.app,
5004
                id,
5005
                serde_json::json!({ "exit_code": null, "duration_ms": 10, "error": "the microVM did not start: /dev/kvm busy" }),
5006
            )
5007
            .await;
5008
            assert_eq!(st, StatusCode::NO_CONTENT);
5009
            errors += 1;
5010
            if errors == 5 {
5011
                break;
5012
            }
5013
        }
5014
    }
5015
    let state = |id: i64| {
5016
        let db = h.app.db.clone();
5017
        async move { db::runners::get(&db, id).await.unwrap().unwrap().state }
5018
    };
5019
    let id = runner_id().await;
5020
    assert_eq!(state(id).await, "draining");
5021
    let drained: Vec<_> =
5022
        db::notify::inbox(&h.app.db, andy.id, 50).await.unwrap().into_iter().filter(|n| n.kind == "flow.runner_drained").collect();
5023
    assert_eq!(drained.len(), 1, "the administrator is told");
5024
    assert!(drained[0].title.contains("/dev/kvm busy"), "{}", drained[0].title);
5025
    assert!(
5026
        !told(bob.id).await.is_empty()
5027
            && db::notify::inbox(&h.app.db, bob.id, 50).await.unwrap().iter().all(|n| n.kind != "flow.runner_drained")
5028
    );
5029
    // Made active again, past errors no longer count.
5030
    db::runners::set_state(&h.app.db, id, "active").await.unwrap();
5031
    assert_eq!(db::runners::erroring(&h.app.db, id, 5).await.unwrap(), None);
f7bcee49 Andy McCall ↶ 5032
}
5033
5034
/// #197: landing a proposal moves its target as a push does, so the
5035
/// target's pipeline runs on the landed state.
5036
#[tokio::test(flavor = "multi_thread")]
5037
async fn a_landed_proposal_runs_its_targets_pipeline() {
5038
    let h = hub().await;
5039
    create(&h.app, "andy", "demo").await;
5040
    let url = format!("{}/andy/demo", h.base);
5041
    let work = tempfile::tempdir().unwrap();
5042
    let mut c = client(&url, work.path());
5043
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5044
    write(work.path(), "test.sh", "echo ok\n");
5045
    c.snapshot("test").unwrap();
5046
    c.commit("Add a pipeline", &[]).unwrap();
5047
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5048
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
5049
    c.bookmark_create("feature", None).unwrap();
5050
    c.bookmark_switch("feature", false).unwrap();
5051
    write(work.path(), "b.txt", "more\n");
5052
    c.snapshot("test").unwrap();
5053
    c.commit("More", &[]).unwrap();
5054
    assert!(c.push_bookmark("origin", "feature", false).unwrap().iter().all(|r| r.ok));
5055
    let runs_before =
5056
        db::flow::runs(&h.app.db, db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap().id, 10, None).await.unwrap().len();
5057
5058
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
5059
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
5060
    db::proposals::create(
5061
        &h.app.db,
5062
        db::proposals::NewProposal {
5063
            repo_id: row.id,
5064
            title: "More",
5065
            body: "",
5066
            author_id: Some(andy.id),
5067
            author: "andy",
5068
            draft: false,
5069
            target: "main",
5070
            source_kind: "bookmark",
5071
            source_repo_id: Some(row.id),
5072
            source_bookmark: "feature",
5073
            source_changes: "",
5074
        },
5075
    )
5076
    .await
5077
    .unwrap();
5078
    let repo = RepoName::parse("andy/demo").unwrap();
2a8b6216 Andy McCall ↶ 5079
    let state = oxygenhub::web::proposals::land_as(&h.app, &repo, &row, &andy, 1, "web", false, None).await.ok().expect("landed");
f7bcee49 Andy McCall ↶ 5080
    let mut runs = vec![];
5081
    for _ in 0..100 {
5082
        runs = db::flow::runs(&h.app.db, row.id, 10, None).await.unwrap();
5083
        if runs.len() > runs_before {
5084
            break;
5085
        }
5086
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
5087
    }
5088
    let landed = runs.iter().find(|r| r.bookmark == "main" && r.state == state).expect("a run of the landed state on main");
5089
    assert_eq!((landed.trigger.as_str(), landed.actor.as_str()), ("push", "andy"));
4a4400c5 Andy McCall ↶ 5090
}
1870e4fa Andy McCall ↶ 5091
5092
/// #225: an ordinary user turns Flow on for their repository on their own
5093
/// runner, and the site's runners never take its jobs.
5094
#[tokio::test(flavor = "multi_thread")]
5095
async fn owners_run_flow_on_their_own_runners_only() {
5096
    use oxy_core::identity::SecretKey;
5097
    let h = hub().await;
5098
    let register = |name: &'static str| {
5099
        let app = h.app.clone();
5100
        async move {
c8684d44 Andy McCall 5101
            let body = format!("username={name}&email={name}%40example.com&password=correct-horse-battery&setup=test-setup");
1870e4fa Andy McCall ↶ 5102
            let res = oxygenhub::router(app)
5103
                .oneshot(
5104
                    Request::post("/register")
5105
                        .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
5106
                        .body(Body::from(body))
5107
                        .unwrap(),
5108
                )
5109
                .await
5110
                .unwrap();
5111
            res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string()
5112
        }
5113
    };
5114
    register("andy").await; // the first account: the site's administrator
5115
    let bob = register("bob").await;
5116
    create(&h.app, "bob", "game").await;
5117
    let web = |method: &'static str, path: &str, body: Option<String>| {
5118
        let (app, cookie, path) = (h.app.clone(), bob.clone(), path.to_string());
5119
        async move {
c7067c7b Andy McCall 5120
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie.clone());
1870e4fa Andy McCall ↶ 5121
            if body.is_some() {
5122
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
5123
            }
c7067c7b Andy McCall 5124
            let req = req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap();
5125
            let mut res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
5126
            // A repository settings form returns to its page (#278).
5127
            let back =
5128
                res.headers().get(header::LOCATION).and_then(|v| v.to_str().ok()).filter(|l| l.contains("/settings/")).map(String::from);
5129
            if let Some(to) = back {
5130
                let req = Request::get(to).header(header::COOKIE, cookie).body(Body::empty()).unwrap();
5131
                res = oxygenhub::router(app).oneshot(req).await.unwrap();
5132
            }
1870e4fa Andy McCall ↶ 5133
            String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned()
5134
        }
5135
    };
5136
    let csrf_of = |page: &str| {
5137
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
5138
        page[i..].split('"').next().unwrap().to_string()
5139
    };
5140
    // No runner of his own yet: he is told how, and cannot switch it on.
c7067c7b Andy McCall 5141
    let page = web("GET", "/bob/game/settings/flow", None).await;
1870e4fa Andy McCall ↶ 5142
    assert!(page.contains("register a runner for this repository") && !page.contains("value=\"own\""), "{page}");
5143
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=own", csrf_of(&page)))).await;
5144
    assert!(page.contains("Register a runner for this repository"), "{page}");
5145
    // He registers one.
5146
    let page = web("GET", "/bob/game/settings", None).await;
5147
    let page = web("POST", "/bob/game/settings/runners/token", Some(format!("_csrf={}", csrf_of(&page)))).await;
5148
    let i = page.find("--token ").unwrap() + "--token ".len();
5149
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
5150
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
5151
    let identity = SecretKey::generate().identity("bobs", "", 1);
5152
    let reg = serde_json::json!({ "token": token, "name": "bobs", "identity": hex::encode(identity.encode()), "info": info });
5153
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
5154
    assert_eq!(st, StatusCode::OK, "{body}");
5155
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
5156
    // The site's runners stay a site administrator's to grant; his own he may choose.
c7067c7b Andy McCall 5157
    let page = web("GET", "/bob/game/settings/flow", None).await;
1870e4fa Andy McCall ↶ 5158
    assert!(page.contains("value=\"own\"") && !page.contains("value=\"on\""), "{page}");
5159
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=on", csrf_of(&page)))).await;
5160
    assert!(page.contains("Only site administrators let the site's runners"), "{page}");
5161
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=own", csrf_of(&page)))).await;
5162
    assert!(page.contains("value=\"own\" checked") && page.contains("start runs"), "{page}");
5163
    assert_eq!(db::repos::get(&h.app.db, "bob", "game").await.unwrap().unwrap().flow, "own");
5164
    // A push starts a run; the site's runner is not offered it, his is.
5165
    let work = tempfile::tempdir().unwrap();
5166
    let c = client(&format!("{}/bob/game", h.base), work.path());
5167
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5168
    write(work.path(), "test.sh", "echo ok\n");
5169
    c.snapshot("t").unwrap();
5170
    c.commit("A pipeline", &[]).unwrap();
5171
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5172
    assert_eq!(runs_of(&h.app, "bob", "game").await.len(), 1, "a run started");
5173
    assert!(claim(&h.app).await.is_none(), "the site's runner is not offered it");
5174
    let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
5175
    let (st, job) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(body)).await;
5176
    assert_eq!(st, StatusCode::OK, "{job}");
5177
    assert_eq!(serde_json::from_str::<serde_json::Value>(&job).unwrap()["repo"], "bob/game");
5178
}
cd437c4f Andy McCall ↶ 5179
5180
#[tokio::test(flavor = "multi_thread")]
5181
async fn a_job_takes_the_artifact_its_producer_kept() {
5182
    let h = hub().await;
5183
    create(&h.app, "andy", "demo").await;
5184
    let url = format!("{}/andy/demo", h.base);
5185
    let work = tempfile::tempdir().unwrap();
5186
    let c = client(&url, work.path());
5187
    write(
5188
        work.path(),
5189
        ".flow/pipeline.kdl",
5190
        &format!(
5191
            "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"
5192
        ),
5193
    );
5194
    c.snapshot("test").unwrap();
5195
    c.commit("Plan, then apply that plan", &[]).unwrap();
5196
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5197
5198
    // The plan job runs and keeps its plan, named by its receipt.
5199
    let runs = runs_of(&h.app, "andy", "demo").await;
5200
    assert_eq!(runs.len(), 1, "a run");
5201
    let jobs = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap();
5202
    assert!(!jobs.is_empty(), "jobs: {:?}", runs[0]);
5203
    let p = claim(&h.app)
5204
        .await
5205
        .unwrap_or_else(|| panic!("nothing to claim: {:?}", jobs.iter().map(|j| (&j.name, &j.status, &j.error)).collect::<Vec<_>>()));
5206
    assert_eq!(p["job"]["name"], "plan");
5207
    let plan_id = p["job_id"].as_i64().unwrap();
5208
    let plan = b"the reviewed plan".to_vec();
5209
    let (st, text) = upload(&h.app, plan_id, "tfplan", &plan).await;
5210
    assert_eq!(st, StatusCode::OK, "{text}");
5211
    let blob = oxy_core::repo::Repo::blob_ref(&plan).to_hex();
5212
    let mut r = receipt("plan", p["pipeline_hash"].as_str().unwrap(), 0);
5213
    r["outputs"] = serde_json::json!([blob]);
5214
    assert_eq!(
5215
        finish(&h.app, plan_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r })).await,
5216
        StatusCode::NO_CONTENT
5217
    );
5218
5219
    // The apply job is told what to take and the blob to expect, and the
5220
    // runner fetches exactly those bytes.
5221
    let a = claim(&h.app).await.unwrap();
5222
    assert_eq!(a["job"]["name"], "apply");
5223
    let apply_id = a["job_id"].as_i64().unwrap();
5224
    assert_eq!(
5225
        a["inputs"],
5226
        serde_json::json!([{ "artifact": "tfplan", "from": "plan", "path": "/src/tfplan", "blob": blob }]),
5227
        "the claim names the producer's blob"
5228
    );
5229
    let req = Request::get(format!("/api/v1/flow/jobs/{apply_id}/inputs/0")).header(header::AUTHORIZATION, "Bearer runner-secret");
5230
    let res = oxygenhub::router(h.app.clone()).oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
5231
    assert_eq!(res.status(), StatusCode::OK);
5232
    assert_eq!(res.into_body().collect().await.unwrap().to_bytes().to_vec(), plan);
5233
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{apply_id}/inputs/1"), Some("runner-secret"), None).await;
5234
    assert_eq!(st, StatusCode::NOT_FOUND, "no second input");
5235
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{apply_id}/inputs/0"), None, None).await;
5236
    assert_eq!(st, StatusCode::UNAUTHORIZED, "runners only");
5237
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{plan_id}/inputs/0"), Some("runner-secret"), None).await;
5238
    assert_eq!(st, StatusCode::CONFLICT, "only a running job's");
5239
}
417184c7 Andy McCall ↶ 5240
5241
#[tokio::test(flavor = "multi_thread")]
5242
async fn a_job_waits_for_approval_and_is_approved_rejected_or_expires() {
5243
    let h = hub().await;
5244
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
5245
    let bob = db::accounts::create_account(&h.app.db, "bob", "[email protected]", "x", "salt", false).await.unwrap();
5246
    let carol = db::accounts::create_account(&h.app.db, "carol", "[email protected]", "x", "salt", true).await.unwrap();
5247
    create(&h.app, "andy", "gated").await;
5248
    let row = db::repos::get(&h.app.db, "andy", "gated").await.unwrap().unwrap();
5249
    let work = tempfile::tempdir().unwrap();
5250
    let c = client(&format!("{}/andy/gated", h.base), work.path());
5251
    write(
5252
        work.path(),
5253
        ".flow/pipeline.kdl",
5254
        &format!(
47e37402 Andy McCall ↶ 5255
            "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 ↶ 5256
        ),
5257
    );
5258
    let mut n = 0;
5259
    let mut push = || {
5260
        n += 1;
5261
        write(work.path(), "n.txt", &format!("{n}\n"));
5262
        c.snapshot("test").unwrap();
5263
        c.commit(&format!("Push {n}"), &[]).unwrap();
5264
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5265
    };
5266
    // Runs `plan` to a pass; returns the run, its actor set to andy.
5267
    let plan_passes = |number: i64| {
5268
        let app = h.app.clone();
5269
        let row = row.clone();
5270
        async move {
5271
            let mut run = None;
5272
            for _ in 0..100 {
5273
                if let Some(r) = db::flow::run(&app.db, row.id, number).await.unwrap() {
5274
                    run = Some(r);
5275
                    break;
5276
                }
5277
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
5278
            }
5279
            let run = run.expect("the run");
3b1bc27f Andy McCall 5280
            sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&app.db).await.unwrap();
417184c7 Andy McCall ↶ 5281
            let j = claim(&app).await.expect("plan is claimed");
5282
            assert_eq!(j["job"]["name"], "plan");
5283
            let (id, ph) = (j["job_id"].as_i64().unwrap(), j["pipeline_hash"].as_str().unwrap().to_string());
5284
            finish(&app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("plan", &ph, 0) })).await;
5285
            db::flow::run(&app.db, row.id, number).await.unwrap().unwrap()
5286
        }
5287
    };
5288
5289
    // Run 1: apply waits; only someone with the role, other than the pusher, approves it.
5290
    push();
5291
    let run = runs_of(&h.app, "andy", "gated").await[0].clone();
7e01a766 Andy McCall ↶ 5292
    // Live pages hear of the push (oxygenhub#203).
33d98147 Andy McCall 5293
    let heard = |topic: String| match h.app.bus.live.since(0, &[topic]) {
7e01a766 Andy McCall ↶ 5294
        oxygenhub::events::Replay::Events(e) => e.into_iter().map(|e| e.kind).collect::<Vec<_>>(),
5295
        oxygenhub::events::Replay::Reload => vec!["reload".into()],
5296
    };
5297
    assert!(heard(oxygenhub::events::topic::repo(row.id)).contains(&"push".to_string()), "the push is on the repository's topic");
3b1bc27f Andy McCall 5298
    sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = $1").bind(run.id).execute(&h.app.db).await.unwrap();
05f1a85a Andy McCall ↶ 5299
    let early = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true, None).await.unwrap_err();
417184c7 Andy McCall ↶ 5300
    assert!(early.contains("waits for plan first"), "{early}");
5301
    let run = plan_passes(run.number).await;
5302
    assert!(claim(&h.app).await.is_none(), "apply waits for a person, so no runner gets it");
7e01a766 Andy McCall ↶ 5303
    assert!(heard(oxygenhub::events::topic::run(run.id)).contains(&"jobs".to_string()), "the run's topic hears its jobs");
dc59d1b5 Andy McCall ↶ 5304
    // Those who may approve are told, once; the pusher (others-only) and
5305
    // someone without the role are not.
5306
    let told = |id: i64| {
5307
        let db = h.app.db.clone();
5308
        async move { db::notify::inbox(&db, id, 20).await.unwrap().into_iter().filter(|n| n.kind == "flow.approval").count() }
5309
    };
5310
    assert_eq!((told(carol.id).await, told(andy.id).await, told(bob.id).await), (1, 0, 0));
417184c7 Andy McCall ↶ 5311
    let (_, page) = call(&h.app, "GET", &format!("/andy/gated/flow/{}", run.number), None, None).await;
5312
    assert!(page.contains("waits for approval by someone with the <em>maintain</em> role, other than andy"), "the run page says so");
b1860d60 Andy McCall ↶ 5313
    // The API says which job waits for a person (oxygenhub-android#5).
5314
    let (_, v) = call(&h.app, "GET", &format!("/api/v1/repos/andy/gated/flow/runs/{}", run.number), None, None).await;
5315
    let v: serde_json::Value = serde_json::from_str(&v).unwrap();
5316
    let apply = v["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "apply").unwrap().clone();
5317
    assert_eq!(apply["approval"], "waiting", "{v}");
5318
    assert!(v["jobs"].as_array().unwrap().iter().filter(|j| j["name"] != "apply").all(|j| j.get("approval").is_none()), "{v}");
05f1a85a Andy McCall ↶ 5319
    let own = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &andy, true, None).await.unwrap_err();
417184c7 Andy McCall ↶ 5320
    assert!(own.contains("someone other than andy"), "{own}");
05f1a85a Andy McCall ↶ 5321
    let no_role = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &bob, true, None).await.unwrap_err();
417184c7 Andy McCall ↶ 5322
    assert!(no_role.contains("takes the maintain role"), "{no_role}");
05f1a85a Andy McCall ↶ 5323
    assert_eq!(oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true, None).await.unwrap(), "apply: approved by carol");
dc59d1b5 Andy McCall ↶ 5324
    assert_eq!(told(carol.id).await, 1, "told once");
417184c7 Andy McCall ↶ 5325
    let j = claim(&h.app).await.expect("approved, it runs");
5326
    assert_eq!(j["job"]["name"], "apply");
b644e175 Andy McCall ↶ 5327
    // Approved, its identity token names the environment (oxygenflow#59).
5328
    let token =
5329
        j["secrets"].as_array().unwrap().iter().find(|s| s["path"] == "/run/secrets/cloud").unwrap()["value"].as_str().unwrap().to_string();
5330
    let claims = h.app.oidc().await.unwrap().verify(&token, "https://sts.example", db::now_ms()).expect("a valid token");
5331
    assert_eq!(claims["environment"], "prod");
417184c7 Andy McCall ↶ 5332
    let (id, ph) = (j["job_id"].as_i64().unwrap(), j["pipeline_hash"].as_str().unwrap().to_string());
5333
    finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("apply", &ph, 0) })).await;
5334
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
5335
    assert!(audit.iter().any(|r| r.action == "flow.approved" && r.actor == "carol" && r.target.ends_with("#1 apply")), "audited");
5336
    let (_, page) = call(&h.app, "GET", &format!("/andy/gated/flow/{}", run.number), None, None).await;
5337
    assert!(page.contains("approved by carol"), "the run says who");
b644e175 Andy McCall ↶ 5338
    let (_, page) = call(&h.app, "GET", "/andy/gated/deployments", None, None).await;
5339
    assert!(page.contains("<strong>prod</strong>") && page.contains(">#1</a>") && page.contains("<td>carol</td>"), "the Deployments page");
5340
    let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/gated/deployments", Some("site"), None).await;
5341
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
5342
    assert_eq!((list[0]["environment"].as_str(), list[0]["approved_by"].as_str()), (Some("prod"), Some("carol")));
417184c7 Andy McCall ↶ 5343
05f1a85a Andy McCall ↶ 5344
    // Run 2: rejected through the API with carol's agent token: the job
5345
    // ends cancelled, the run ends, and it says the agent did it
5346
    // (oxygenhub#229).
417184c7 Andy McCall ↶ 5347
    push();
5348
    let run = plan_passes(2).await;
05f1a85a Andy McCall ↶ 5349
    let (secret, hash) = oxygenhub::auth::new_token();
5350
    let tok = db::accounts::create_token(&h.app.db, carol.id, "claude-code", &hash, "repo:write", "", None).await.unwrap();
5351
    db::accounts::set_token_agent(&h.app.db, carol.id, tok.id, true).await.unwrap();
4a68f106 Andy McCall ↶ 5352
    // An agent's token decides a gate only where the repository allows it
5353
    // (#258).
05f1a85a Andy McCall ↶ 5354
    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 ↶ 5355
    assert_eq!(st, StatusCode::CONFLICT, "{body}");
5356
    assert!(body.contains("decided by a person here") && body.contains("Settings › OxygenFlow"), "{body}");
5357
    let gated = db::repos::get(&h.app.db, "andy", "gated").await.unwrap().unwrap();
5358
    db::repos::set_agents_decide_gates(&h.app.db, gated.id, true).await.unwrap();
5359
    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 ↶ 5360
    assert_eq!(st, StatusCode::OK, "{body}");
5361
    assert!(body.contains("rejected by carol via claude-code"), "{body}");
417184c7 Andy McCall ↶ 5362
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
5363
    let apply = jobs.iter().find(|j| j.name == "apply").unwrap();
05f1a85a Andy McCall ↶ 5364
    assert_eq!((apply.status.as_str(), apply.error.as_str()), ("cancelled", "rejected by carol via claude-code"));
5365
    assert_eq!((apply.approved_by.as_str(), apply.approved_via.as_str()), ("carol", "claude-code"));
5366
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
5367
    assert!(
5368
        audit.iter().any(|r| r.action == "flow.rejected" && r.actor == "carol" && r.detail.contains("via claude-code")),
5369
        "audited with the agent"
5370
    );
417184c7 Andy McCall ↶ 5371
    assert!(claim(&h.app).await.is_none());
5372
5373
    // Run 3: nobody decides in time.
5374
    push();
5375
    let run = plan_passes(3).await;
5376
    assert_eq!(oxygenhub::flow::expire_approvals(&h.app, db::now_ms() + 3_600_000).await.unwrap(), 0, "not yet");
5377
    assert_eq!(oxygenhub::flow::expire_approvals(&h.app, db::now_ms() + 25 * 3_600_000).await.unwrap(), 1);
5378
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
5379
    let apply = jobs.iter().find(|j| j.name == "apply").unwrap();
5380
    assert_eq!((apply.status.as_str(), apply.error.as_str()), ("cancelled", "no approval within 24h"));
5381
}
67be8ac0 Andy McCall ↶ 5382
5383
#[tokio::test(flavor = "multi_thread")]
5384
async fn live_streams_only_topics_the_viewer_may_hear_and_replays() {
5385
    let h = hub().await;
5386
    create(&h.app, "andy", "open").await;
5387
    h.app.repos.create(&RepoName::parse("andy/shut").unwrap(), None).unwrap();
5388
    db::repos::create(&h.app.db, "andy", "shut", "", hub_api::Visibility::Private).await.unwrap();
5389
    let open = db::repos::get(&h.app.db, "andy", "open").await.unwrap().unwrap();
5390
    let shut = db::repos::get(&h.app.db, "andy", "shut").await.unwrap().unwrap();
33d98147 Andy McCall 5391
    let live = &h.app.bus.live;
67be8ac0 Andy McCall ↶ 5392
    let first = live.publish(&oxygenhub::events::topic::repo(open.id), "push");
5393
    live.publish(&oxygenhub::events::topic::repo(shut.id), "push");
5394
    live.publish(&oxygenhub::events::topic::proposal(open.id, 3), "review");
5395
5396
    // The first bytes of a stream, within a moment.
5397
    let read = |path: String, last: Option<u64>| {
5398
        let app = h.app.clone();
5399
        async move {
5400
            let mut req = Request::get(&path);
5401
            if let Some(l) = last {
5402
                req = req.header("last-event-id", l.to_string());
5403
            }
5404
            let res = oxygenhub::router(app).oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
5405
            let status = res.status();
5406
            let mut body = res.into_body();
5407
            let mut text = String::new();
5408
            while let Ok(Some(Ok(frame))) = tokio::time::timeout(std::time::Duration::from_millis(300), body.frame()).await {
5409
                if let Some(d) = frame.data_ref() {
5410
                    text.push_str(&String::from_utf8_lossy(d));
5411
                }
5412
            }
5413
            (status, text)
5414
        }
5415
    };
5416
    let topics = format!("/live?topics=repo:{},repo:{}/proposal:3", open.id, open.id);
5417
    // From the first event on: what came after it on these topics only.
5418
    let (st, text) = read(topics.clone(), Some(first.id)).await;
5419
    assert_eq!(st, StatusCode::OK);
5420
    assert!(text.contains("event: change") && text.contains(&format!("\"topic\":\"repo:{}/proposal:3\"", open.id)), "{text}");
5421
    assert!(!text.contains(&format!("\"topic\":\"repo:{}\"", shut.id)), "never another topic: {text}");
5422
    assert!(!text.contains(&format!("id: {}\n", first.id)), "not what was already seen: {text}");
5423
    // A private repository's topic, or someone else's, is refused whole.
5424
    let (st, _) = read(format!("/live?topics=repo:{},repo:{}", open.id, shut.id), None).await;
5425
    assert_eq!(st, StatusCode::FORBIDDEN);
5426
    assert_eq!(read("/live?topics=user:1".into(), None).await.0, StatusCode::FORBIDDEN);
5427
    assert_eq!(read("/live?topics=nonsense".into(), None).await.0, StatusCode::BAD_REQUEST);
5428
    assert_eq!(read("/live?topics=".into(), None).await.0, StatusCode::BAD_REQUEST);
5429
    // Too far behind: told to reload.
5430
    for _ in 0..oxygenhub::events::REPLAY {
5431
        live.publish("repo:999999", "push");
5432
    }
5433
    let (_, text) = read(topics, Some(first.id)).await;
5434
    assert!(text.contains("event: reload"), "{text}");
5435
}
47e37402 Andy McCall ↶ 5436
5437
#[tokio::test(flavor = "multi_thread")]
5438
async fn a_sealed_approval_releases_exactly_the_reviewed_plan() {
5439
    use oxy_core::approval::{SignedApproval, Statement};
5440
    use oxy_core::hash::ObjectRef;
5441
    use oxy_core::identity::SecretKey;
5442
    let h = hub().await;
5443
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
5444
    let carol = db::accounts::create_account(&h.app.db, "carol", "[email protected]", "x", "salt", true).await.unwrap();
5445
    let sk = SecretKey::generate();
5446
    let carol_id = sk.identity("Carol", "[email protected]", 1);
5447
    db::accounts::link_identity(&h.app.db, carol.id, &carol_id.hash().to_hex(), "Carol", "[email protected]", &carol_id.encode())
5448
        .await
5449
        .unwrap();
5450
    create(&h.app, "andy", "infra").await;
5451
    let row = db::repos::get(&h.app.db, "andy", "infra").await.unwrap().unwrap();
5452
    let work = tempfile::tempdir().unwrap();
5453
    let c = client(&format!("{}/andy/infra", h.base), work.path());
5454
    write(
5455
        work.path(),
5456
        ".flow/pipeline.kdl",
5457
        &format!(
5458
            "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"
5459
        ),
5460
    );
5461
    c.snapshot("test").unwrap();
5462
    c.commit("Plan, then apply", &[]).unwrap();
5463
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5464
    let run = runs_of(&h.app, "andy", "infra").await[0].clone();
5465
    let p = claim(&h.app).await.unwrap();
5466
    let plan_id = p["job_id"].as_i64().unwrap();
5467
    let plan = b"the reviewed plan".to_vec();
5468
    upload(&h.app, plan_id, "tfplan", &plan).await;
5469
    let mut r = receipt("plan", p["pipeline_hash"].as_str().unwrap(), 0);
5470
    r["outputs"] = serde_json::json!([oxy_core::repo::Repo::blob_ref(&plan).to_hex()]);
5471
    finish(&h.app, plan_id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": r })).await;
5472
    let run = db::flow::run(&h.app.db, row.id, run.number).await.unwrap().unwrap();
5473
5474
    // An environment's gate takes a sealed approval: pressing Approve is not enough.
05f1a85a Andy McCall ↶ 5475
    let plain = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true, None).await.unwrap_err();
47e37402 Andy McCall ↶ 5476
    assert!(plain.contains(&format!("oxy seal --flow {}/andy/infra/flow/{} --job apply", h.base, run.number)), "{plain}");
5477
    // What there is to sign.
5478
    let (st, body) =
5479
        call(&h.app, "GET", &format!("/api/v1/repos/andy/infra/flow/runs/{}/jobs/apply/approval", run.number), Some("site"), None).await;
5480
    assert_eq!(st, StatusCode::OK, "{body}");
5481
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
5482
    assert_eq!(v["environment"], "prod");
5483
    assert_eq!(v["inputs"], serde_json::json!([oxy_core::repo::Repo::blob_ref(&plan).to_hex()]), "the reviewed plan");
5484
    let mut repo = [0u8; 16];
5485
    repo.copy_from_slice(&hex::decode(v["repo"].as_str().unwrap()).unwrap());
5486
    let oref = |k: &str| ObjectRef::from_hex(v[k].as_str().unwrap()).unwrap();
5487
    let statement = Statement {
5488
        repo,
5489
        run: v["run"].as_str().unwrap().into(),
5490
        job: "apply".into(),
5491
        job_hash: oref("job_hash"),
5492
        state: oref("state"),
5493
        inputs: v["inputs"].as_array().unwrap().iter().map(|i| ObjectRef::from_hex(i.as_str().unwrap()).unwrap()).collect(),
5494
        environment: "prod".into(),
5495
        approve: true,
5496
    };
5497
    let seal = |s: &Statement, key: &SecretKey, id: &oxy_core::identity::Identity| {
5498
        let body = serde_json::json!({ "signed": hex::encode(SignedApproval::sign(s, id, key).encode()) }).to_string();
5499
        let app = h.app.clone();
5500
        let path = format!("/api/v1/repos/andy/infra/flow/runs/{}/jobs/apply/seal", run.number);
5501
        async move { call(&app, "POST", &path, Some("site"), Some(body)).await }
5502
    };
5503
    // Another plan, or a key linked to nobody (an agent's), is refused.
5504
    let other_plan = Statement { inputs: vec![ObjectRef([9; 32])], ..statement.clone() };
5505
    let (st, body) = seal(&other_plan, &sk, &carol_id).await;
5506
    assert!(st == StatusCode::CONFLICT && body.contains("approves something else"), "{st} {body}");
5507
    let agent = SecretKey::generate();
5508
    let agent_id = agent.identity("Claude Code", "[email protected]", 1);
5509
    let (st, body) = seal(&statement, &agent, &agent_id).await;
5510
    assert!(st == StatusCode::CONFLICT && body.contains("not linked to an account"), "{st} {body}");
5511
    assert!(claim(&h.app).await.is_none(), "still waiting");
5512
317d776c Andy McCall ↶ 5513
    // A key that claims Carol's as its predecessor but has other keys: refused.
5514
    let forged = oxy_core::identity::Identity { previous: Some(carol_id.hash()), ..agent_id.clone() };
5515
    let (st, body) = seal(&statement, &agent, &forged).await;
5516
    assert!(st == StatusCode::CONFLICT && body.contains("not linked"), "{st} {body}");
5517
5518
    // Carol's seal, by a renewal of her linked key never linked itself
5519
    // (oxygenhub#236), releases it and links it; it is kept in the
5520
    // repository; the token names her and it.
5521
    let renewed = carol_id.successor(vec![], None, 2);
5522
    let (st, body) = seal(&statement, &sk, &renewed).await;
47e37402 Andy McCall ↶ 5523
    assert_eq!(st, StatusCode::OK, "{body}");
317d776c Andy McCall ↶ 5524
    assert!(
5525
        db::accounts::identity_by_key(&h.app.db, &renewed.hash().to_hex()).await.unwrap().is_some_and(|l| l.account_id == carol.id),
5526
        "linked now"
5527
    );
47e37402 Andy McCall ↶ 5528
    assert!(body.contains("approved by carol, sealed"), "{body}");
5529
    let name = oxygenhub::repos::RepoName::parse("andy/infra").unwrap();
5530
    let state = statement.state;
5531
    let kept = h.app.repos.read(&name, move |r, _| Ok(r.store().approvals_for(&state)?)).await.unwrap();
5532
    assert_eq!(kept.len(), 1, "the approval is in the repository");
5533
    let j = claim(&h.app).await.expect("released");
5534
    assert_eq!(j["job"]["name"], "apply");
5535
    let token =
5536
        j["secrets"].as_array().unwrap().iter().find(|s| s["path"] == "/run/secrets/cloud").unwrap()["value"].as_str().unwrap().to_string();
5537
    let claims = h.app.oidc().await.unwrap().verify(&token, "https://sts.example", db::now_ms()).unwrap();
5538
    assert_eq!((claims["environment"].as_str(), claims["approved_by"].as_str()), (Some("prod"), Some("carol")));
5539
    assert_eq!(claims["approval"].as_str(), Some(kept[0].to_hex().as_str()));
5540
    let (_, page) = call(&h.app, "GET", &format!("/andy/infra/flow/{}", run.number), None, None).await;
5541
    assert!(page.contains("sealed with their key"), "the run page says so");
5542
}
55673c65 Andy McCall ↶ 5543
5544
/// Repositories take turns (oxygenhub#244): a repository with a job running
5545
/// waits behind one with none, so a burst can't hold up the rest.
5546
#[tokio::test(flavor = "multi_thread")]
5547
async fn repositories_take_turns_on_the_runners() {
5548
    let h = hub().await;
5549
    for name in ["busy", "quiet"] {
5550
        create(&h.app, "andy", name).await;
5551
        let work = tempfile::tempdir().unwrap();
5552
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
5553
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5554
        write(work.path(), "test.sh", "echo ok\n");
5555
        c.snapshot("test").unwrap();
5556
        c.commit("Add a pipeline", &[]).unwrap();
5557
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5558
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
5559
    }
5560
    // busy pushed first: its first job goes first; then quiet's turn, though
5561
    // busy's other independent job is older; then busy's again.
5562
    let order: Vec<String> = {
5563
        let mut out = Vec::new();
5564
        for _ in 0..3 {
5565
            let c = claim(&h.app).await.expect("a job to claim");
5566
            out.push(c["repo"].as_str().unwrap().to_string());
5567
        }
5568
        out
5569
    };
5570
    assert_eq!(order, ["andy/busy", "andy/quiet", "andy/busy"]);
5571
}
107eaba5 Andy McCall ↶ 5572
53a0fb2e Andy McCall ↶ 5573
/// A pipeline lowers its jobs, never raises them (oxygenhub#244): a
5574
/// repository whose pipeline says `priority "low"` waits for another's
5575
/// everyday jobs, even set high itself; the queue says why; an expedited
5576
/// run is still urgent.
5577
#[tokio::test(flavor = "multi_thread")]
5578
async fn a_pipeline_lowers_its_jobs_and_expediting_still_wins() {
5579
    let h = hub().await;
5580
    for (name, extra) in [("nightly", "priority \"low\"\n"), ("everyday", "")] {
5581
        create(&h.app, "andy", name).await;
5582
        let work = tempfile::tempdir().unwrap();
5583
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
5584
        write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
5585
        write(work.path(), "test.sh", "echo ok\n");
5586
        c.snapshot("test").unwrap();
5587
        c.commit("Add a pipeline", &[]).unwrap();
5588
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5589
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
5590
    }
5591
    let nightly = db::repos::get(&h.app.db, "andy", "nightly").await.unwrap().unwrap();
5592
    db::repos::set_flow_priority(&h.app.db, nightly.id, "high").await.unwrap();
5593
    let q = db::flow::queue(&h.app.db).await.unwrap();
5594
    assert!(
5595
        q.iter().filter(|e| e.name == "nightly").all(|e| e.priority() == "low" && e.priority_note == "pipeline: low"),
5596
        "{:?}",
5597
        q.iter().map(|e| (&e.name, e.priority(), &e.priority_note)).collect::<Vec<_>>()
5598
    );
5599
    let repo_of = |c: serde_json::Value| c["repo"].as_str().unwrap().to_string();
5600
    // nightly pushed first and its repository is high, but its pipeline
5601
    // says low: everyday's jobs go first.
5602
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/everyday");
5603
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/everyday");
5604
    let run = &runs_of(&h.app, "andy", "nightly").await[0];
5605
    assert!(db::flow::expedite(&h.app.db, run.id, "expedited by andy: needed now").await.unwrap());
5606
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/nightly", "an expedited run is urgent whatever its jobs say");
5607
}
5608
107eaba5 Andy McCall ↶ 5609
/// Priority comes before taking turns (oxygenhub#244): a low repository's
5610
/// jobs wait for a normal one's, and an expedited run goes first of all.
5611
#[tokio::test(flavor = "multi_thread")]
5612
async fn priority_then_turns_and_an_expedited_run_first() {
5613
    let h = hub().await;
5614
    for name in ["early", "later"] {
5615
        create(&h.app, "andy", name).await;
5616
        let work = tempfile::tempdir().unwrap();
5617
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
5618
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5619
        write(work.path(), "test.sh", "echo ok\n");
5620
        c.snapshot("test").unwrap();
5621
        c.commit("Add a pipeline", &[]).unwrap();
5622
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5623
        assert_eq!(runs_of(&h.app, "andy", name).await.len(), 1);
5624
    }
5625
    let early = db::repos::get(&h.app.db, "andy", "early").await.unwrap().unwrap();
5626
    db::repos::set_flow_priority(&h.app.db, early.id, "low").await.unwrap();
5627
    // early pushed first, but it is low: later's jobs go first.
5628
    let repo_of = |c: serde_json::Value| c["repo"].as_str().unwrap().to_string();
5629
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/later");
5630
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/later");
5631
    // Expedited, early's run goes before anything else.
5632
    let run = &runs_of(&h.app, "andy", "early").await[0];
5633
    assert!(db::flow::expedite(&h.app.db, run.id, "expedited by andy: an incident").await.unwrap());
76f93eae Andy McCall ↶ 5634
    // What the cap on expedited runs counts: andy's live urgent runs.
5635
    assert_eq!(db::flow::expedited_live(&h.app.db, "andy").await.unwrap(), 1);
5636
    assert_eq!(db::flow::expedited_live(&h.app.db, "someone-else").await.unwrap(), 0);
107eaba5 Andy McCall ↶ 5637
    assert_eq!(repo_of(claim(&h.app).await.unwrap()), "andy/early");
5638
    let q = db::flow::queue(&h.app.db).await.unwrap();
5639
    assert!(
5640
        q.iter().any(|e| e.name == "early" && e.priority() == "urgent" && e.priority_note.contains("an incident")),
5641
        "{:?}",
5642
        q.iter().map(|e| (&e.name, e.priority())).collect::<Vec<_>>()
5643
    );
5644
    // The site's level is the default for everyone else.
5645
    db::accounts::set_setting(&h.app.db, "flow_priority", "high").await.unwrap();
5646
    let q = db::flow::queue(&h.app.db).await.unwrap();
5647
    assert!(q.iter().filter(|e| e.name == "later").all(|e| e.priority() == "high"));
5648
}
026a76d2 Andy McCall ↶ 5649
5650
/// Keyless (oxygenhub#241): a running job's token gets a ten-minute
5651
/// certificate for a fresh key from the hub, signed with the hub's key and
5652
/// naming the job's repository and bookmark; a proof made for another
5653
/// credential, an OIDC token for another audience, and a finished job's
5654
/// token get nothing.
5655
#[tokio::test(flavor = "multi_thread")]
5656
async fn a_running_job_gets_a_short_certificate_for_a_fresh_key() {
5657
    use oxy_core::cert::{certify_challenge, SignedCertificate};
5658
    use oxy_core::identity::{Scope, SecretKey};
5659
    let h = hub().await;
5660
    create(&h.app, "andy", "demo").await;
5661
    let work = tempfile::tempdir().unwrap();
5662
    let c = client(&format!("{}/andy/demo", h.base), work.path());
5663
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5664
    write(work.path(), "test.sh", "echo ok\n");
5665
    c.snapshot("test").unwrap();
5666
    c.commit("Add a pipeline", &[]).unwrap();
5667
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5668
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
5669
    let job = claim(&h.app).await.expect("a job");
5670
    let token = job["token"].as_str().unwrap().to_string();
5671
    let job_id = job["job_id"].as_i64().unwrap();
5672
5673
    let sk = SecretKey::generate();
5674
    let id = sk.identity("job", "[email protected]", 1);
5675
    let ask = |credential: &str, signed_for: &str| {
5676
        let proof = sk.sign_challenge(&id.hash(), &certify_challenge(signed_for)).unwrap();
5677
        let body = serde_json::json!({
5678
            "identity": oxy_core::dsse::base64(&id.encode()),
5679
            "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
5680
            "scope": "changes,refs",
5681
        });
5682
        let (credential, app) = (credential.to_string(), h.app.clone());
5683
        async move { call(&app, "POST", "/api/v1/keyless/certify", Some(&credential), Some(body.to_string())).await }
5684
    };
5685
    let (st, body) = ask(&token, &token).await;
5686
    assert_eq!(st, StatusCode::OK, "{body}");
5687
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
5688
    let sc = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
5689
    assert!(sc.verify(&h.app.hub_key.identity).is_ok(), "signed with the hub's key");
5690
    assert_eq!(sc.cert.key_id(), id.hash());
5691
    assert_eq!(sc.cert.subject, "repo:andy/demo:bookmark:main");
5692
    assert_eq!(sc.cert.claim("repository"), Some("andy/demo"));
5693
    assert!(sc.cert.claim("job").is_some() && sc.cert.claim("run") == Some("1"));
5694
    assert_eq!(sc.cert.scope, Scope::CHANGES | Scope::REFS);
5695
    assert!(sc.cert.expires - sc.cert.not_before <= 10 * 60_000 + 30_000, "ten minutes");
5696
5697
    // A proof made for another credential is not this one's.
5698
    let (st, body) = ask(&token, "flowjob_someone_else").await;
5699
    assert_eq!(st, StatusCode::UNAUTHORIZED, "{body}");
5700
    assert!(body.contains("the proof does not show"), "{body}");
5701
5702
    // The hub's own OIDC token, for the keyless audience, works too; for
5703
    // another audience it does not.
5704
    let issuer = h.app.oidc().await.unwrap();
5705
    let now = oxygenhub::db::now_ms();
5706
    let aud = oxygenhub::keyless::audience(h.app.config.base_url());
5707
    let good = issuer.mint_for(h.app.config.base_url(), "agent:claude@andy", &aud, now, 600);
5708
    let (st, body) = ask(&good, &good).await;
5709
    assert_eq!(st, StatusCode::OK, "{body}");
5710
    assert!(body.contains("\"subject\":\"agent:claude@andy\""), "{body}");
5711
    let other = issuer.mint_for(h.app.config.base_url(), "agent:claude@andy", "sts.amazonaws.com", now, 600);
5712
    let (st, _) = ask(&other, &other).await;
5713
    assert_eq!(st, StatusCode::UNAUTHORIZED);
5714
5715
    // A job that has finished asks with a token that no longer counts.
5716
    sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE id = $1").bind(job_id).execute(&h.app.db).await.unwrap();
5717
    let (st, body) = ask(&token, &token).await;
5718
    assert_eq!(st, StatusCode::UNAUTHORIZED, "{body}");
5719
}
2c31915f Andy McCall ↶ 5720
5721
/// Keyless step 3 (oxygenhub#241): a job signs its receipt with a fresh
5722
/// key the hub certified for it, and the hub keeps the receipt without
5723
/// binding any runner key; a certificate for another job, or from another
5724
/// issuer, is not this job's.
5725
#[tokio::test(flavor = "multi_thread")]
5726
async fn a_receipt_signed_by_a_certified_key_is_kept() {
5727
    use oxy_core::cert::{certify_challenge, SignedCertificate};
5728
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
5729
    use oxy_core::identity::SecretKey;
5730
    use oxy_core::objects::StateObject;
5731
    use oxy_core::receipt::SignedReceipt;
5732
    let h = hub().await;
5733
    create(&h.app, "andy", "demo").await;
5734
    let url = format!("{}/andy/demo", h.base);
5735
    let work = tempfile::tempdir().unwrap();
5736
    let c = client(&url, work.path());
5737
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
5738
    c.snapshot("test").unwrap();
5739
    c.commit("Add a pipeline", &[]).unwrap();
5740
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5741
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
5742
    let heads: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
5743
    let state = hash_object(ObjectType::State, &StateObject::new(heads.clone()).encode());
5744
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
5745
5746
    // Certify a fresh key with a job's token, as a runner does just before
5747
    // it signs the receipt.
5748
    let certify = |token: String| {
5749
        let app = h.app.clone();
5750
        async move {
5751
            let sk = SecretKey::generate();
5752
            let id = sk.identity("test-1 job", "", 1);
5753
            let proof = sk.sign_challenge(&id.hash(), &certify_challenge(&token)).unwrap();
5754
            let body = serde_json::json!({
5755
                "identity": oxy_core::dsse::base64(&id.encode()),
5756
                "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
5757
                "scope": "seal",
5758
            });
5759
            let (st, body) = call(&app, "POST", "/api/v1/keyless/certify", Some(&token), Some(body.to_string())).await;
5760
            assert_eq!(st, StatusCode::OK, "{body}");
5761
            let v: serde_json::Value = serde_json::from_str(&body).unwrap();
5762
            let cert = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
5763
            (sk, id, cert)
5764
        }
5765
    };
5766
    let sign = |r: &serde_json::Value,
5767
                sk: &SecretKey,
5768
                id: &oxy_core::identity::Identity,
5769
                cert: SignedCertificate,
5770
                issuer: oxy_core::identity::Identity| {
5771
        let r: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
5772
        let run_url = format!("{url}/flow/{}", run.number);
5773
        hex::encode(SignedReceipt::sign(r.to_oxy(), repo_id, state, &run_url, id, sk).with_certificate(cert, issuer).encode())
5774
    };
5775
    let hub_id = h.app.hub_key.identity.clone();
5776
5777
    let a = claim(&h.app).await.unwrap();
5778
    let b = claim(&h.app).await.unwrap();
5779
    let ph = a["pipeline_hash"].as_str().unwrap().to_string();
5780
    let (a_name, b_name) = (a["job"]["name"].as_str().unwrap().to_string(), b["job"]["name"].as_str().unwrap().to_string());
5781
    let (a_id, b_id) = (a["job_id"].as_i64().unwrap(), b["job_id"].as_i64().unwrap());
5782
    let (sk_a, id_a, cert_a) = certify(a["token"].as_str().unwrap().to_string()).await;
5783
5784
    // Job b's receipt signed with job a's certified key: another job's.
5785
    let rb = receipt(&b_name, &ph, 0);
5786
    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()) });
5787
    assert_eq!(finish(&h.app, b_id, body).await, StatusCode::NO_CONTENT);
5788
    // Job a's, with its own certificate: kept.
5789
    let ra = receipt(&a_name, &ph, 0);
5790
    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()) });
5791
    assert_eq!(finish(&h.app, a_id, body).await, StatusCode::NO_CONTENT);
5792
5793
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
5794
    let job = |n: &str| jobs.iter().find(|j| j.name == n).unwrap().clone();
5795
    assert_eq!(job(&a_name).receipt_attest.len(), 64, "{}", job(&a_name).receipt_note);
5796
    assert!(job(&a_name).receipt_signer.ends_with("(short-lived key)"), "{}", job(&a_name).receipt_signer);
5797
    assert!(job(&b_name).receipt_attest.is_empty());
5798
    assert!(job(&b_name).receipt_note.contains("another run or job"), "{}", job(&b_name).receipt_note);
5799
    // The kept receipt carries its certificate, and verifies on its own.
5800
    let kept = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().receipts(&heads).unwrap();
5801
    assert_eq!(kept.len(), 1);
5802
    assert!(kept[0].problem.is_none() && kept[0].signed.certificate.is_some());
5803
5804
    // A certificate from another issuer, for the third job: not this hub's.
5805
    let t = claim(&h.app).await.unwrap();
5806
    let t_name = t["job"]["name"].as_str().unwrap().to_string();
5807
    let fake_sk = SecretKey::generate();
5808
    let fake = fake_sk.identity("not the hub", "", 1);
5809
    let (sk_t, id_t, mut cert_t) = certify(t["token"].as_str().unwrap().to_string()).await;
5810
    cert_t.cert.issuer = fake.hash();
5811
    let cert_t = SignedCertificate::sign(cert_t.cert, &fake, &fake_sk);
5812
    let rt = receipt(&t_name, &ph, 0);
5813
    let body =
5814
        serde_json::json!({ "exit_code": 0, "duration_ms": 500, "receipt": rt, "signed_receipt": sign(&rt, &sk_t, &id_t, cert_t, fake) });
5815
    assert_eq!(finish(&h.app, t["job_id"].as_i64().unwrap(), body).await, StatusCode::NO_CONTENT);
5816
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
5817
    let t_job = jobs.iter().find(|j| j.name == t_name).unwrap();
5818
    assert!(t_job.receipt_note.contains("not issued by this hub"), "{}", t_job.receipt_note);
5819
}
3eb491e9 Andy McCall ↶ 5820
24472413 Andy McCall ↶ 5821
/// oxygenhub#241: a release asset whose receipt a short-lived key signed,
5822
/// certified by this hub for the job, is an attested build of a known
5823
/// signer on the release's trust report (it was "not one this hub's
5824
/// runners use" with 0.4.5).
5825
#[tokio::test(flavor = "multi_thread")]
5826
async fn a_release_built_by_a_certified_key_is_attested() {
5827
    use oxy_core::cert::{certify_challenge, SignedCertificate};
5828
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
5829
    use oxy_core::identity::SecretKey;
5830
    use oxy_core::objects::StateObject;
5831
    use oxy_core::receipt::SignedReceipt;
5832
    let h = hub().await;
5833
    create(&h.app, "andy", "demo").await;
5834
    let url = format!("{}/andy/demo", h.base);
5835
    let work = tempfile::tempdir().unwrap();
5836
    let mut c = client(&url, work.path());
5837
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5838
    write(
5839
        work.path(),
5840
        ".flow/pipeline.kdl",
5841
        &format!(
5842
            "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"
5843
        ),
5844
    );
5845
    c.snapshot("test").unwrap();
5846
    c.commit("Build a tool", &[]).unwrap();
5847
    let heads = c.bookmark_heads().unwrap();
5848
    c.tag_create("v1", &heads, "first").unwrap();
5849
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5850
5851
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
5852
    let a = claim(&h.app).await.unwrap();
5853
    let id = a["job_id"].as_i64().unwrap();
5854
    let token = a["token"].as_str().unwrap().to_string();
5855
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
5856
    let (_, text) = upload(&h.app, id, "tool", &body).await;
5857
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
5858
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
5859
    r["outputs"] = serde_json::json!([blob]);
5860
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
5861
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
5862
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
5863
    // The job's fresh key, certified with its token.
5864
    let sk = SecretKey::generate();
5865
    let key = sk.identity("test-1 job", "", 1);
5866
    let proof = sk.sign_challenge(&key.hash(), &certify_challenge(&token)).unwrap();
5867
    let ask = serde_json::json!({
5868
        "identity": oxy_core::dsse::base64(&key.encode()),
5869
        "proof": oxy_core::dsse::base64(&oxy_core::cbor::encode(&proof.to_value())),
5870
        "scope": "seal",
5871
    });
5872
    let (st, answer) = call(&h.app, "POST", "/api/v1/keyless/certify", Some(&token), Some(ask.to_string())).await;
5873
    assert_eq!(st, StatusCode::OK, "{answer}");
5874
    let v: serde_json::Value = serde_json::from_str(&answer).unwrap();
5875
    let cert = SignedCertificate::decode(&oxy_core::dsse::base64_decode(v["certificate"].as_str().unwrap()).unwrap()).unwrap();
5876
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
5877
    let signed = hex::encode(
5878
        SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/{}", run.number), &key, &sk)
5879
            .with_certificate(cert, h.app.hub_key.identity.clone())
5880
            .encode(),
5881
    );
5882
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
5883
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
5884
5885
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
5886
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
5887
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
5888
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
5889
    assert_eq!(st, StatusCode::OK);
5890
    for want in [
5891
        "tool: signed receipt from run #1 build",
5892
        "a short-lived key this hub certified for repo:andy/demo:bookmark:main",
5893
        "1 of 1 assets built and attested by OxygenFlow",
5894
    ] {
5895
        assert!(page.contains(want), "missing {want:?}");
5896
    }
5897
    assert!(!page.contains("not one this hub"), "not an unknown key");
5898
}
5899
965b950f Andy McCall ↶ 5900
/// The transparency log (oxygenhub#238): a push's reference attestation,
5901
/// seal and policy become entries; the checkpoint is signed by the hub's
5902
/// key; the tiles and entry bundles served rebuild the checkpoint's root;
5903
/// and the `/log` page lists them.
5904
#[tokio::test(flavor = "multi_thread")]
5905
async fn a_push_is_logged_and_the_log_checks_out() {
5906
    use oxy_core::tlog::{self, Checkpoint, Entry, Hash, Note, Tile};
5907
    let h = hub().await;
5908
    create(&h.app, "andy", "demo").await;
5909
    let url = format!("{}/andy/demo", h.base);
5910
    let work = tempfile::tempdir().unwrap();
5911
    let mut c = client(&url, work.path());
5912
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5913
    write(work.path(), "a.txt", "a\n");
5914
    c.commit("a", &[]).unwrap();
5915
    c.policy_init().unwrap();
5916
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5917
    let host = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
5918
    let (attest, _) = host.latest_ref_attest("main").unwrap().unwrap();
5919
5920
    // Sign a checkpoint now rather than wait for the next tick.
5921
    let (_, sk) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
5922
    h.app.tlog.refresh_checkpoint(&h.app.hub_key.identity, &sk).unwrap();
5923
    let (st, note) = call(&h.app, "GET", "/log/checkpoint", None, None).await;
5924
    assert_eq!(st, StatusCode::OK, "{note}");
5925
    let origin = oxygenhub::tlog::origin_of(h.app.config.base_url());
5926
    let cp = Checkpoint::verify(&Note::parse(&note).unwrap(), &origin, &h.app.hub_key.identity).unwrap();
5927
    assert!(cp.size >= 3, "ref, seal and policy: {}", cp.size);
5928
5929
    // The entries, from the bundle beside the partial level-0 tile.
5930
    let bundle_path = Tile { level: 0, n: 0, width: cp.size as u32 }.entries_path();
5931
    let (st, _) = call(&h.app, "GET", &format!("/log/{bundle_path}"), None, None).await;
5932
    assert_eq!(st, StatusCode::OK);
5933
    let res =
5934
        oxygenhub::router(h.app.clone()).oneshot(Request::get(format!("/log/{bundle_path}")).body(Body::empty()).unwrap()).await.unwrap();
5935
    assert_eq!(res.headers()[header::CACHE_CONTROL], "public, max-age=5", "a partial tile changes");
5936
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
5937
    let entries: Vec<Entry> = tlog::decode_bundle(&bytes).unwrap().iter().map(|b| Entry::decode(b).unwrap()).collect();
5938
    let kinds: Vec<&str> = entries.iter().map(|e| e.kind.as_str()).collect();
5939
    assert!(kinds.contains(&"ref") && kinds.contains(&"seal") && kinds.contains(&"policy"), "{kinds:?}");
5940
    let r = entries.iter().find(|e| e.kind == "ref").unwrap();
5941
    assert_eq!(r.object, attest);
5942
    assert_eq!(r.repo, c.id().unwrap());
5943
5944
    // The leaves rebuild the checkpoint's root, and the hash tile served
5945
    // is what they make.
5946
    let mut stored: Vec<Hash> = Vec::new();
5947
    for (n, e) in entries.iter().enumerate() {
5948
        stored.extend(tlog::stored_hashes_for_leaf(n as u64, e.leaf_hash(), &stored).unwrap());
5949
    }
5950
    assert_eq!(tlog::tree_hash(cp.size, &stored).unwrap(), cp.root);
5951
    let t = Tile { level: 0, n: 0, width: cp.size as u32 };
5952
    let res =
5953
        oxygenhub::router(h.app.clone()).oneshot(Request::get(format!("/log/{}", t.path())).body(Body::empty()).unwrap()).await.unwrap();
5954
    assert_eq!(res.status(), StatusCode::OK);
5955
    let data = res.into_body().collect().await.unwrap().to_bytes();
5956
    assert_eq!(data.to_vec(), t.read_data(&stored).unwrap());
5957
    let (st, _) = call(&h.app, "GET", "/log/tile/0/000.p/200", None, None).await;
5958
    assert_eq!(st, StatusCode::NOT_FOUND, "not held yet");
5959
5960
    // Pushing the same again logs nothing new.
5961
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
5962
    assert_eq!(h.app.tlog.size(), cp.size);
5963
    let (st, page) = call(&h.app, "GET", "/log", None, None).await;
5964
    assert_eq!(st, StatusCode::OK);
5965
    assert!(page.contains("Transparency log") && page.contains("andy/demo") && page.contains(&origin), "{page}");
5966
}
5967
e5b97ac3 Andy McCall ↶ 5968
/// Fetching checks the hub's log (oxygenhub#238, step A3): the checkpoint
5969
/// comes with the refs, each attestation with its entry and inclusion
5970
/// proof; a later checkpoint is proved to extend the one seen before, from
5971
/// the hub's tiles; an attestation not in a checkpoint yet is a note; and a
5972
/// log that does not extend what this user saw fails the fetch.
5973
#[tokio::test(flavor = "multi_thread")]
5974
async fn a_fetch_checks_the_hub_s_log_and_refuses_a_fork() {
5975
    use oxy_core::tlog::{Checkpoint, Note};
5976
    let h = hub().await;
5977
    create(&h.app, "andy", "demo").await;
5978
    let url = format!("{}/andy/demo", h.base);
5979
    let work = tempfile::tempdir().unwrap();
5980
    let mut a = client(&url, &work.path().join("a"));
5981
    a.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
5982
    let (_, sk) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
5983
    let hub_id = h.app.hub_key.identity.clone();
5984
    let checkpoint = || h.app.tlog.refresh_checkpoint(&hub_id, &sk).unwrap();
5985
    let mut n = 0;
5986
    let mut push = |a: &Repo| {
5987
        n += 1;
5988
        write(&work.path().join("a"), "a.txt", &format!("{n}\n"));
5989
        a.commit(&format!("change {n}"), &[]).unwrap();
5990
        assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
5991
    };
5992
    push(&a);
5993
    checkpoint();
5994
5995
    let home = work.path().join("home-b");
5996
    let b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(home.clone());
5997
    let report = b.fetch("origin").unwrap();
5998
    assert!(report.log_notes.is_empty(), "{:?}", report.log_notes);
5999
    let pin = std::fs::read_dir(home.join("tlog")).unwrap().next().unwrap().unwrap().path();
6000
    let seen = |p: &std::path::Path| {
6001
        let t = std::fs::read_to_string(p).unwrap();
6002
        Checkpoint::parse(&Note::parse(t.split_once('\n').unwrap().1).unwrap().text).unwrap()
6003
    };
6004
    let first = seen(&pin);
6005
6006
    // A later checkpoint: proved to extend the first from the tiles.
6007
    push(&a);
6008
    checkpoint();
6009
    let report = b.fetch("origin").unwrap();
6010
    assert!(report.log_notes.is_empty(), "{:?}", report.log_notes);
6011
    assert!(seen(&pin).size > first.size);
6012
6013
    // Pushed after the last checkpoint: not provable yet, only a note.
6014
    push(&a);
6015
    let report = b.fetch("origin").unwrap();
6016
    assert!(report.log_notes.iter().any(|n| n.contains("not in its transparency log yet")), "{:?}", report.log_notes);
6017
7dbb41b0 Andy McCall ↶ 6018
    // A log key other than the one pinned (a hub given a new key, or a
6019
    // port reused by another hub): a note, and the new key pinned.
6020
    let text = std::fs::read_to_string(&pin).unwrap();
6021
    let other_sk = oxy_core::identity::SecretKey::generate();
6022
    let other = other_sk.identity("another hub", "[email protected]", 1);
6023
    let note = text.split_once('\n').unwrap().1;
6024
    std::fs::write(&pin, format!("{}\n{note}", oxy_core::dsse::base64(&other.encode()))).unwrap();
6025
    let report = b.fetch("origin").unwrap();
6026
    assert!(report.log_notes.iter().any(|n| n.contains("signed by another key")), "{:?}", report.log_notes);
6027
    let report = b.fetch("origin").unwrap();
6028
    assert!(!report.log_notes.iter().any(|n| n.contains("another key")), "pinned now: {:?}", report.log_notes);
6029
e5b97ac3 Andy McCall ↶ 6030
    // What this user saw replaced by another log of the same size, signed
6031
    // by the hub's own key: the hub's real log does not extend it.
6032
    let size = seen(&pin).size;
6033
    let forged = Checkpoint { origin: oxygenhub::tlog::origin_of(h.app.config.base_url()), size, root: [7; 32], extensions: vec![] };
6034
    let text = std::fs::read_to_string(&pin).unwrap();
6035
    let key = text.split_once('\n').unwrap().0;
6036
    std::fs::write(&pin, format!("{key}\n{}", forged.sign(&hub_id, &sk).unwrap().encode())).unwrap();
f87a74ff Andy McCall ↶ 6037
    // A push first, so the real log is longer than what was seen even when
6038
    // the hub's own background checkpoint already took the last one (#354).
6039
    push(&a);
e5b97ac3 Andy McCall ↶ 6040
    checkpoint();
6041
    let err = b.fetch("origin").unwrap_err().to_string();
6042
    assert!(err.contains("showed two histories") && err.contains("does not extend"), "{err}");
6043
}
6044
4f40eed0 Andy McCall ↶ 6045
/// Witnesses (oxygenhub#238, step A5): one hub cosigns another's
6046
/// checkpoints when each extends the last it cosigned, and the log serves
6047
/// the cosignatures with its checkpoint; the witness refuses a fork (422),
6048
/// tells a log that guessed its size wrong (409), and knows only the logs
6049
/// it was told to witness (404).
6050
#[tokio::test(flavor = "multi_thread")]
6051
async fn a_hub_witnesses_another_hub_s_log() {
6052
    use oxy_core::tlog::{AddCheckpoint, Checkpoint, Note};
6053
    let log = hub().await;
6054
    let witness = hub().await;
6055
    let origin = oxygenhub::tlog::origin_of(log.app.config.base_url());
6056
    witness.app.tlog.add_witness_for(&origin, log.app.hub_key.identity.clone());
6057
    let name = witness.app.tlog.witness_name().to_string();
6058
    log.app.tlog.set_witnesses(vec![oxygenhub::tlog::Peer {
6059
        name: name.clone(),
6060
        url: format!("{}/log/witness/add-checkpoint", witness.base),
6061
        identity: witness.app.hub_key.identity.clone(),
6062
    }]);
6063
    create(&log.app, "andy", "demo").await;
6064
    let work = tempfile::tempdir().unwrap();
6065
    let mut c = client(&format!("{}/andy/demo", log.base), work.path());
6066
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
6067
    let (_, sk) = oxygenhub::keys::load_secret(&log.app.config.keys_dir()).unwrap();
6068
    let log_id = log.app.hub_key.identity.clone();
6069
    let wid = witness.app.hub_key.identity.clone();
6070
    for n in 0..2 {
6071
        write(work.path(), "a.txt", &format!("{n}\n"));
6072
        c.commit(&format!("change {n}"), &[]).unwrap();
6073
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6074
        log.app.tlog.refresh_checkpoint(&log_id, &sk).unwrap();
6075
        oxygenhub::tlog::collect(&log.app).await;
6076
        let note = Note::parse(&log.app.tlog.checkpoint().unwrap()).unwrap();
6077
        assert!(note.cosigned_by(&name, &wid).is_ok(), "round {n}: {}", note.encode());
6078
        // Served as such.
6079
        let (_, served) = call(&log.app, "GET", "/log/checkpoint", None, None).await;
6080
        assert!(Note::parse(&served).unwrap().cosigned_by(&name, &wid).is_ok());
6081
    }
6082
    let cp = Checkpoint::parse(&Note::parse(&log.app.tlog.checkpoint().unwrap()).unwrap().text).unwrap();
13b27cb2 Andy McCall ↶ 6083
6084
    // Trusted time (#240): the log lists its witnesses, and a fetch's refs
6085
    // carry, for a logged bookmark, the cosigned checkpoints that first held
6086
    // its entry, from which the client takes the integrated time.
6087
    let (_, listed) = call(&log.app, "GET", "/log/witnesses", None, None).await;
6088
    assert!(listed.starts_with(&format!("{name} ")), "{listed}");
6089
    let url = format!("{}/andy/demo", log.base);
6090
    let refs = tokio::task::spawn_blocking(move || {
6091
        let opts = RemoteOptions { token: Some("site".into()), ..Default::default() };
6092
        open_remote(&url, &opts).unwrap().refs().unwrap()
6093
    })
6094
    .await
6095
    .unwrap();
6096
    assert_eq!(refs.witnesses.len(), 1);
6097
    assert_eq!(refs.witnesses[0].0, name);
6098
    let main = refs.refs.iter().find(|r| r.name == "main").expect("main");
6099
    let logged = main.logged.as_ref().expect("logged");
6100
    assert!(!main.integration.is_empty(), "a witnessed checkpoint holds it");
6101
    let cosigned: Vec<(&str, &[[u8; 32]])> = main.integration.iter().map(|i| (i.note.as_str(), i.proof.as_slice())).collect();
6102
    let at = oxy_core::tlog::integrated_time(&logged.entry, logged.index, &cosigned, &origin, &log_id, &[(name.clone(), wid.clone())])
6103
        .expect("an integrated time");
6104
    assert_eq!(at.witness, name);
6105
    assert!(at.size > logged.index);
4f40eed0 Andy McCall ↶ 6106
6107
    let ask = |req: AddCheckpoint| {
6108
        let app = witness.app.clone();
6109
        async move { call(&app, "POST", "/log/witness/add-checkpoint", None, Some(req.encode())).await }
6110
    };
6111
    // Another log of the same size, signed by the log's own key: a fork.
6112
    let forked = Checkpoint { root: [7; 32], ..cp.clone() }.sign(&log_id, &sk).unwrap().encode();
6113
    let (st, body) = ask(AddCheckpoint { old_size: cp.size, proof: vec![], note: forked.clone() }).await;
6114
    assert_eq!(st, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
6115
    // A wrong idea of what the witness saw: its size, to try again from.
6116
    let (st, body) = ask(AddCheckpoint { old_size: 1, proof: vec![], note: forked }).await;
6117
    assert_eq!((st, body.trim()), (StatusCode::CONFLICT, cp.size.to_string().as_str()));
6118
    // A log it was not told to witness.
6119
    let stranger = oxy_core::identity::SecretKey::generate();
6120
    let sid = stranger.identity("elsewhere", "[email protected]", 1);
6121
    let other = Checkpoint { origin: "elsewhere.example/log".into(), ..cp.clone() }.sign(&sid, &stranger).unwrap().encode();
6122
    let (st, _) = ask(AddCheckpoint { old_size: 0, proof: vec![], note: other }).await;
6123
    assert_eq!(st, StatusCode::NOT_FOUND);
6124
}
6125
8dcaeeb8 Andy McCall ↶ 6126
/// Terraform state (oxygenhub#252): the HTTP backend's calls as
6127
/// Terraform and OpenTofu make them, with a running job's token as the
6128
/// Basic-auth password; the lock is honoured, versions are kept, the state
6129
/// is sealed at rest, and another repository's job is refused.
6130
#[tokio::test(flavor = "multi_thread")]
6131
async fn a_job_keeps_its_terraform_state_on_the_hub() {
6132
    let h = hub().await;
6133
    create(&h.app, "andy", "infra").await;
6134
    create(&h.app, "andy", "other").await;
6135
    let work = tempfile::tempdir().unwrap();
6136
    let c = client(&format!("{}/andy/infra", h.base), work.path());
6137
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
6138
    write(work.path(), "test.sh", "echo ok\n");
6139
    c.snapshot("test").unwrap();
6140
    c.commit("Add a pipeline", &[]).unwrap();
6141
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6142
    assert_eq!(runs_of(&h.app, "andy", "infra").await.len(), 1);
6143
    let job = claim(&h.app).await.expect("a job");
6144
    let token = job["token"].as_str().unwrap().to_string();
6145
    let basic = format!("Basic {}", oxy_core::dsse::base64(format!("flow:{token}").as_bytes()));
6146
    let path = "/api/v1/repos/andy/infra/terraform/state/prod";
6147
    let send = |method: &str, uri: String, auth: Option<String>, body: &str| {
6148
        let mut req = Request::builder().method(method).uri(uri);
6149
        if let Some(a) = auth {
6150
            req = req.header(header::AUTHORIZATION, a);
6151
        }
6152
        let req = req.body(Body::from(body.to_string())).unwrap();
6153
        let app = h.app.clone();
6154
        async move {
6155
            let res = oxygenhub::router(app).oneshot(req).await.unwrap();
6156
            let st = res.status();
6157
            let b = res.into_body().collect().await.unwrap().to_bytes();
6158
            (st, String::from_utf8_lossy(&b).into_owned())
6159
        }
6160
    };
6161
    let lock = r#"{"ID":"lock-1","Operation":"OperationTypeApply","Who":"flow@runner","Version":"1.8.0"}"#;
6162
    // No state yet; no token, nothing.
6163
    assert_eq!(send("GET", path.into(), None, "").await.0, StatusCode::UNAUTHORIZED);
6164
    assert_eq!(send("GET", path.into(), Some(basic.clone()), "").await.0, StatusCode::NO_CONTENT);
6165
    // Lock, write under the lock, unlock.
6166
    let (st, body) = send("LOCK", path.into(), Some(basic.clone()), lock).await;
6167
    assert_eq!(st, StatusCode::OK, "{body}");
6168
    let other_lock = r#"{"ID":"lock-2","Operation":"OperationTypePlan"}"#;
6169
    let (st, held) = send("LOCK", path.into(), Some(basic.clone()), other_lock).await;
6170
    assert_eq!(st, StatusCode::LOCKED);
6171
    assert!(held.contains("lock-1"), "the holder's lock info: {held}");
6172
    let state1 = r#"{"version":4,"serial":1,"lineage":"l","resources":[{"secret":"hunter2"}]}"#;
6173
    assert_eq!(send("POST", path.into(), Some(basic.clone()), state1).await.0, StatusCode::LOCKED, "not under its lock");
6174
    assert_eq!(send("POST", format!("{path}?ID=lock-1"), Some(basic.clone()), state1).await.0, StatusCode::OK);
6175
    assert_eq!(send("UNLOCK", path.into(), Some(basic.clone()), other_lock).await.0, StatusCode::CONFLICT, "not its lock");
6176
    assert_eq!(send("UNLOCK", path.into(), Some(basic.clone()), lock).await.0, StatusCode::OK);
6177
    let (st, got) = send("GET", path.into(), Some(basic.clone()), "").await;
6178
    assert_eq!((st, got.as_str()), (StatusCode::OK, state1));
6179
    // A second write keeps the first as a version; the body is sealed.
6180
    let state2 = state1.replace("\"serial\":1", "\"serial\":2");
6181
    assert_eq!(send("POST", path.into(), Some(basic.clone()), &state2).await.0, StatusCode::OK);
6182
    let row = db::repos::get(&h.app.db, "andy", "infra").await.unwrap().unwrap();
6183
    assert_eq!(db::terraform::versions(&h.app.db, row.id, "prod").await.unwrap(), 1);
6184
    let kept = db::terraform::get(&h.app.db, row.id, "prod").await.unwrap().unwrap();
6185
    assert_eq!(kept.serial, 2);
6186
    assert!(!String::from_utf8_lossy(&kept.body).contains("hunter2"), "sealed at rest");
6187
    // Another repository's state is not this job's; a bad name is refused.
6188
    let (st, _) = send("GET", "/api/v1/repos/andy/other/terraform/state/prod".into(), Some(basic.clone()), "").await;
6189
    assert_eq!(st, StatusCode::FORBIDDEN);
6190
    assert_eq!(
6191
        send("GET", "/api/v1/repos/andy/infra/terraform/state/..x".into(), Some(basic.clone()), "").await.0,
6192
        StatusCode::BAD_REQUEST
6193
    );
bb018142 Andy McCall ↶ 6194
    // A stranger reads a public repository, but not its state: states hold
6195
    // secrets (#256), so reading one needs the write role, whatever the token.
6196
    let mallory = db::accounts::create_account(&h.app.db, "mallory", "[email protected]", "x", "salt", false).await.unwrap();
6197
    let (secret, hash) = oxygenhub::auth::new_token();
6198
    db::accounts::create_token(&h.app.db, mallory.id, "cli", &hash, "repo:write", "", None).await.unwrap();
6199
    let (st, got) = send("GET", path.into(), Some(format!("Bearer {secret}")), "").await;
6200
    assert_eq!(st, StatusCode::FORBIDDEN, "{got}");
6201
    assert!(!got.contains("hunter2"));
6202
    let (_, page) = call(&h.app, "GET", "/andy/infra/terraform", Some(&secret), None).await;
6203
    assert!(!page.contains("<strong>prod</strong>") && page.contains("shown to people who can write"), "{page}");
8dcaeeb8 Andy McCall ↶ 6204
    // The site token is no person's: refused.
6205
    let (st, _) = send("GET", path.into(), Some("Bearer site".into()), "").await;
6206
    assert_eq!(st, StatusCode::UNAUTHORIZED, "the site token is not a person's token");
6207
    // A job's identity token for the Terraform audience, as its pipeline's
6208
    // identity block mounts it: its own repository only, that audience only.
6209
    let issuer = h.app.oidc().await.unwrap();
6210
    let now = db::now_ms();
6211
    let aud = oxygenhub::terraform::audience(h.app.config.base_url());
6212
    let own = issuer.mint_for(h.app.config.base_url(), "repo:andy/infra:bookmark:main", &aud, now, 600);
6213
    let (st, got) = send("GET", path.into(), Some(format!("Bearer {own}")), "").await;
6214
    assert_eq!((st, got.contains("\"serial\":2")), (StatusCode::OK, true));
6215
    let other = issuer.mint_for(h.app.config.base_url(), "repo:andy/other:bookmark:main", &aud, now, 600);
6216
    assert_eq!(send("GET", path.into(), Some(format!("Bearer {other}")), "").await.0, StatusCode::FORBIDDEN);
6217
    let elsewhere = issuer.mint_for(h.app.config.base_url(), "repo:andy/infra:bookmark:main", "sts.amazonaws.com", now, 600);
6218
    assert_eq!(send("GET", path.into(), Some(format!("Bearer {elsewhere}")), "").await.0, StatusCode::UNAUTHORIZED);
16ee5d19 Andy McCall ↶ 6219
    // Its page under Artifacts (#254) lists the state and the backend block.
bb018142 Andy McCall ↶ 6220
    // Its owner, signed in, sees the states.
6221
    let res = oxygenhub::router(h.app.clone())
6222
        .oneshot(
6223
            Request::post("/register")
6224
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
6225
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
6226
                .unwrap(),
6227
        )
6228
        .await
6229
        .unwrap();
6230
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
6231
    let res = oxygenhub::router(h.app.clone())
67523e06 Andy McCall ↶ 6232
        .oneshot(Request::get("/andy/infra/terraform").header(header::COOKIE, cookie.clone()).body(Body::empty()).unwrap())
bb018142 Andy McCall ↶ 6233
        .await
6234
        .unwrap();
6235
    let st = res.status();
6236
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
16ee5d19 Andy McCall ↶ 6237
    assert_eq!(st, StatusCode::OK, "{page}");
6238
    assert!(page.contains("<strong>prod</strong>") && page.contains("/api/v1/repos/andy/infra/terraform/state/NAME"), "{page}");
6239
    assert!(page.contains("allow &quot;") || page.contains("allow \""), "the egress line names the hub");
67523e06 Andy McCall ↶ 6240
    assert!(page.contains("1 kept version") && page.contains(">restore</button>"), "its versions, restorable by its owner: {page}");
6241
6242
    // Versions (#255) through the API: listed and read with the write role,
6243
    // restored with the maintain role (never by a job, never under a lock),
6244
    // as a new serial, so nothing is lost and going forward again works.
6245
    let andy = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap();
6246
    let (pat, hash) = oxygenhub::auth::new_token();
6247
    db::accounts::create_token(&h.app.db, andy.id, "cli", &hash, "repo:write", "", None).await.unwrap();
6248
    let bearer = format!("Bearer {pat}");
6249
    let (st, list) = send("GET", format!("{path}/versions"), Some(bearer.clone()), "").await;
6250
    assert_eq!(st, StatusCode::OK, "{list}");
6251
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
6252
    assert_eq!((list.as_array().unwrap().len(), list[0]["serial"].as_i64()), (1, Some(1)), "{list}");
6253
    let first = list[0]["id"].as_i64().unwrap();
6254
    let (st, got) = send("GET", format!("{path}/versions/{first}"), Some(bearer.clone()), "").await;
6255
    assert_eq!((st, got.as_str()), (StatusCode::OK, state1));
6256
    assert_eq!(send("GET", format!("{path}/versions"), Some(format!("Bearer {secret}")), "").await.0, StatusCode::FORBIDDEN, "a stranger");
6257
    let restore = |id: i64, auth: String| send("POST", format!("{path}/versions/{id}/restore"), Some(auth), "");
6258
    assert_eq!(restore(first, basic.clone()).await.0, StatusCode::FORBIDDEN, "a job does not restore");
6259
    assert_eq!(restore(first, format!("Bearer {secret}")).await.0, StatusCode::FORBIDDEN, "nor a stranger");
6260
    assert_eq!(restore(9999, bearer.clone()).await.0, StatusCode::NOT_FOUND);
6261
    assert_eq!(send("LOCK", path.into(), Some(basic.clone()), lock).await.0, StatusCode::OK);
6262
    assert_eq!(restore(first, bearer.clone()).await.0, StatusCode::LOCKED, "not under someone's lock");
6263
    assert_eq!(send("UNLOCK", path.into(), Some(basic.clone()), lock).await.0, StatusCode::OK);
6264
    let (st, got) = restore(first, bearer.clone()).await;
6265
    assert_eq!((st, got.contains("\"serial\":3")), (StatusCode::OK, true), "{got}");
6266
    let (_, now) = send("GET", path.into(), Some(bearer.clone()), "").await;
6267
    let now: serde_json::Value = serde_json::from_str(&now).unwrap();
6268
    assert_eq!(
6269
        (now["serial"].as_i64(), now["lineage"].as_str(), now["resources"][0]["secret"].as_str()),
6270
        (Some(3), Some("l"), Some("hunter2"))
6271
    );
6272
    // Forward again: serial 2 is a kept version now.
6273
    let (_, list) = send("GET", format!("{path}/versions"), Some(bearer.clone()), "").await;
6274
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
6275
    let serials: Vec<i64> = list.as_array().unwrap().iter().map(|v| v["serial"].as_i64().unwrap()).collect();
6276
    assert_eq!(serials, vec![2, 1], "{list}");
6277
    let (st, got) = restore(list[0]["id"].as_i64().unwrap(), bearer.clone()).await;
6278
    assert_eq!((st, got.contains("\"serial\":4")), (StatusCode::OK, true), "{got}");
6279
6280
    // And from the page: download a version, restore one with the form.
6281
    let page_with = |req: axum::http::request::Builder, body: Body| {
6282
        let (app, cookie) = (h.app.clone(), cookie.clone());
6283
        async move {
6284
            let res = oxygenhub::router(app).oneshot(req.header(header::COOKIE, cookie).body(body).unwrap()).await.unwrap();
6285
            let st = res.status();
6286
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
6287
        }
6288
    };
6289
    let (st, file) = page_with(Request::get(format!("/andy/infra/terraform/prod/download?version={first}")), Body::empty()).await;
6290
    assert_eq!((st, file.as_str()), (StatusCode::OK, state1));
6291
    let (_, page) = page_with(Request::get("/andy/infra/terraform"), Body::empty()).await;
6292
    let csrf = page.split("name=\"_csrf\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
6293
    let (st, page) = page_with(
6294
        Request::post("/andy/infra/terraform/prod/restore").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"),
6295
        Body::from(format!("_csrf={csrf}&version={first}")),
6296
    )
6297
    .await;
6298
    assert_eq!(st, StatusCode::OK, "{page}");
6299
    assert!(page.contains("Restored prod: it is now serial 5."), "{page}");
6300
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
6301
    assert_eq!(audit.iter().filter(|r| r.action == "terraform.restored").count(), 3, "every restore audited");
8dcaeeb8 Andy McCall ↶ 6302
}
6303
6304
/// The real OpenTofu against the backend (oxygenhub#252): init, apply,
6305
/// a second apply that changes nothing, all through the hub's state with a
6306
/// job's token. Needs Docker and the `oxygenflow-tofu` image; run with
6307
/// `cargo test -p oxygenhub --test flow -- --ignored tofu_keeps`.
6308
#[tokio::test(flavor = "multi_thread")]
6309
#[ignore]
6310
async fn tofu_keeps_its_state_on_the_hub() {
6311
    let h = hub().await;
6312
    create(&h.app, "andy", "infra").await;
6313
    let work = tempfile::tempdir().unwrap();
6314
    let c = client(&format!("{}/andy/infra", h.base), work.path());
6315
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
6316
    write(work.path(), "test.sh", "echo ok\n");
6317
    c.snapshot("test").unwrap();
6318
    c.commit("Add a pipeline", &[]).unwrap();
6319
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6320
    assert_eq!(runs_of(&h.app, "andy", "infra").await.len(), 1);
6321
    let job = claim(&h.app).await.expect("a job");
6322
    let token = job["token"].as_str().unwrap().to_string();
6323
    let tf = tempfile::tempdir().unwrap();
6324
    let address = format!("{}/api/v1/repos/andy/infra/terraform/state/prod", h.base);
6325
    std::fs::write(
6326
        tf.path().join("main.tf"),
6327
        format!(
6328
            "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"
6329
        ),
6330
    )
6331
    .unwrap();
6332
    let tofu = |args: &[&str]| {
6333
        let out = std::process::Command::new("docker")
6334
            .args(["run", "--rm", "--network", "host", "-v"])
6335
            .arg(format!("{}:/w", tf.path().display()))
6336
            .args(["-w", "/w", "-e"])
6337
            .arg(format!("TF_HTTP_PASSWORD={token}"))
6338
            .args(["--entrypoint", "tofu", "oxygenflow-tofu:latest"])
6339
            .args(args)
6340
            .output()
6341
            .expect("docker");
6342
        let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
6343
        assert!(out.status.success(), "tofu {args:?}: {text}");
6344
        text
6345
    };
6346
    tofu(&["init", "-input=false", "-no-color"]);
6347
    let applied = tofu(&["apply", "-auto-approve", "-input=false", "-no-color"]);
6348
    assert!(applied.contains("1 added"), "{applied}");
6349
    let again = tofu(&["apply", "-auto-approve", "-input=false", "-no-color"]);
6350
    assert!(again.contains("No changes"), "the state was kept: {again}");
6351
    let row = db::repos::get(&h.app.db, "andy", "infra").await.unwrap().unwrap();
6352
    let kept = db::terraform::get(&h.app.db, row.id, "prod").await.unwrap().unwrap();
6353
    assert!(kept.lock_id.is_empty(), "unlocked after each run");
6354
    assert!(kept.serial >= 1);
6355
}
6356
8a48dd83 Andy McCall ↶ 6357
/// `/metrics` (oxygenhub#212): off until a token is set, then served only
6358
/// to its bearer, in the Prometheus text format, with Flow's jobs counted.
6359
#[tokio::test(flavor = "multi_thread")]
6360
async fn metrics_are_private_and_count_flow_jobs() {
6361
    let h = hub().await;
6362
    let (st, _) = call(&h.app, "GET", "/metrics", None, None).await;
6363
    assert_eq!(st, StatusCode::NOT_FOUND, "off by default");
6364
    let text = oxygenhub::metrics::render(&h.app).await;
6365
    for want in [
6366
        "# TYPE oxyhub_uptime_seconds gauge",
6367
        "oxyhub_flow_jobs{state=\"queued\"} 0",
6368
        "oxyhub_bucket_requests_total{kind=\"list\"}",
6369
        "oxyhub_tlog_entries",
a6d824c5 Andy McCall ↶ 6370
        "oxyhub_db_connections{idle=\"true\"}",
6371
        "oxyhub_pushes_last_day{result=\"refused\"} 0",
6372
        "# TYPE oxyhub_backup_last_run_ok gauge",
2c47eecf Andy McCall ↶ 6373
        "# TYPE oxyhub_flow_runner_last_seen_seconds gauge",
6374
        "oxyhub_flow_runs_last_day{result=\"failed\"} 0",
6375
        "oxyhub_mail_total{result=\"sent\"}",
8a48dd83 Andy McCall ↶ 6376
    ] {
6377
        assert!(text.contains(want), "missing {want}:\n{text}");
6378
    }
6379
    create(&h.app, "andy", "demo").await;
6380
    let work = tempfile::tempdir().unwrap();
6381
    let c = client(&format!("{}/andy/demo", h.base), work.path());
6382
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
6383
    write(work.path(), "test.sh", "echo ok\n");
6384
    c.snapshot("test").unwrap();
6385
    c.commit("Add a pipeline", &[]).unwrap();
6386
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6387
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
6388
    let text = oxygenhub::metrics::render(&h.app).await;
6389
    assert!(!text.contains("oxyhub_flow_jobs{state=\"queued\"} 0"), "the run's jobs are queued:\n{text}");
a6d824c5 Andy McCall ↶ 6390
    assert!(text.contains("oxyhub_pushes_last_day{result=\"accepted\"}"), "{text}");
85ec74fd Andy McCall ↶ 6391
    // The push's bytes are counted (other tests share the counters, so
6392
    // only that they are there and not nothing).
6393
    let pushed = text
6394
        .lines()
6395
        .find_map(|l| l.strip_prefix("oxyhub_protocol_bytes_total{endpoint=\"push\",direction=\"received\"} "))
6396
        .and_then(|v| v.parse::<f64>().ok())
6397
        .unwrap_or(0.0);
6398
    assert!(pushed > 0.0, "{text}");
b9b74d99 Andy McCall ↶ 6399
    // Requests through the router are counted by route class.
6400
    call(&h.app, "GET", "/andy/demo", None, None).await;
6401
    let text = oxygenhub::metrics::render(&h.app).await;
6402
    assert!(text.contains("oxyhub_http_requests_total{route=\"page:repository\",method=\"GET\",status=\"2xx\"}"), "{text}");
6403
    assert!(text.contains("oxyhub_http_request_duration_seconds_bucket{route=\"page:repository\",method=\"GET\",le=\"+Inf\"}"));
8a48dd83 Andy McCall ↶ 6404
}
6405
e97500b7 Andy McCall ↶ 6406
/// Insights (oxygenhub#257): a job is ready when it could run (queued, its
6407
/// dependencies passed), so its pickup time is from then to its claim; the
6408
/// repository's page charts its jobs, an owner's numbers are its own and
6409
/// the site's are the administrators'.
6410
#[tokio::test(flavor = "multi_thread")]
6411
async fn insights_chart_pickup_from_when_a_job_could_run() {
6412
    let h = hub().await;
6413
    create(&h.app, "andy", "demo").await;
6414
    let work = tempfile::tempdir().unwrap();
6415
    let c = client(&format!("{}/andy/demo", h.base), work.path());
6416
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
6417
    write(work.path(), "test.sh", "echo ok\n");
6418
    c.snapshot("test").unwrap();
6419
    c.commit("Add a pipeline", &[]).unwrap();
6420
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6421
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), 1);
6422
    let mut finished = std::collections::HashMap::new();
6423
    for want in ["build", "lint", "test"] {
6424
        let j = claim(&h.app).await.expect("a job");
6425
        assert_eq!(j["job"]["name"].as_str(), Some(want));
6426
        let id = j["job_id"].as_i64().unwrap();
6427
        let row = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
6428
        let (queued, ready, started) = (row.queued_ms.unwrap(), row.ready_ms.unwrap(), row.started_ms.unwrap());
6429
        assert!(queued <= ready && ready <= started, "{want}: {queued} {ready} {started}");
6430
        if want == "test" {
6431
            assert_eq!(Some(ready), finished["build"], "ready when build passed, not when it was queued");
6432
        }
6433
        let ph = j["pipeline_hash"].as_str().unwrap();
6434
        let st = finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt(want, ph, 0) })).await;
6435
        assert_eq!(st, StatusCode::NO_CONTENT);
6436
        finished.insert(want, db::flow::job(&h.app.db, id).await.unwrap().unwrap().finished_ms);
6437
    }
6438
    let (st, page) = call(&h.app, "GET", "/andy/demo/insights", None, None).await;
6439
    assert_eq!(st, StatusCode::OK, "{page}");
6440
    assert!(page.contains("<span class=\"kpi-v\">3</span><span class=\"kpi-l\">jobs finished"), "{page}");
6441
    assert!(page.contains("100% passed"), "{page}");
6442
    assert_eq!(page.matches("<svg class=\"chart\"").count(), 5, "five charts");
6443
    assert!(page.contains("class=\"bar s-ok\""), "the passed jobs drawn");
6444
    assert!(page.contains("data-refresh=\"30\" data-fragment=\"insights\""), "it refreshes itself");
6445
    assert!(page.contains("<summary class=\"on\">More</summary>"), "the bar's More menu holds it");
6446
    let (_, wall) = call(&h.app, "GET", "/andy/demo/insights?range=7d&wall=1", None, None).await;
6447
    assert!(wall.contains("<body class=\"wall\"") && wall.contains("the last 7 days") && wall.contains("leave the wall view"), "{wall}");
6448
    // An owner's numbers are not anyone's; the site's are administrators'.
6449
    assert_eq!(call(&h.app, "GET", "/insights/andy", None, None).await.0, StatusCode::NOT_FOUND);
6450
    assert_eq!(call(&h.app, "GET", "/admin/insights", None, None).await.0, StatusCode::NOT_FOUND);
6451
    let res = oxygenhub::router(h.app.clone())
6452
        .oneshot(
6453
            Request::post("/register")
6454
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
6455
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
6456
                .unwrap(),
6457
        )
6458
        .await
6459
        .unwrap();
6460
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
6461
    let andy = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap();
6462
    db::accounts::set_admin(&h.app.db, andy.id, true).await.unwrap();
6463
    for path in ["/insights/andy", "/admin/insights?runner=test-1&range=1h"] {
6464
        let res = oxygenhub::router(h.app.clone())
6465
            .oneshot(Request::get(path).header(header::COOKIE, cookie.clone()).body(Body::empty()).unwrap())
6466
            .await
6467
            .unwrap();
6468
        let st = res.status();
6469
        let body = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
6470
        assert_eq!(st, StatusCode::OK, "{path}: {body}");
6471
        assert!(body.contains("<svg class=\"chart\""), "{path}");
6472
    }
6473
}
6474
7c06f5b2 Andy McCall ↶ 6475
/// Readers never wait (oxygenhub#249): a page, the API and a fetch's refs
6476
/// answer while a writer (a push, a gc) holds the repository; writers take
6477
/// turns; deleting or moving it waits for everyone and holds off newcomers.
6478
#[tokio::test(flavor = "multi_thread")]
6479
async fn reads_do_not_wait_for_a_writer() {
6480
    use std::time::Duration;
6481
    let h = hub().await;
6482
    create(&h.app, "andy", "demo").await;
6483
    let work = tempfile::tempdir().unwrap();
6484
    let c = client(&format!("{}/andy/demo", h.base), work.path());
6485
    write(work.path(), "a.txt", "a\n");
6486
    c.commit("A change", &[]).unwrap();
6487
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6488
    let name = RepoName::parse("andy/demo").unwrap();
6489
    let writer = h.app.repos.write_guard(&name).await;
6490
    for path in ["/andy/demo", "/andy/demo/changes/main", "/api/v1/repos/andy/demo/bookmarks"] {
6491
        let (st, body) = tokio::time::timeout(Duration::from_secs(10), call(&h.app, "GET", path, None, None))
6492
            .await
6493
            .unwrap_or_else(|_| panic!("{path} waited for the writer"));
6494
        assert_eq!(st, StatusCode::OK, "{path}: {body}");
6495
    }
6496
    let refs = tokio::time::timeout(Duration::from_secs(10), call(&h.app, "POST", "/andy/demo/oxy/v1/refs", Some("site"), None)).await;
6497
    assert!(refs.is_ok(), "a fetch's refs waited for the writer");
6498
    assert!(tokio::time::timeout(Duration::from_millis(300), h.app.repos.write_guard(&name)).await.is_err(), "writers take turns");
6499
    assert!(tokio::time::timeout(Duration::from_millis(300), h.app.repos.exclusive_guard(&name)).await.is_err(), "a delete waits");
6500
    drop(writer);
6501
    let all = tokio::time::timeout(Duration::from_secs(5), h.app.repos.exclusive_guard(&name)).await.expect("then it runs");
6502
    assert!(
6503
        tokio::time::timeout(Duration::from_millis(300), h.app.repos.read_guard(&name)).await.is_err(),
6504
        "nothing reads a repository being deleted"
6505
    );
6506
    drop(all);
6507
}
6508
a10446c6 Andy McCall ↶ 6509
/// Live L5 (docs/live.md, oxygenhub#207): the issue page's timeline
6510
/// listens on the issue's topic and the repository's, the overview's latest
6511
/// change and bookmarks on the repository's, and its Diffusion card and the
6512
/// Diffusion tab on the repository's Diffusion topic.
6513
#[tokio::test(flavor = "multi_thread")]
6514
async fn the_issue_overview_and_diffusion_pages_listen_on_their_topics() {
6515
    let h = hub().await;
6516
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
6517
    create(&h.app, "andy", "demo").await;
6518
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
6519
    let work = tempfile::tempdir().unwrap();
6520
    let c = client(&format!("{}/andy/demo", h.base), work.path());
6521
    write(work.path(), "a.txt", "a\n");
6522
    c.snapshot("t").unwrap();
6523
    c.commit("a", &[]).unwrap();
6524
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6525
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/issues", Some("site"), Some(r#"{"title":"Broken"}"#.into())).await;
6526
    assert!(st.is_success(), "{st} {body}");
6527
    let repo = format!("repo:{}", row.id);
6528
    let (_, issue) = call(&h.app, "GET", "/andy/demo/issue/1", None, None).await;
6529
    assert!(issue.contains(&format!("data-live=\"{repo}/issue:1 {repo}\" data-fragment=\"timeline\"")), "the issue's timeline");
6530
    let (_, overview) = call(&h.app, "GET", "/andy/demo", None, None).await;
6531
    assert!(overview.contains(&format!("data-live=\"{repo}\" data-fragment=\"latest\"")), "the latest change");
6532
    assert!(overview.contains(&format!("data-live=\"{repo}\" data-fragment=\"bookmarks\"")), "the bookmarks");
6533
    let (_, diffusion) = call(&h.app, "GET", "/andy/demo/diffusion", None, None).await;
6534
    assert!(diffusion.contains(&format!("data-live=\"diffusion:{} {repo}\" data-fragment=\"diffusion\"", row.id)), "the Diffusion tab");
6535
}
6536
3eb491e9 Andy McCall ↶ 6537
/// Keyless step 4c (oxygenhub#241): when a key the hub certified moves a
6538
/// bookmark, the hub signs when it accepted the update and serves that
6539
/// with the bookmark, so a fetch checks the certificate at the hub's time
6540
/// rather than the time the key claimed.
6541
#[tokio::test(flavor = "multi_thread")]
6542
async fn the_hub_countersigns_an_update_by_a_key_it_certified() {
6543
    use oxy_core::attest::AttestBody;
6544
    use oxy_core::cert::{Certificate, SignedCertificate};
6545
    use oxy_core::identity::Scope;
6546
    use oxy_core::repo::IdentityScope;
6547
    let h = hub().await;
6548
    create(&h.app, "andy", "demo").await;
6549
    let url = format!("{}/andy/demo", h.base);
6550
    let work = tempfile::tempdir().unwrap();
6551
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
6552
    a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
6553
    write(&work.path().join("a"), "a.txt", "a\n");
6554
    a.commit("a", &[]).unwrap();
6555
    a.policy_init().unwrap();
6556
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6557
    let hub_id = h.app.hub_key.identity.clone();
6558
    a.policy_grant_subject("agent:claude@andy", hub_id.clone(), Scope::CHANGES | Scope::REFS, None).unwrap();
6559
    assert!(a.push("origin", false).unwrap().iter().any(|r| r.name == "policy" && r.ok));
6560
6561
    // An agent whose fresh key the hub certified pushes.
6562
    let mut b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(work.path().join("home-b"));
6563
    b.config.set("remote.origin.token", "site").unwrap();
6564
    b.save_config().unwrap();
6565
    let (_, key) = b.create_identity("claude", "[email protected]", IdentityScope::User).unwrap();
6566
    let (_, secret) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
6567
    let now = db::now_ms() as u64;
6568
    let cert = SignedCertificate::sign(
6569
        Certificate {
6570
            key,
6571
            issuer: hub_id.hash(),
6572
            subject: "agent:claude@andy".into(),
6573
            claims: vec![],
6574
            scope: Scope::CHANGES | Scope::REFS,
6575
            not_before: now - 60_000,
6576
            expires: now + 600_000,
8aa5ef38 Andy McCall ↶ 6577
            grant: None,
3eb491e9 Andy McCall ↶ 6578
        },
6579
        &hub_id,
6580
        &secret,
6581
    );
6582
    b.store().put_identity(&hub_id).unwrap();
6583
    b.store().put_certificate(&cert).unwrap();
6584
    write(&work.path().join("b"), "b.txt", "agent work\n");
6585
    b.commit("work", &[]).unwrap();
6586
    let r = b.push("origin", false).unwrap();
6587
    assert!(r.iter().all(|x| x.ok), "{r:?}");
6588
6589
    // The hub serves its acceptance of that update, signed by its key.
6590
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
6591
    let main = refs.refs.iter().find(|r| r.name == "main").unwrap();
6592
    let (attest, acc) = (main.attestation.clone().unwrap(), main.accepted.clone().expect("an acceptance"));
6593
    assert!(matches!(acc.attest.body, AttestBody::Accepted { attest: r } if r == attest.attest.hash()));
6594
    assert_eq!(acc.sigs[0].key, hub_id.hash());
6595
    assert!(acc.attest.hlc.wall_ms >= now);
6596
    // An update signed by a long-lived key gets none.
6597
    a.pull("origin").unwrap();
6598
    write(&work.path().join("a"), "a.txt", "again\n");
6599
    a.commit("again", &[]).unwrap();
6600
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6601
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
6602
    assert!(refs.refs.iter().find(|r| r.name == "main").unwrap().accepted.is_none());
6603
}
8aa5ef38 Andy McCall ↶ 6604
b5c199bd Andy McCall ↶ 6605
/// A keyless agent's release tag (oxygen#129): a key the hub certified
6606
/// creates a tag and pushes it under the policy's subject grant; the hub
6607
/// accepts it, countersigns when, logs both and serves them with the tag,
6608
/// and a fresh clone fetches it at the hub's time rather than the tag's.
6609
#[tokio::test(flavor = "multi_thread")]
6610
async fn a_tag_by_a_key_the_hub_certified_is_accepted_and_fetched() {
6611
    use oxy_core::attest::AttestBody;
6612
    use oxy_core::cert::{Certificate, SignedCertificate};
6613
    use oxy_core::identity::Scope;
6614
    use oxy_core::repo::IdentityScope;
6615
    use oxy_core::tlog::Entry;
6616
    let h = hub().await;
6617
    create(&h.app, "andy", "demo").await;
6618
    let url = format!("{}/andy/demo", h.base);
6619
    let work = tempfile::tempdir().unwrap();
6620
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
6621
    a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
6622
    write(&work.path().join("a"), "a.txt", "a\n");
6623
    a.commit("a", &[]).unwrap();
6624
    a.policy_init().unwrap();
6625
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6626
    let hub_id = h.app.hub_key.identity.clone();
6627
    a.policy_grant_subject("agent:claude@andy", hub_id.clone(), Scope::CHANGES | Scope::REFS, None).unwrap();
6628
    assert!(a.push("origin", false).unwrap().iter().any(|r| r.name == "policy" && r.ok));
6629
6630
    // An agent whose fresh key the hub certified tags what it fetched.
6631
    let mut b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(work.path().join("home-b"));
6632
    b.config.set("remote.origin.token", "site").unwrap();
6633
    b.save_config().unwrap();
6634
    let (_, key) = b.create_identity("claude", "[email protected]", IdentityScope::User).unwrap();
6635
    let (_, secret) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
6636
    let now = db::now_ms() as u64;
6637
    let cert = SignedCertificate::sign(
6638
        Certificate {
6639
            key,
6640
            issuer: hub_id.hash(),
6641
            subject: "agent:claude@andy".into(),
6642
            claims: vec![],
6643
            scope: Scope::CHANGES | Scope::REFS,
6644
            not_before: now - 60_000,
6645
            expires: now + 600_000,
6646
            grant: None,
6647
        },
6648
        &hub_id,
6649
        &secret,
6650
    );
6651
    b.store().put_identity(&hub_id).unwrap();
6652
    b.store().put_certificate(&cert).unwrap();
6653
    let heads = b.bookmark_heads().unwrap();
6654
    b.tag_create("v0.2.0", &heads, "OxygenFlow 0.2.0").unwrap();
6655
    let r = b.push("origin", false).unwrap();
6656
    assert!(r.iter().any(|x| x.name == "tags/v0.2.0" && x.ok), "{r:?}");
6657
6658
    // The hub serves its acceptance of the tag, signed by its key, and
6659
    // logs both.
6660
    h.app.tlog.refresh_checkpoint(&hub_id, &secret).unwrap();
6661
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
6662
    let tag = refs.tags.iter().find(|t| t.name == "v0.2.0").expect("the tag");
6663
    let (attest, acc) = (tag.attestation.clone().unwrap(), tag.accepted.clone().expect("an acceptance"));
6664
    assert!(matches!(acc.attest.body, AttestBody::Accepted { attest: r } if r == attest.attest.hash()));
6665
    assert_eq!(acc.sigs[0].key, hub_id.hash());
6666
    assert!(acc.attest.hlc.wall_ms >= now);
6667
    let logged = tag.logged.as_ref().expect("the tag's place in the log");
6668
    let entry = Entry::decode(&logged.entry).unwrap();
6669
    assert_eq!((entry.kind.as_str(), entry.object), ("tag", attest.attest.hash()));
6670
    let logged_acceptance = db::tlog::entry_of(&h.app.db, &acc.attest.hash().to_hex(), "accepted").await.unwrap();
6671
    assert!(logged_acceptance.is_some(), "the acceptance is logged too");
6672
6673
    // A fresh clone takes the tag at the hub's time.
6674
    let c = Repo::clone(&url, &work.path().join("c")).unwrap().with_home(work.path().join("home-c"));
6675
    assert_eq!(c.tag_heads("v0.2.0").unwrap(), Some(heads));
6676
    let report = c.fetch("origin").unwrap();
6677
    assert!(report.skipped.is_empty(), "{:?}", report.skipped);
6678
    // Andy's checkout too, the tag signed by the agent's key.
6679
    a.pull("origin").unwrap();
6680
    let t = a.tags().unwrap().into_iter().find(|t| t.name == "v0.2.0").expect("pulled");
6681
    assert_eq!(t.signer.as_deref(), Some("claude"));
a0a1601e Andy McCall ↶ 6682
6683
    // oxy 0.5.0 and older, which send no `Oxy-Features`, refuse a tag only a
6684
    // certificate authorizes and, with it, the whole clone (oxygen#131): the
6685
    // hub leaves it out of their refs answer, and Andy's own tag in.
6686
    a.tag_create("v0.1.0", &a.bookmark_heads().unwrap(), "by Andy").unwrap();
6687
    assert!(a.push("origin", false).unwrap().iter().any(|r| r.name == "tags/v0.1.0" && r.ok));
6688
    let bare = oxy_core::protocol::http_get(&format!("{url}/oxy/v1/refs"), &RemoteOptions::default()).unwrap();
6689
    let (_, old) = oxy_core::protocol::wire::decode_refs(&bare).unwrap();
6690
    let names: Vec<String> = old.tags.into_iter().map(|t| t.name).collect();
6691
    assert_eq!(names, ["v0.1.0"], "no Oxy-Features header");
6692
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
6693
    let mut names: Vec<String> = refs.tags.into_iter().map(|t| t.name).collect();
6694
    names.sort();
6695
    assert_eq!(names, ["v0.1.0", "v0.2.0"], "a current client declares certified-tags");
b5c199bd Andy McCall ↶ 6696
}
6697
8aa5ef38 Andy McCall ↶ 6698
/// Keyless step 5 (oxygenhub#241): Andy grants an agent with his own key;
6699
/// the agent, holding only the grant token, commits and pushes in Andy's
6700
/// name with fresh keys the hub certifies under the grant. A grant by a
6701
/// key not linked to the account, or for another account's agent, is
6702
/// refused; a revoked grant certifies no more.
6703
#[tokio::test(flavor = "multi_thread")]
6704
async fn an_agent_with_a_grant_pushes_in_its_owner_s_name() {
6705
    use oxy_core::cert::{Grant, SignedGrant};
6706
    use oxy_core::identity::{Identity, Scope, SecretKey};
6707
    use oxy_core::repo::{IdentityScope, SignatureStatus};
6708
    let h = hub().await;
6709
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
6710
    let (pat, pat_hash) = oxygenhub::auth::new_token();
6711
    db::accounts::create_token(&h.app.db, andy.id, "cli", &pat_hash, "repo:write", "", None).await.unwrap();
6712
    create(&h.app, "andy", "demo").await;
6713
    let url = format!("{}/andy/demo", h.base);
6714
    let work = tempfile::tempdir().unwrap();
6715
    // Andy's checkout, its policy granting the agent's subject.
6716
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
6717
    let (andy_key, andy_id) = a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
6718
    db::accounts::link_identity(&h.app.db, andy.id, &andy_key.to_hex(), "Andy", "[email protected]", &andy_id.encode()).await.unwrap();
6719
    write(&work.path().join("a"), "a.txt", "a\n");
6720
    a.commit("a", &[]).unwrap();
6721
    a.policy_init().unwrap();
6722
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6723
    let hub_id = h.app.hub_key.identity.clone();
6724
    a.policy_grant_subject("agent:claude@andy", hub_id.clone(), Scope::CHANGES | Scope::REFS, None).unwrap();
6725
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6726
6727
    // Andy grants the agent, as `oh agent grant claude` does.
6728
    let (_, andy_sk) = a.secret_key().unwrap().unwrap();
6729
    let now = db::now_ms() as u64;
6730
    let grant = |by: &Identity, sk: &SecretKey, subject: &str| {
6731
        SignedGrant::sign(
6732
            Grant {
6733
                grantor: by.hash(),
6734
                subject: subject.into(),
6735
                issuer: hub_id.hash(),
6736
                scope: Scope::CHANGES | Scope::SEAL | Scope::REFS,
6737
                not_before: now - 60_000,
6738
                expires: now + 86_400_000,
6739
            },
6740
            by,
6741
            sk,
6742
        )
6743
    };
6744
    let post = |g: SignedGrant| {
6745
        let (app, pat) = (h.app.clone(), pat.clone());
6746
        let body = serde_json::json!({ "grant": oxy_core::dsse::base64(&g.encode()) }).to_string();
6747
        async move { call(&app, "POST", "/api/v1/agents/grants", Some(&pat), Some(body)).await }
6748
    };
6749
    let stray_sk = SecretKey::generate();
6750
    let stray = stray_sk.identity("stray", "[email protected]", 1);
6751
    let (st, body) = post(grant(&stray, &stray_sk, "agent:claude@andy")).await;
6752
    assert_eq!(st, StatusCode::FORBIDDEN, "a key not linked to the account: {body}");
6753
    let (st, body) = post(grant(&andy_id, &andy_sk, "agent:claude@mallory")).await;
6754
    assert_eq!(st, StatusCode::BAD_REQUEST, "another account's agent: {body}");
6755
    let (st, body) = post(grant(&andy_id, &andy_sk, "agent:claude@andy")).await;
6756
    assert_eq!(st, StatusCode::CREATED, "{body}");
6757
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
6758
    let token = v["token"].as_str().unwrap().to_string();
6759
    assert!(token.starts_with("oxyagent_"));
6760
    let grant_id = v["id"].as_i64().unwrap();
205d8f86 Andy McCall ↶ 6761
    // The grant token works for the API too, as its owner's agent
6762
    // (#253), but cannot manage grants.
6763
    let (st, me) = call(&h.app, "GET", "/api/v1/user", Some(&token), None).await;
6764
    assert!(st == StatusCode::OK && me.contains("\"andy\""), "{st} {me}");
6765
    let (st, _) = call(&h.app, "GET", "/api/v1/agents/grants", Some(&token), None).await;
6766
    assert_eq!(st, StatusCode::FORBIDDEN, "an agent does not manage grants");
d4a0043f Andy McCall ↶ 6767
    // What the agent does through the API is told to its owner, as an
6768
    // agent token's is (#183).
6769
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
6770
    db::notify::set_watch(&h.app.db, andy.id, repo.id, true).await.unwrap();
6771
    let body = serde_json::json!({ "title": "Filed by the agent", "body": "" }).to_string();
6772
    let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/demo/issues", Some(&token), Some(body)).await;
6773
    assert_eq!(st, StatusCode::CREATED, "{out}");
6774
    let actor: String = sqlx::query_scalar("SELECT actor FROM notifications WHERE account_id = $1 AND title LIKE '%Filed by the agent%'")
6775
        .bind(andy.id)
6776
        .fetch_one(&h.app.db)
6777
        .await
6778
        .expect("told of the agent's issue");
6779
    assert!(actor.starts_with("andy (agent token "), "{actor}");
8aa5ef38 Andy McCall ↶ 6780
6781
    // The agent: a home holding only the grant token, Andy the author.
6782
    let agent_home = work.path().join("home-claude");
6783
    oxy_core::credentials::Credentials::at(&agent_home).save_grant(&h.base, &token).unwrap();
6784
    let agent = || {
6785
        let n = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
6786
        let dir = work.path().join(format!("claude-{n}"));
6787
        let mut r = Repo::clone(&url, &dir).unwrap().with_home(agent_home.clone());
559c3920 Andy McCall ↶ 6788
        // The grant token is its only credential: it pushes with it too.
6789
        r.config.set("remote.origin.token", &token).unwrap();
8aa5ef38 Andy McCall ↶ 6790
        r.save_config().unwrap();
6791
        r.set_user_config("author.key", &andy_key.to_hex()).unwrap();
6792
        r.set_user_config("author.signer", "keyless").unwrap();
6793
        (r, dir)
6794
    };
6795
    let (claude, dir) = agent();
6796
    assert!(!agent_home.join("keys").exists(), "no key on disk");
6797
    write(&dir, "work.txt", "agent work\n");
6798
    let change = claude.commit("Agent work", &[]).unwrap();
6799
    let r = claude.push("origin", false).unwrap();
6800
    assert!(r.iter().all(|x| x.ok), "{r:?}");
6801
    let signer = claude.signing_key().expect("a certified key");
6802
    assert_ne!(signer, andy_key);
6803
    assert!(!agent_home.join("keys").exists(), "still no key on disk");
6804
6805
    // The hub holds it in Andy's name, sealed by the certified key, and
6806
    // countersigned when it accepted the update.
6807
    let host = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
6808
    assert_eq!(host.store().get_change_meta(&change).unwrap().author, andy_key);
6809
    assert!(matches!(
6810
        host.authenticate_change(&change).unwrap(),
6811
        SignatureStatus::Valid { key, sealed: true, .. } if key == signer
6812
    ));
6813
    let refs = open_remote(&url, &RemoteOptions::default()).unwrap().refs().unwrap();
6814
    assert!(refs.refs.iter().find(|r| r.name == "main").unwrap().accepted.is_some());
6815
    a.pull("origin").unwrap();
6816
    assert!(matches!(a.authenticate_change(&change).unwrap(), SignatureStatus::Valid { .. }));
6817
a66c05a6 Andy McCall ↶ 6818
    // oxygen#134: in a repository that has never seen Andy's identity, the
6819
    // agent's change still verifies, locally and on the hub: the grant's
6820
    // signer comes with the certificate and travels with the push.
6821
    create(&h.app, "andy", "fresh").await;
6822
    let fresh_url = format!("{}/andy/fresh", h.base);
6823
    let fresh_dir = work.path().join("claude-fresh");
6824
    let mut fresh = client(&fresh_url, &fresh_dir).with_home(agent_home.clone());
6825
    fresh.config.set("remote.origin.token", &token).unwrap();
6826
    fresh.save_config().unwrap();
6827
    fresh.set_user_config("author.key", &andy_key.to_hex()).unwrap();
6828
    fresh.set_user_config("author.signer", "keyless").unwrap();
6829
    assert!(fresh.store().get_identity(&andy_key).is_err(), "the fresh repository has never seen Andy");
6830
    write(&fresh_dir, "first.txt", "first\n");
6831
    let first = fresh.commit("First, by the agent", &[]).unwrap();
6832
    let r = fresh.push("origin", false).unwrap();
6833
    assert!(r.iter().all(|x| x.ok), "{r:?}");
6834
    assert!(matches!(fresh.authenticate_change(&first).unwrap(), SignatureStatus::Valid { .. }), "locally");
6835
    let fresh_host = h.app.repos.open(&RepoName::parse("andy/fresh").unwrap()).unwrap();
6836
    assert!(
6837
        matches!(fresh_host.authenticate_change(&first).unwrap(), SignatureStatus::Valid { sealed: true, .. }),
6838
        "on the hub: {:?}",
6839
        fresh_host.authenticate_change(&first).unwrap()
6840
    );
6841
27babfa1 Andy McCall ↶ 6842
    // oxygen#82: Andy rotates. A home with `author.for` follows his newest
6843
    // identity, which the hub names with each certificate, and its changes
6844
    // still verify by the grant his earlier key made.
6845
    let rot = a.rotate_identity().unwrap();
6846
    db::accounts::link_identity(&h.app.db, andy.id, &rot.new.to_hex(), "Andy", "[email protected]", &rot.identity.encode()).await.unwrap();
6847
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
6848
    let (mut warm, dir) = agent();
6849
    warm.set_user_config("author.for", "andy").unwrap();
6850
    write(&dir, "warm.txt", "before the hub has said\n");
6851
    warm.commit("Warm", &[]).unwrap();
6852
    assert!(warm.push("origin", false).unwrap().iter().all(|r| r.ok));
6853
    let followed = std::fs::read_to_string(agent_home.join("keys").join("author.for")).unwrap();
6854
    assert_eq!(followed.trim(), rot.new.to_hex(), "the hub named Andy's newest identity");
6855
    let (follower, dir) = agent();
6856
    assert_eq!(follower.config.author_key, Some(rot.new));
6857
    write(&dir, "follow.txt", "as Andy's newest identity\n");
6858
    let followed = follower.commit("Followed", &[]).unwrap();
6859
    assert!(follower.push("origin", false).unwrap().iter().all(|r| r.ok));
6860
    assert_eq!(host.store().get_change_meta(&followed).unwrap().author, rot.new);
6861
    assert!(
6862
        matches!(host.authenticate_change(&followed).unwrap(), SignatureStatus::Valid { sealed: true, .. }),
6863
        "{:?}",
6864
        host.authenticate_change(&followed).unwrap()
6865
    );
6866
8aa5ef38 Andy McCall ↶ 6867
    // Revoked: the next command gets no certificate.
6868
    let (st, _) = call(&h.app, "DELETE", &format!("/api/v1/agents/grants/{grant_id}"), Some(&pat), None).await;
6869
    assert_eq!(st, StatusCode::NO_CONTENT);
6870
    let (late, dir) = agent();
6871
    write(&dir, "late.txt", "after the revocation\n");
6872
    late.commit("Late", &[]).unwrap();
6873
    let err = late.push("origin", false).unwrap_err().to_string();
559c3920 Andy McCall ↶ 6874
    assert!(err.contains("not valid") || err.contains("would not certify"), "{err}");
6875
    // The hub recorded the push as the agent's, for its owner.
6876
    let by_agent: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM pushes WHERE via = 'claude'").fetch_one(&h.app.db).await.unwrap();
6877
    assert!(by_agent >= 1, "recorded as via the agent");
8aa5ef38 Andy McCall ↶ 6878
    let (_, body) = call(&h.app, "GET", "/api/v1/agents/grants", Some(&pat), None).await;
6879
    let list: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
6880
    assert!(list[0]["revoked_ms"].is_i64() && list[0].get("token").is_none(), "{body}");
6881
}
a9f1c0bf Andy McCall ↶ 6882
6883
/// oxygenhub#267, newest run wins: a proposal's new run supersedes its
6884
/// older runs still live, as a push run does its bookmark's; a repository
6885
/// that keeps running runs has only the queued ones cancelled; manual
6886
/// runs and reruns supersede nothing and nothing supersedes them.
6887
#[tokio::test(flavor = "multi_thread")]
6888
async fn newest_run_wins() {
6889
    use oxy_core::hash::ChangeHash;
6890
    let h = hub().await;
6891
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
6892
    create(&h.app, "andy", "newest").await;
6893
    let url = format!("{}/andy/newest", h.base);
6894
    let work = tempfile::tempdir().unwrap();
6895
    let c = client(&url, work.path());
6896
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
6897
    write(work.path(), "test.sh", "echo ok\n");
6898
    c.commit("Start", &[]).unwrap();
6899
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
6900
    let pushed = runs_of(&h.app, "andy", "newest").await[0].clone();
6901
    assert_eq!((pushed.number, pushed.trigger.as_str()), (1, "push"));
6902
    let heads: Vec<ChangeHash> = pushed.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
6903
    let start = |row: db::repos::RepoRow, bookmark: &'static str, trigger: &'static str| {
6904
        let (app, state, heads) = (h.app.clone(), pushed.state.clone(), heads.clone());
6905
        async move {
6906
            oxygenhub::flow::start_run_scoped(&app, &row, bookmark, &state, &heads, "andy", trigger, None).await.unwrap().expect("a run")
6907
        }
6908
    };
6909
    let row = db::repos::get(&h.app.db, "andy", "newest").await.unwrap().unwrap();
6910
    let run = |n: i64| {
6911
        let (app, id) = (h.app.clone(), row.id);
6912
        async move { db::flow::run(&app.db, id, n).await.unwrap().unwrap() }
6913
    };
6914
    let superseded_by = |n: i64, by: i64| {
6915
        let app = h.app.clone();
6916
        let run = run(n);
6917
        async move {
6918
            let r = run.await;
6919
            assert_eq!(r.status, "cancelled", "run #{n} is superseded");
6920
            let jobs = db::flow::jobs(&app.db, r.id).await.unwrap();
6921
            let why = format!("superseded by run #{by}");
6922
            assert!(jobs.iter().all(|j| j.status == "cancelled" && j.error == why), "{jobs:?}");
6923
        }
6924
    };
6925
6926
    // A proposal's new run supersedes its older one, not another
6927
    // proposal's, nor the push run of a bookmark.
6928
    assert_eq!(start(row.clone(), "proposal/7", "proposal").await, 2);
6929
    assert_eq!(start(row.clone(), "proposal/7", "proposal").await, 3);
6930
    superseded_by(2, 3).await;
6931
    assert_eq!(start(row.clone(), "proposal/8", "proposal").await, 4);
6932
    assert!(run(3).await.live(), "another proposal's run is not superseded");
6933
    assert!(run(1).await.live(), "a proposal's run leaves push runs alone");
6934
6935
    // Manual runs and reruns supersede nothing, and a push supersedes
6936
    // only push runs.
6937
    assert_eq!(start(row.clone(), "main", "manual").await, 5);
6938
    assert_eq!(start(row.clone(), "main", "rerun:1:push").await, 6);
6939
    assert!(run(1).await.live(), "a manual run or a rerun supersedes nothing");
6940
    assert_eq!(start(row.clone(), "main", "push").await, 7);
6941
    superseded_by(1, 7).await;
6942
    assert!(run(5).await.live() && run(6).await.live(), "a push leaves manual runs and reruns alone");
6943
6944
    // Kept running: a superseded run already running finishes; queued
6945
    // ones are still cancelled.
6946
    db::repos::set_flow_keep_running(&h.app.db, row.id, true).await.unwrap();
6947
    let kept = db::repos::get(&h.app.db, "andy", "newest").await.unwrap().unwrap();
6948
    assert!(kept.flow_keep_running);
6949
    let three = run(3).await;
6950
    sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = $1").bind(three.id).execute(&h.app.db).await.unwrap();
6951
    sqlx::query("UPDATE flow_jobs SET status = 'running' WHERE run_id = $1 AND name = 'build'")
6952
        .bind(three.id)
6953
        .execute(&h.app.db)
6954
        .await
6955
        .unwrap();
6956
    assert_eq!(start(kept.clone(), "proposal/7", "proposal").await, 8);
6957
    assert_eq!(start(kept.clone(), "proposal/7", "proposal").await, 9);
6958
    assert_eq!(run(3).await.status, "running", "a running run is kept");
6959
    superseded_by(8, 9).await;
6960
    // The default again: running runs are cancelled too.
6961
    db::repos::set_flow_keep_running(&h.app.db, row.id, false).await.unwrap();
6962
    let row = db::repos::get(&h.app.db, "andy", "newest").await.unwrap().unwrap();
6963
    assert_eq!(start(row.clone(), "proposal/7", "proposal").await, 10);
6964
    superseded_by(3, 10).await;
6965
    superseded_by(9, 10).await;
50928fab Andy McCall ↶ 6966
6967
    // The default bookmark's push runs already running finish whatever the
6968
    // setting (#369): a release is cut from them. Queued ones still go.
6969
    assert_eq!(row.default_bookmark, "main");
6970
    let eleven = start(row.clone(), "main", "push").await;
6971
    superseded_by(7, eleven).await;
6972
    let running = run(eleven).await;
6973
    sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = $1").bind(running.id).execute(&h.app.db).await.unwrap();
6974
    let twelve = start(row.clone(), "main", "push").await;
6975
    assert_eq!(run(eleven).await.status, "running", "main's running push run is kept");
6976
    let thirteen = start(row.clone(), "main", "push").await;
6977
    superseded_by(twelve, thirteen).await;
6978
    // Another bookmark's running push run is still superseded.
6979
    let other = start(row.clone(), "feature", "push").await;
6980
    let r = run(other).await;
6981
    sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = $1").bind(r.id).execute(&h.app.db).await.unwrap();
6982
    let next = start(row.clone(), "feature", "push").await;
6983
    superseded_by(other, next).await;
a9f1c0bf Andy McCall ↶ 6984
}
8501fd58 Andy McCall ↶ 6985
6986
/// oxygenhub#322: runners are offered the build their nearest update
6987
/// setting asks for, off unless some level turns it on; a test group of
6988
/// chosen runners tries it first.
6989
#[tokio::test(flavor = "multi_thread")]
6990
async fn runners_are_offered_updates_by_their_nearest_setting() {
6991
    use oxy_core::identity::SecretKey;
6992
    let h = hub().await;
6993
    create(&h.app, "andy", "oxygenflow").await;
6994
    let res = oxygenhub::router(h.app.clone())
6995
        .oneshot(
6996
            Request::post("/register")
6997
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
6998
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
6999
                .unwrap(),
7000
        )
7001
        .await
7002
        .unwrap();
7003
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
7004
    let admin = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
7005
    db::accounts::set_admin(&h.app.db, admin.id, true).await.unwrap();
7006
    let web = |method: &'static str, path: &str, body: Option<String>| {
7007
        let (app, cookie, path) = (h.app.clone(), cookie.clone(), path.to_string());
7008
        async move {
7009
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
7010
            if body.is_some() {
7011
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
7012
            }
7013
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
7014
            let st = res.status();
7015
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
7016
        }
7017
    };
7018
    let (st, page) = web("GET", "/admin/runners/updates", None).await;
7019
    assert_eq!(st, StatusCode::OK, "{page}");
7020
    let csrf = {
7021
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
7022
        page[i..].split('"').next().unwrap().to_string()
7023
    };
7024
    assert_eq!(call(&h.app, "GET", "/admin/runners/updates", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
7025
    let mut creds = vec![];
7026
    for name in ["plex", "narvi"] {
7027
        let (_, page) = web("POST", "/admin/runners/token", Some(format!("_csrf={csrf}"))).await;
7028
        let i = page.find("--token ").unwrap() + "--token ".len();
7029
        let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
7030
        let identity = SecretKey::generate().identity(&format!("{name} (OxygenFlow runner)"), "", 1);
7031
        let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0 (build)", "max_jobs": 1 });
7032
        let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
7033
        let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
7034
        assert_eq!(st, StatusCode::OK, "{body}");
7035
        creds.push(serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string());
7036
    }
7037
    let ask = |who: usize| {
7038
        let (app, cred) = (h.app.clone(), creds[who].clone());
7039
        async move {
7040
            let (st, body) = call(&app, "GET", "/api/v1/flow/runner/update", Some(&cred), None).await;
7041
            assert_eq!(st, StatusCode::OK, "{body}");
7042
            serde_json::from_str::<flow_core::api::UpdateAnswer>(&body).unwrap()
7043
        }
7044
    };
7045
    let a = ask(0).await;
7046
    assert!(!a.policy.updates && a.offer.is_none(), "off unless chosen: {a:?}");
7047
    assert_eq!(a.note, "updates are off (default)");
7048
    assert_eq!(call(&h.app, "GET", "/api/v1/flow/runner/update", Some("flowrunner_nope"), None).await.0, StatusCode::UNAUTHORIZED);
7049
7050
    // A release of builds, and the site taking them from it.
7051
    let repo = db::repos::get(&h.app.db, "andy", "oxygenflow").await.unwrap().unwrap();
7052
    let rel = db::releases::create(&h.app.db, repo.id, "v0.2.0", "0.2.0", "", false, None).await.unwrap();
c26267b3 Andy McCall ↶ 7053
    let build: Vec<u8> = (0..300_000u32).map(|i| (i.wrapping_mul(2654435761) >> 13) as u8).collect();
7054
    let build_hash = blake3::hash(&build).to_hex().to_string();
7055
    let at = h.app.config.data.join("assets").join(&build_hash[..2]);
7056
    std::fs::create_dir_all(&at).unwrap();
7057
    std::fs::write(at.join(&build_hash), &build).unwrap();
7058
    db::releases::add_asset(&h.app.db, rel.id, "flow-linux-x86_64", build.len() as i64, &build_hash, "application/octet-stream")
7059
        .await
7060
        .unwrap();
8501fd58 Andy McCall ↶ 7061
    let (_, page) = web("POST", "/admin/runners/updates/source", Some(format!("_csrf={csrf}&repo=andy%2Fnope"))).await;
7062
    assert!(page.contains("There is no repository"), "{page}");
7063
    let (_, page) = web("POST", "/admin/runners/updates/source", Some(format!("_csrf={csrf}&repo=andy%2Foxygenflow"))).await;
7064
    assert!(page.contains("runner builds come from andy/oxygenflow"), "{page}");
7065
7066
    // A test group of one chosen runner, with updates on: plex, not narvi.
7067
    let plex = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
7068
    let (_, page) =
7069
        web("POST", "/admin/runners/updates/groups", Some(format!("_csrf={csrf}&name=canary&mode=chosen&runner={}", plex.id))).await;
7070
    assert!(page.contains("Test group canary made: 1 chosen runners"), "{page}");
7071
    let group = db::runner_updates::groups(&h.app.db).await.unwrap().remove(0);
7072
    let (_, page) =
7073
        web("POST", "/admin/runners/updates/policy", Some(format!("_csrf={csrf}&scope=group&key={}&updates=on", group.id))).await;
7074
    assert!(page.contains("Saved for group canary: updates on."), "{page}");
7075
    let a = ask(0).await;
7076
    let offer = a.offer.clone().expect("plex is offered the build");
7077
    assert_eq!((offer.version.as_str(), offer.asset.as_str(), offer.blake3.len()), ("0.2.0", "flow-linux-x86_64", 64));
7078
    assert!(offer.url.starts_with("/andy/oxygenflow/asset/") && !offer.older, "{offer:?}");
7079
    assert_eq!(a.policy.from[0], "group canary");
7080
    assert!(ask(1).await.offer.is_none(), "narvi is not in the group");
c26267b3 Andy McCall ↶ 7081
    // Offered, the build is shared with the swarm (oxygenflow#84): an image
7082
    // named by its BLAKE3 whose chunks make it, for runners to fetch.
7083
    let mut shared = None;
7084
    for _ in 0..100 {
7085
        shared = h.app.images().manifest(&build_hash);
7086
        if shared.is_some() {
7087
            break;
7088
        }
7089
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
7090
    }
7091
    let m = shared.expect("the build is shared with the swarm");
7092
    assert_eq!((m.size, m.arch.as_deref()), (build.len() as u64, Some("x86_64")));
7093
    let mut whole = vec![];
7094
    for c in &m.chunks {
7095
        whole.extend(h.app.images().chunk(c.hash()).unwrap());
7096
    }
7097
    assert_eq!(whole, build);
7098
    let kept = oxygenhub::images::kept(&h.app.db).await.unwrap();
7099
    assert!(kept.iter().any(|k| k.hash == build_hash && k.uploader == "runner build flow 0.2.0"));
8501fd58 Andy McCall ↶ 7100
7101
    // The site's dry run reaches plex; narvi's own setting pins its version.
7102
    let (_, page) = web("POST", "/admin/runners/updates/policy", Some(format!("_csrf={csrf}&scope=site&updates=off&dry_run=on"))).await;
7103
    assert!(page.contains("Saved for the site"), "{page}");
7104
    let a = ask(0).await;
7105
    assert!(a.policy.dry_run && a.policy.from[3] == "site" && a.note.contains("dry run"), "{a:?}");
7106
    let narvi = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "narvi").unwrap();
7107
    web("POST", "/admin/runners/updates/policy", Some(format!("_csrf={csrf}&scope=runner&key={}&updates=on&channel=0.1.0", narvi.id)))
7108
        .await;
7109
    let b = ask(1).await;
7110
    assert!(b.policy.updates && b.offer.is_none() && b.note.contains("has no release"), "{b:?}");
7111
7112
    // Outside its window it waits.
7113
    let now = time::OffsetDateTime::now_utc().hour();
7114
    let (from, to) = ((now + 2) % 24, (now + 4) % 24);
7115
    web(
7116
        "POST",
7117
        "/admin/runners/updates/policy",
7118
        Some(format!("_csrf={csrf}&scope=group&key={}&updates=on&window={from:02}-{to:02}", group.id)),
7119
    )
7120
    .await;
7121
    let a = ask(0).await;
7122
    assert!(a.offer.is_none() && a.note.contains("waits for its window"), "{a:?}");
7123
7124
    // Mistakes are refused, saying why.
7125
    let (_, page) = web("POST", "/admin/runners/updates/policy", Some(format!("_csrf={csrf}&scope=site&channel=latest"))).await;
7126
    assert!(page.contains("A channel is stable, canary or a version"), "{page}");
7127
    let (_, page) = web("POST", "/admin/runners/updates/policy", Some(format!("_csrf={csrf}&scope=site&window=9"))).await;
7128
    assert!(page.contains("a window is two hours"), "{page}");
7129
    let (_, page) = web("POST", "/admin/runners/updates/groups", Some(format!("_csrf={csrf}&name=farm&mode=percent&percent=0"))).await;
7130
    assert!(page.contains("A percentage is a whole number from 1 to 100."), "{page}");
7131
7132
    // What a runner says shows on the page and in the audit log.
7133
    let report = serde_json::json!({ "note": "dry run: flow 0.2.0 checks out" }).to_string();
7134
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runner/update", Some(&creds[0]), Some(report)).await.0, StatusCode::NO_CONTENT);
7135
    let (_, page) = web("GET", "/admin/runners/updates", None).await;
7136
    assert!(page.contains("dry run: flow 0.2.0 checks out") && page.contains(">canary</span>"), "{page}");
7137
    assert!(page.contains("updates on (group canary)") && page.contains("updates on (runner) · channel 0.1.0 (runner)"), "{page}");
7138
9bbca80f Andy McCall ↶ 7139
    // The same through the API (`oh runner-updates`), for administrators only.
7140
    let (_, tokens) = web("GET", "/settings/tokens", None).await;
7141
    let tcsrf = {
7142
        let i = tokens.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
7143
        tokens[i..].split('"').next().unwrap().to_string()
7144
    };
7145
    let (_, made) = web("POST", "/settings/tokens", Some(format!("_csrf={tcsrf}&name=admin&scopes=user%3Aread"))).await;
7146
    let i = made.find("oxyhub_").unwrap();
7147
    let admin_token: String = made[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
7148
    let (st, body) = call(&h.app, "GET", "/api/v1/admin/runner-updates", Some(&admin_token), None).await;
7149
    assert_eq!(st, StatusCode::OK, "{body}");
7150
    let all: hub_api::RunnerUpdates = serde_json::from_str(&body).unwrap();
7151
    assert_eq!(all.repo, "andy/oxygenflow");
7152
    assert!(all.settings.iter().any(|s| s.scope == "group" && s.updates == Some(true) && s.window.is_some()), "{all:?}");
7153
    let plex_row = all.runners.iter().find(|r| r.name == "plex").unwrap();
7154
    assert!(plex_row.updates && plex_row.from[0] == "group canary" && plex_row.groups == ["canary"], "{plex_row:?}");
7155
    let put = |body: serde_json::Value| {
7156
        let (app, t) = (h.app.clone(), admin_token.clone());
7157
        async move { call(&app, "PUT", "/api/v1/admin/runner-updates/settings", Some(&t), Some(body.to_string())).await }
7158
    };
7159
    let (st, body) =
7160
        put(serde_json::json!({ "scope": "runner", "key": narvi.id.to_string(), "updates": true, "channel": "0.1.0", "dry_run": true }))
7161
            .await;
7162
    assert_eq!(st, StatusCode::OK, "{body}");
7163
    assert!(body.contains("Saved for runner narvi: updates on, channel 0.1.0, dry run on."), "{body}");
7164
    let (st, body) = put(serde_json::json!({ "scope": "site", "channel": "latest" })).await;
7165
    assert_eq!(st, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
7166
    assert_eq!(
7167
        call(&h.app, "GET", "/api/v1/admin/runner-updates", Some(&creds[0]), None).await.0,
7168
        StatusCode::UNAUTHORIZED,
7169
        "not a runner's"
7170
    );
7171
faf5246c Andy McCall ↶ 7172
    // #326: a build that rolls back on one runner is held for every other.
7173
    let report = serde_json::json!({ "note": "rolled back from flow 0.2.0 to 0.1.0: 3 starts without reaching the hub" }).to_string();
7174
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runner/update", Some(&creds[0]), Some(report)).await.0, StatusCode::NO_CONTENT);
7175
    let a = ask(0).await;
7176
    assert!(a.offer.is_none() && a.note.contains("flow 0.2.0 is held: it rolled back on plex (3 starts"), "{a:?}");
7177
    let (_, page) = web("GET", "/admin/runners/updates", None).await;
7178
    assert!(page.contains("Held builds") && page.contains("<strong>flow 0.2.0</strong>"), "{page}");
9bbca80f Andy McCall ↶ 7179
    let (_, body) = call(&h.app, "GET", "/api/v1/admin/runner-updates", Some(&admin_token), None).await;
7180
    assert!(body.contains("\"version\":\"0.2.0\"") && body.contains("\"runner\":\"plex\""), "the hold through the API: {body}");
faf5246c Andy McCall ↶ 7181
    let (_, page) = web("POST", "/admin/runners/updates/holds/lift", Some(format!("_csrf={csrf}&version=0.2.0"))).await;
7182
    assert!(page.contains("flow 0.2.0 is offered again"), "{page}");
9bbca80f Andy McCall ↶ 7183
    let (st, _) = call(&h.app, "POST", "/api/v1/admin/runner-updates/holds/0.2.0/lift", Some(&admin_token), Some("{}".into())).await;
7184
    assert_eq!(st, StatusCode::NOT_FOUND, "no longer held");
faf5246c Andy McCall ↶ 7185
    assert!(ask(0).await.note.contains("waits for its window"), "lifted: back to what its settings say");
7186
    let (_, page) = web("POST", "/admin/runners/updates/holds/lift", Some(format!("_csrf={csrf}&version=0.2.0"))).await;
7187
    assert!(page.contains("flow 0.2.0 is not held."), "{page}");
7188
8501fd58 Andy McCall ↶ 7189
    // A group of a share: removed, its runners follow the levels above.
7190
    let (_, page) =
7191
        web("POST", &format!("/admin/runners/updates/groups/{}", group.id), Some(format!("_csrf={csrf}&mode=percent&percent=100"))).await;
7192
    assert!(page.contains("Test group canary is now 100% of its runners."), "{page}");
7193
    assert!(ask(1).await.policy.from[0] == "runner", "narvi's own setting is nearer than any group");
7194
    let (_, page) = web("POST", &format!("/admin/runners/updates/groups/{}/delete", group.id), Some(format!("_csrf={csrf}"))).await;
7195
    assert!(page.contains("Test group canary removed"), "{page}");
7196
    assert!(!ask(0).await.policy.updates, "back to the site's off");
2f79b17e Andy McCall ↶ 7197
7198
    // A phone's runner follows the app's releases, never a runner build
7199
    // (oxygenflow#84): with updates on, it is offered nothing and told why.
7200
    let (_, page) = web("POST", "/admin/runners/token", Some(format!("_csrf={csrf}"))).await;
7201
    let i = page.find("--token ").unwrap() + "--token ".len();
7202
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
7203
    let identity = SecretKey::generate().identity("phone (OxygenFlow runner)", "", 1);
7204
    let info = serde_json::json!({ "arch": "aarch64", "os": "android", "version": "0.1.0 (app)", "max_jobs": 1 });
7205
    let reg = serde_json::json!({ "token": token, "name": "phone", "identity": hex::encode(identity.encode()), "info": info });
7206
    let (_, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
7207
    let phone = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
7208
    web("POST", "/admin/runners/updates/policy", Some(format!("_csrf={csrf}&scope=site&updates=on"))).await;
7209
    let (st, body) = call(&h.app, "GET", "/api/v1/flow/runner/update", Some(&phone), None).await;
7210
    assert_eq!(st, StatusCode::OK, "{body}");
7211
    let a: flow_core::api::UpdateAnswer = serde_json::from_str(&body).unwrap();
7212
    assert!(a.offer.is_none() && a.note.contains("follows the OxygenHub app's releases"), "{a:?}");
8501fd58 Andy McCall ↶ 7213
}
d7050703 Andy McCall ↶ 7214
1ec29691 Andy McCall ↶ 7215
/// oxygenflow#84: a version reaches a later wave once every runner of the
7216
/// waves before it that took it has run its soak jobs on it; a job ending
7217
/// in error there stops it for every runner.
7218
#[tokio::test(flavor = "multi_thread")]
7219
async fn a_version_reaches_wave_two_once_wave_one_proves_it() {
7220
    use oxy_core::identity::SecretKey;
7221
    let h = hub().await;
7222
    create(&h.app, "andy", "oxygenflow").await;
7223
    let res = oxygenhub::router(h.app.clone())
7224
        .oneshot(
7225
            Request::post("/register")
7226
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
7227
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
7228
                .unwrap(),
7229
        )
7230
        .await
7231
        .unwrap();
7232
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
7233
    let admin = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
7234
    db::accounts::set_admin(&h.app.db, admin.id, true).await.unwrap();
7235
    let web = |method: &'static str, path: &str, body: Option<String>| {
7236
        let (app, cookie, path) = (h.app.clone(), cookie.clone(), path.to_string());
7237
        async move {
7238
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
7239
            if body.is_some() {
7240
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
7241
            }
7242
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
7243
            (res.status(), String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
7244
        }
7245
    };
7246
    let (_, page) = web("GET", "/admin/runners/updates", None).await;
7247
    let csrf = {
7248
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
7249
        page[i..].split('"').next().unwrap().to_string()
7250
    };
7251
    let mut creds = vec![];
7252
    for name in ["plex", "narvi"] {
7253
        let (_, page) = web("POST", "/admin/runners/token", Some(format!("_csrf={csrf}"))).await;
7254
        let i = page.find("--token ").unwrap() + "--token ".len();
7255
        let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
7256
        let identity = SecretKey::generate().identity(&format!("{name} (OxygenFlow runner)"), "", 1);
7257
        let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0 (build)", "max_jobs": 1 });
7258
        let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
7259
        let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
7260
        assert_eq!(st, StatusCode::OK, "{body}");
7261
        creds.push(serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string());
7262
    }
7263
    let ask = |who: usize| {
7264
        let (app, cred) = (h.app.clone(), creds[who].clone());
7265
        async move {
7266
            let (st, body) = call(&app, "GET", "/api/v1/flow/runner/update", Some(&cred), None).await;
7267
            assert_eq!(st, StatusCode::OK, "{body}");
7268
            serde_json::from_str::<flow_core::api::UpdateAnswer>(&body).unwrap()
7269
        }
7270
    };
7271
    let repo = db::repos::get(&h.app.db, "andy", "oxygenflow").await.unwrap().unwrap();
7272
    let rel = db::releases::create(&h.app.db, repo.id, "v0.2.0", "0.2.0", "", false, None).await.unwrap();
7273
    db::releases::add_asset(&h.app.db, rel.id, "flow-linux-x86_64", 42, &"ab".repeat(32), "application/octet-stream").await.unwrap();
7274
    let (_, page) =
7275
        web("POST", "/admin/runners/updates/source", Some(format!("_csrf={csrf}&repo=andy%2Foxygenflow&soak_jobs=2&soak_hours=48"))).await;
7276
    assert!(page.contains("runner builds come from andy/oxygenflow") && page.contains("value=\"2\""), "{page}");
7277
    let (_, page) = web("POST", "/admin/runners/updates/source", Some(format!("_csrf={csrf}&repo=andy%2Foxygenflow&soak_jobs=0"))).await;
7278
    assert!(page.contains("is a whole number from 1 to 1000"), "{page}");
7279
    web("POST", "/admin/runners/updates/policy", Some(format!("_csrf={csrf}&scope=site&updates=on"))).await;
7280
7281
    // plex in wave 1, narvi in wave 2.
7282
    let runners = db::runners::list(&h.app.db).await.unwrap();
7283
    let id = |name: &str| runners.iter().find(|r| r.name == name).unwrap().id;
7284
    let (_, page) =
7285
        web("POST", "/admin/runners/updates/groups", Some(format!("_csrf={csrf}&name=first&mode=chosen&runner={}&wave=1", id("plex"))))
7286
            .await;
7287
    assert!(page.contains("Test group first made: 1 chosen runners, wave 1") && page.contains(" · wave 1</small>"), "{page}");
7288
    let (_, page) =
7289
        web("POST", "/admin/runners/updates/groups", Some(format!("_csrf={csrf}&name=rest&mode=chosen&runner={}&wave=0", id("narvi"))))
7290
            .await;
7291
    assert!(page.contains("A wave is a whole number from 1 to 9"), "{page}");
7292
    web("POST", "/admin/runners/updates/groups", Some(format!("_csrf={csrf}&name=rest&mode=chosen&runner={}&wave=2", id("narvi")))).await;
7293
    assert_eq!(ask(0).await.offer.map(|o| o.version).as_deref(), Some("0.2.0"), "wave 1 goes first");
7294
    let b = ask(1).await;
7295
    assert!(b.offer.is_none() && b.note.contains("flow 0.2.0 waits for wave 1 to prove it: 0 of 1 runner on it, 0 jobs"), "{b:?}");
7296
7297
    // plex runs 0.2.0: one job is not enough, two are.
7298
    let run: i64 = sqlx::query_scalar(
7299
        "INSERT INTO flow_runs (repo_id, bookmark, state, heads, status, created_ms, number) VALUES ($1, 'main', 's', 'h', 'passed', 1, 1) RETURNING id",
7300
    )
7301
    .bind(repo.id)
7302
    .fetch_one(&h.app.db)
7303
    .await
7304
    .unwrap();
7305
    let job = |name: &'static str, status: &'static str| {
7306
        let (app, plex) = (h.app.clone(), id("plex"));
7307
        async move {
7308
            sqlx::query(
7309
                "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status, runner, runner_id, started_ms, finished_ms, error, runner_version)
7310
                 VALUES ($1, $2, 0, '', '{}', 'microvm', 'microvm', $3, 'plex', $4, $5, $5, $6, '0.2.0')",
7311
            )
7312
            .bind(run)
7313
            .bind(name)
7314
            .bind(status)
7315
            .bind(plex)
7316
            .bind(db::now_ms())
7317
            .bind(if status == "error" { "the runner lost its disk" } else { "" })
7318
            .execute(&app.db)
7319
            .await
7320
            .unwrap();
7321
        }
7322
    };
7323
    job("build", "passed").await;
7324
    assert!(ask(1).await.note.contains("1 of 1 runner on it, 1 job (each needs 2"), "still soaking");
7325
    job("test", "failed").await;
7326
    assert_eq!(ask(1).await.offer.map(|o| o.version).as_deref(), Some("0.2.0"), "a failed test is not the runner's fault: proved");
7327
    let (_, page) = web("GET", "/admin/runners/updates", None).await;
7328
    assert!(!page.contains("waits for wave"), "{page}");
7329
7330
    // An error on wave 1 stops it: the page only says so; the next runner to ask holds it for all.
7331
    job("lint", "error").await;
7332
    let (_, page) = web("GET", "/admin/runners/updates", None).await;
7333
    assert!(page.contains("wave 1 stopped it on plex: job lint of andy/oxygenflow run #1: the runner lost its disk"), "{page}");
7334
    assert!(db::runner_updates::held(&h.app.db, "0.2.0").await.unwrap().is_none(), "a page view holds nothing");
7335
    let b = ask(1).await;
7336
    assert!(b.offer.is_none() && b.note.contains("flow 0.2.0 is held: wave 1 stopped it on plex"), "{b:?}");
7337
    assert!(ask(0).await.note.contains("is held"), "wave 1 too");
7338
    let (_, page) = web("GET", "/admin/runners/updates", None).await;
7339
    assert!(page.contains("Held builds") && page.contains("wave 1 stopped it on plex"), "{page}");
7340
}
7341
d7050703 Andy McCall ↶ 7342
/// #323: a WASM job has no image, so its placement says nothing of one.
7343
#[tokio::test(flavor = "multi_thread")]
7344
async fn a_wasm_jobs_placement_names_no_image() {
7345
    let h = hub().await;
7346
    create(&h.app, "andy", "wasm").await;
7347
    let work = tempfile::tempdir().unwrap();
7348
    let c = client(&format!("{}/andy/wasm", h.base), work.path());
7349
    write(
7350
        work.path(),
7351
        ".flow/pipeline.kdl",
7352
        "schema-version 1\nsandbox \"w\" {\n    runtime \"wasm\"\n}\njob \"count\" {\n    sandbox \"w\"\n    exec \"count.wasm\"\n}\n",
7353
    );
7354
    write(work.path(), "count.wasm", "\0asm");
7355
    c.commit("A WASM job", &[]).unwrap();
7356
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
7357
    runs_of(&h.app, "andy", "wasm").await;
7358
    let (st, body) =
7359
        call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(r#"{"runner":"test-1","runtimes":["wasm"]}"#.into())).await;
7360
    assert_eq!(st, StatusCode::OK, "{body}");
7361
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
7362
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
7363
    assert!(placed.starts_with("idle") && !placed.contains("image"), "{placed}");
c26267b3 Andy McCall ↶ 7364
7365
    // oxygenflow#80: the page that runs it in a browser tab lists it, with
7366
    // the zip of the bookmark's files its worker reads, and the worker.
7367
    let (st, page) = call(&h.app, "GET", "/andy/wasm/flow/tab", None, None).await;
7368
    assert_eq!(st, StatusCode::OK, "{page}");
7369
    assert!(page.contains("Run all 1") && page.contains("&#34;exec&#34;:[&#34;count.wasm&#34;]"), "{page}");
7370
    assert!(page.contains("data-archive=\"/andy/wasm/archive?ref=main&#38;format=zip\""), "{page}");
7371
    let (st, zip) = get_bytes(&h.app, "/andy/wasm/archive?ref=main&format=zip").await;
7372
    assert!(st == StatusCode::OK && zip.starts_with(b"PK"), "{st}");
7373
    assert_eq!(get_bytes(&h.app, "/static/wasi-worker.js").await.0, StatusCode::OK);
7374
    let (_, runs) = call(&h.app, "GET", "/andy/wasm/flow", None, None).await;
7375
    assert!(runs.contains("/andy/wasm/flow/tab"), "linked from Flow");
7376
    let (_, none) = call(&h.app, "GET", "/andy/wasm/flow/tab?bookmark=nope", None, None).await;
7377
    assert!(none.contains("Run all 1"), "an unknown bookmark shows the default's");
d7050703 Andy McCall ↶ 7378
}
dc5c6429 Andy McCall ↶ 7379
7380
/// oxygenhub#322: an organisation's owners set their own runners' updates,
7381
/// test groups of their own runners, and nothing beyond them.
7382
#[tokio::test(flavor = "multi_thread")]
7383
async fn an_organisation_sets_its_own_runners_updates() {
7384
    use oxy_core::identity::SecretKey;
7385
    let h = hub().await;
7386
    let res = oxygenhub::router(h.app.clone())
7387
        .oneshot(
7388
            Request::post("/register")
7389
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
7390
                .body(Body::from("username=andy&email=andy%40example.com&password=correct-horse-battery&setup=test-setup"))
7391
                .unwrap(),
7392
        )
7393
        .await
7394
        .unwrap();
7395
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
7396
    let web = |method: &'static str, path: String, body: Option<String>| {
7397
        let (app, cookie) = (h.app.clone(), cookie.clone());
7398
        async move {
7399
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
7400
            if body.is_some() {
7401
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
7402
            }
7403
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
7404
            let st = res.status();
7405
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
7406
        }
7407
    };
7408
    let csrf_of = |page: &str| {
7409
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
7410
        page[i..].split('"').next().unwrap().to_string()
7411
    };
7412
    let (_, page) = web("GET", "/orgs/new".into(), None).await;
7413
    let csrf = csrf_of(&page);
7414
    web("POST", "/orgs/new".into(), Some(format!("_csrf={csrf}&name=acme&display_name=Acme"))).await;
7415
    // Two of acme's runners, and the site's (hub.toml's, from its first claim).
7416
    let mut creds = vec![];
7417
    for name in ["a1", "a2"] {
7418
        let (_, page) = web("POST", "/orgs/acme/settings/runners/token".into(), Some(format!("_csrf={csrf}"))).await;
7419
        let i = page.find("--token ").unwrap() + "--token ".len();
7420
        let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
7421
        let identity = SecretKey::generate().identity(name, "", 1);
7422
        let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "max_jobs": 1 });
7423
        let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
7424
        let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
7425
        assert_eq!(st, StatusCode::OK, "{body}");
7426
        creds.push(serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string());
7427
    }
7428
    claim(&h.app).await;
7429
    let all = db::runners::list(&h.app.db).await.unwrap();
7430
    let id = |n: &str| all.iter().find(|r| r.name == n).unwrap().id;
7431
    let set = |form: String| web("POST", "/orgs/acme/settings/runners/updates/policy".into(), Some(format!("_csrf={csrf}&{form}")));
7432
7433
    let (_, page) = set("scope=owner&key=acme&updates=on".into()).await;
7434
    assert!(page.contains("Saved for owner acme: updates on."), "{page}");
7435
    let (_, page) = set("scope=site&updates=on".into()).await;
7436
    assert!(page.contains("Choose the site, an owner, a test group or a runner."), "not the site's: {page}");
7437
    let (_, page) = set("scope=owner&key=andy&updates=on".into()).await;
7438
    assert!(page.contains("An organisation sets its own runners"), "{page}");
7439
    let (_, page) = set(format!("scope=runner&key={}&updates=on", id("test-1"))).await;
7440
    assert!(page.contains("That runner is gone."), "the site's runner is not acme's: {page}");
7441
7442
    // A test group of acme's runners; a runner not acme's is left out.
7443
    let (_, page) = web(
7444
        "POST",
7445
        "/orgs/acme/settings/runners/updates/groups".into(),
7446
        Some(format!("_csrf={csrf}&name=canary&owner=&mode=chosen&runner={}&runner={}", id("a1"), id("test-1"))),
7447
    )
7448
    .await;
7449
    assert!(page.contains("Test group canary made: 1 chosen runners"), "{page}");
7450
    let canary = db::runner_updates::groups(&h.app.db).await.unwrap().remove(0);
7451
    assert_eq!(canary.owner, "acme", "an organisation's groups are its own");
7452
    let (_, page) = set(format!("scope=group&key={}&channel=canary", canary.id)).await;
7453
    assert!(page.contains("Saved for group canary: channel canary."), "{page}");
7454
    let (_, page) = set(format!("scope=runner&key={}&updates=off", id("a2"))).await;
7455
    assert!(page.contains("Saved for runner a2: updates off."), "{page}");
7456
7457
    // A site group is not the organisation's to change.
7458
    let site = db::runner_updates::create_group(&h.app.db, "", "everyone", Some(100)).await.unwrap();
7459
    let (_, page) =
7460
        web("POST", format!("/orgs/acme/settings/runners/updates/groups/{}/delete", site.id), Some(format!("_csrf={csrf}"))).await;
7461
    assert!(page.contains("That test group is gone."), "{page}");
7462
    assert!(db::runner_updates::group(&h.app.db, site.id).await.unwrap().is_some());
7463
7464
    // The page shows it; each runner gets its policy.
7465
    let (_, page) = web("GET", "/orgs/acme/settings".into(), None).await;
7466
    assert!(page.contains("id=\"runner-updates\"") && page.contains(">canary <small"), "{page}");
7467
    assert!(page.contains("updates on (owner acme)") && page.contains("updates off (runner)"), "{page}");
7468
    let ask = |cred: String| {
7469
        let app = h.app.clone();
7470
        async move {
7471
            let (_, body) = call(&app, "GET", "/api/v1/flow/runner/update", Some(&cred), None).await;
7472
            serde_json::from_str::<flow_core::api::UpdateAnswer>(&body).unwrap().policy
7473
        }
7474
    };
7475
    let a1 = ask(creds[0].clone()).await;
7476
    assert!(a1.updates && a1.channel == "canary" && a1.from[..2] == ["owner acme".to_string(), "group canary".to_string()], "{a1:?}");
7477
    assert!(!ask(creds[1].clone()).await.updates, "a2's own setting wins");
7478
}
42c77f65 Andy McCall ↶ 7479
7480
/// oxygenhub#352: a keyless agent's change, authored by its owner and sealed
7481
/// with a short-lived key the hub certified under the owner's grant, shows
7482
/// as sealed via the agent: on the change over the API (not "unsigned"), on
7483
/// the change page, and among the repository's contributors.
7484
#[tokio::test(flavor = "multi_thread")]
7485
async fn a_change_a_keyless_agent_sealed_shows_the_agent() {
7486
    use oxy_core::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
7487
    use oxy_core::identity::Scope;
7488
    use oxy_core::repo::IdentityScope;
7489
    let h = hub().await;
7490
    create(&h.app, "andy", "demo").await;
7491
    let url = format!("{}/andy/demo", h.base);
7492
    let work = tempfile::tempdir().unwrap();
7493
    let mut a = client(&url, &work.path().join("a")).with_home(work.path().join("home-a"));
7494
    let (_, andy) = a.create_identity("Andy", "[email protected]", IdentityScope::User).unwrap();
7495
    write(&work.path().join("a"), "a.txt", "a\n");
7496
    a.commit("base", &[]).unwrap();
7497
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
7498
7499
    // The owner's grant to agent:kimi@andy, and the hub's certificate for
7500
    // the agent's fresh key carrying it, as `oxy auth grant` and keyless
7501
    // signing make them.
7502
    let hub_id = h.app.hub_key.identity.clone();
7503
    let (_, hub_secret) = oxygenhub::keys::load_secret(&h.app.config.keys_dir()).unwrap();
7504
    let (_, andy_secret) = a.secret_key().unwrap().unwrap();
7505
    let now = db::now_ms() as u64;
7506
    let scope = Scope::CHANGES | Scope::REFS | Scope::SEAL;
7507
    let grant = SignedGrant::sign(
7508
        Grant {
7509
            grantor: andy.hash(),
7510
            subject: "agent:kimi@andy".into(),
7511
            issuer: hub_id.hash(),
7512
            scope,
7513
            not_before: now - 60_000,
7514
            expires: now + 86_400_000,
7515
        },
7516
        &andy,
7517
        &andy_secret,
7518
    );
7519
    let mut b = Repo::clone(&url, &work.path().join("b")).unwrap().with_home(work.path().join("home-b"));
7520
    b.config.set("remote.origin.token", "site").unwrap();
7521
    b.save_config().unwrap();
7522
    let (_, agent) = b.create_identity("kimi", "[email protected]", IdentityScope::User).unwrap();
7523
    let cert = SignedCertificate::sign(
7524
        Certificate {
7525
            key: agent.clone(),
7526
            issuer: hub_id.hash(),
7527
            subject: "agent:kimi@andy".into(),
7528
            claims: vec![],
7529
            scope,
7530
            not_before: now - 60_000,
7531
            expires: now + 600_000,
7532
            grant: Some(grant),
7533
        },
7534
        &hub_id,
7535
        &hub_secret,
7536
    );
7537
    b.store().put_identity(&hub_id).unwrap();
7538
    b.store().put_certificate(&cert).unwrap();
7539
    // Authored as the owner, sealed (not signed) by the agent's key.
7540
    b.config.set("author.key", &andy.hash().to_hex()).unwrap();
7541
    b.config.set("author.signer", &agent.hash().to_hex()).unwrap();
7542
    b.save_config().unwrap();
7543
    write(&work.path().join("b"), "b.txt", "agent work\n");
7544
    let change = b.commit("agent work", &[]).unwrap();
7545
    assert!(b.store().signatures(&change).unwrap().is_empty(), "the change itself is unsigned");
7546
    b.seal(&[change]).unwrap();
7547
    let r = b.push("origin", false).unwrap();
7548
    assert!(r.iter().all(|x| x.ok), "{r:?}");
7549
7550
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/changes/{}", change.to_hex()), None, None).await;
7551
    assert!(st.is_success(), "{st} {body}");
7552
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
7553
    let sig = &v["change"]["signature"];
7554
    assert_eq!(sig["status"], "valid", "a sealed change is not unsigned: {sig}");
7555
    assert_eq!(sig["sealed"], true, "{sig}");
7556
    assert_eq!(sig["key"], agent.hash().to_hex());
7557
7558
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/change/{}", change.to_hex()), None, None).await;
7559
    assert!(page.contains("agent:kimi@andy"), "the change page names the agent");
7560
    assert!(page.contains("keyless, under your grant"), "a certified key is not flagged as a lost delegation");
7561
    let (_, overview) = call(&h.app, "GET", "/andy/demo", None, None).await;
7562
    let contributors = &overview[overview.find("Contributors").expect("a Contributors panel")..];
7563
    assert!(contributors.contains("agent:kimi@andy"), "Contributors names the agent under its owner");
7564
}
1c52d940 Andy McCall ↶ 7565
7566
/// oxygenhub#350: files attached to issues. Over the API, with the file's
7567
/// bytes; an image (by its bytes) shows in place, anything else, an SVG
7568
/// included, is a download; nothing served can run; a private repository's
7569
/// attachments are its readers' only; uploading needs a token.
7570
#[tokio::test(flavor = "multi_thread")]
7571
async fn attachments_are_uploaded_and_served_safely() {
7572
    let h = hub().await;
7573
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
7574
    create(&h.app, "andy", "demo").await;
7575
    let send = |path: String, bytes: Vec<u8>, token: Option<&'static str>| {
7576
        let app = h.app.clone();
7577
        async move {
7578
            let mut req = Request::builder().method("POST").uri(path).header(header::CONTENT_TYPE, "application/octet-stream");
7579
            if let Some(t) = token {
7580
                req = req.header(header::AUTHORIZATION, format!("Bearer {t}"));
7581
            }
7582
            let res = oxygenhub::router(app).oneshot(req.body(Body::from(bytes)).unwrap()).await.unwrap();
7583
            let status = res.status();
7584
            let body = res.into_body().collect().await.unwrap().to_bytes();
7585
            (status, String::from_utf8_lossy(&body).into_owned())
7586
        }
7587
    };
7588
    let get = |path: String| {
7589
        let app = h.app.clone();
7590
        async move {
7591
            let res = oxygenhub::router(app).oneshot(Request::get(path).body(Body::empty()).unwrap()).await.unwrap();
7592
            let hd = |k: header::HeaderName| res.headers().get(k).and_then(|v| v.to_str().ok()).unwrap_or("").to_string();
7593
            let heads = (
7594
                hd(header::CONTENT_TYPE),
7595
                hd(header::CONTENT_DISPOSITION),
7596
                hd(header::X_CONTENT_TYPE_OPTIONS),
7597
                hd(header::CONTENT_SECURITY_POLICY),
7598
                hd(header::CACHE_CONTROL),
7599
            );
7600
            let status = res.status();
7601
            let body = res.into_body().collect().await.unwrap().to_bytes().to_vec();
7602
            (status, heads, body)
7603
        }
7604
    };
7605
    let png = b"\x89PNG\r\n\x1a\nnot really a picture".to_vec();
7606
7607
    let (st, _) = send("/api/v1/repos/andy/demo/attachments?name=shot.png".into(), png.clone(), None).await;
7608
    assert_eq!(st, StatusCode::UNAUTHORIZED, "attaching needs a token");
7609
    let (st, body) = send("/api/v1/repos/andy/demo/attachments?name=dir/shot.png".into(), png.clone(), Some("site")).await;
7610
    assert_eq!(st, StatusCode::CREATED, "{body}");
7611
    let a: hub_api::Attachment = serde_json::from_str(&body).unwrap();
7612
    assert_eq!((a.name.as_str(), a.content_type.as_str(), a.inline), ("shot.png", "image/png", true));
7613
    assert_eq!(a.markdown, format!("![shot.png]({})", a.url));
7614
    let path = a.url.strip_prefix(&h.base).unwrap().to_string();
7615
    assert_eq!(path, format!("/andy/demo/attachments/{}/shot.png", a.id));
7616
    let (st, (ct, cd, nosniff, csp, cache), bytes) = get(path.clone()).await;
7617
    assert_eq!(st, StatusCode::OK);
7618
    assert_eq!((ct.as_str(), nosniff.as_str()), ("image/png", "nosniff"));
7619
    assert!(cd.starts_with("inline"), "{cd}");
7620
    assert!(csp.contains("default-src 'none'") && csp.contains("sandbox"), "{csp}");
7621
    assert!(cache.starts_with("private"), "{cache}");
7622
    assert_eq!(bytes, png);
7623
    let (st, _, _) = get(format!("/andy/demo/attachments/{}/other.png", a.id)).await;
7624
    assert_eq!(st, StatusCode::NOT_FOUND, "the name must match");
7625
7626
    // An SVG says it is an image; its bytes are a script's: a download.
7627
    let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><script>alert(1)</script></svg>".to_vec();
7628
    let (st, body) = send("/api/v1/repos/andy/demo/attachments?name=logo.svg".into(), svg, Some("site")).await;
7629
    assert_eq!(st, StatusCode::CREATED, "{body}");
7630
    let s: hub_api::Attachment = serde_json::from_str(&body).unwrap();
7631
    assert!(!s.inline && s.content_type == "application/octet-stream" && s.markdown == format!("[logo.svg]({})", s.url));
7632
    let (_, (ct, cd, _, _, _), _) = get(s.url.strip_prefix(&h.base).unwrap().to_string()).await;
7633
    assert_eq!(ct, "application/octet-stream");
7634
    assert!(cd.starts_with("attachment"), "{cd}");
7635
    let (st, _) = send("/api/v1/repos/andy/demo/attachments?name=.env".into(), b"x".to_vec(), Some("site")).await;
7636
    assert_eq!(st, StatusCode::UNPROCESSABLE_ENTITY, "a hidden file name is refused");
7637
7638
    // A private repository's attachments are for its readers.
7639
    h.app.repos.create(&RepoName::parse("andy/secret").unwrap(), None).unwrap();
7640
    db::repos::create(&h.app.db, "andy", "secret", "", hub_api::Visibility::Private).await.unwrap();
7641
    let (st, body) = send("/api/v1/repos/andy/secret/attachments?name=s.png".into(), png.clone(), Some("site")).await;
7642
    assert_eq!(st, StatusCode::CREATED, "{body}");
7643
    let p: hub_api::Attachment = serde_json::from_str(&body).unwrap();
7644
    let (st, _, _) = get(p.url.strip_prefix(&h.base).unwrap().to_string()).await;
7645
    assert_eq!(st, StatusCode::NOT_FOUND, "not to someone signed out");
7646
}