subc-daemon 0.52.0

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
use super::*;

#[derive(Clone)]
pub(crate) struct VerifiedRoot {
    pub root: AgentCommandRoot,
    pub native_start: u64,
    pub inside: bool,
    pub members: BTreeSet<(u32, u64)>,
    #[cfg(windows)]
    pub process: Option<Arc<subc_os::Process>>,
}

pub(super) enum Validation {
    Valid(VerifiedRoot),
    Invalid,
    Exited,
    Incomplete,
}

pub(crate) struct Prepared {
    pub scope_target: crate::subtree_resources::Target,
    pub module_pid: u32,
    pub before_cpu: Option<(u128, u64)>,
    pub started: Vec<(AgentCommandRoot, Option<VerifiedRoot>)>,
    pub exited_before_admission: Vec<AgentCommandRoot>,
    pub pending: Vec<AgentCommandRoot>,
    pub finished: Vec<AgentCommandFinished>,
    pub known: Option<Vec<(AgentCommandRoot, Option<VerifiedRoot>)>>,
    pub table: ProcessTable,
    pub at_ms: u64,
    pub finish_until: u64,
    #[cfg(unix)]
    pub scope: Option<(TreeReading, BTreeSet<(u32, u64)>)>,
}

pub(super) struct Snapshot {
    pub(super) before_cpu: Option<(u128, u64)>,
    pub(super) table: ProcessTable,
    #[cfg(unix)]
    pub(super) scope: Option<(TreeReading, BTreeSet<(u32, u64)>)>,
}

impl Snapshot {
    #[cfg(test)]
    pub(super) fn read(target: &crate::subtree_resources::Target) -> Option<Self> {
        Self::read_with(target, || ProcessTable::read().ok())
    }

    pub(super) fn read_with(
        target: &crate::subtree_resources::Target,
        read_table: impl FnOnce() -> Option<ProcessTable>,
    ) -> Option<Self> {
        let before_cpu = target.counter_cpu();
        let table = read_table()?;
        #[cfg(unix)]
        let scope = target
            .has_container()
            .then(|| target.tree(&table))
            .flatten();
        Some(Self {
            before_cpu,
            table,
            #[cfg(unix)]
            scope,
        })
    }
}

#[cfg(test)]
pub(super) fn prepare(
    module_pid: u32,
    target: crate::subtree_resources::Target,
    batch: Declaration,
    trusted: &BTreeMap<AgentCommandRoot, u64>,
    finish_until: &mut Option<u64>,
) -> Option<Prepared> {
    let snapshot = Snapshot::read(&target)?;
    let finish_until = *finish_until.get_or_insert(snapshot.table.revision());
    prepare_snapshot(module_pid, target, batch, trusted, snapshot, finish_until)
}

pub(super) fn prepare_snapshot(
    module_pid: u32,
    target: crate::subtree_resources::Target,
    batch: Declaration,
    trusted: &BTreeMap<AgentCommandRoot, u64>,
    snapshot: Snapshot,
    finish_until: u64,
) -> Option<Prepared> {
    let before_cpu = snapshot.before_cpu;
    let table = snapshot.table;
    #[cfg(unix)]
    let scope = snapshot.scope;
    let validate = |root: AgentCommandRoot, resync| {
        let native = trusted.iter().find_map(|(known, start)| {
            (known.pid == root.pid
                && known.start_time_ms.abs_diff(root.start_time_ms)
                    < subc_os::process_start_time_precision_ms())
            .then_some(*start)
        });
        if resync && native.is_none() {
            Validation::Invalid
        } else {
            validate_root(
                module_pid,
                &target,
                root,
                &table,
                resync.then_some(native).flatten(),
            )
        }
    };
    let mut pending = Vec::new();
    let mut exited_before_admission = Vec::new();
    let started: Vec<_> = batch
        .started
        .into_iter()
        .filter_map(|root| match validate(root, false) {
            Validation::Valid(verified) => Some((root, Some(verified))),
            Validation::Invalid => Some((root, None)),
            Validation::Exited => {
                exited_before_admission.push(root);
                None
            }
            Validation::Incomplete => {
                pending.push(root);
                None
            }
        })
        .collect();
    let known = match batch.known {
        Some(roots) => Some(
            roots
                .into_iter()
                .map(|root| {
                    let accepted_start = started.iter().find_map(|(started, verified)| {
                        (started.pid == root.pid
                            && started.start_time_ms.abs_diff(root.start_time_ms)
                                < subc_os::process_start_time_precision_ms())
                        .then(|| verified.clone())
                        .flatten()
                    });
                    Some((
                        root,
                        if accepted_start.is_some() {
                            accepted_start
                        } else {
                            match validate(root, true) {
                                Validation::Valid(verified) => Some(verified),
                                Validation::Invalid
                                | Validation::Exited
                                | Validation::Incomplete => None,
                            }
                        },
                    ))
                })
                .collect::<Option<_>>()?,
        ),
        None => None,
    };
    Some(Prepared {
        scope_target: target,
        module_pid,
        before_cpu,
        started,
        exited_before_admission,
        pending,
        finished: batch.finished,
        known,
        table,
        at_ms: now_ms(),
        finish_until,
        #[cfg(unix)]
        scope,
    })
}

