OXYGENHUB
# b6b7e4cf6b24 oxygenhub / crates / hub / tests / flow.rs
60.1 KiB · Rust · last changed Runners: registration, Admin -> Runners, history, drain/disable/remove 1 month ago source blame history raw
1
//! OxygenFlow on the hub (hub spec §13.2), end to end: a real `oxy` push
2
//! starts a run, a runner claims jobs through the API in dependency order,
3
//! job tokens read only their repository, results become checks and pages.
4
5
use axum::body::Body;
6
use axum::http::{header, Request, StatusCode};
7
use http_body_util::BodyExt;
8
use oxy_core::protocol::{open_remote, RemoteOptions};
9
use oxy_core::repo::Repo;
10
use oxygenhub::config::Config;
11
use oxygenhub::repos::RepoName;
12
use oxygenhub::{db, Shared};
13
use std::path::Path;
14
use tower::ServiceExt;
15
16
const ROOTFS: &str = "36fc4e3238044e424219a2b9002bf61bbe1805fec14d52cf37e17fae77c9ff16";
17
18
fn hermetic() {
19
    static ONCE: std::sync::Once = std::sync::Once::new();
20
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
21
    ONCE.call_once(|| {
22
        let d = tempfile::tempdir().unwrap();
23
        std::env::set_var("OXY_HOME", d.path());
24
        DIR.set(d).ok();
25
    });
26
}
27
28
fn write(root: &Path, rel: &str, content: &str) {
29
    let p = root.join(rel);
30
    std::fs::create_dir_all(p.parent().unwrap()).unwrap();
31
    std::fs::write(p, content).unwrap();
32
}
33
34
struct Hub {
35
    app: Shared,
36
    base: String,
37
    _dir: tempfile::TempDir,
38
}
39
40
async fn hub() -> Hub {
41
    hermetic();
42
    let dir = tempfile::tempdir().unwrap();
43
    let mut config = Config::load(dir.path()).unwrap();
44
    config.auth.push_tokens = vec!["site".into()];
45
    config.flow.runner_tokens = vec!["runner-secret".into()];
46
    config.flow.repos = vec!["andy/*".into()];
47
    config.registration.mode = "open".into();
48
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
49
    let port = listener.local_addr().unwrap().port();
50
    config.server.base_url = format!("http://127.0.0.1:{port}");
51
    let app = oxygenhub::build(config).await.unwrap();
52
    let router = oxygenhub::router(app.clone());
53
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
54
    Hub { app, base: format!("http://127.0.0.1:{port}"), _dir: dir }
55
}
56
57
async fn call(app: &Shared, method: &str, path: &str, bearer: Option<&str>, json: Option<String>) -> (StatusCode, String) {
58
    let mut req = Request::builder().method(method).uri(path);
59
    if let Some(b) = bearer {
60
        req = req.header(header::AUTHORIZATION, format!("Bearer {b}"));
61
    }
62
    let body = match json {
63
        Some(j) => {
64
            req = req.header(header::CONTENT_TYPE, "application/json");
65
            Body::from(j)
66
        }
67
        None => Body::empty(),
68
    };
69
    let res = oxygenhub::router(app.clone()).oneshot(req.body(body).unwrap()).await.unwrap();
70
    let status = res.status();
71
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
72
    (status, String::from_utf8_lossy(&bytes).into_owned())
73
}
74
75
/// A GET's status, `Location` and `Content-Type`.
76
async fn head(app: &Shared, path: &str) -> (StatusCode, String, String) {
77
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(path).body(Body::empty()).unwrap()).await.unwrap();
78
    let h = |k: header::HeaderName| res.headers().get(k).and_then(|v| v.to_str().ok()).unwrap_or("").to_string();
79
    (res.status(), h(header::LOCATION), h(header::CONTENT_TYPE))
