cosca 0.8.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! Truth tables for the composed creation-flag word. Pure: nothing here spawns anything, so
//! every rule is pinned across the whole request space rather than at the shapes a live spawn
//! happens to take.
#![cfg(windows)]

use windows::Win32::System::Threading::{
    CREATE_BREAKAWAY_FROM_JOB, CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW, CREATE_SUSPENDED,
    CREATE_UNICODE_ENVIRONMENT, DEBUG_ONLY_THIS_PROCESS, DEBUG_PROCESS, DETACHED_PROCESS, EXTENDED_STARTUPINFO_PRESENT,
    IDLE_PRIORITY_CLASS,
};

use super::{windows_spawn, FlagsRequest, SpawnBackend};
use crate::containment::{ContainMode, ContainRequest, Nesting};
use crate::error::Error;

fn uncontained() -> ContainRequest {
    ContainRequest {
        mode: None,
        nesting: Nesting::Mark,
    }
}

fn contained() -> ContainRequest {
    ContainRequest {
        mode: Some(ContainMode::Strongest),
        nesting: Nesting::Mark,
    }
}

fn word(contain: &ContainRequest, flags: FlagsRequest, is_root: bool, backend: SpawnBackend) -> u32 {
    windows_spawn(contain, flags, is_root, backend)
        .expect("this request shape is allowed")
        .creation_flags
}

fn refusal(flags: FlagsRequest) -> String {
    match windows_spawn(&uncontained(), flags, false, SpawnBackend::Std) {
        Ok(w) => panic!("expected a refusal, got the word {:#x}", w.creation_flags),
        Err(Error::Unsupported { detail, .. }) => detail,
        Err(other) => panic!("expected Unsupported, got {other:?}"),
    }
}

/// A caller's raw word reaches an uncontained spawn untouched — the shape `prepare` composes
/// the word for above its `mode.is_none()` early return.
#[skuld::test]
fn an_uncontained_std_request_carries_only_the_callers_flags() {
    let flags = FlagsRequest {
        raw: IDLE_PRIORITY_CLASS.0,
        ..Default::default()
    };
    assert_eq!(
        word(&uncontained(), flags, false, SpawnBackend::Std),
        IDLE_PRIORITY_CLASS.0,
        "an uncontained std spawn supplies nothing of its own"
    );
}

/// The containment decision and the caller's intent are ORed, not chosen between: a `Strongest`
/// root keeps its suspend and its process group while also getting the caller's suppression.
#[skuld::test]
fn contained_root_flags_and_caller_flags_compose() {
    let flags = FlagsRequest {
        no_window: true,
        ..Default::default()
    };
    assert_eq!(
        word(&contained(), flags, true, SpawnBackend::Std),
        CREATE_SUSPENDED.0 | CREATE_NEW_PROCESS_GROUP.0 | CREATE_NO_WINDOW.0,
    );
}

/// The two bits the raw `CreateProcessW` backend cannot spawn without are supplied by
/// `windows_spawn` for that backend and by nothing else, so no backend ORs anything on
/// afterwards.
///
/// **This pins a cosca-side difference only.** Per `library/std/src/sys/process/windows.rs`, std
/// ORs `CREATE_UNICODE_ENVIRONMENT` into whatever word it was given at spawn time, so this test
/// does not say the OS receives a `Std` word without it — only that cosca does not supply it.
#[skuld::test]
fn cosca_supplies_the_structural_bits_only_on_the_raw_backend() {
    let flags = FlagsRequest {
        no_window: true,
        ..Default::default()
    };
    let std_word = word(&contained(), flags, true, SpawnBackend::Std);
    let raw_word = word(&contained(), flags, true, SpawnBackend::Raw);
    assert_eq!(
        raw_word ^ std_word,
        CREATE_UNICODE_ENVIRONMENT.0 | EXTENDED_STARTUPINFO_PRESENT.0,
        "the backends differ by exactly the two structural bits",
    );
}