/// Unknown ownership is not evidence of an invalid declaration. Keep starts
/// pending until a later snapshot can prove both identity and tree membership.
pub(super) fn validate_root(
    module_pid: u32,
    target: &crate::subtree_resources::Target,
    root: AgentCommandRoot,
    table: &ProcessTable,
    trusted_start: Option<u64>,
) -> Validation {
    if root.pid == module_pid || is_ancestor(table, root.pid, module_pid) {
        return Validation::Invalid;
    }
    let process = match subc_os::Process::open(root.pid) {
        Ok(Some(process)) => process,
        // A missing process cannot establish ownership. Its CPU stays with
        // the module; a later finish report cannot supply that proof.
        Ok(None) => return Validation::Exited,
        Err(_) => return Validation::Incomplete,
    };
    let Some(observed) = process.observe() else {
        return Validation::Incomplete;
    };
    if trusted_start.is_some_and(|start| start != observed.start_time) {
        return Validation::Invalid;
    }
    let Some(start_time_ms) = subc_os::process_start_time_ms(root.pid) else {
        return Validation::Incomplete;
    };
    if start_time_ms.abs_diff(root.start_time_ms) >= subc_os::process_start_time_precision_ms() {
        return Validation::Invalid;
    }
    let direct_child = match subc_os::parent_pid(root.pid) {
        Some(parent) => parent == module_pid,
        None if trusted_start.is_some() => false,
        None => return Validation::Incomplete,
    };
    if !direct_child && trusted_start.is_none() {
        return Validation::Invalid;
    }
    // Membership is read after identity validation, then the same native
    // identity is rechecked. Windows queries the retained handle itself.
    let Some(contained) = target.contains_identity(root.pid, observed.start_time, &process) else {
        return Validation::Incomplete;
    };
    match subc_os::start_time(root.pid) {
        Some(start) if start != observed.start_time => return Validation::Invalid,
        None => return Validation::Incomplete,
        Some(_) => {}
    }
    let members = match table.tree_identities(root.pid, observed.start_time, true) {
        Some(members) => members,
        None if trusted_start.is_some() => BTreeSet::from([(root.pid, observed.start_time)]),
        None => return Validation::Incomplete,
    };
    Validation::Valid(VerifiedRoot {
        root: AgentCommandRoot {
            pid: root.pid,
            start_time_ms,
        },
        native_start: observed.start_time,
        inside: if target.has_container() {
            contained
        } else {
            direct_child && !cfg!(windows)
        },
        members,
        #[cfg(windows)]
        process: Some(Arc::new(process)),
    })
}