80
}
81
82
async fn claim(app: &Shared) -> Option<serde_json::Value> {
83
    let (st, body) =
84
        call(app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(r#"{"runner":"test-1","runtimes":["microvm"]}"#.into())).await;
85
    match st {
86
        StatusCode::NO_CONTENT => None,
87
        StatusCode::OK => Some(serde_json::from_str(&body).unwrap()),
88
        other => panic!("claim: {other} {body}"),
89
    }
90
}
91
92
fn receipt(job: &str, pipeline_hash: &str, exit: u32) -> serde_json::Value {
93
    serde_json::json!({
94
        "job_name": job, "pipeline_hash": pipeline_hash, "scope_tree_hash": "11".repeat(32),
95
        "inputs": [], "environment": "22".repeat(32), "outputs": [], "exit_code": exit, "duration_ms": 640
96
    })
97
}
98
99
async fn finish(app: &Shared, id: i64, body: serde_json::Value) -> StatusCode {
100
    call(app, "POST", &format!("/api/v1/flow/jobs/{id}/finish"), Some("runner-secret"), Some(body.to_string())).await.0
101
}
102
103
async fn create(app: &Shared, owner: &str, name: &str) {
104
    app.repos.create(&RepoName::parse(&format!("{owner}/{name}")).unwrap(), None).unwrap();
105
    db::repos::create(&app.db, owner, name, "", hub_api::Visibility::Public).await.unwrap();
106
}
107
108
fn client(url: &str, work: &Path) -> Repo {
109
    let mut c = Repo::init(work).unwrap();
110
    c.config.set("remote.origin.url", url).unwrap();
111
    c.config.set("remote.origin.token", "site").unwrap();
112
    c.save_config().unwrap();
113
    c
114
}
115
116
fn pipeline(extra: &str) -> String {
117
    format!(
118
        "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}"
119
    )
120
}
121
122
async fn runs_of(app: &Shared, owner: &str, name: &str) -> Vec<db::flow::Run> {
123
    let row = db::repos::get(&app.db, owner, name).await.unwrap().unwrap();
124
    for _ in 0..100 {
125
        let r = db::flow::runs(&app.db, row.id, 10, None).await.unwrap();
126
        if !r.is_empty() {
127
            return r;
128
        }
129
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
130
    }
131
    vec![]
132
}
133
134
/// The checks on a state once there are `n` of them (they follow the run).
135
async fn checks_when(app: &Shared, repo_id: i64, state: &str, n: usize) -> Vec<db::hooks::Check> {
136
    for _ in 0..100 {
137
        let c = db::hooks::checks_for_state(&app.db, repo_id, state).await.unwrap();
138
        if c.len() >= n {
139
            return c;
140
        }
141
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
142
    }
143
    db::hooks::checks_for_state(&app.db, repo_id, state).await.unwrap()
144
}
145
146
#[tokio::test(flavor = "multi_thread")]
147
async fn a_push_runs_the_pipeline_through_a_runner() {
148
    let h = hub().await;
149
    create(&h.app, "andy", "demo").await;
150
    create(&h.app, "andy", "secret").await;
151
    create(&h.app, "other", "plain").await;
152
    let url = format!("{}/andy/demo", h.base);
153
    let work = tempfile::tempdir().unwrap();
154
    let mut c = client(&url, work.path());
155
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
156
    write(work.path(), "test.sh", "echo ok\n");
157
    c.snapshot("test").unwrap();
158
    c.commit("Add a pipeline", &[]).unwrap();
159
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
160
161
    // The push started a run with three queued jobs, and checks for them.
162
    let runs = runs_of(&h.app, "andy", "demo").await;
163
    assert_eq!(runs.len(), 1);
164
    let run = &runs[0];
165
    assert_eq!((run.bookmark.as_str(), run.status.as_str(), run.actor.as_str()), ("main", "queued", "site token"));
166
    assert_eq!(run.pipeline_hash.len(), 64);
167
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
168
    assert_eq!(jobs.iter().map(|j| (j.name.as_str(), j.depth)).collect::<Vec<_>>(), [("build", 0), ("lint", 0), ("test", 1)]);
169
    // The checks are reported just after the run is recorded.
170
    let checks = checks_when(&h.app, run.repo_id, &run.state, 3).await;
171
    assert_eq!(
172
        checks.iter().map(|c| (c.name.as_str(), c.status.as_str())).collect::<Vec<_>>(),
173
        [("flow/build", "queued"), ("flow/lint", "queued"), ("flow/test", "queued")]
174
    );
175
176
    // Runners need a runner token.
177
    assert_eq!(
178
        call(&h.app, "POST", "/api/v1/flow/claim", Some("site"), Some(r#"{"runner":"x","runtimes":["microvm"]}"#.into())).await.0,
179
        StatusCode::UNAUTHORIZED
180
    );
181
    assert_eq!(
182
        call(&h.app, "POST", "/api/v1/flow/claim", None, Some(r#"{"runner":"x","runtimes":["microvm"]}"#.into())).await.0,
183
        StatusCode::UNAUTHORIZED
184
    );
185
    // A runner without the tier gets nothing.
186
    let (st, _) =
187
        call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(r#"{"runner":"x","runtimes":["wasm"]}"#.into())).await;
188
    assert_eq!(st, StatusCode::NO_CONTENT);
189
190
    // Claims come in dependency order; `test` waits for `build`.
191
    let a = claim(&h.app).await.unwrap();
192
    let b = claim(&h.app).await.unwrap();
193
    assert_eq!((a["job"]["name"].as_str(), b["job"]["name"].as_str()), (Some("build"), Some("lint")));
194
    assert!(claim(&h.app).await.is_none(), "test waits for build");
195
    assert_eq!(a["repo"], "andy/demo");
196
    assert_eq!(a["clone_url"], url.as_str());
197
    assert_eq!(a["sandbox"]["rootfs"], ROOTFS);
198
    assert_eq!(a["job"]["exec"], serde_json::json!(["make"]));
199
    assert_eq!(a["timeout_s"], 3600);
200
    // The job is told what it builds (FLOW_STATE, FLOW_BOOKMARK, FLOW_RUN).
201
    assert_eq!(
202
        (a["state"].as_str(), a["bookmark"].as_str(), a["run_number"].as_i64()),
203
        (Some(run.state.as_str()), Some("main"), Some(run.number))
204
    );
205
    let heads: Vec<String> = a["heads"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
206
    assert_eq!(heads.join("+"), run.heads);
207
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
208
    assert_eq!(checks.iter().find(|c| c.name == "flow/build").unwrap().status, "running");
209
210
    // The job token reads this repository over the wire, and nothing else.
211
    let token = a["token"].as_str().unwrap().to_string();
212
    assert!(token.starts_with("flowjob_"));
213
    let opts = RemoteOptions { token: Some(token.clone()), ca: None, repo_id: None };
214
    open_remote(&url, &opts).unwrap().refs().unwrap();
215
    assert!(open_remote(&format!("{}/andy/secret", h.base), &opts).unwrap().refs().is_err(), "another repository");
216
    let bad = RemoteOptions { token: Some("flowjob_00".into()), ca: None, repo_id: None };
217
    assert!(open_remote(&url, &bad).unwrap().refs().is_err(), "an unknown job token");
218
    // … and cannot push.
219
    c.config.set("remote.origin.token", &token).unwrap();
220
    c.save_config().unwrap();
221
    write(work.path(), "more.txt", "x\n");
222
    c.snapshot("test").unwrap();
223
    c.commit("More", &[]).unwrap();
224
    let pushed = c.push("origin", false);
225
    assert!(pushed.is_err() || pushed.unwrap().iter().all(|r| !r.ok), "a job token cannot push");
226
    c.config.set("remote.origin.token", "site").unwrap();
227
    c.save_config().unwrap();
228
229
    // Logs, then results with receipts.
230
    let a_id = a["job_id"].as_i64().unwrap();
231
    let b_id = b["job_id"].as_i64().unwrap();
232
    let log = serde_json::json!({ "records": [
233
        { "t": 5, "stream": "flow", "text": "booting" },
234
        { "t": 120, "stream": "out", "text": "cc -o demo demo.c" },
235
        { "t": 130, "stream": "weird", "text": "x".repeat(20_000) },
236
    ]});
237
    assert_eq!(
238
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{a_id}/log"), Some("runner-secret"), Some(log.to_string())).await.0,
239
        StatusCode::NO_CONTENT
240
    );
241
    let lines = db::flow::log(&h.app.db, a_id, 0, 100).await.unwrap();
242
    assert_eq!(lines.len(), 3);
243
    assert_eq!((lines[2].stream.as_str(), lines[2].text.len()), ("console", 16 * 1024), "streams are known ones, text is capped");
244
    let ph = a["pipeline_hash"].as_str().unwrap();
245
    assert_eq!(
246
        finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("lint", ph, 0) })).await,
247
        StatusCode::BAD_REQUEST,
248
        "a receipt for another job"
249
    );
250
    assert_eq!(
251
        finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("build", ph, 0) })).await,
252
        StatusCode::NO_CONTENT
253
    );
254
    assert_eq!(finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700 })).await, StatusCode::CONFLICT, "only once");
255
    assert!(open_remote(&url, &opts).unwrap().refs().is_err(), "the token ends with its job");
256
    assert_eq!(
257
        finish(&h.app, b_id, serde_json::json!({ "exit_code": 0, "duration_ms": 300, "receipt": receipt("lint", ph, 0) })).await,
258
        StatusCode::NO_CONTENT
259
    );
260
    let t = claim(&h.app).await.unwrap();
261
    assert_eq!(t["job"]["name"], "test");
262
    let t_id = t["job_id"].as_i64().unwrap();
263
    assert_eq!(
264
        finish(&h.app, t_id, serde_json::json!({ "exit_code": 3, "duration_ms": 500, "receipt": receipt("test", ph, 3) })).await,
265
        StatusCode::NO_CONTENT
266
    );
267
268
    let run = db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap();
269
    assert_eq!(run.status, "failed");
270
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
271
    let build = jobs.iter().find(|j| j.name == "build").unwrap();
272
    assert_eq!((build.status.as_str(), build.exit_code, build.receipt_hash.len()), ("passed", Some(0), 64));
273
    assert_eq!(jobs.iter().find(|j| j.name == "test").unwrap().status, "failed");
274
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
275
    assert_eq!(
276
        checks.iter().map(|c| (c.name.as_str(), c.status.as_str())).collect::<Vec<_>>(),
277
        [("flow/build", "passed"), ("flow/lint", "passed"), ("flow/test", "failed")]
278
    );
279
    assert!(checks[2].summary.contains("exit 3") && checks[2].url.ends_with(&format!("/andy/demo/flow/{}", run.number)));
280
281
    // Pages: the list, the run with its graph and logs, and the live view.
282
    let (st, list) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
283
    assert_eq!(st, StatusCode::OK);
284
    assert!(list.contains(&format!("/andy/demo/flow/{}", run.number)) && list.contains("st-failed"), "{list}");