/// Both intents are emitted; neither normalizes the other away. Measured: a child with both
/// behaves as detached, and cosca reports what it asked for rather than second-guessing it.
#[skuld::test]
fn detached_and_no_window_both_appear() {
    let flags = FlagsRequest {
        detached: true,
        no_window: true,
        ..Default::default()
    };
    let w = word(&uncontained(), flags, false, SpawnBackend::Std);
    assert_eq!(w, DETACHED_PROCESS.0 | CREATE_NO_WINDOW.0);
}

/// The breakaway bit is emitted from the request alone, never from a reading of the ambient job:
/// a probe taken before the spawn could go stale in the gap, and omitting the bit would silently
/// leave the child in a job the caller asked it to escape. Asserted for both backends and both
/// root-nesses so no backend can drop it.
#[skuld::test]
fn a_breakaway_request_always_emits_the_bit() {
    let flags = FlagsRequest {
        breakaway_from_job: true,
        ..Default::default()
    };
    for backend in [SpawnBackend::Std, SpawnBackend::Raw] {
        for is_root in [true, false] {
            let w = word(&uncontained(), flags, is_root, backend);
            assert_ne!(
                w & CREATE_BREAKAWAY_FROM_JOB.0,
                0,
                "{backend:?}/is_root={is_root} dropped the breakaway request"
            );
        }
    }
}

/// An uncontained word does not depend on the root marker at all, which is what licenses
/// `prepare` composing the word once, above its containment branch.
#[skuld::test]
fn an_uncontained_word_ignores_is_root() {
    let flags = FlagsRequest {
        no_window: true,
        raw: IDLE_PRIORITY_CLASS.0,
        ..Default::default()
    };
    assert_eq!(
        word(&uncontained(), flags, true, SpawnBackend::Std),
        word(&uncontained(), flags, false, SpawnBackend::Std),
    );
}

/// Every reserved bit is refused, and the refusal names the bit symbolically — a caller who
/// passed `0x0800_0000` should not have to look up which flag that was.
///
/// The list is written out here rather than read from the production table, so dropping a row
/// from that table fails this test instead of silently un-reserving a bit. The length equality
/// closes the other direction: a row ADDED to that table cannot land uncovered.
#[skuld::test]
fn each_reserved_bit_is_refused_by_name() {
    let reserved = [
        (DEBUG_PROCESS.0, "DEBUG_PROCESS"),
        (DEBUG_ONLY_THIS_PROCESS.0, "DEBUG_ONLY_THIS_PROCESS"),
        (CREATE_SUSPENDED.0, "CREATE_SUSPENDED"),
        (DETACHED_PROCESS.0, "DETACHED_PROCESS"),
        (CREATE_NEW_CONSOLE.0, "CREATE_NEW_CONSOLE"),
        (CREATE_NEW_PROCESS_GROUP.0, "CREATE_NEW_PROCESS_GROUP"),
        (CREATE_UNICODE_ENVIRONMENT.0, "CREATE_UNICODE_ENVIRONMENT"),
        (EXTENDED_STARTUPINFO_PRESENT.0, "EXTENDED_STARTUPINFO_PRESENT"),
        (CREATE_BREAKAWAY_FROM_JOB.0, "CREATE_BREAKAWAY_FROM_JOB"),
        (CREATE_NO_WINDOW.0, "CREATE_NO_WINDOW"),
    ];
    assert_eq!(
        reserved.len(),
        super::reserved_table().len(),
        "mirror every production reserved row here, or the new one ships untested"
    );
    for (bit, name) in reserved {
        let detail = refusal(FlagsRequest {
            raw: bit,
            ..Default::default()
        });
        assert!(detail.contains(name), "refusal for {bit:#x} must name {name}: {detail}");
    }
}