fn is_ancestor(table: &ProcessTable, candidate: u32, module_pid: u32) -> bool {
    let mut current = Some(module_pid);
    let mut seen = BTreeSet::new();
    while let Some(pid) = current.filter(|pid| seen.insert(*pid)) {
        if pid == candidate {
            return true;
        }
        current = table
            .process(pid)
            .and_then(|member| (member.parent_pid != 0).then_some(member.parent_pid));
    }
    false
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;

    struct Child(std::process::Child);
    impl Drop for Child {
        fn drop(&mut self) {
            let _ = self.0.kill();
            let _ = self.0.wait();
        }
    }

    #[test]
    fn root_gone_at_first_validation_is_not_rejected_or_credited() {
        let mut child = Child(
            std::process::Command::new("sh")
                .args(["-c", "exec sleep 30"])
                .spawn()
                .unwrap(),
        );
        let root = AgentCommandRoot {
            pid: child.0.id(),
            start_time_ms: subc_os::process_start_time_ms(child.0.id()).unwrap(),
        };
        child.0.kill().unwrap();
        child.0.wait().unwrap();
        assert!(matches!(subc_os::Process::open(root.pid), Ok(None)));

        let tracker = Tracker::default();
        let target = crate::subtree_resources::Target::Unavailable("no_container");
        let declare = |batch| {
            let prepared = tracker
                .prepare(
                    "module",
                    1,
                    std::process::id(),
                    target.clone(),
                    batch,
                    &mut Receipt::default(),
                )
                .unwrap();
            tracker
                .commit_fenced("module", 1, prepared, &CommitFence::default())
                .unwrap()
        };
        let committed = declare(Declaration {
            started: vec![root],
            known: Some(vec![root]),
            ..Declaration::default()
        });
        assert!(
            committed.rejected.is_empty(),
            "exited root was rejected: {:?}",
            committed.rejected
        );
        assert_eq!(committed.exited_before_admission, vec![root]);

        declare(Declaration {
            finished: vec![AgentCommandFinished {
                pid: root.pid,
                start_time_ms: root.start_time_ms,
                cpu_ms: Some(1_000),
            }],
            ..Declaration::default()
        });
        let state = tracker.state.lock().unwrap();
        let module = &state.modules["module"];
        assert!(module.roots.is_empty());
        assert!(module.pending.is_empty());
        assert!(module.finished.is_empty());
        assert_eq!(module.cpu_model.rows().1, 0);
    }

    #[test]
    fn known_reconfirms_accepted_roots_but_never_admits_a_new_child() {
        let child = Child(
            std::process::Command::new("sh")
                .args(["-c", "exec sleep 30"])
                .spawn()
                .unwrap(),
        );
        let root = AgentCommandRoot {
            pid: child.0.id(),
            start_time_ms: subc_os::process_start_time_ms(child.0.id()).unwrap(),
        };
        let batch = || Declaration {
            started: Vec::new(),
            finished: Vec::new(),
            known: Some(vec![root]),
        };
        let target = crate::subtree_resources::Target::Unavailable("no_container");
        let unknown = prepare(
            std::process::id(),
            target.clone(),
            batch(),
            &BTreeMap::new(),
            &mut None,
        )
        .unwrap();
        assert!(
            unknown.known.unwrap()[0].1.is_none(),
            "known is not an alternative started call"
        );
        let trusted = prepare(
            std::process::id(),
            target.clone(),
            batch(),
            &BTreeMap::from([(root, subc_os::start_time(root.pid).unwrap())]),
            &mut None,
        )
        .unwrap();
        assert!(trusted.known.unwrap()[0].1.is_some());
        let reused = prepare(
            std::process::id(),
            target,
            batch(),
            &BTreeMap::from([(root, 0)]),
            &mut None,
        )
        .unwrap();
        assert!(
            reused.known.unwrap()[0].1.is_none(),
            "matching rounded wire time cannot admit a new native identity"
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn known_cannot_launder_the_module_even_when_the_container_contains_it() {
        let pid = std::process::id();
        let root = AgentCommandRoot {
            pid,
            start_time_ms: subc_os::process_start_time_ms(pid).unwrap(),
        };
        let prepared = prepare(
            pid,
            crate::subtree_resources::Target::Cgroup("/sys/fs/cgroup".into()),
            Declaration {
                started: Vec::new(),
                finished: Vec::new(),
                known: Some(vec![root]),
            },
            &BTreeMap::from([(root, subc_os::start_time(root.pid).unwrap())]),
            &mut None,
        )
        .unwrap();
        assert!(prepared.known.unwrap()[0].1.is_none());
    }
}