285
    let (st, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
286
    assert_eq!(st, StatusCode::OK);
287
    assert!(page.contains("<svg class=\"flow-graph\""), "graph");
288
    assert_eq!(page.matches("data-job-node=").count(), 3);
289
    assert_eq!(page.matches("<path class=\"edge").count(), 1, "one dependency edge");
290
    assert!(page.contains("cc -o demo demo.c"), "log shown");
291
    assert!(!page.contains("data-flow-live"), "a finished run does not poll");
292
    let (st, live) = call(&h.app, "GET", &format!("/andy/demo/flow/{}/live?after={a_id}:1", run.number), None, None).await;
293
    assert_eq!(st, StatusCode::OK);
294
    let live: serde_json::Value = serde_json::from_str(&live).unwrap();
295
    assert_eq!(live["status"], "failed");
296
    let build_live = live["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "build").unwrap().clone();
297
    assert_eq!(build_live["lines"].as_array().unwrap().len(), 2, "lines after seq 1");
298
    assert_eq!(call(&h.app, "GET", "/andy/demo/flow/999", None, None).await.0, StatusCode::NOT_FOUND);
299
300
    // A failed dependency skips what follows; an unrun job is an error.
301
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
302
    write(work.path(), "test.sh", "echo changed\n");
303
    c.snapshot("test").unwrap();
304
    c.commit("Change the test", &[]).unwrap();
305
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
306
    let mut second = None;
307
    for _ in 0..100 {
308
        let r = runs_of(&h.app, "andy", "demo").await;
309
        if r.len() == 2 {
310
            second = Some(r[0].clone());
311
            break;
312
        }
313
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
314
    }
315
    let second = second.expect("a second run");
316
    let x = claim(&h.app).await.unwrap();
317
    let y = claim(&h.app).await.unwrap();
318
    let (build_id, lint_id) = if x["job"]["name"] == "build" {
319
        (x["job_id"].as_i64().unwrap(), y["job_id"].as_i64().unwrap())
320
    } else {
321
        (y["job_id"].as_i64().unwrap(), x["job_id"].as_i64().unwrap())
322
    };
323
    assert_eq!(
324
        finish(&h.app, build_id, serde_json::json!({ "exit_code": null, "duration_ms": 10, "error": "rootfs is not on this runner" }))
325
            .await,
326
        StatusCode::NO_CONTENT
327
    );
328
    assert_eq!(finish(&h.app, lint_id, serde_json::json!({ "exit_code": 0, "duration_ms": 10 })).await, StatusCode::NO_CONTENT);
329
    assert!(claim(&h.app).await.is_none(), "test was skipped");
330
    let jobs = db::flow::jobs(&h.app.db, second.id).await.unwrap();
331
    assert_eq!(
332
        jobs.iter().map(|j| (j.name.as_str(), j.status.as_str())).collect::<Vec<_>>(),
333
        [("build", "error"), ("lint", "passed"), ("test", "skipped")]
334
    );
335
    assert_eq!(db::flow::run_by_id(&h.app.db, second.id).await.unwrap().unwrap().status, "failed");
336
337
    // An invalid pipeline is a run in error with the line.
338
    write(work.path(), ".flow/pipeline.kdl", &pipeline("job \"broken\" {\n    sandbox \"missing\"\n    exec \"x\"\n}\n"));
339
    c.snapshot("test").unwrap();
340
    c.commit("Break the pipeline", &[]).unwrap();
341
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
342
    let mut third = None;
343
    for _ in 0..100 {
344
        let r = runs_of(&h.app, "andy", "demo").await;
345
        if r.len() == 3 {
346
            third = Some(r[0].clone());
347
            break;
348
        }
349
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
350
    }
351
    let third = third.expect("a third run");
352
    assert_eq!(third.status, "error");
353
    assert!(third.error.contains("line 18") && third.error.contains("\"missing\""), "{}", third.error);
354
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", third.number), None, None).await;
355
    assert!(page.contains("The pipeline is not valid"));
356
357
    // State stamps (hub spec §13.2) and images in READMEs.
358
    write(work.path(), "README.md", "# Demo\n\n[![flow](.flow/stamp)](.flow/run)\n\n![logo](img/logo.png)\n");
359
    std::fs::create_dir_all(work.path().join("img")).unwrap();
360
    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")
361
        .unwrap();
362
    c.snapshot("test").unwrap();
363
    c.commit("A README with a stamp", &[]).unwrap();
364
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
365
    let mut fourth = None;
366
    for _ in 0..100 {
367
        let r = runs_of(&h.app, "andy", "demo").await;
368
        if r.len() == 4 {
369
            fourth = Some(r[0].clone());
370
            break;
371
        }
372
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
373
    }
374
    let fourth = fourth.expect("a fourth run");
375
    let (_, overview) = call(&h.app, "GET", "/andy/demo", None, None).await;
376
    assert!(overview.contains("src=\"/andy/demo/raw/main/.flow/stamp\""), "{overview}");
377
    assert!(overview.contains("href=\"/andy/demo/file/main/.flow/run\""));
378
    assert!(overview.contains("src=\"/andy/demo/raw/main/img/logo.png\""), "images use the raw route");
379
    let (st, _, ct) = head(&h.app, "/andy/demo/raw/main/img/logo.png").await;
380
    assert_eq!((st, ct.as_str()), (StatusCode::OK, "image/png"));
381
    let (st, loc, _) = head(&h.app, "/andy/demo/raw/main/.flow/stamp").await;
382
    assert!(st.is_redirection() && loc == "/andy/demo/flow/stamp/main", "{st} {loc}");
383
    let (st, loc, _) = head(&h.app, "/andy/demo/flow/stamp/main").await;
384
    assert!(st.is_redirection() && loc == format!("/andy/demo/flow/stamp/{}", fourth.heads), "a bookmark's stamp names its state: {loc}");
385
    let (st, _, ct) = head(&h.app, &loc).await;
386
    assert_eq!((st, ct.as_str()), (StatusCode::OK, "image/svg+xml; charset=utf-8"));
387
    let (_, svg) = call(&h.app, "GET", &loc, None, None).await;
388
    assert!(svg.starts_with("<svg") && svg.contains("error ·") && svg.contains(&fourth.heads[..12]), "{svg}");
389
    let (_, svg1) = call(&h.app, "GET", &format!("/andy/demo/flow/stamp/{}", run.heads), None, None).await;
390
    assert!(svg1.contains("failed ·") && svg1.contains(&format!("run #{} failed", run.id)), "an older state keeps its own result: {svg1}");
391
    assert!(svg1.contains(&build.receipt_hash), "receipt hashes in the metadata");
392
    assert_eq!(svg1.matches("text-anchor=\"middle\"").count(), 3, "one glyph per job");
393
    let (st, loc, _) = head(&h.app, "/andy/demo/file/main/.flow/run").await;
394
    assert!(st.is_redirection() && loc == "/andy/demo/flow/at/main", "{loc}");
395
    let (st, loc, _) = head(&h.app, "/andy/demo/flow/at/main").await;
396
    assert!(st.is_redirection() && loc == format!("/andy/demo/flow/{}", fourth.id), "{loc}");
397
398
    // A repository outside [flow] repos starts nothing.
399
    let work2 = tempfile::tempdir().unwrap();
400
    let c2 = client(&format!("{}/other/plain", h.base), work2.path());
401
    write(work2.path(), ".flow/pipeline.kdl", &pipeline(""));
402
    c2.snapshot("test").unwrap();
403
    c2.commit("Pipeline", &[]).unwrap();
404
    assert!(c2.push("origin", false).unwrap().iter().all(|r| r.ok));
405
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
406
    let row = db::repos::get(&h.app.db, "other", "plain").await.unwrap().unwrap();
407
    assert!(db::flow::runs(&h.app.db, row.id, 10, None).await.unwrap().is_empty());
408
    let (_, page) = call(&h.app, "GET", "/other/plain/flow", None, None).await;
409
    assert!(page.contains("not enabled for this repository"));
410
    let (_, loc, _) = head(&h.app, "/other/plain/flow/stamp/main").await;
411
    let (_, svg) = call(&h.app, "GET", &loc, None, None).await;
412
    assert!(svg.contains("no run ·"), "{svg}");
413
    let (_, loc, _) = head(&h.app, "/other/plain/flow/at/main").await;
414
    assert_eq!(loc, "/other/plain/flow");
415
}
416
417
#[tokio::test(flavor = "multi_thread")]
418
async fn claims_carry_pinned_subrepos_and_the_job_token_reads_only_those() {
419
    let h = hub().await;
420
    for n in ["base", "lib", "vault", "other", "app"] {
421
        create(&h.app, "andy", n).await;
422
    }
423
    let push = |name: &str, file: &str| {
424
        let work = tempfile::tempdir().unwrap();
425
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
426
        write(work.path(), file, "x\n");
427
        c.snapshot("t").unwrap();
428
        c.commit("first", &[]).unwrap();
429
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
430
        let heads = c.bookmark_heads().unwrap();
431
        (work, heads)
432
    };
433
    let (_b, base_heads) = push("base", "base.rs");
434
    // lib pins base in turn: a subrepo of a subrepo.
435
    let lib_work = tempfile::tempdir().unwrap();
436
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
437
    lib.submodule_add(&format!("{}/andy/base", h.base), "deps/base", Some("main")).unwrap();
438
    write(lib_work.path(), "lib.rs", "x\n");
439
    lib.snapshot("t").unwrap();
440
    lib.commit("lib on base", &[]).unwrap();
441
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
442
    let lib_heads = lib.bookmark_heads().unwrap();
443
    let (_v, _) = push("vault", "secret.rs");
444
    let (_o, _) = push("other", "o.rs");
445
446
    // The app pins lib and vault as subrepos and pushes as the site token.
447
    let work = tempfile::tempdir().unwrap();
448
    let app = client(&format!("{}/andy/app", h.base), work.path());
449
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
450
    // Vault is private: adding it takes the environment's token, as a clone does.
451
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'vault'").execute(&h.app.db).await.unwrap();
452
    assert!(app.submodule_add(&format!("{}/andy/vault", h.base), "deps/vault2", Some("main")).is_err(), "not without a token");
453
    std::env::set_var("OXY_TOKEN", "site");
454
    app.submodule_add(&format!("{}/andy/vault", h.base), "deps/vault", Some("main")).unwrap();
455
    std::env::remove_var("OXY_TOKEN");
456
    // The pusher below is the site token, which has no account: it cannot read vault.
457
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
458
    write(work.path(), "Makefile", "all:\n");
459
    app.snapshot("t").unwrap();
460
    app.commit("app with deps", &[]).unwrap();
461
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
462
    assert!(!runs_of(&h.app, "andy", "app").await.is_empty());
463
464
    let job = claim(&h.app).await.unwrap();
465
    let subs = job["subrepos"].as_array().cloned().unwrap_or_default();
466
    assert_eq!(subs.len(), 2, "lib and what lib pins; vault is private and the pusher has no account: {subs:?}");
467
    assert_eq!(subs[1]["path"], "deps/lib/deps/base", "nested under its parent, after it");
468
    assert_eq!(subs[1]["heads"], serde_json::json!(base_heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>()));
469
    let _ = std::fs::remove_dir_all(work.path().join("deps/vault2"));
470
    assert_eq!(subs[0]["path"], "deps/lib");
471
    assert_eq!(subs[0]["repo"], "andy/lib");
472
    assert_eq!(subs[0]["heads"], serde_json::json!(lib_heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>()));
473
    assert!(subs[0]["clone_url"].as_str().unwrap().ends_with("/andy/lib"));
474
475
    // The job token reads its repository and the pinned lib, nothing else.
476
    let token = job["token"].as_str().unwrap().to_string();
477
    let read = |name: &str| {
478
        let opts = RemoteOptions { token: Some(token.clone()), ..Default::default() };
479
        open_remote(&format!("{}/andy/{name}", h.base), &opts).and_then(|r| r.refs()).is_ok()
480
    };
481
    assert!(read("app") && read("lib") && read("base"));
482
    assert!(!read("vault"), "not pinned for this pusher");
483
    assert!(!read("other"), "public, but not the job's to read");
484
}
485
486
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
487
async fn concurrent_log_appends_never_fail_on_a_locked_database() {
488
    let h = hub().await;
489
    create(&h.app, "andy", "demo").await;
490
    let work = tempfile::tempdir().unwrap();
491
    let c = client(&format!("{}/andy/demo", h.base), work.path());
492
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
493
    write(work.path(), "Makefile", "all:\n");
494
    c.snapshot("t").unwrap();
495
    c.commit("pipeline", &[]).unwrap();
496
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
497
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
498
    let job = db::flow::jobs(&h.app.db, run.id).await.unwrap().remove(0);
499
    // Many writers at once, each reading the count and then inserting: a
500
    // deferred transaction would fail with "database is locked".
501
    let mut tasks = Vec::new();
502
    for w in 0..16 {
503
        let pool = h.app.db.clone();
504
        tasks.push(tokio::spawn(async move {
505
            let records: Vec<flow_core::api::Record> =
506
                (0..20).map(|i| flow_core::api::Record { t: i, stream: "out".into(), text: format!("writer {w} line {i}") }).collect();
507
            db::flow::append_log(&pool, job.id, &records, 100_000).await
508
        }));
509
    }
510
    for t in tasks {
511
        assert_eq!(t.await.unwrap().unwrap(), 20, "every append succeeds");
512
    }
513
    let lines = db::flow::log(&h.app.db, job.id, 0, 1_000).await.unwrap();
514
    assert_eq!(lines.len(), 320);
515
    let seqs: std::collections::BTreeSet<i64> = lines.iter().map(|l| l.seq).collect();
516
    assert_eq!(seqs.len(), 320, "sequence numbers are unique");
517
}
518
519
/// A repository's own Flow setting overrides hub.toml either way.
520
#[tokio::test(flavor = "multi_thread")]
521
async fn a_repository_setting_turns_flow_on_or_off() {
522
    let h = hub().await;
523
    create(&h.app, "other", "plain").await;
524
    create(&h.app, "andy", "quiet").await;
525
    // A run elsewhere first, so hub-wide ids and per-repository numbers differ.
526
    create(&h.app, "andy", "first").await;
527
    {
528
        let work = tempfile::tempdir().unwrap();
529
        let c = client(&format!("{}/andy/first", h.base), work.path());
530
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
531
        write(work.path(), "test.sh", "echo ok\n");
532
        c.commit("Add a pipeline", &[]).unwrap();
533
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
534
        assert_eq!(runs_of(&h.app, "andy", "first").await.len(), 1);
535
    }
536
    let row = db::repos::get(&h.app.db, "other", "plain").await.unwrap().unwrap();
537
    db::repos::set_flow(&h.app.db, row.id, "on").await.unwrap();
538
    let quiet = db::repos::get(&h.app.db, "andy", "quiet").await.unwrap().unwrap();
539
    db::repos::set_flow(&h.app.db, quiet.id, "off").await.unwrap();
540
    for (owner, name) in [("other", "plain"), ("andy", "quiet")] {
541
        let work = tempfile::tempdir().unwrap();
542
        let c = client(&format!("{}/{owner}/{name}", h.base), work.path());
543
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
544
        write(work.path(), "test.sh", "echo ok\n");
545
        c.commit("Add a pipeline", &[]).unwrap();
546
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
547
    }
548
    let plain = runs_of(&h.app, "other", "plain").await;
549
    assert_eq!(plain.len(), 1, "turned on");
550
    // With andy/first's jobs ahead, plain's run says where it stands.
551
    let a = claim(&h.app).await.unwrap();
552
    assert_eq!(a["repo"], "andy/first");
553
    let (_, page) = call(&h.app, "GET", "/other/plain/flow/1", None, None).await;
554
    assert!(page.contains("Waiting for a runner: 3rd in line") && page.contains("Running now: andy/first #1"), "{page}");
555
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/other/plain/flow/runs/1", None, None).await;
556
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["queue_position"], 3);
557
    let (_, list) = call(&h.app, "GET", "/other/plain/flow", None, None).await;
558
    assert!(list.contains("queued, 3rd in line"), "{list}");
559
    // Runs are numbered per repository: this is plain's first, whatever
560
    // other repositories ran before.
561
    assert_eq!(plain[0].number, 1);
562
    let checks = checks_when(&h.app, row.id, &plain[0].state, 3).await;
563
    assert!(checks.iter().all(|c| c.url.ends_with("/other/plain/flow/1")), "{checks:?}");
564
    let (st, page) = call(&h.app, "GET", "/other/plain/flow/1", None, None).await;
565
    assert!(st == StatusCode::OK && page.contains("Run #1"), "{st}");
566
    assert!(runs_of(&h.app, "andy", "quiet").await.is_empty(), "turned off despite andy/*");
567
}
568
569
/// "Run pipeline" and "Re-run" (hub spec §13.2): runs that move no
570
/// bookmark, through the API and the pages.
571
#[tokio::test(flavor = "multi_thread")]
572
async fn runs_start_without_a_push_and_finished_runs_re_run() {
573
    let h = hub().await;
574
    // The site token acts as the first site administrator.
575
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
576
    create(&h.app, "andy", "demo").await;
577
    let url = format!("{}/andy/demo", h.base);
578
    let work = tempfile::tempdir().unwrap();
579
    let c = client(&url, work.path());
580
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
581
    write(work.path(), "test.sh", "echo ok\n");
582
    c.commit("Add a pipeline", &[]).unwrap();
583
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
584
    let first = runs_of(&h.app, "andy", "demo").await;
585
    assert_eq!((first.len(), first[0].trigger.as_str()), (1, "push"));
586
587
    // Run pipeline on the default bookmark: a new run of the same state.
588
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
589
    assert_eq!(st, StatusCode::CREATED, "{body}");
590
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
591
    assert_eq!(v["number"], 2);
592
    assert!(v["url"].as_str().unwrap().ends_with("/andy/demo/flow/2"));
593
    let second = db::flow::run(&h.app.db, first[0].repo_id, 2).await.unwrap().unwrap();
594
    assert_eq!((second.trigger.as_str(), second.actor.as_str(), second.state.as_str()), ("manual", "andy", first[0].state.as_str()));
595
    assert_eq!(db::flow::jobs(&h.app.db, second.id).await.unwrap().len(), 3);
596
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/2", None, None).await;
597
    assert!(page.contains("started by andy"), "the run page says what started it");
598
599
    // A live run is not re-run; unknown bookmarks and runs are refused.
600
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/1/rerun", Some("site"), None).await;
601
    assert!(st == StatusCode::CONFLICT && body.contains("still queued"), "{st} {body}");
602
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"bookmark":"nope"}"#.into())).await;
603
    assert_eq!(st, StatusCode::CONFLICT);