/// Two reserved bits at once name both, so a caller fixes one call instead of iterating through
/// a refusal per bit.
#[skuld::test]
fn several_reserved_bits_are_all_named() {
    let detail = refusal(FlagsRequest {
        raw: CREATE_SUSPENDED.0 | CREATE_NO_WINDOW.0,
        ..Default::default()
    });
    assert!(detail.contains("CREATE_SUSPENDED"), "{detail}");
    assert!(detail.contains("CREATE_NO_WINDOW"), "{detail}");
}

/// The two bits the raw backend supplies structurally are themselves reserved, so a caller can
/// never set one and have it doubled — or clear one the backend cannot spawn without.
#[skuld::test]
fn the_structural_bits_are_reserved() {
    for (bit, name) in [
        (CREATE_UNICODE_ENVIRONMENT.0, "CREATE_UNICODE_ENVIRONMENT"),
        (EXTENDED_STARTUPINFO_PRESENT.0, "EXTENDED_STARTUPINFO_PRESENT"),
    ] {
        let detail = refusal(FlagsRequest {
            raw: bit,
            ..Default::default()
        });
        assert!(detail.contains(name), "{detail}");
    }
}

/// The three containment shapes must not all report the same cooperative-signal mechanism: an
/// uncontained spawn leads no group, while both contained shapes do. Asserted on the COMPOSED
/// word, which is the only word any spawn path derives a mechanism from.
#[skuld::test]
fn the_composed_word_reports_a_different_mechanism_for_each_containment_shape() {
    use crate::containment::windows::mechanism_from_flags;
    use crate::graceful::GracefulMechanism;

    let none = FlagsRequest::default();
    assert_eq!(
        mechanism_from_flags(word(&uncontained(), none, true, SpawnBackend::Std)),
        GracefulMechanism::None,
        "an uncontained spawn passes no group flag, so it leads no group"
    );
    assert_eq!(
        mechanism_from_flags(word(&contained(), none, true, SpawnBackend::Std)),
        GracefulMechanism::ConsoleGroup,
        "a Strongest root spawns suspended into its own group"
    );
    assert_eq!(
        mechanism_from_flags(word(&contained(), none, false, SpawnBackend::Std)),
        GracefulMechanism::ConsoleGroup,
        "a nested spawn leads its own group too"
    );
    assert_eq!(
        mechanism_from_flags(word(
            &contained(),
            FlagsRequest {
                no_window: true,
                ..Default::default()
            },
            true,
            SpawnBackend::Std
        )),
        GracefulMechanism::OtherConsoleGroup,
        "window suppression puts the child's group in a console of its own"
    );
}

// ===== breakaway: the pre-spawn rule and the post-failure classifier =====

use crate::containment::windows::JobBreakaway;

fn breakaway() -> FlagsRequest {
    FlagsRequest {
        breakaway_from_job: true,
        ..Default::default()
    }
}

/// `ERROR_ACCESS_DENIED` as the classifier sees it: the bare Win32 code, from either backend.
const ACCESS_DENIED: i32 = windows::Win32::Foundation::ERROR_ACCESS_DENIED.0 as i32;

fn io_err(code: i32) -> Error {
    Error::Io(std::io::Error::from_raw_os_error(code))
}

/// Breaking away while contained is refused for a ROOT and a NESTED request alike, so the verdict
/// is order- and root-independent: making it depend on root-ness would mean the identical
/// `Command` succeeds in one process and fails in a nested one.
#[skuld::test]
fn breakaway_with_containment_is_refused() {
    for is_root in [true, false] {
        let err = windows_spawn(&contained(), breakaway(), is_root, SpawnBackend::Std)
            .expect_err("breakaway plus containment is refused");
        let Error::Unsupported { detail, .. } = &err else {
            panic!("is_root={is_root}: got {err:?}");
        };
        crate::error::assert_detail_is_not_hard_wrapped(detail);
    }
}

