zebflow 0.11.14

Reactive web automation platform — pipelines, templates, and real-time collaboration in a single binary.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Regression cover for the shared path-containment mistake (S1-S3).
//!
//! Each of these reached the filesystem through an *authorised* request: the
//! caller had the capability the route asks for, on the project the route
//! names, and then handed a path in the request body that pointed somewhere
//! else entirely. What was checked was `joined.starts_with(root)`, which
//! compares path components without resolving them — so `root/../../elsewhere`
//! "starts with" `root`.

use std::fs;
use std::sync::Arc;

use axum::body::{Body, to_bytes};
use axum::http::{Request, StatusCode, header};
use serde_json::{Value, json};
use tower::ServiceExt;

use zebflow::platform::model::CreateProjectRequest;
use zebflow::platform::{PlatformConfig, PlatformService};

/// A temp dir whose removal is tied to the returned value's lifetime; the
/// caller must keep the `tempfile::TempDir` bound (not `_`) for as long as
/// `path` is used.
fn temp_test_dir(name: &str) -> (tempfile::TempDir, std::path::PathBuf) {
    let tmp = tempfile::tempdir().expect("tempdir");
    let path = tmp.path().join(format!("zebflow-containment-{name}"));
    (tmp, path)
}

async fn login_cookie(app: axum::Router, identifier: &str, password: &str) -> String {
    let login = app
        .oneshot(
            Request::builder()
                .uri("/login")
                .method("POST")
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(Body::from(format!(
                    "identifier={identifier}&password={password}"
                )))
                .expect("request"),
        )
        .await
        .expect("login response");
    assert_eq!(login.status(), StatusCode::SEE_OTHER);
    login
        .headers()
        .get(header::SET_COOKIE)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.split(';').next())
        .expect("session cookie")
        .to_string()
}

async fn post_json(
    app: &axum::Router,
    cookie: &str,
    uri: &str,
    body: Value,
) -> (StatusCode, Value) {
    let response = app
        .clone()
        .oneshot(
            Request::builder()
                .uri(uri)
                .method("POST")
                .header(header::COOKIE, cookie)
                .header(header::CONTENT_TYPE, "application/json")
                .body(Body::from(body.to_string()))
                .expect("request"),
        )
        .await
        .expect("response");
    let status = response.status();
    let text = to_bytes(response.into_body(), usize::MAX)
        .await
        .map(|bytes| String::from_utf8_lossy(&bytes).to_string())
        .unwrap_or_default();
    let value = serde_json::from_str::<Value>(&text).unwrap_or(Value::String(text));
    (status, value)
}

fn pipeline_source(id: &str, path: &str) -> String {
    json!({
        "apiVersion": "zebflow.com/v1",
        "kind": "Pipeline",
        "metadata": { "name": id },
        "spec": {
            "id": id,
            "entry_nodes": ["wh"],
            "nodes": [{
                "id": "wh",
                "kind": "trigger.webhook",
                "input_pins": [],
                "output_pins": ["out"],
                "config": { "route": path, "method": "POST" }
            }],
            "edges": []
        }
    })
    .to_string()
}