604
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/99/rerun", Some("site"), None).await;
605
    assert_eq!(st, StatusCode::NOT_FOUND);
606
    // Anonymous callers cannot start runs.
607
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", None, Some("{}".into())).await;
608
    assert_ne!(st, StatusCode::CREATED);
609
610
    // A finished run re-runs as a new run of the same state.
611
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
612
    for r in [&first[0], &second] {
613
        for j in db::flow::jobs(&h.app.db, r.id).await.unwrap() {
614
            sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE id = ?").bind(j.id).execute(&h.app.db).await.unwrap();
615
        }
616
        sqlx::query("UPDATE flow_runs SET status = 'passed', finished_ms = 1 WHERE id = ?").bind(r.id).execute(&h.app.db).await.unwrap();
617
    }
618
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/1/rerun", Some("site"), None).await;
619
    assert_eq!(st, StatusCode::CREATED, "{body}");
620
    let third = db::flow::run(&h.app.db, row.id, 3).await.unwrap().unwrap();
621
    assert_eq!((third.trigger.as_str(), third.status.as_str(), third.state.as_str()), ("rerun:1", "queued", first[0].state.as_str()));
622
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, &third.state).await.unwrap();
623
    assert!(
624
        checks.iter().all(|c| c.status == "queued" && c.url.ends_with("/flow/3")),
625
        "the re-run's checks replace the old ones: {checks:?}"
626
    );