/// With a forbidding ambient job, an emitted breakaway bit GUARANTEES an access-denied
/// failure, so the request is a sufficient cause of the failure the caller just got.
///
/// The detail names the measured limit, the request, and the first-refusal qualifier. It must not
/// claim the request was the spawn's only problem: the breakaway check runs before the image is
/// resolved, so a genuine "no such program" is masked by it.
#[skuld::test]
fn a_forbidding_job_turns_access_denied_into_a_typed_containment_error() {
    let out = super::classify_spawn_denial(io_err(ACCESS_DENIED), breakaway(), JobBreakaway::Forbidden);
    let Error::Containment { detail, .. } = &out else {
        panic!("expected Containment, got {out:?}");
    };
    assert!(detail.contains("JOB_OBJECT_LIMIT_BREAKAWAY_OK"), "{detail}");
    assert!(detail.contains("breakaway_from_job()"), "{detail}");
    assert!(detail.contains("FIRST"), "{detail}");
    crate::error::assert_detail_is_not_hard_wrapped(detail);
    assert_eq!(
        crate::error::first_os_code(&out),
        Some(ACCESS_DENIED),
        "the refused spawn's error is the source"
    );
}

/// Measured (Windows 11 26100, 2026-08-18): a silent-breakaway job ACCEPTS the flag, so no
/// breakaway request can reach the classifier from such a job at all. The verdict exists solely
/// to stop that job being misread as `Forbidden`, whose message would be wrong about the world —
/// a silent-breakaway job does not forbid children from leaving, it removes them itself.
#[skuld::test]
fn the_silent_breakaway_verdict_keeps_the_raw_io_error() {
    let out = super::classify_spawn_denial(io_err(ACCESS_DENIED), breakaway(), JobBreakaway::SilentBreakaway);
    assert!(matches!(out, Error::Io(_)), "got {out:?}");
}

/// The typed variant must never assert a cause the process just measured to be false — nor
/// one it could not measure at all.
#[skuld::test]
fn a_contradicted_or_unmeasurable_probe_keeps_the_raw_io_error() {
    for job in [JobBreakaway::Permitted, JobBreakaway::NotInJob, JobBreakaway::Unknown] {
        let out = super::classify_spawn_denial(io_err(ACCESS_DENIED), breakaway(), job);
        assert!(matches!(out, Error::Io(_)), "{job:?}: got {out:?}");
    }
}

/// An unrelated failure code stays itself whatever the ambient job looks like.
#[skuld::test]
fn an_unrelated_failure_code_is_never_reclassified() {
    let not_found = windows::Win32::Foundation::ERROR_FILE_NOT_FOUND.0 as i32;
    for job in [
        JobBreakaway::Forbidden,
        JobBreakaway::Permitted,
        JobBreakaway::SilentBreakaway,
        JobBreakaway::NotInJob,
        JobBreakaway::Unknown,
    ] {
        let out = super::classify_spawn_denial(io_err(not_found), breakaway(), job);
        assert!(matches!(out, Error::Io(_)), "{job:?}: got {out:?}");
    }
}

/// The classifier's opening `let-else` returns every non-`Io` error unchanged, in the one
/// configuration that would otherwise rewrite it — a breakaway request plus a forbidding job. A
/// broadening of that pattern would reclassify one error kind as another in silence.
#[skuld::test]
fn a_non_io_error_is_returned_unchanged() {
    let out = super::classify_spawn_denial(
        Error::Unsupported {
            op: "some op".into(),
            platform: "windows",
            detail: "some detail".into(),
            source: None,
        },
        breakaway(),
        JobBreakaway::Forbidden,
    );
    let Error::Unsupported {
        op, platform, detail, ..
    } = &out
    else {
        panic!("a non-Io error must pass through unchanged, got {out:?}");
    };
    assert_eq!(
        (op.as_str(), *platform, detail.as_str()),
        ("some op", "windows", "some detail")
    );
}