/// S2 + S3. Two projects, one owner, one session. Every pipeline door takes
/// `file_rel_path` from the request body while authorising against the project
/// in the route, so a body full of `..` used the attacker's capability on the
/// victim's disk. Revert `normalize_pipeline_file_rel_path` and the file
/// appears under `victim/repo/src/`; revert the lock handler and it reads and
/// rewrites the victim's pipeline in place.
#[tokio::test]
async fn a_pipeline_body_cannot_reach_across_projects_through_any_door() {
    let (_tmp, data_root) = temp_test_dir("pipeline-cross-project");
    let mut config = PlatformConfig::default();
    config.data_root = data_root;
    config.default_password = "test-pass".to_string();
    let platform = Arc::new(PlatformService::from_config(config).expect("platform service"));
    let app = zebflow::platform::web::router(platform.clone()).await;
    let cookie = login_cookie(app.clone(), "superadmin", "test-pass").await;

    for project in ["attacker", "victim"] {
        platform
            .projects
            .create_or_update_project(
                "superadmin",
                &CreateProjectRequest {
                    project: project.to_string(),
                    title: Some(project.to_string()),
                    local_branch: None,
                    runtime: Default::default(),
                },
            )
            .expect("project");
    }
    let attacker = platform
        .projects
        .project_layout("superadmin", "attacker")
        .expect("attacker layout");
    let victim = platform
        .projects
        .project_layout("superadmin", "victim")
        .expect("victim layout");

    // The victim owns a real, unlocked pipeline.
    let (status, _) = post_json(
        &app,
        &cookie,
        "/api/projects/superadmin/victim/pipelines/definition",
        json!({
            "file_rel_path": "api/payouts",
            "title": "Payouts",
            "description": "",
            "trigger_kind": "webhook",
            "source": pipeline_source("payouts", "/payouts"),
        }),
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let victim_file = victim.repo_source_dir().join("api/payouts.zf.json");
    assert!(victim_file.is_file());
    let victim_before = fs::read_to_string(&victim_file).expect("victim pipeline");

    // Counted so it genuinely lands on the victim's file: the pipeline doors
    // join onto `<data_root>/users/superadmin/attacker/repo/<source>`, and
    // `<data_root>/users/superadmin` is the source's own depth plus two —
    // out of `repo/` and out of the project. The source root is the repository
    // itself unless a project declares otherwise, so the depth is counted
    // rather than assumed.
    let source_rel = attacker
        .repo_source_dir()
        .strip_prefix(&attacker.repo_dir)
        .expect("source root under repo")
        .to_string_lossy()
        .to_string();
    let ups = "../".repeat(source_rel.split('/').filter(|s| !s.is_empty()).count() + 2);
    let source_segment = if source_rel.is_empty() {
        String::new()
    } else {
        format!("{source_rel}/")
    };
    let hostile = format!("{ups}victim/repo/{source_segment}api/payouts.zf.json");
    let hostile = hostile.as_str();
    assert_eq!(
        attacker.repo_source_dir().join(hostile).canonicalize().ok(),
        victim_file.canonicalize().ok(),
        "the fixture must actually aim at the victim's pipeline"
    );

    // Door 1: write. It is contained, not refused -- the caller wrote into
    // their own project at a mangled name, which is their business.
    let (status, body) = post_json(
        &app,
        &cookie,
        "/api/projects/superadmin/attacker/pipelines/definition",
        json!({
            "file_rel_path": hostile,
            "title": "Owned",
            "description": "",
            "trigger_kind": "webhook",
            "source": pipeline_source("owned", "/owned"),
        }),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(
        fs::read_to_string(&victim_file).expect("victim pipeline"),
        victim_before,
        "the victim's pipeline was overwritten from another project"
    );
    let identity = body["meta"]["file_rel_path"]
        .as_str()
        .expect("identity")
        .to_string();
    assert!(
        !identity.contains(".."),
        "the stored identity kept traversal: {identity}"
    );
    assert!(
        attacker.repo_source_dir().join(&identity).is_file(),
        "the contained write did not land in the caller's own project"
    );

    // Door 2: the lock toggle, which had no path guard at all -- it read any
    // file decoding as a Pipeline envelope and wrote the file back.
    let (status, body) = post_json(
        &app,
        &cookie,
        "/api/projects/superadmin/attacker/pipelines/lock-toggle",
        json!({ "file_rel_path": hostile, "locked": true }),
    )
    .await;
    assert!(
        status == StatusCode::NOT_FOUND || status == StatusCode::OK,
        "unexpected lock-toggle status {status}: {body}"
    );
    assert_eq!(
        fs::read_to_string(&victim_file).expect("victim pipeline"),
        victim_before,
        "the lock toggle rewrote a pipeline in another project"
    );

    // Door 3: read. It must not hand back the victim's source.
    let (_, body) = post_json(
        &app,
        &cookie,
        "/api/projects/superadmin/attacker/pipelines/by-id",
        json!({ "file_rel_path": hostile }),
    )
    .await;
    assert!(
        !body.to_string().contains("/payouts"),
        "the victim's pipeline source was read across projects: {body}"
    );

    // Door 4: delete.
    let response = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/api/projects/superadmin/attacker/pipelines/definition")
                .method("DELETE")
                .header(header::COOKIE, &cookie)
                .header(header::CONTENT_TYPE, "application/json")
                .body(Body::from(json!({ "file_rel_path": hostile }).to_string()))
                .expect("request"),
        )
        .await
        .expect("delete response");
    let _ = response.status();
    assert!(
        victim_file.is_file(),
        "the victim's pipeline was deleted from another project"
    );
}

/// S1. `target_folder` arrives from the hub install request body and names
/// where a package's files land. Its only cleaning stripped a leading `./` and
/// `/`, and the destination guard was the same non-resolving `starts_with`, so
/// a hostile folder wrote the package anywhere the server process could reach.
/// Revert `normalize_repo_rel` and the install root escapes the repository.
#[tokio::test]
async fn a_hub_install_target_folder_cannot_write_outside_the_repository() {
    let (_tmp, data_root_path) = temp_test_dir("hub-target-folder");
    let mut config = PlatformConfig::default();
    config.data_root = data_root_path;
    config.default_password = "test-pass".to_string();
    let data_root = config.data_root.clone();
    let platform = Arc::new(PlatformService::from_config(config).expect("platform service"));
    let app = zebflow::platform::web::router(platform.clone()).await;
    let cookie = login_cookie(app.clone(), "superadmin", "test-pass").await;

    for project in ["producer", "consumer"] {
        platform
            .projects
            .create_or_update_project(
                "superadmin",
                &CreateProjectRequest {
                    project: project.to_string(),
                    title: Some(project.to_string()),
                    local_branch: None,
                    runtime: Default::default(),
                },
            )
            .expect("project");
    }
    platform
        .hub
        .ensure_default_service_instance("standalone", "http://127.0.0.1/api", true)
        .expect("enable hub service");
    platform
        .hub
        .set_authority_enabled("superadmin", "producer", true)
        .expect("authority");
    platform
        .hub
        .upsert_publisher(
            "superadmin",
            "producer",
            "escape-lab",
            "Escape Lab",
            "https://publishers.example/escape-lab",
            "escape@example.com",
            "",
            "",
            "",
            true,
            true,
            true,
            false,
            20,
            10 * 1024 * 1024,
            8,
            2 * 1024 * 1024,
        )
        .expect("publisher");
    platform
        .projects
        .upsert_pipeline_definition(
            "superadmin",
            "producer",
            "pipelines/escapee.zf.json",
            "Escapee",
            "",
            "webhook",
            &pipeline_source("escapee", "/escapee"),
        )
        .expect("producer pipeline");
    platform
        .hub
        .publish_asset(
            "superadmin",
            "producer",
            "superadmin",
            "escape-lab",
            "",
            "",
            "",
            "superadmin",
            "producer",
            "pipeline_with_dependencies",
            "pipelines/escapee.zf.json",
            "escapee",
            "1.0.0",
            "Escapee",
            "A package that asks to be installed outside the repository.",
            "",
            "public",
            Default::default(),
            vec!["escape".to_string()],
        )
        .expect("publish");

    let consumer = platform
        .projects
        .project_layout("superadmin", "consumer")
        .expect("consumer layout");
    // A canary outside the repository, at the depth the traversal aims for.
    let canary = data_root.join("users").join("canary.txt");
    fs::write(&canary, "untouched").expect("canary");

    for hostile in [
        "../../../../tmp/zebflow-hub-escape",
        "billing/../../../../..",
        "/../../../../users",
    ] {
        let (status, body) = post_json(
            &app,
            &cookie,
            "/api/projects/superadmin/consumer/hub/assets/escape-lab.escapee/1.0.0/review",
            json!({ "target_folder": hostile }),
        )
        .await;
        assert_eq!(status, StatusCode::OK, "review for {hostile:?}: {body}");
        let install_root = body["review"]["install_root"]
            .as_str()
            .expect("install root")
            .to_string();
        assert!(
            !install_root.contains(".."),
            "target_folder {hostile:?} produced install root {install_root:?}"
        );
        for added in body["review"]["files_added"]
            .as_array()
            .cloned()
            .unwrap_or_default()
        {
            let added = added.as_str().unwrap_or_default();
            assert!(
                !added.contains(".."),
                "target_folder {hostile:?} would write {added}"
            );
        }

        let (status, body) = post_json(
            &app,
            &cookie,
            "/api/projects/superadmin/consumer/hub/assets/escape-lab.escapee/1.0.0/add",
            json!({ "target_folder": hostile }),
        )
        .await;
        assert_eq!(status, StatusCode::OK, "add for {hostile:?}: {body}");
        for identity in body["result"]["pipelines_registered"]
            .as_array()
            .cloned()
            .unwrap_or_default()
        {
            let identity = identity.as_str().expect("identity");
            assert!(!identity.contains(".."), "registered identity {identity}");
            platform
                .projects
                .delete_pipeline("superadmin", "consumer", identity)
                .expect("remove install");
        }
        assert_eq!(
            fs::read_to_string(&canary).expect("canary"),
            "untouched",
            "target_folder {hostile:?} reached outside the project repository"
        );
        assert!(
            !std::path::Path::new("/tmp/zebflow-hub-escape").exists(),
            "target_folder {hostile:?} wrote into /tmp"
        );
        assert!(consumer.repo_dir.is_dir());
    }
}