627
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/3", None, None).await;
628
    assert!(page.contains("re-run of #1 by andy"));
629
    assert!(!page.contains("RE-RUN"), "anonymous viewers get no button");
630
631
    // With Flow off, nothing starts.
632
    db::repos::set_flow(&h.app.db, row.id, "off").await.unwrap();
633
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
634
    assert!(st == StatusCode::CONFLICT && body.contains("not enabled"), "{body}");
635
}
636
637
/// The Flow API (hub spec §13.2): runs, a run with its jobs, a job's log,
638
/// checks by the heads a client has, and JSON for unknown API routes.
639
#[tokio::test(flavor = "multi_thread")]
640
async fn runs_jobs_and_logs_are_in_the_api() {
641
    let h = hub().await;
642
    create(&h.app, "andy", "demo").await;
643
    let url = format!("{}/andy/demo", h.base);
644
    let work = tempfile::tempdir().unwrap();
645
    let c = client(&url, work.path());
646
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
647
    write(work.path(), "test.sh", "echo ok\n");
648
    let head = c.commit("Add a pipeline", &[]).unwrap();
649
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
650
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
651
652
    // A job runs and logs.
653
    let a = claim(&h.app).await.unwrap();
654
    let id = a["job_id"].as_i64().unwrap();
655
    let recs =
656
        serde_json::json!({ "records": [{ "t": 1, "stream": "stdout", "text": "one" }, { "t": 3, "stream": "stderr", "text": "three" }] });
657
    let (st, _) = call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(recs.to_string())).await;
658
    assert!(st.is_success(), "{st}");
659
660
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs", None, None).await;
661
    assert_eq!(st, StatusCode::OK, "{body}");
662
    let runs: Vec<hub_api::FlowRun> = serde_json::from_str(&body).unwrap();
663
    assert_eq!(runs.len(), 1);
