subc-daemon 0.54.21

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
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
use super::*;

#[cfg(not(feature = "dev-desktop-approval"))]
#[test]
fn release_effective_floor_is_always_sentinel() {
    assert_eq!(effective_release_floor(), RELEASE_FLOOR);
    assert_eq!(OperatorAppPolicy::default().floor, RELEASE_FLOOR);
}

#[cfg(feature = "dev-desktop-approval")]
#[test]
fn development_effective_floor_uses_compiled_semver_or_sentinel() {
    let floor = OperatorAppPolicy::default().floor;
    match option_env!("SUBC_DEV_OPERATOR_APP_FLOOR") {
        Some("0.1.0") => assert_eq!(floor, Version::new(0, 1, 0)),
        None => assert_eq!(floor, RELEASE_FLOOR),
        Some(raw) if Version::parse(raw).is_err() => assert_eq!(floor, RELEASE_FLOOR),
        Some(raw) => assert_eq!(floor.to_string(), raw),
    }
}

#[test]
fn release_floor_uses_numeric_semver_and_rejects_unknown_versions() {
    let floor = Version::new(1, 2, 10);
    for version in ["1.2.10", "1.2.11", "1.3.0", "1.2.10+build.1"] {
        assert!(meets_release_floor(Some(version), &floor), "{version}");
    }
    for version in [
        None,
        Some("1.2.9"),
        Some("1.2.10-rc.1"),
        Some("1.2"),
        Some("oops"),
    ] {
        assert!(!meets_release_floor(version, &floor), "{version:?}");
    }
}

#[test]
fn advisory_peer_facts_cannot_produce_a_stamp() {
    let policy: OperatorAppPolicy = TestOperatorAppPolicy {
        macos_enabled: true,
        windows_enabled: false,
        linux_enabled: false,
        app: "test-app",
        requirement: "always",
        floor: Version::new(1, 2, 10),
        windows_publisher: None,
        windows_path: None,
        linux_path: None,
        windows_breakaway: true,
        linux_force_direct: false,
    }
    .into();
    let peer = ObservedPeer::Observed(subc_os::local_peer::PeerObservation {
        user: subc_os::local_peer::PeerUser::Uid(501),
        pid: 42,
        exe: Some("/Applications/Alfonso.app/Contents/MacOS/Alfonso".into()),
        signing_id: Some("io.cortexkit.alfonso.desktop".into()),
    });
    assert!(policy.stamp(peer.into()).is_none());
}

#[cfg(target_os = "macos")]
mod macos {
    use super::*;
    use subc_os::local_peer::fixture::SignedPeerFixture;
    use subc_os::local_peer::CodeRequirementOutcome;

    pub(super) const REQUIREMENT: &str = concat!(
        "identifier \"io.cortexkit.alfonso.fixture\" ",
        "and entitlement[\"com.apple.security.get-task-allow\"] absent ",
        "and entitlement[\"com.apple.security.cs.disable-library-validation\"] absent ",
        "and entitlement[\"com.apple.security.cs.allow-dyld-environment-variables\"] absent"
    );

    fn policy() -> OperatorAppPolicy {
        TestOperatorAppPolicy {
            macos_enabled: true,
            windows_enabled: false,
            linux_enabled: false,
            app: "test-app",
            requirement: REQUIREMENT,
            floor: Version::new(1, 2, 10),
            windows_publisher: None,
            windows_path: None,
            linux_path: None,
            windows_breakaway: true,
            linux_force_direct: false,
        }
        .into()
    }