/// The other half: an access-denied spawn with NO breakaway request is never blamed on a job.
/// Without this, an unrelated denial would be rewritten into a containment error naming a flag
/// that was never submitted to anything.
#[skuld::test]
fn a_spawn_denial_without_a_breakaway_request_is_never_reclassified() {
    for job in [
        JobBreakaway::Forbidden,
        JobBreakaway::Permitted,
        JobBreakaway::SilentBreakaway,
        JobBreakaway::NotInJob,
        JobBreakaway::Unknown,
    ] {
        let out = super::classify_spawn_denial(io_err(ACCESS_DENIED), FlagsRequest::default(), job);
        assert!(matches!(out, Error::Io(_)), "{job:?}: got {out:?}");
    }
}

/// A suspended request adds `CREATE_SUSPENDED` to every containment shape on both backends, so the
/// child exists frozen however it is contained. A shape that drops it would run before the caller
/// could record its identity.
#[skuld::test]
fn suspended_request_adds_create_suspended_for_every_containment_shape() {
    let treewalk = ContainRequest {
        mode: Some(ContainMode::TreeWalk),
        nesting: Nesting::Mark,
    };
    let suspended = FlagsRequest {
        suspended: true,
        ..Default::default()
    };
    for backend in [SpawnBackend::Std, SpawnBackend::Raw] {
        let shapes = [
            ("uncontained", uncontained(), false),
            ("strongest root", contained(), true),
            ("strongest nested member", contained(), false),
            ("treewalk root", treewalk, true),
            ("treewalk nested member", treewalk, false),
        ];
        for (name, contain, is_root) in shapes {
            let w = word(&contain, suspended, is_root, backend);
            assert_ne!(
                w & CREATE_SUSPENDED.0,
                0,
                "{name} on {backend:?} must be created suspended"
            );
        }
    }
}

/// Without the request the word is exactly as before: an uncontained spawn is not suspended, and
/// a `TreeWalk` root is not either.
#[skuld::test]
fn no_suspended_request_leaves_the_word_without_create_suspended_unchanged() {
    let treewalk = ContainRequest {
        mode: Some(ContainMode::TreeWalk),
        nesting: Nesting::Mark,
    };
    for backend in [SpawnBackend::Std, SpawnBackend::Raw] {
        assert_eq!(
            word(&uncontained(), FlagsRequest::default(), false, backend) & CREATE_SUSPENDED.0,
            0
        );
        assert_eq!(
            word(&treewalk, FlagsRequest::default(), true, backend) & CREATE_SUSPENDED.0,
            0
        );
    }
}

/// `CREATE_SUSPENDED` is the only bit a suspended request adds. In particular it adds no process
/// group, which would change the cooperative signal an uncontained child can be sent.
#[skuld::test]
fn suspended_request_adds_no_other_bit_so_the_graceful_mechanism_is_unchanged() {
    for (contain, is_root) in [(uncontained(), false), (contained(), true), (contained(), false)] {
        let plain = word(&contain, FlagsRequest::default(), is_root, SpawnBackend::Std);
        let frozen = word(
            &contain,
            FlagsRequest {
                suspended: true,
                ..Default::default()
            },
            is_root,
            SpawnBackend::Std,
        );
        assert_eq!(frozen & !CREATE_SUSPENDED.0, plain & !CREATE_SUSPENDED.0);
        assert_eq!(
            crate::containment::windows::mechanism_from_flags(frozen),
            crate::containment::windows::mechanism_from_flags(plain),
        );
    }
}

/// The raw hatch still refuses `CREATE_SUSPENDED`, and the refusal now points at the API that
/// does the job.
#[skuld::test]
fn create_suspended_is_still_refused_in_the_raw_hatch_and_the_remedy_names_spawn_suspended() {
    let detail = refusal(FlagsRequest {
        raw: CREATE_SUSPENDED.0,
        ..Default::default()
    });
    assert!(detail.contains("CREATE_SUSPENDED"), "{detail}");
    assert!(detail.contains("spawn_suspended"), "{detail}");
}