664
    assert_eq!((runs[0].number, runs[0].state.as_str(), runs[0].trigger.as_str()), (1, run.state.as_str(), "push"));
665
    assert!(runs[0].url.ends_with("/andy/demo/flow/1") && runs[0].jobs.is_empty());
666
667
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", None, None).await;
668
    let one: hub_api::FlowRun = serde_json::from_str(&body).unwrap();
669
    let names: Vec<(&str, &str)> = one.jobs.iter().map(|j| (j.name.as_str(), j.status.as_str())).collect();
670
    assert_eq!(names.len(), 3);
671
    let running = one.jobs.iter().find(|j| j.status == "running").unwrap();
672
    assert_eq!(running.name, a["job"]["name"].as_str().unwrap());
673
    assert!(one.jobs.iter().any(|j| j.name == "test" && j.depends_on == ["build"]));
674
675
    let job = running.name.clone();
676
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/1/jobs/{job}/log"), None, None).await;
677
    assert_eq!(st, StatusCode::OK, "{body}");
678
    let lines: Vec<hub_api::FlowLogLine> = serde_json::from_str(&body).unwrap();
679
    assert!(lines.iter().any(|l| l.text == "three"), "{body}");
680
    let last = lines.last().unwrap().seq;
681
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/1/jobs/{job}/log?after={last}"), None, None).await;
682
    assert_eq!(body, "[]", "nothing after the last line");
683
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/9", None, None).await.0, StatusCode::NOT_FOUND);
684
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1/jobs/nope/log", None, None).await.0, StatusCode::NOT_FOUND);
685
686
    // Checks by the state hash, by the head `oxy log` shows, and by bookmark.
687
    let by = |key: String| {
688
        let app = h.app.clone();
689
        async move {
690
            let (st, body) = call(&app, "GET", &format!("/api/v1/repos/andy/demo/checks/{key}"), None, None).await;
691
            assert_eq!(st, StatusCode::OK, "{key}: {body}");
692
            serde_json::from_str::<Vec<hub_api::Check>>(&body).unwrap().len()
693
        }
694
    };
695
    checks_when(&h.app, run.repo_id, &run.state, 3).await;
696
    assert_eq!(by(run.state.clone()).await, 3);
697
    assert_eq!(by(head.to_hex()).await, 3, "a single head names its state");
698
    assert_eq!(by("main".into()).await, 3);
699
    let (st, _) = call(&h.app, "GET", "/api/v1/repos/andy/demo/checks/no-such-bookmark", None, None).await;
700
    assert_eq!(st, StatusCode::NOT_FOUND);
701
702
    // An unknown API route answers with a problem document.
703
    let (st, body) = call(&h.app, "GET", "/api/v1/users/andy/repos", None, None).await;
704
    assert_eq!(st, StatusCode::NOT_FOUND);
705
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
706
    assert_eq!(v["status"], 404, "{body}");
707
}
708
709
async fn get_bytes(app: &Shared, path: &str) -> (StatusCode, Vec<u8>) {
710
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(path).body(Body::empty()).unwrap()).await.unwrap();
711
    let status = res.status();
712
    (status, res.into_body().collect().await.unwrap().to_bytes().to_vec())
713
}
714
715
#[tokio::test(flavor = "multi_thread")]
716
async fn signed_receipts_are_checked_kept_and_shown() {
717
    use oxy_core::hash::{hash_object, ChangeHash, ObjectRef, ObjectType};
718
    use oxy_core::identity::SecretKey;
719
    use oxy_core::objects::StateObject;
720
    use oxy_core::receipt::SignedReceipt;
721
    let h = hub().await;
722
    create(&h.app, "andy", "demo").await;
723
    let url = format!("{}/andy/demo", h.base);
724
    let work = tempfile::tempdir().unwrap();
725
    let c = client(&url, work.path());
726
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
727
    c.snapshot("test").unwrap();
728
    c.commit("Add a pipeline", &[]).unwrap();
729
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
730
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
731
    let heads: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
732
    let state = hash_object(ObjectType::State, &StateObject::new(heads.clone()).encode());
733
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
734
    let sk = SecretKey::generate();
735
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
736
    let sign = |r: &serde_json::Value, state: ObjectRef, sk: &SecretKey, id: &oxy_core::identity::Identity| {
737
        let r: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
738
        let run_url = format!("{url}/flow/{}", run.number);
739
        hex::encode(SignedReceipt::sign(r.to_oxy(), repo_id, state, &run_url, id, sk).encode())
740
    };
741
742
    let a = claim(&h.app).await.unwrap();
743
    let b = claim(&h.app).await.unwrap();
744
    let ph = a["pipeline_hash"].as_str().unwrap().to_string();
745
    let (a_id, b_id) = (a["job_id"].as_i64().unwrap(), b["job_id"].as_i64().unwrap());
746
    // The first signed receipt binds the runner token to its key, and is kept.
747
    let rb = receipt("build", &ph, 0);
748
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": rb, "signed_receipt": sign(&rb, state, &sk, &runner) });
749
    assert_eq!(finish(&h.app, a_id, body).await, StatusCode::NO_CONTENT);
750
    // Another key under the same token: the result counts, the receipt is not kept.
751
    let other = SecretKey::generate();
752
    let rl = receipt("lint", &ph, 0);
753
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 300, "receipt": rl,
754
        "signed_receipt": sign(&rl, state, &other, &other.identity("mallory", "", 1)) });
755
    assert_eq!(finish(&h.app, b_id, body).await, StatusCode::NO_CONTENT);
756
    // The right key, but for another state.
757
    let t = claim(&h.app).await.unwrap();
758
    let rt = receipt("test", &ph, 0);
759
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 500, "receipt": rt,
760
        "signed_receipt": sign(&rt, ObjectRef([9; 32]), &sk, &runner) });
761
    assert_eq!(finish(&h.app, t["job_id"].as_i64().unwrap(), body).await, StatusCode::NO_CONTENT);
762
763
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
764
    let job = |n: &str| jobs.iter().find(|j| j.name == n).unwrap().clone();
765
    assert_eq!(job("build").status, "passed");
766
    assert_eq!((job("build").receipt_attest.len(), job("build").receipt_signer.as_str()), (64, "test-1 (OxygenFlow runner)"));
767
    assert_eq!(job("lint").status, "passed", "the job's result stands");
768
    assert!(job("lint").receipt_attest.is_empty());
769
    assert!(job("lint").receipt_note.contains("not the key this runner signs with"), "{}", job("lint").receipt_note);
770
    assert!(job("test").receipt_note.contains("another state"), "{}", job("test").receipt_note);
771
772
    // The repository keeps it, and anyone who can read the repository can
773
    // download it and check it on their own.
774
    let kept = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().receipts(&heads).unwrap();
775
    assert_eq!(kept.len(), 1);
776
    let attest = job("build").receipt_attest;
777
    let (st, bytes) = get_bytes(&h.app, &format!("/andy/demo/receipts/{attest}")).await;
778
    assert_eq!(st, StatusCode::OK);
779
    let sr = SignedReceipt::decode(&bytes).unwrap();
780
    sr.verify().unwrap();
781
    assert_eq!((sr.state(), sr.receipt.job_name.as_str()), (state, "build"));
782
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/receipts/{}", "0".repeat(64))).await.0, StatusCode::NOT_FOUND);
783
784
    // Pages: the run names the signer or why a receipt was not kept; the