    #[tokio::test]
    async fn a_timed_out_native_stamp_check_keeps_its_slot_until_it_returns() {
        let stamp = OperatorAppStamp::fixture("test-app", 42);
        let mut policy = policy();
        let lane = Arc::new(PeerIdentityLane::start());
        policy.test_lane = Some(lane.clone());
        let (started, entered) = tokio::sync::oneshot::channel();
        let (release, blocked) = std::sync::mpsc::channel();
        let first = stamp.share_route_check(&policy, move || {
            started.send(()).unwrap();
            let _ = blocked.recv();
            Ok(true)
        });
        let (result, entered) = tokio::join!(first, tokio::time::timeout(EVIDENCE_BUDGET, entered));
        entered.expect("native work starts").unwrap();
        assert!(matches!(result, Err(RouteStampFailure::Deadline)));

        let second = stamp.share_route_check(&policy, || panic!("do not resubmit hanging work"));
        assert!(matches!(second.await, Err(RouteStampFailure::CheckRunning)));
        assert_eq!(lane.run(|| 42).await, Some(42), "the second worker is free");

        release.send(()).unwrap();
        tokio::time::timeout(Duration::from_secs(5), async {
            while stamp.generation.flight.lock().unwrap().is_some() {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("completed native check releases the slot");
        assert!(matches!(
            stamp.share_route_check(&policy, || Ok(true)).await,
            Ok(true)
        ));
    }

    #[tokio::test]
    async fn a_new_bind_replaces_an_expired_non_running_flight() {
        let stamp = OperatorAppStamp::fixture("test-app", 42);
        let mut policy = policy();
        policy.test_lane = Some(Arc::new(PeerIdentityLane::start()));
        let (_pending, result) = watch::channel(None);
        *stamp.generation.flight.lock().unwrap() = Some(RouteStampCheck {
            deadline: Instant::now(),
            revocation_revision: None,
            result,
            running: false,
        });
        assert!(matches!(
            stamp.share_route_check(&policy, || Ok(true)).await,
            Ok(true)
        ));
    }

    #[tokio::test]
    async fn expired_revalidation_result_cannot_stamp_a_waiting_bind() {
        use std::{
            future::{poll_fn, Future},
            pin::pin,
            task::Poll,
        };

        let stamp = OperatorAppStamp::fixture("test-app", 42);
        let policy = policy();
        let deadline = Instant::now() + EVIDENCE_BUDGET;
        let (publish, result) = watch::channel(None);
        *stamp.generation.flight.lock().unwrap() = Some(RouteStampCheck {
            deadline,
            revocation_revision: None,
            result,
            running: false,
        });
        let mut bind =
            pin!(stamp.share_route_check(&policy, || panic!("bind joins the staged flight")));
        poll_fn(|cx| {
            assert!(bind.as_mut().poll(cx).is_pending());
            Poll::Ready(())
        })
        .await;
        tokio::time::sleep_until(deadline.into()).await;
        publish.send_replace(Some(Ok(true)));
        assert!(
            matches!(bind.await, Err(RouteStampFailure::Deadline)),
            "a ready result must not beat its elapsed deadline"
        );
    }

    #[cfg(not(feature = "dev-desktop-approval"))]
    #[test]
    fn release_sentinel_skips_native_requirement_check() {
        let root = cortexkit_test_support::ScratchDir::new("operator-app-sentinel");
        let mut fixture = SignedPeerFixture::app(
            &root.join("good"),
            "io.cortexkit.alfonso.fixture",
            Some("0.1.0"),
            true,
            None,
        );
        let (_stream, peer) = fixture.connect();
        assert!(matches!(
            peer.check_code_requirement(REQUIREMENT),
            CodeRequirementOutcome::Satisfied(_)
        ));
        let release = OperatorAppPolicy {
            requirement: REQUIREMENT,
            ..Default::default()
        };
        assert!(release.macos_enabled);
        assert!(release.stamp(peer.clone()).is_none());
        assert!(release.config_identity(peer).is_none());
        assert_eq!(
            release
                .requirement_checks
                .load(std::sync::atomic::Ordering::Relaxed),
            0,
            "sentinel must skip native requirement verification"
        );
    }

    #[test]
    fn production_table_at_development_floor_stamps_cross_platform_id() {
        let root = cortexkit_test_support::ScratchDir::new("operator-app-production-id");
        let mut fixture = SignedPeerFixture::app(
            &root.join("good"),
            "io.cortexkit.alfonso.fixture",
            Some("0.1.0"),
            true,
            None,
        );
        let (_stream, peer) = fixture.connect();
        // Ad-hoc fixtures cannot satisfy the production Apple certificate chain.
        // Keep the production identity table and only substitute that requirement.
        let production = OperatorAppPolicy {
            requirement: REQUIREMENT,
            floor: Version::new(0, 1, 0),
            ..Default::default()
        };
        let stamp = production.stamp(peer).expect("signed peer at floor");
        assert_eq!(stamp.app.app, "alfonso-desktop");
    }

    #[test]
    fn explicit_development_floor_keeps_signature_and_version_guards() {
        let root = cortexkit_test_support::ScratchDir::new("operator-app-development-floor");
        let mut development = policy();
        development.floor = Version::new(0, 1, 0);
        for (label, identifier, version, accepted) in [
            ("good", "io.cortexkit.alfonso.fixture", "0.1.0", true),
            ("lower", "io.cortexkit.alfonso.fixture", "0.0.9", false),
            ("wrong", "io.cortexkit.other.fixture", "0.1.0", false),
        ] {
            let mut fixture =
                SignedPeerFixture::app(&root.join(label), identifier, Some(version), true, None);
            let (_stream, peer) = fixture.connect();
            assert_eq!(development.stamp(peer).is_some(), accepted, "{label}");
        }
    }

    #[test]
    fn config_desktop_macos_identity_keeps_signature_and_floor_without_prompt_exemption() {
        let root = cortexkit_test_support::ScratchDir::new("config-desktop-identity");
        let mut identity = policy();
        identity.macos_enabled = false;
        for (label, identifier, version, accepted) in [
            ("good", "io.cortexkit.alfonso.fixture", "1.2.10", true),
            ("lower", "io.cortexkit.alfonso.fixture", "1.2.9", false),
            ("wrong", "io.cortexkit.other.fixture", "1.2.10", false),
        ] {
            let mut fixture =
                SignedPeerFixture::app(&root.join(label), identifier, Some(version), true, None);
            let (_stream, peer) = fixture.connect();
            assert!(identity.stamp(peer.clone()).is_none());
            assert!(OperatorAppPolicy::default()
                .config_identity(peer.clone())
                .is_none());
            let review = identity.config_identity(peer);
            assert_eq!(review.is_some(), accepted, "{label}");
            if let Some(review) = review {
                assert!(review.revalidate());
                drop(fixture);
                assert!(!review.revalidate());
            }
        }
    }

    #[test]
    fn macos_native_requirement_floor_and_restart() {
        let root = cortexkit_test_support::ScratchDir::new("operator-app");
        let mut fixture = SignedPeerFixture::app(
            &root.join("good"),
            "io.cortexkit.alfonso.fixture",
            Some("1.2.10"),
            true,
            None,
        );
        let (stream, peer) = fixture.connect();
        assert!(
            matches!(
                peer.check_code_requirement(REQUIREMENT),
                CodeRequirementOutcome::Satisfied(_)
            ),
            "{:?}",
            peer.check_code_requirement(REQUIREMENT)
        );
        let stamp = policy()
            .stamp(peer.clone())
            .expect("test-signed fixture at floor");
        assert_eq!(stamp.app.pid, fixture.pid());
        assert!(stamp.revalidate());
        std::fs::write(root.join("good").join("Info.plist"), "<plist><dict><key>CFBundleShortVersionString</key><string>1.2.9</string></dict></plist>").unwrap();
        assert!(
            stamp.revalidate(),
            "an exterior plist cannot replace the signed version source"
        );
        assert!(OperatorAppPolicy::default().stamp(peer.clone()).is_none());
        // The production Apple-chain and Team ID clauses must reject an ad-hoc fixture.
        for requirement in [
            MACOS_REQUIREMENT,
            "anchor apple generic",
            "certificate 1[field.1.2.840.113635.100.6.2.6] exists",
            "certificate leaf[field.1.2.840.113635.100.6.1.13] exists",
            "certificate leaf[subject.OU] = \"5R5846NBPW\"",
            "identifier \"wrong.identifier\"",
        ] {
            assert_eq!(
                peer.check_code_requirement(requirement),
                CodeRequirementOutcome::NotSatisfied,
                "{requirement}"
            );
            let mut mutated = policy();
            mutated.requirement = requirement;
            assert!(mutated.stamp(peer.clone()).is_none(), "{requirement}");
        }
        drop(stamp);
        drop(stream);
        // A new daemon has no launch history: reconnect the same live process
        // and derive its eligibility again from the newly captured token.
        let (_stream, peer) = fixture.connect();
        let stamp = policy().stamp(peer).expect("same app after restart");
        assert_eq!(stamp.app.pid, fixture.pid());
        for (label, identifier, version, runtime, entitlement) in [
            (
                "lower",
                "io.cortexkit.alfonso.fixture",
                Some("1.2.9"),
                true,
                None,
            ),
            ("missing", "io.cortexkit.alfonso.fixture", None, true, None),
            (
                "malformed",
                "io.cortexkit.alfonso.fixture",
                Some("banana"),
                true,
                None,
            ),
            ("dev", "dev.cortexkit.alfonso", Some("1.2.10"), true, None),
            (
                "runtime",
                "io.cortexkit.alfonso.fixture",
                Some("1.2.10"),
                false,
                None,
            ),
            (
                "debug",
                "io.cortexkit.alfonso.fixture",
                Some("1.2.10"),
                true,
                Some(("com.apple.security.get-task-allow", true)),
            ),
            (
                "library",
                "io.cortexkit.alfonso.fixture",
                Some("1.2.10"),
                true,
                Some(("com.apple.security.cs.disable-library-validation", true)),
            ),
            (
                "dyld",
                "io.cortexkit.alfonso.fixture",
                Some("1.2.10"),
                true,
                Some((
                    "com.apple.security.cs.allow-dyld-environment-variables",
                    true,
                )),
            ),
        ] {
            let mut fixture = SignedPeerFixture::app(
                &root.join(label),
                identifier,
                version,
                runtime,
                entitlement,
            );
            let (_stream, peer) = fixture.connect();
            assert!(policy().stamp(peer).is_none(), "{label}");
        }
        // Presence is disallowed even when an entitlement's value is false.
        for (label, key) in [
            ("debug-false", "com.apple.security.get-task-allow"),
            (
                "library-false",
                "com.apple.security.cs.disable-library-validation",
            ),
            (
                "dyld-false",
                "com.apple.security.cs.allow-dyld-environment-variables",
            ),
        ] {
            let mut fixture = SignedPeerFixture::app(
                &root.join(label),
                "io.cortexkit.alfonso.fixture",
                Some("1.2.10"),
                true,
                Some((key, false)),
            );
            let (_stream, peer) = fixture.connect();
            assert!(policy().stamp(peer).is_none(), "{label}");
        }
        drop(fixture);
        assert!(
            !stamp.revalidate(),
            "an exited incarnation cannot revalidate"
        );
    }
}