785
    // change whose state it is lists it.
786
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
787
    assert!(page.contains("signed receipt</a> by test-1"), "run page");
788
    assert!(page.contains("receipt not kept"), "run page");
789
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/change/{}", heads[0].to_hex()), None, None).await;
790
    assert!(page.contains("<dt>Receipts</dt>") && page.contains(&format!("/andy/demo/receipts/{attest}")), "change page");
791
}
792
793
async fn upload(app: &Shared, job: i64, name: &str, bytes: &[u8]) -> (StatusCode, String) {
794
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/artifacts/{name}"))
795
        .header(header::AUTHORIZATION, "Bearer runner-secret")
796
        .header(header::CONTENT_TYPE, "application/octet-stream")
797
        .body(Body::from(bytes.to_vec()))
798
        .unwrap();
799
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
800
    let status = res.status();
801
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
802
}
803
804
#[tokio::test(flavor = "multi_thread")]
805
async fn artifacts_are_kept_named_by_the_receipt_and_served() {
806
    let h = hub().await;
807
    create(&h.app, "andy", "demo").await;
808
    let url = format!("{}/andy/demo", h.base);
809
    let work = tempfile::tempdir().unwrap();
810
    let c = client(&url, work.path());
811
    write(
812
        work.path(),
813
        ".flow/pipeline.kdl",
814
        &format!(
815
            "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"
816
        ),
817
    );
818
    c.snapshot("test").unwrap();
819
    c.commit("Build a tool", &[]).unwrap();
820
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
821
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
822
    let a = claim(&h.app).await.unwrap();
823
    assert_eq!(a["job"]["outputs"], serde_json::json!([{ "name": "tool", "path": "/src/out/tool" }]), "the runner is told");
824
    let id = a["job_id"].as_i64().unwrap();
825
826
    let body: Vec<u8> = (0..300_000u32).map(|i| (i % 253) as u8).collect();
827
    let (st, text) = upload(&h.app, id, "other", &body).await;
828
    assert_eq!(st, StatusCode::BAD_REQUEST, "an undeclared artifact: {text}");
829
    let (st, text) = upload(&h.app, id, "tool", &body).await;
830
    assert_eq!(st, StatusCode::OK, "{text}");
831
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
832
    assert_eq!(blob, oxy_core::repo::Repo::blob_ref(&body).to_hex(), "the same blob the runner computes");
833
834
    // The receipt must name exactly the uploaded artifacts.
835
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
836
    assert_eq!(
837
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r.clone() })).await,
838
        StatusCode::BAD_REQUEST
839
    );
840
    r["outputs"] = serde_json::json!([blob]);
841
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r })).await, StatusCode::NO_CONTENT);
842
843
    // The run page lists it; anyone who can read the repository downloads it.
844
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
845
    let link = format!("/andy/demo/flow/{}/artifacts/build/tool", run.number);
846
    assert!(page.contains(&link), "run page lists the artifact");
847
    let (st, got) = get_bytes(&h.app, &link).await;
848
    assert_eq!((st, got == body), (StatusCode::OK, true));
849
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/flow/{}/artifacts/build/none", run.number)).await.0, StatusCode::NOT_FOUND);
850
851
    // A writer attaches the artifact to a release from the run page; the
852
    // release then names the run and job that built it, as does the API.
853
    let form = |f: String| {
854
        Request::post("/register").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(Body::from(f)).unwrap()
855
    };
856
    let res = oxygenhub::router(h.app.clone())
857
        .oneshot(form("username=andy&email=a%40example.com&password=correct-horse-battery".into()))
858
        .await
859
        .unwrap();
860
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
861
    let with_cookie = |method: &str, path: &str, body: Option<String>| {
862
        let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie.clone());
863
        if body.is_some() {
864
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
865
        }
866
        req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()
867
    };
868
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
869
    db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
870
    let res = oxygenhub::router(h.app.clone()).oneshot(with_cookie("GET", &format!("/andy/demo/flow/{}", run.number), None)).await.unwrap();
871
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
872
    let attach = format!("/andy/demo/flow/{}/artifacts/build/tool/attach", run.number);
873
    assert!(page.contains(&attach), "a writer is offered the release");
874
    let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
875
    let csrf = page[i..].split('"').next().unwrap().to_string();
876
    let release_id = db::releases::list(&h.app.db, row.id).await.unwrap()[0].id;
877
    let res = oxygenhub::router(h.app.clone())
878
        .oneshot(with_cookie("POST", &attach, Some(format!("_csrf={csrf}&release={release_id}"))))
879
        .await
880
        .unwrap();
881
    assert_eq!(res.status(), StatusCode::SEE_OTHER);
882
    let (_, page) = call(&h.app, "GET", "/andy/demo/releases/tag/v1", None, None).await;
883
    assert!(
884
        page.contains(">tool</a>") && page.contains(&format!("built by <a href=\"/andy/demo/flow/{0}\">run #{0}</a> build", run.number)),
885
        "{page}"
886
    );
887
    let (_, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases", None, None).await;
888
    let api: serde_json::Value = serde_json::from_str(&api).unwrap();
889
    let asset = &api[0]["assets"][0];
890
    assert_eq!(
891
        (asset["name"].as_str(), asset["built_by"]["run"].as_i64(), asset["built_by"]["job"].as_str()),
892
        (Some("tool"), Some(run.number), Some("build"))
893
    );
894
    assert!(asset["built_by"]["receipt"].is_null(), "that receipt was not signed");
895
}
896
897
/// A release's trust report (hub spec §9.1): a signed tag, an asset built
898
/// by a job with a signed receipt from the tagged state, and one uploaded
899
/// by hand; the page, its JSON export and the API.
900
#[tokio::test(flavor = "multi_thread")]
901
async fn a_release_is_audited_from_authors_to_receipts() {
902
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
903
    use oxy_core::identity::SecretKey;
904
    use oxy_core::objects::StateObject;
905
    use oxy_core::receipt::SignedReceipt;
906
    let h = hub().await;
907
    create(&h.app, "andy", "demo").await;
908
    let url = format!("{}/andy/demo", h.base);
909
    let work = tempfile::tempdir().unwrap();
910
    let mut c = client(&url, work.path());
911
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
912
    write(
913
        work.path(),
914
        ".flow/pipeline.kdl",
915
        &format!(
916
            "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"
917
        ),
918
    );
919
    c.snapshot("test").unwrap();
920
    c.commit("Build a tool", &[]).unwrap();
921
    let heads = c.bookmark_heads().unwrap();
922
    c.tag_create("v1", &heads, "first").unwrap();
923
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
924
925
    // The runner builds, uploads the artifact and signs its receipt.
926
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
927
    let a = claim(&h.app).await.unwrap();
928
    let id = a["job_id"].as_i64().unwrap();
929
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
930
    let (_, text) = upload(&h.app, id, "tool", &body).await;
931
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
932
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
933
    r["outputs"] = serde_json::json!([blob]);
934
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
935
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
936
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
937
    let sk = SecretKey::generate();
938
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
939
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
940
    let signed = hex::encode(SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/1"), &runner, &sk).encode());
941
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
942
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
943
944
    // A release with the built asset and a file uploaded by hand.
945
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
946
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
947
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
948
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "notes.txt", "", b"by hand\n").await.unwrap();
949
950
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
951
    assert_eq!(st, StatusCode::OK);
952
    for want in [
953
        "Tag v1 is signed",
954
        "The one change in the release is authenticated",
955
        "tool: signed receipt from run #1 build",
956
        "a runner key of this hub",
957
        "tool: built from the tagged state",
958
        "tool: pinned environment",
959
        "notes.txt: no build found",
960
        "<svg class=\"trust-graph\"",
961
    ] {
962
        assert!(page.contains(want), "missing {want:?}");
963
    }
964
    let (_, releases) = call(&h.app, "GET", "/andy/demo/releases", None, None).await;
965
    assert!(releases.contains("/andy/demo/releases/trust/v1"), "the release links its audit");
966
967
    // The export carries the signed receipt, which checks on its own.
968
    let (st, json) = call(&h.app, "GET", "/andy/demo/releases/trust/v1?format=json", None, None).await;
969
    assert_eq!(st, StatusCode::OK);
970
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
971
    assert_eq!((t["tag"].as_str(), t["tag_signature"].as_str(), t["changes"].as_i64()), (Some("v1"), Some("valid"), Some(1)));
972
    assert_eq!(t["authors"][0]["who"]["name"], "Andy");
973
    let tool = t["assets"].as_array().unwrap().iter().find(|a| a["name"] == "tool").unwrap();
974
    let hex_receipt = tool["build"]["signed_receipt"].as_str().unwrap();
975
    let sr = SignedReceipt::decode(&hex::decode(hex_receipt).unwrap()).unwrap();
976
    sr.verify().unwrap();
977
    assert_eq!(sr.receipt.outputs[0].to_hex(), blob);
978
    let audit = t["audit"].as_array().unwrap();
979
    assert!(audit.iter().any(|c| c["verdict"] == "warn" && c["title"].as_str().unwrap().starts_with("notes.txt")));
980
    assert!(!audit.iter().any(|c| c["verdict"] == "fail"), "{audit:?}");
981
    // The API gives the same report; an unknown release is a 404.
982
    let (st, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v1", None, None).await;
983
    assert_eq!(st, StatusCode::OK);
984
    assert_eq!(serde_json::from_str::<serde_json::Value>(&api).unwrap()["assets"].as_array().unwrap().len(), 2);
985
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
986
    assert_eq!(call(&h.app, "GET", "/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
987
}
988
989
/// Runners (hub spec §13.2): an administrator makes a registration token,
990
/// a runner registers with it (binding its key), claims, shows on Admin →
991
/// Runners with its history, and is drained, disabled and removed.
992
#[tokio::test(flavor = "multi_thread")]
993
async fn runners_register_show_their_history_and_are_drained_and_removed() {
994
    use oxy_core::identity::SecretKey;
995
    let h = hub().await;
996
    create(&h.app, "andy", "demo").await;
997
    // A signed-in site administrator.
998
    let res = oxygenhub::router(h.app.clone())
999
        .oneshot(
1000
            Request::post("/register")
1001
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1002
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery"))
1003
                .unwrap(),
1004
        )
1005
        .await
1006
        .unwrap();
1007
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1008
    let admin = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
1009
    db::accounts::set_admin(&h.app.db, admin.id, true).await.unwrap();
1010
    let web = |method: &'static str, path: String, body: Option<String>| {
1011
        let (app, cookie) = (h.app.clone(), cookie.clone());
1012
        async move {
1013
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1014
            if body.is_some() {
1015
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1016
            }
1017
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1018
            let st = res.status();
1019
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1020
        }
1021
    };
1022
    let csrf_of = |page: &str| {
1023
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1024
        page[i..].split('"').next().unwrap().to_string()
1025
    };
1026
    let (st, page) = web("GET", "/admin/runners".into(), None).await;
1027
    assert_eq!(st, StatusCode::OK);
1028
    assert!(page.contains("No runners yet"));
1029
    assert_eq!(call(&h.app, "GET", "/admin/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1030
1031
    // A one-time registration token, shown once with the command.
1032
    let (_, page) = web("POST", "/admin/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1033
    let i = page.find("--token ").unwrap() + "--token ".len();
1034
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1035
    assert!(token.starts_with("flowreg_"), "{token}");
1036
1037
    // The runner registers, binding its key; the token then is spent.
1038
    let sk = SecretKey::generate();
1039
    let identity = sk.identity("plex (OxygenFlow runner)", "", 1);
1040
    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 });
1041
    let reg = serde_json::json!({ "token": token, "name": "plex", "identity": hex::encode(identity.encode()), "info": info });
1042
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1043
    assert_eq!(st, StatusCode::OK, "{body}");
1044
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1045
    assert!(credential.starts_with("flowrunner_"));
1046
    assert_eq!(
1047
        call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0,
1048
        StatusCode::FORBIDDEN,
1049
        "used once"
1050
    );
1051
1052
    // It claims with its credential; the hub.toml runner shows too.
1053
    let claim_as = |who: String| {
1054
        let app = h.app.clone();
1055
        let info = info.clone();
1056
        async move {
1057
            let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
1058
            call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await
1059
        }
1060
    };
1061
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "nothing queued");
1062
    assert_eq!(claim(&h.app).await, None);
1063
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1064
    assert!(
1065
        page.contains(">plex</strong>") && page.contains("st-online") && page.contains("x86_64 · linux") && page.contains("big-disk"),
1066
        "{page}"
1067
    );
1068
    assert!(page.contains(">test-1</strong>") && page.contains("hub.toml"), "the configured runner, by its claimed name");
1069
    let plex = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1070
    assert_eq!(plex.key, identity.hash().to_hex(), "bound at registration");
1071
1072
    // A run: plex takes a job, and its history shows it.
1073
    let url = format!("{}/andy/demo", h.base);
1074
    let work = tempfile::tempdir().unwrap();
1075
    let c = client(&url, work.path());
1076
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1077
    c.snapshot("test").unwrap();
1078
    c.commit("Add a pipeline", &[]).unwrap();
1079
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1080
    runs_of(&h.app, "andy", "demo").await;
1081
    let (st, body) = claim_as(credential.clone()).await;
1082
    assert_eq!(st, StatusCode::OK, "{body}");
1083
    let job: serde_json::Value = serde_json::from_str(&body).unwrap();
1084
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1085
    assert!(
1086
        page.contains("andy/demo") && page.contains(job["job"]["name"].as_str().unwrap()) && page.contains("Running now</dt><dd>1 job"),
1087
        "{page}"
1088
    );
1089
1090
    // Draining: no new work; removing while busy is refused.
1091
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1092
    let csrf = csrf_of(&page);
1093
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=draining"))).await;
1094
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "a draining runner takes nothing");
1095
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1096
    assert!(page.contains("is running jobs: drain it first"), "{page}");
1097
    // Its job finishes; disabled, it is refused; removed, its credential is dead.
1098
    let id = job["job_id"].as_i64().unwrap();
1099
    let done = call(
1100
        &h.app,
1101
        "POST",
1102
        &format!("/api/v1/flow/jobs/{id}/finish"),
1103
        Some(&credential),
1104
        Some(r#"{"exit_code":0,"duration_ms":5}"#.into()),
1105
    )
1106
    .await;
1107
    assert_eq!(done.0, StatusCode::NO_CONTENT);
1108
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=disabled"))).await;
1109
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::FORBIDDEN);
1110
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1111
    assert!(page.contains("Removed plex."), "{page}");
1112
    assert_eq!(claim_as(credential).await.0, StatusCode::UNAUTHORIZED);
1113
}