Skip to main content

sysprims_proc/observation/
mod.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Read-only OS collectors and private continuity handles for
4//! `urn:3leaps:identity-evidence:native-process-observation:v0`.
5//!
6//! Authority boundary:
7//! - Collection and continuity handles use strictly non-destructive read-only
8//!   OS facilities (`sysctl` + `kqueue` `EVFILT_PROC` `NOTE_EXIT` on macOS;
9//!   descriptor-anchored `/proc` via `openat2` + `pidfd_open` on Linux).
10//! - Live OS handles are private in-memory resources: they expose no raw file
11//!   descriptor getter, expose no signal API, and are never serialized.
12//! - `HostScope` is supplied across an explicit caller boundary and does not
13//!   authenticate physical-machine uniqueness.
14
15use std::time::{Duration, SystemTime, UNIX_EPOCH};
16
17use serde::{Deserialize, Serialize};
18use serde_json::{json, Map, Value};
19#[cfg(any(target_os = "linux", target_os = "macos"))]
20use sysprims_evidence::NATIVE_PROCESS_OBSERVATION_README_REVISION;
21use sysprims_evidence::{
22    admit_and_validate_report, admit_live_observation, bind_native_observation_report,
23    canonical_sha256_value, compare_native_observations, parse_strict_utc_unix,
24    validate_observation_shape, AdmittedWire, ComparisonOutcome, ComparisonPolicy, ProfileRef,
25    IDENTITY_EVIDENCE_CONTRACT, NATIVE_PROCESS_OBSERVATION_PROFILE_ID,
26    NATIVE_PROCESS_OBSERVATION_PROFILE_REVISION,
27};
28use thiserror::Error;
29use time::OffsetDateTime;
30
31#[cfg(target_os = "linux")]
32mod linux;
33#[cfg(target_os = "macos")]
34mod macos;
35#[cfg(not(any(target_os = "linux", target_os = "macos")))]
36mod other;
37
38#[cfg(target_os = "linux")]
39use linux as imp;
40#[cfg(target_os = "macos")]
41use macos as imp;
42#[cfg(not(any(target_os = "linux", target_os = "macos")))]
43use other as imp;
44
45/// Minimum observable numeric PID (`1`).
46pub const MIN_OBSERVABLE_PID: u32 = 1;
47/// Maximum observable numeric PID (`2147483647`, `i32::MAX`).
48pub const MAX_OBSERVABLE_PID: u32 = 2_147_483_647;
49/// Maximum raw `argv` / `cmdline` / `KERN_PROCARGS2` buffer size (`262,144` bytes).
50pub const MAX_ARGUMENTS_RAW_BYTES: usize = 262_144;
51/// Maximum regular-file executable size hashed for `executable_digest` (`67,108,864` bytes, 64 MiB).
52pub const MAX_EXECUTABLE_FILE_BYTES: u64 = 67_108_864;
53
54/// Start-identity sub-profile ID for macOS `kinfo_proc.kp_proc.p_starttime`.
55pub const MACOS_START_IDENTITY_PROFILE_ID: &str =
56    "urn:3leaps:identity-evidence:start-identity:macos-kinfo-starttime:v0";
57/// Start-identity sub-profile ID for Linux `/proc/<pid>/stat` field 22 ticks.
58pub const LINUX_START_IDENTITY_PROFILE_ID: &str =
59    "urn:3leaps:identity-evidence:start-identity:linux-procfs-stat:v0";
60/// Security-principal derivation ID for macOS `kinfo_proc` credentials.
61pub const MACOS_PRINCIPAL_DERIVATION_ID: &str =
62    "urn:3leaps:identity-evidence:principal-derivation:macos-kinfo-ucred:v0";
63/// Security-principal derivation ID for Linux `/proc/<pid>/status` UID/GID sets.
64pub const LINUX_PRINCIPAL_DERIVATION_ID: &str =
65    "urn:3leaps:identity-evidence:principal-derivation:linux-procfs-status-uidgid:v0";
66/// Context derivation ID for `arguments_digest`.
67pub const ARGV_DIGEST_DERIVATION_ID: &str =
68    "urn:3leaps:identity-evidence:context-derivation:argv-bytes:v0";
69/// Context derivation ID for `executable_digest`.
70pub const EXEC_DIGEST_DERIVATION_ID: &str =
71    "urn:3leaps:identity-evidence:context-derivation:executable-file-bytes:v0";
72/// Context derivation ID for Linux `namespace_context_digest`.
73pub const LINUX_NS_DIGEST_DERIVATION_ID: &str =
74    "urn:3leaps:identity-evidence:context-derivation:linux-ns-inum-set:v0";
75/// Context derivation ID for Linux `security_context_digest`.
76pub const LINUX_SECCTX_DIGEST_DERIVATION_ID: &str =
77    "urn:3leaps:identity-evidence:context-derivation:linux-procfs-status-secctx:v0";
78
79const HOST_STABILITIES: &[&str] = &[
80    "unknown",
81    "process",
82    "boot",
83    "installation",
84    "enrollment",
85    "device",
86];
87const CLONE_BEHAVIORS: &[&str] = &["unknown", "copyable", "regenerated", "device-bound"];
88
89/// Pinned `{id, revision}` reference to `native-process-observation:v0` `profile.json`.
90pub fn accepted_observation_profile() -> ProfileRef {
91    ProfileRef::new(
92        NATIVE_PROCESS_OBSERVATION_PROFILE_ID,
93        NATIVE_PROCESS_OBSERVATION_PROFILE_REVISION,
94    )
95}
96
97/// Caller-supplied host-scope descriptor (`process.host_scope`).
98///
99/// This descriptor crosses an explicit caller trust boundary; it does not
100/// self-authenticate physical-machine uniqueness.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102pub struct HostScope {
103    /// Optional report-local identifier ID (`^[a-z][a-z0-9-]{0,63}$`).
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub identifier_ref: Option<String>,
106    /// Identifier namespace (`1..=512` Unicode scalar values).
107    pub namespace: String,
108    /// Identifier value (`1..=512` Unicode scalar values).
109    pub value: String,
110    /// Pinned derivation `{id, revision}`.
111    pub derivation: ProfileRef,
112    /// Lifecycle stability (`unknown | process | boot | installation | enrollment | device`).
113    pub stability: String,
114    /// Clone behavior (`unknown | copyable | regenerated | device-bound`).
115    pub clone_behavior: String,
116}
117
118impl HostScope {
119    /// Validate against `native-process-observation/evidence.schema.json` and encode as JSON.
120    pub fn to_json(&self) -> Result<Value, CollectorRefusal> {
121        if let Some(ref id_ref) = self.identifier_ref {
122            if !is_local_id(id_ref) {
123                return Err(CollectorRefusal::error(
124                    "invalid-host-scope",
125                    "host_scope.identifier_ref must match ^[a-z][a-z0-9-]{0,63}$",
126                ));
127            }
128        }
129        if !is_nonempty_512(&self.namespace)
130            || !is_nonempty_512(&self.value)
131            || !is_nonempty_512(&self.derivation.id)
132            || !is_sha256_digest(&self.derivation.revision)
133            || !HOST_STABILITIES.contains(&self.stability.as_str())
134            || !CLONE_BEHAVIORS.contains(&self.clone_behavior.as_str())
135        {
136            return Err(CollectorRefusal::error(
137                "invalid-host-scope",
138                "host_scope fields violate native-process-observation schema constraints",
139            ));
140        }
141        let mut obj = Map::new();
142        if let Some(ref id_ref) = self.identifier_ref {
143            obj.insert("identifier_ref".into(), Value::String(id_ref.clone()));
144        }
145        obj.insert("namespace".into(), Value::String(self.namespace.clone()));
146        obj.insert("value".into(), Value::String(self.value.clone()));
147        obj.insert(
148            "derivation".into(),
149            json!({
150                "id": self.derivation.id,
151                "revision": self.derivation.revision,
152            }),
153        );
154        obj.insert("stability".into(), Value::String(self.stability.clone()));
155        obj.insert(
156            "clone_behavior".into(),
157            Value::String(self.clone_behavior.clone()),
158        );
159        Ok(Value::Object(obj))
160    }
161}
162
163/// Disclosure and probe budget options for `observe_process` and `open_continuity_handle`.
164///
165/// By default, `probe_security_principal` is `true` and all four digest context
166/// facts (`namespace_context_digest`, `executable_digest`, `arguments_digest`,
167/// `security_context_digest`) are `false` (`status: "not-probed"`).
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct ObservationOptions {
170    /// Report-local process subject ID (`^[a-z][a-z0-9-]{0,63}$`, default `"process-target"`).
171    pub subject_ref: String,
172    /// Optional explicit UTC timestamp (`YYYY-MM-DDTHH:MM:SSZ`); defaults to current system UTC time.
173    pub observed_at: Option<String>,
174    /// Probe `execution_context.security_principal` (default `true`).
175    pub probe_security_principal: bool,
176    /// Opt in to `execution_context.namespace_context_digest` (default `false`).
177    pub include_namespace_context_digest: bool,
178    /// Opt in to `execution_context.executable_digest` (default `false`).
179    pub include_executable_digest: bool,
180    /// Opt in to `execution_context.arguments_digest` (default `false`).
181    pub include_arguments_digest: bool,
182    /// Opt in to `execution_context.security_context_digest` (default `false`).
183    pub include_security_context_digest: bool,
184}
185
186impl Default for ObservationOptions {
187    fn default() -> Self {
188        Self {
189            subject_ref: "process-target".to_string(),
190            observed_at: None,
191            probe_security_principal: true,
192            include_namespace_context_digest: false,
193            include_executable_digest: false,
194            include_arguments_digest: false,
195            include_security_context_digest: false,
196        }
197    }
198}
199
200impl ObservationOptions {
201    /// Enable all opt-in execution-context facts supported by the platform.
202    pub fn with_all_context_facts(mut self) -> Self {
203        self.probe_security_principal = true;
204        self.include_namespace_context_digest = true;
205        self.include_executable_digest = true;
206        self.include_arguments_digest = true;
207        self.include_security_context_digest = true;
208        self
209    }
210}
211
212/// Deterministic collector or continuity-handle refusal.
213#[derive(Debug, Clone, PartialEq, Eq, Error)]
214#[error("{status}:{code}: {detail}")]
215pub struct CollectorRefusal {
216    /// 7-state capability/fact status category (`unsupported`, `inaccessible`, `not-present`, `error`, `unknown`).
217    pub status: String,
218    /// Stable machine-readable refusal code.
219    pub code: String,
220    /// Diagnostic detail (not exported into portable observation payloads).
221    pub detail: String,
222}
223
224impl CollectorRefusal {
225    /// Construct a new [`CollectorRefusal`].
226    pub fn new(
227        status: impl Into<String>,
228        code: impl Into<String>,
229        detail: impl Into<String>,
230    ) -> Self {
231        Self {
232            status: status.into(),
233            code: code.into(),
234            detail: detail.into(),
235        }
236    }
237
238    /// Construct an `"unsupported"` collector refusal.
239    pub fn unsupported(code: impl Into<String>, detail: impl Into<String>) -> Self {
240        Self::new("unsupported", code, detail)
241    }
242
243    /// Construct an `"inaccessible"` collector refusal.
244    pub fn inaccessible(code: impl Into<String>, detail: impl Into<String>) -> Self {
245        Self::new("inaccessible", code, detail)
246    }
247
248    /// Construct a `"not-present"` collector refusal.
249    pub fn not_present(code: impl Into<String>, detail: impl Into<String>) -> Self {
250        Self::new("not-present", code, detail)
251    }
252
253    /// Construct an `"error"` collector refusal.
254    pub fn error(code: impl Into<String>, detail: impl Into<String>) -> Self {
255        Self::new("error", code, detail)
256    }
257}
258
259/// Optional live continuity-handle probe outcome to record in `report.capabilities[]`.
260#[derive(Debug, Clone, PartialEq, Eq)]
261pub struct CapabilityProbe {
262    /// Adapter provider slug (e.g. `"macos-kqueue-proc"` or `"linux-pidfd"`).
263    pub provider: String,
264    /// Report capability status (`available | not-present | inaccessible | unsupported | not-probed | error | unknown`).
265    pub status: String,
266    /// Human-readable reason (required when `status != "available"`).
267    pub reason: String,
268}
269
270/// Envelope metadata for wrapping a collected observation in an observation-only
271/// `identity-evidence/v0` report (`assessments: []`, `evaluator` omitted).
272#[derive(Debug, Clone, PartialEq, Eq)]
273pub struct ReportMetadata {
274    /// Report identifier (`^[a-z][a-z0-9-]{0,63}$`).
275    pub report_id: String,
276    /// Optional report `created_at` (`YYYY-MM-DDTHH:MM:SSZ`, defaults to `observation.observed_at`).
277    pub created_at: Option<String>,
278    /// Producer name (`1..=128` chars).
279    pub producer_name: String,
280    /// Producer revision (`sha256:<64 lowercase hex>`).
281    pub producer_revision: String,
282    /// Report-local host subject ID (`^[a-z][a-z0-9-]{0,63}$`, distinct from `process.subject_ref`).
283    pub host_subject_id: String,
284    /// Report-local evidence descriptor ID (`^[a-z][a-z0-9-]{0,63}$`).
285    pub evidence_id: String,
286    /// Evidence `source` label (e.g. `"macos-sysctl-proc"` or `"linux-procfs-openat2"`).
287    pub source: String,
288    /// Evidence `collector` label.
289    pub collector: String,
290    /// Optional capability entry describing live exit-handle acquisition.
291    pub exit_handle_capability: Option<CapabilityProbe>,
292}
293
294impl Default for ReportMetadata {
295    fn default() -> Self {
296        Self {
297            report_id: "native-process-observation".to_string(),
298            created_at: None,
299            producer_name: "sysprims-proc".to_string(),
300            producer_revision:
301                "sha256:0000000000000000000000000000000000000000000000000000000000000000"
302                    .to_string(),
303            host_subject_id: "host-local".to_string(),
304            evidence_id: "e-process-observation".to_string(),
305            source: default_collector_source().to_string(),
306            collector: "sysprims-proc".to_string(),
307            exit_handle_capability: None,
308        }
309    }
310}
311
312/// Private, non-serializable read-only OS continuity handle (`kqueue` `EVFILT_PROC`
313/// `NOTE_EXIT` on macOS; `pidfd` on Linux) bracketed at registration against
314/// kernel start-identity metadata.
315///
316/// This type intentionally exposes no raw file descriptor accessor, redacts OS
317/// descriptors from [`std::fmt::Debug`], implements neither `Serialize` nor
318/// `Deserialize`, and provides no signal delivery API.
319pub struct ProcessContinuityHandle {
320    pid: u32,
321    baseline: Value,
322    host_scope: HostScope,
323    options: ObservationOptions,
324    inner: imp::PlatformHandle,
325}
326
327impl std::fmt::Debug for ProcessContinuityHandle {
328    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
329        f.debug_struct("ProcessContinuityHandle")
330            .field("pid", &self.pid)
331            .field("subject_ref", &self.options.subject_ref)
332            .field("inner", &self.inner)
333            .finish_non_exhaustive()
334    }
335}
336
337impl ProcessContinuityHandle {
338    /// Numeric PID (`1..=2147483647`) bound at handle creation.
339    pub fn pid(&self) -> u32 {
340        self.pid
341    }
342
343    /// Borrow the bracketed baseline observation captured across handle registration.
344    pub fn baseline_observation(&self) -> &Value {
345        &self.baseline
346    }
347
348    /// Non-blocking exit check (`true` once the bound incarnation has exited).
349    pub fn poll_exited(&self) -> Result<bool, CollectorRefusal> {
350        self.inner.poll_exited()
351    }
352
353    /// Wait up to `timeout` for the bound incarnation to exit (`Ok(true)` if exited,
354    /// `Ok(false)` if `timeout` elapsed while still running).
355    pub fn wait_exit(&self, timeout: Duration) -> Result<bool, CollectorRefusal> {
356        self.inner.wait_exit(timeout)
357    }
358
359    /// Collect a fresh read-only observation for `self.pid` using the stored
360    /// `HostScope` and `ObservationOptions`.
361    pub fn reobserve(&self, observed_at: Option<&str>) -> Result<Value, CollectorRefusal> {
362        let mut opts = self.options.clone();
363        opts.observed_at = observed_at.map(str::to_string);
364        observe_process(self.pid, &self.host_scope, &opts)
365    }
366
367    /// Re-observe `self.pid` at trusted UTC instant `now_utc`, enforce
368    /// `admit_live_observation`, and evaluate `compare_native_observations`
369    /// against [`Self::baseline_observation`].
370    pub fn reverify(
371        &self,
372        policy: &ComparisonPolicy,
373        now_utc: &str,
374    ) -> Result<(Value, ComparisonOutcome), CollectorRefusal> {
375        let candidate = self.reobserve(Some(now_utc))?;
376        let accepted = accepted_observation_profile();
377        admit_live_observation(&candidate, Some(now_utc), &accepted, None, None).map_err(|e| {
378            CollectorRefusal::error(e.code(), "live observation freshness gate refused")
379        })?;
380        let outcome = compare_native_observations(&self.baseline, &candidate, policy, &accepted);
381        Ok((candidate, outcome))
382    }
383}
384
385/// Format current system wall clock as strict whole-second UTC (`YYYY-MM-DDTHH:MM:SSZ`).
386pub fn current_utc_timestamp() -> Result<String, CollectorRefusal> {
387    let secs = SystemTime::now()
388        .duration_since(UNIX_EPOCH)
389        .map_err(|_| {
390            CollectorRefusal::error("trusted-clock-unavailable", "system clock pre-epoch")
391        })?
392        .as_secs();
393    let secs_i64 = i64::try_from(secs)
394        .map_err(|_| CollectorRefusal::error("trusted-clock-unavailable", "clock overflow"))?;
395    let dt = OffsetDateTime::from_unix_timestamp(secs_i64)
396        .map_err(|_| CollectorRefusal::error("trusted-clock-unavailable", "invalid unix time"))?;
397    let formatted = format!(
398        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
399        dt.year(),
400        u8::from(dt.month()),
401        dt.day(),
402        dt.hour(),
403        dt.minute(),
404        dt.second()
405    );
406    if parse_strict_utc_unix(&formatted).is_none() {
407        return Err(CollectorRefusal::error(
408            "trusted-clock-unavailable",
409            "formatted timestamp outside four-digit UTC range",
410        ));
411    }
412    Ok(formatted)
413}
414
415fn validate_common_inputs(
416    pid: u32,
417    host_scope: &HostScope,
418    options: &ObservationOptions,
419) -> Result<(Value, String), CollectorRefusal> {
420    if !(MIN_OBSERVABLE_PID..=MAX_OBSERVABLE_PID).contains(&pid) {
421        return Err(CollectorRefusal::error(
422            "invalid-pid-range",
423            "pid must be within 1..=2147483647",
424        ));
425    }
426    if !is_local_id(&options.subject_ref) {
427        return Err(CollectorRefusal::error(
428            "invalid-subject-ref",
429            "subject_ref must match ^[a-z][a-z0-9-]{0,63}$",
430        ));
431    }
432    let host_scope_json = host_scope.to_json()?;
433    let observed_at = match options.observed_at.as_deref() {
434        Some(ts) => {
435            if parse_strict_utc_unix(ts).is_none() {
436                return Err(CollectorRefusal::error(
437                    "invalid-observed-at",
438                    "observed_at must be a valid YYYY-MM-DDTHH:MM:SSZ instant",
439                ));
440            }
441            ts.to_string()
442        }
443        None => current_utc_timestamp()?,
444    };
445    Ok((host_scope_json, observed_at))
446}
447
448/// Collect a bracketed read-only `native-process-observation:v0` evidence payload
449/// for `pid` (`1..=2147483647`).
450///
451/// Target absence (`ESRCH` / verified `ENOENT` without `hidepid` concealment)
452/// returns an `Ok(Value)` payload whose `process_state` and `start_identity`
453/// record `status: "not-present"` so downstream comparison deterministically
454/// yields `mismatch:process-exited`. Collector-level precondition, platform, or
455/// confinement failures return `Err(CollectorRefusal)`.
456pub fn observe_process(
457    pid: u32,
458    host_scope: &HostScope,
459    options: &ObservationOptions,
460) -> Result<Value, CollectorRefusal> {
461    let (host_scope_json, observed_at) = validate_common_inputs(pid, host_scope, options)?;
462    let obs = imp::observe_process_impl(pid, host_scope_json, &observed_at, options)?;
463    validate_observation_shape(&obs).map_err(|e| {
464        CollectorRefusal::error(
465            e.code(),
466            "internal collector output failed native-process-observation schema validation",
467        )
468    })?;
469    Ok(obs)
470}
471
472/// Open a private read-only continuity handle (`kqueue` `EVFILT_PROC` `NOTE_EXIT`
473/// on macOS; `pidfd_open` on Linux) bracketed by pre/post incarnation checks.
474///
475/// Requires the target process to be observed in `"live"` state across handle
476/// registration; absent or zombie targets return `Err(CollectorRefusal)`.
477pub fn open_continuity_handle(
478    pid: u32,
479    host_scope: &HostScope,
480    options: &ObservationOptions,
481) -> Result<ProcessContinuityHandle, CollectorRefusal> {
482    let (host_scope_json, observed_at) = validate_common_inputs(pid, host_scope, options)?;
483    let (baseline, inner) =
484        imp::open_continuity_handle_impl(pid, host_scope_json, &observed_at, options)?;
485    validate_observation_shape(&baseline).map_err(|e| {
486        CollectorRefusal::error(
487            e.code(),
488            "internal baseline output failed native-process-observation schema validation",
489        )
490    })?;
491    Ok(ProcessContinuityHandle {
492        pid,
493        baseline,
494        host_scope: host_scope.clone(),
495        options: options.clone(),
496        inner,
497    })
498}
499
500/// Build and canonically admit an observation-only `identity-evidence/v0` report
501/// (`assessments: []`, `evaluator` omitted) bound to `observation`.
502pub fn build_observation_report(
503    observation: &Value,
504    metadata: &ReportMetadata,
505) -> Result<AdmittedWire, CollectorRefusal> {
506    validate_observation_shape(observation)
507        .map_err(|e| CollectorRefusal::error(e.code(), "observation failed schema validation"))?;
508    let observed_at = observation
509        .get("observed_at")
510        .and_then(Value::as_str)
511        .ok_or_else(|| CollectorRefusal::error("invalid-observed-at", "missing observed_at"))?;
512    let created_at = metadata.created_at.as_deref().unwrap_or(observed_at);
513    if parse_strict_utc_unix(created_at).is_none() {
514        return Err(CollectorRefusal::error(
515            "invalid-report-metadata",
516            "created_at must be strict UTC YYYY-MM-DDTHH:MM:SSZ",
517        ));
518    }
519    let proc_obj = observation
520        .get("process")
521        .and_then(Value::as_object)
522        .ok_or_else(|| CollectorRefusal::error("invalid-observation-shape", "missing process"))?;
523    let proc_subject = proc_obj
524        .get("subject_ref")
525        .and_then(Value::as_str)
526        .ok_or_else(|| {
527            CollectorRefusal::error("invalid-observation-shape", "missing subject_ref")
528        })?;
529    if !is_local_id(&metadata.report_id)
530        || !is_local_id(&metadata.host_subject_id)
531        || !is_local_id(&metadata.evidence_id)
532        || metadata.host_subject_id == proc_subject
533        || !is_sha256_digest(&metadata.producer_revision)
534    {
535        return Err(CollectorRefusal::error(
536            "invalid-report-metadata",
537            "report metadata IDs or digests violate report.schema.json constraints",
538        ));
539    }
540
541    let payload_digest = canonical_sha256_value(observation)
542        .map_err(|e| CollectorRefusal::error(e.code(), "failed to canonicalize observation"))?;
543
544    let hs_obj = proc_obj
545        .get("host_scope")
546        .and_then(Value::as_object)
547        .ok_or_else(|| {
548            CollectorRefusal::error("invalid-observation-shape", "missing host_scope")
549        })?;
550    let mut identifiers = Vec::new();
551    if let Some(id_ref) = hs_obj.get("identifier_ref").and_then(Value::as_str) {
552        identifiers.push(json!({
553            "id": id_ref,
554            "subject_ref": metadata.host_subject_id,
555            "namespace": hs_obj.get("namespace").cloned().unwrap_or(Value::Null),
556            "value": hs_obj.get("value").cloned().unwrap_or(Value::Null),
557            "derivation": hs_obj.get("derivation").cloned().unwrap_or(Value::Null),
558            "stability": hs_obj.get("stability").cloned().unwrap_or(Value::Null),
559            "clone_behavior": hs_obj.get("clone_behavior").cloned().unwrap_or(Value::Null),
560        }));
561    }
562
563    let provider = default_collector_source();
564    let mut capabilities = Vec::new();
565    if let Some(ref exit_cap) = metadata.exit_handle_capability {
566        let mut cap = Map::new();
567        cap.insert("id".into(), Value::String("cap-exit-handle".into()));
568        cap.insert("subject_ref".into(), Value::String(proc_subject.into()));
569        cap.insert("provider".into(), Value::String(exit_cap.provider.clone()));
570        cap.insert(
571            "capability".into(),
572            Value::String("process-exit-observation".into()),
573        );
574        cap.insert("status".into(), Value::String(exit_cap.status.clone()));
575        let reason = if exit_cap.reason.is_empty() {
576            "Acquired private read-only process continuity handle.".to_string()
577        } else {
578            exit_cap.reason.clone()
579        };
580        cap.insert("reason".into(), Value::String(reason));
581        cap.insert("observed_at".into(), Value::String(observed_at.into()));
582        capabilities.push(Value::Object(cap));
583    }
584
585    if let Some(tpns) = proc_obj.get("target_pid_namespace") {
586        capabilities.push(fact_to_capability(
587            "cap-pid-namespace",
588            proc_subject,
589            provider,
590            "pid-namespace-observation",
591            tpns,
592            observed_at,
593        ));
594    }
595    if let Some(ec) = proc_obj.get("execution_context").and_then(Value::as_object) {
596        for (cap_id, cap_name, key) in [
597            (
598                "cap-security-principal",
599                "security-principal",
600                "security_principal",
601            ),
602            (
603                "cap-namespace-context-digest",
604                "namespace-context-digest",
605                "namespace_context_digest",
606            ),
607            (
608                "cap-executable-digest",
609                "executable-digest",
610                "executable_digest",
611            ),
612            (
613                "cap-arguments-digest",
614                "arguments-digest",
615                "arguments_digest",
616            ),
617            (
618                "cap-security-context-digest",
619                "security-context-digest",
620                "security_context_digest",
621            ),
622        ] {
623            if let Some(fact) = ec.get(key) {
624                capabilities.push(fact_to_capability(
625                    cap_id,
626                    proc_subject,
627                    provider,
628                    cap_name,
629                    fact,
630                    observed_at,
631                ));
632            }
633        }
634    }
635
636    let report_val = json!({
637        "contract": IDENTITY_EVIDENCE_CONTRACT,
638        "report_id": metadata.report_id,
639        "created_at": created_at,
640        "producer": {
641            "name": metadata.producer_name,
642            "revision": metadata.producer_revision,
643        },
644        "subjects": [
645            {
646                "id": metadata.host_subject_id,
647                "kind": "os-installation",
648            },
649            {
650                "id": proc_subject,
651                "kind": "process",
652            },
653        ],
654        "identifiers": identifiers,
655        "evidence": [
656            {
657                "id": metadata.evidence_id,
658                "subject_ref": proc_subject,
659                "method": "os-observation",
660                "source": metadata.source,
661                "collector": metadata.collector,
662                "collected_at": observed_at,
663                "digest": payload_digest,
664                "format_profile": {
665                    "id": NATIVE_PROCESS_OBSERVATION_PROFILE_ID,
666                    "revision": NATIVE_PROCESS_OBSERVATION_PROFILE_REVISION,
667                },
668            }
669        ],
670        "assessments": [],
671        "capabilities": capabilities,
672        "keys": [],
673        "claims": [],
674        "input_reports": [],
675    });
676
677    bind_native_observation_report(&report_val, observation, &accepted_observation_profile())
678        .map_err(|e| CollectorRefusal::error(e.code(), "observation report binding failed"))?;
679
680    let raw = serde_json::to_vec(&report_val)
681        .map_err(|_| CollectorRefusal::error("invalid-json", "report serialization failed"))?;
682    admit_and_validate_report(&raw, None)
683        .map_err(|e| CollectorRefusal::error(e.code(), "report envelope validation failed"))
684}
685
686fn default_collector_source() -> &'static str {
687    if cfg!(target_os = "macos") {
688        "macos-sysctl-proc"
689    } else if cfg!(target_os = "linux") {
690        "linux-procfs-openat2"
691    } else {
692        "unsupported-platform"
693    }
694}
695
696fn fact_to_capability(
697    id: &str,
698    subject_ref: &str,
699    provider: &str,
700    capability: &str,
701    fact: &Value,
702    observed_at: &str,
703) -> Value {
704    let fact_status = fact
705        .get("status")
706        .and_then(Value::as_str)
707        .unwrap_or("unknown");
708    let cap_status = if fact_status == "observed" {
709        "available"
710    } else {
711        fact_status
712    };
713    let mut obj = Map::new();
714    obj.insert("id".into(), Value::String(id.into()));
715    obj.insert("subject_ref".into(), Value::String(subject_ref.into()));
716    obj.insert("provider".into(), Value::String(provider.into()));
717    obj.insert("capability".into(), Value::String(capability.into()));
718    obj.insert("status".into(), Value::String(cap_status.into()));
719    let reason = fact
720        .get("reason")
721        .and_then(Value::as_str)
722        .filter(|s| !s.is_empty())
723        .unwrap_or("Observed within bracketed native process snapshot.");
724    obj.insert("reason".into(), Value::String(reason.into()));
725    obj.insert("observed_at".into(), Value::String(observed_at.into()));
726    Value::Object(obj)
727}
728
729#[cfg(any(target_os = "linux", target_os = "macos"))]
730pub(crate) fn observer_architecture() -> &'static str {
731    std::env::consts::ARCH
732}
733
734pub(crate) fn is_local_id(s: &str) -> bool {
735    let b = s.as_bytes();
736    if b.is_empty() || b.len() > 64 || !b[0].is_ascii_lowercase() {
737        return false;
738    }
739    b[1..]
740        .iter()
741        .all(|&c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
742}
743
744pub(crate) fn is_nonempty_512(s: &str) -> bool {
745    let n = s.chars().count();
746    (1..=512).contains(&n)
747}
748
749pub(crate) fn is_sha256_digest(s: &str) -> bool {
750    let Some(hex) = s.strip_prefix("sha256:") else {
751        return false;
752    };
753    hex.len() == 64
754        && hex
755            .bytes()
756            .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
757}
758
759#[cfg(any(target_os = "linux", target_os = "macos"))]
760pub(crate) fn is_lowercase_uuid(s: &str) -> bool {
761    let b = s.as_bytes();
762    if b.len() != 36 {
763        return false;
764    }
765    for (idx, &ch) in b.iter().enumerate() {
766        if matches!(idx, 8 | 13 | 18 | 23) {
767            if ch != b'-' {
768                return false;
769            }
770        } else if !(ch.is_ascii_digit() || (b'a'..=b'f').contains(&ch)) {
771            return false;
772        }
773    }
774    true
775}
776
777#[cfg(any(target_os = "linux", target_os = "macos"))]
778pub(crate) fn fact_observed(value: impl Into<String>) -> Value {
779    json!({
780        "status": "observed",
781        "value": value.into(),
782    })
783}
784
785#[cfg(any(target_os = "linux", target_os = "macos"))]
786pub(crate) fn fact_non_observed(status: &str, reason: &str) -> Value {
787    json!({
788        "status": status,
789        "reason": reason,
790    })
791}
792
793#[cfg(any(target_os = "linux", target_os = "macos"))]
794pub(crate) fn start_identity_observed(profile_id: &str, value: impl Into<String>) -> Value {
795    json!({
796        "status": "observed",
797        "profile": {
798            "id": profile_id,
799            "revision": NATIVE_PROCESS_OBSERVATION_README_REVISION,
800        },
801        "value": value.into(),
802    })
803}
804
805#[cfg(any(target_os = "linux", target_os = "macos"))]
806pub(crate) fn start_identity_non_observed(profile_id: &str, status: &str, reason: &str) -> Value {
807    json!({
808        "status": status,
809        "profile": {
810            "id": profile_id,
811            "revision": NATIVE_PROCESS_OBSERVATION_README_REVISION,
812        },
813        "reason": reason,
814    })
815}
816
817#[cfg(any(target_os = "linux", target_os = "macos"))]
818pub(crate) fn principal_observed(
819    derivation_id: &str,
820    namespace: impl Into<String>,
821    value: impl Into<String>,
822) -> Value {
823    json!({
824        "status": "observed",
825        "derivation": {
826            "id": derivation_id,
827            "revision": NATIVE_PROCESS_OBSERVATION_README_REVISION,
828        },
829        "principal": {
830            "namespace": namespace.into(),
831            "value": value.into(),
832        },
833    })
834}
835
836#[cfg(any(target_os = "linux", target_os = "macos"))]
837pub(crate) fn digest_observed(derivation_id: &str, digest: impl Into<String>) -> Value {
838    json!({
839        "status": "observed",
840        "derivation": {
841            "id": derivation_id,
842            "revision": NATIVE_PROCESS_OBSERVATION_README_REVISION,
843        },
844        "digest": digest.into(),
845    })
846}
847
848/// Stream regular-file bytes from an already-opened descriptor up to
849/// [`MAX_EXECUTABLE_FILE_BYTES`] (`67,108,864` bytes) into the domain-separated
850/// `executable-file-bytes:v0` SHA-256 preimage without buffering the full image.
851#[cfg(any(target_os = "linux", target_os = "macos"))]
852pub(crate) fn stream_executable_digest_from_fd(raw_fd: libc::c_int) -> Value {
853    use sha2::{Digest, Sha256};
854
855    let mut st: libc::stat = unsafe { std::mem::zeroed() };
856    let fstat_rc = unsafe { libc::fstat(raw_fd, &mut st) };
857    if fstat_rc != 0 {
858        let err = std::io::Error::last_os_error();
859        return errno_to_digest_fact(
860            err.raw_os_error().unwrap_or(libc::EIO),
861            "executable-fstat-failed",
862        );
863    }
864    if (st.st_mode & libc::S_IFMT) != libc::S_IFREG {
865        return fact_non_observed("error", "executable-not-regular-file");
866    }
867    if st.st_size < 0 {
868        return fact_non_observed("error", "executable-negative-size");
869    }
870    if (st.st_size as u64) > MAX_EXECUTABLE_FILE_BYTES {
871        return fact_non_observed("error", "executable-exceeds-size-cap");
872    }
873
874    let mut hasher = Sha256::new();
875    hasher.update(b"3leaps.native-process-observation.executable-image.v0\0");
876
877    let mut buf = [0u8; 65_536];
878    let mut total: u64 = 0;
879    loop {
880        let n = unsafe { libc::read(raw_fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()) };
881        if n == 0 {
882            break;
883        }
884        if n < 0 {
885            let errno = std::io::Error::last_os_error()
886                .raw_os_error()
887                .unwrap_or(libc::EIO);
888            if errno == libc::EINTR {
889                continue;
890            }
891            return errno_to_digest_fact(errno, "executable-read-failed");
892        }
893        total = total.saturating_add(n as u64);
894        if total > MAX_EXECUTABLE_FILE_BYTES {
895            return fact_non_observed("error", "executable-exceeds-size-cap");
896        }
897        hasher.update(&buf[..n as usize]);
898    }
899
900    let digest = format!("sha256:{:x}", hasher.finalize());
901    digest_observed(EXEC_DIGEST_DERIVATION_ID, digest)
902}
903
904#[cfg(any(target_os = "linux", target_os = "macos"))]
905pub(crate) fn errno_to_digest_fact(errno: i32, fallback_reason: &str) -> Value {
906    match errno {
907        libc::EPERM | libc::EACCES => fact_non_observed("inaccessible", "permission-denied"),
908        libc::ENOENT | libc::ESRCH => fact_non_observed("not-present", "backing-entry-absent"),
909        _ => fact_non_observed("error", fallback_reason),
910    }
911}
912
913/// Split non-empty Linux `/proc/<pid>/cmdline` bytes per `native-process-observation:v0` ยง4:
914/// - If `raw` ends with `0x00`, strip exactly one trailing `0x00` and split on `0x00`.
915/// - If `raw` does not end with `0x00` (e.g., a process rewrote its `argv` stack without
916///   NUL terminators), yield the single element `[raw]` without splitting on interior `0x00`.
917#[cfg(any(target_os = "linux", test))]
918pub(crate) fn parse_linux_cmdline_argv(raw: &[u8]) -> Vec<&[u8]> {
919    if raw.is_empty() {
920        return Vec::new();
921    }
922    if let Some(trimmed) = raw.strip_suffix(b"\0") {
923        trimmed.split(|&b| b == 0).collect()
924    } else {
925        vec![raw]
926    }
927}
928
929/// Parse a 64-bit XNU `sysctl` `KERN_PROCARGS2` buffer into `argc` raw argument slices.
930///
931/// Qualified layout (`macos/aarch64`, `macos/x86_64` with 64-bit `P_LP64` target):
932/// XNU `exec_save_path` (`bsd/kern/kern_exec.c`) pads `exec_path + '\0'` to the 8-byte
933/// target pointer boundary (`4 + align_up(exec_path_len + 1, 8)`) before `ip_startargv`.
934/// All bounded padding bytes must be `0x00`. For `argc > 0`, a leading `0x00` byte at
935/// that boundary refuses fail-closed with `"ambiguous-kern-procargs2-padding"` rather
936/// than scanning onward across empty `argv[0]` into environment strings.
937#[cfg(any(target_os = "macos", test))]
938pub(crate) fn parse_procargs2_argv_64(
939    buf: &[u8],
940    max_bytes: usize,
941) -> Result<Vec<&[u8]>, &'static str> {
942    if max_bytes == 0 || buf.len() > max_bytes {
943        return Err("arguments-exceed-cap");
944    }
945    if buf.len() < 4 {
946        return Err("malformed-kern-procargs2");
947    }
948    let argc_i32 = i32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]);
949    if argc_i32 < 0 {
950        return Err("negative-kern-procargs2-argc");
951    }
952    let argc = usize::try_from(argc_i32).map_err(|_| "negative-kern-procargs2-argc")?;
953    if argc > max_bytes {
954        return Err("arguments-exceed-cap");
955    }
956
957    let Some(exec_rel_nul) = buf[4..].iter().position(|&b| b == 0) else {
958        return Err("malformed-kern-procargs2-execpath");
959    };
960    if exec_rel_nul == 0 {
961        return Err("malformed-kern-procargs2-execpath");
962    }
963    let exec_end = 4usize
964        .checked_add(exec_rel_nul)
965        .ok_or("malformed-kern-procargs2-execpath")?;
966    let path_with_nul = exec_rel_nul
967        .checked_add(1)
968        .ok_or("malformed-kern-procargs2-execpath")?;
969    let rem = path_with_nul % 8;
970    let pad_extra = if rem == 0 { 0 } else { 8 - rem };
971    let padded_len = path_with_nul
972        .checked_add(pad_extra)
973        .ok_or("malformed-kern-procargs2-execpath")?;
974    let aligned_off = 4usize
975        .checked_add(padded_len)
976        .ok_or("malformed-kern-procargs2-execpath")?;
977    if aligned_off > buf.len() {
978        return Err("truncated-kern-procargs2-padding");
979    }
980    if buf[exec_end..aligned_off].iter().any(|&b| b != 0) {
981        return Err("malformed-kern-procargs2-padding");
982    }
983
984    if argc == 0 {
985        return Ok(Vec::new());
986    }
987    if aligned_off >= buf.len() {
988        return Err("truncated-kern-procargs2-argv");
989    }
990    if buf[aligned_off] == 0 {
991        return Err("ambiguous-kern-procargs2-padding");
992    }
993
994    let mut argv = Vec::with_capacity(argc.min(256));
995    let mut pos = aligned_off;
996    for _ in 0..argc {
997        if pos >= buf.len() {
998            return Err("truncated-kern-procargs2-argv");
999        }
1000        let Some(arg_nul) = buf[pos..].iter().position(|&b| b == 0) else {
1001            return Err("unterminated-kern-procargs2-arg");
1002        };
1003        let end = pos
1004            .checked_add(arg_nul)
1005            .ok_or("unterminated-kern-procargs2-arg")?;
1006        argv.push(&buf[pos..end]);
1007        pos = end.checked_add(1).ok_or("truncated-kern-procargs2-argv")?;
1008    }
1009    Ok(argv)
1010}
1011
1012#[cfg(test)]
1013mod tests {
1014    use serde_json::json;
1015    use sysprims_evidence::derive_arguments_digest;
1016
1017    use super::*;
1018
1019    fn build_procargs2_64(exec_path: &[u8], argc: i32, argv: &[&[u8]], envp: &[&[u8]]) -> Vec<u8> {
1020        let mut out = Vec::new();
1021        out.extend_from_slice(&argc.to_le_bytes());
1022        out.extend_from_slice(exec_path);
1023        out.push(0);
1024        let path_with_nul = exec_path.len() + 1;
1025        let pad = (8 - (path_with_nul % 8)) % 8;
1026        out.resize(out.len() + pad, 0);
1027        for a in argv {
1028            out.extend_from_slice(a);
1029            out.push(0);
1030        }
1031        for e in envp {
1032            out.extend_from_slice(e);
1033            out.push(0);
1034        }
1035        out
1036    }
1037
1038    #[test]
1039    fn debug_formatting_redacts_internal_os_descriptors() {
1040        let mut handle = ProcessContinuityHandle {
1041            pid: 7777,
1042            baseline: json!({"profile": {"id": "test", "revision": "sha256:0000000000000000000000000000000000000000000000000000000000000000"}}),
1043            host_scope: HostScope {
1044                identifier_ref: None,
1045                namespace: "urn:test:host".to_string(),
1046                value: "node-1".to_string(),
1047                derivation: ProfileRef::new(
1048                    "urn:test:drv",
1049                    "sha256:0000000000000000000000000000000000000000000000000000000000000000",
1050                ),
1051                stability: "boot".to_string(),
1052                clone_behavior: "regenerated".to_string(),
1053            },
1054            options: ObservationOptions::default(),
1055            inner: imp::PlatformHandle::new_sentinel_for_debug_test(424_242),
1056        };
1057
1058        let compact = format!("{handle:?}");
1059        let pretty = format!("{handle:#?}");
1060        handle.inner.disarm_for_debug_test();
1061
1062        assert!(compact.contains("ProcessContinuityHandle"));
1063        assert!(compact.contains("7777"));
1064        for rendered in [&compact, &pretty] {
1065            assert!(!rendered.contains("424242"), "leaked raw fd: {rendered}");
1066            assert!(
1067                !rendered.contains("kq_fd"),
1068                "leaked kq_fd field: {rendered}"
1069            );
1070            let scrubbed = rendered.replace("linux-pidfd", "");
1071            assert!(
1072                !scrubbed.contains("pidfd"),
1073                "leaked pidfd field name: {rendered}"
1074            );
1075        }
1076        assert!(!compact.contains("424_242"));
1077    }
1078
1079    #[test]
1080    fn linux_cmdline_parser_preserves_unterminated_single_element_and_splits_nul_terminated() {
1081        assert_eq!(parse_linux_cmdline_argv(b""), Vec::<&[u8]>::new());
1082        assert_eq!(
1083            parse_linux_cmdline_argv(b"alpha\0beta"),
1084            vec![&b"alpha\0beta"[..]]
1085        );
1086        assert_eq!(
1087            derive_arguments_digest(&parse_linux_cmdline_argv(b"alpha\0beta")),
1088            derive_arguments_digest(&[&b"alpha\0beta"[..]])
1089        );
1090        assert_eq!(
1091            parse_linux_cmdline_argv(b"alpha\0beta\0"),
1092            vec![&b"alpha"[..], &b"beta"[..]]
1093        );
1094        assert_eq!(parse_linux_cmdline_argv(b"\0"), vec![&b""[..]]);
1095        assert_eq!(parse_linux_cmdline_argv(b"\0\0"), vec![&b""[..], &b""[..]]);
1096        assert_eq!(
1097            parse_linux_cmdline_argv(b"\xff\0\xfe\xfd\0"),
1098            vec![&b"\xff"[..], &b"\xfe\xfd"[..]]
1099        );
1100    }
1101
1102    #[test]
1103    fn procargs2_64_parser_handles_all_eight_residues_and_refuses_empty_argv0() {
1104        for extra in 0..8usize {
1105            let mut exec_path = b"/usr/local/bin/worker-".to_vec();
1106            exec_path.resize(exec_path.len() + extra, b'x');
1107            assert_eq!((exec_path.len() + 1) % 8, (23 + extra) % 8);
1108
1109            // 1. Ordinary non-empty argv[0] across all 8 residues: unchanged, env excluded.
1110            let normal_buf = build_procargs2_64(
1111                &exec_path,
1112                3,
1113                &[exec_path.as_slice(), b"--mode", b"strict"],
1114                &[b"SECRET_ENV=MUST_NOT_APPEAR"],
1115            );
1116            let parsed = parse_procargs2_argv_64(&normal_buf, MAX_ARGUMENTS_RAW_BYTES)
1117                .expect("ordinary argv[0] must parse");
1118            assert_eq!(
1119                parsed,
1120                vec![exec_path.as_slice(), &b"--mode"[..], &b"strict"[..]]
1121            );
1122
1123            // 2. Empty leading argv[0] = "" across all 8 residues: refuses fail-closed,
1124            // never shifting SECRET_ENV into argv.
1125            let empty_argv0_buf = build_procargs2_64(
1126                &exec_path,
1127                2,
1128                &[b"", b"arg1"],
1129                &[b"SECRET_ENV=NEVER_IN_ARGV"],
1130            );
1131            let err = parse_procargs2_argv_64(&empty_argv0_buf, MAX_ARGUMENTS_RAW_BYTES)
1132                .expect_err("empty argv[0] must refuse fail-closed");
1133            assert_eq!(err, "ambiguous-kern-procargs2-padding");
1134
1135            // 3. Later empty arguments and non-UTF-8 bytes are preserved verbatim.
1136            let later_empty_buf = build_procargs2_64(
1137                &exec_path,
1138                4,
1139                &[b"prog", b"", b"\xff\xfe", b""],
1140                &[b"SECRET_ENV=NEVER_IN_ARGV"],
1141            );
1142            let parsed_later = parse_procargs2_argv_64(&later_empty_buf, MAX_ARGUMENTS_RAW_BYTES)
1143                .expect("later empty args must succeed");
1144            assert_eq!(
1145                parsed_later,
1146                vec![&b"prog"[..], &b""[..], &b"\xff\xfe"[..], &b""[..]]
1147            );
1148
1149            // 4. argc == 0 never inspects argv[0] or consumes environment bytes.
1150            let argc_zero_buf =
1151                build_procargs2_64(&exec_path, 0, &[], &[b"SECRET_ENV=NEVER_IN_ARGV"]);
1152            let parsed_zero = parse_procargs2_argv_64(&argc_zero_buf, MAX_ARGUMENTS_RAW_BYTES)
1153                .expect("argc=0 must succeed");
1154            assert!(parsed_zero.is_empty());
1155
1156            let mut argc_zero_with_nul = build_procargs2_64(&exec_path, 0, &[], &[]);
1157            argc_zero_with_nul.extend_from_slice(b"\0SECRET_ENV=NEVER\0");
1158            assert!(
1159                parse_procargs2_argv_64(&argc_zero_with_nul, MAX_ARGUMENTS_RAW_BYTES)
1160                    .expect("argc=0 with trailing NUL/env must succeed")
1161                    .is_empty()
1162            );
1163        }
1164    }
1165
1166    #[test]
1167    fn procargs2_64_parser_rejects_malformed_negative_truncated_nonzero_padding_and_cap() {
1168        // Too short (< 4 bytes)
1169        assert_eq!(
1170            parse_procargs2_argv_64(&[1, 0, 0], MAX_ARGUMENTS_RAW_BYTES),
1171            Err("malformed-kern-procargs2")
1172        );
1173        // Oversized buffer and zero cap
1174        let small_valid = build_procargs2_64(b"/bin/ls", 1, &[b"ls"], &[]);
1175        assert_eq!(
1176            parse_procargs2_argv_64(&small_valid, 0),
1177            Err("arguments-exceed-cap")
1178        );
1179        assert_eq!(
1180            parse_procargs2_argv_64(&small_valid, small_valid.len() - 1),
1181            Err("arguments-exceed-cap")
1182        );
1183        // Negative argc
1184        for neg in [-1i32, i32::MIN] {
1185            let neg_buf = build_procargs2_64(b"/bin/ls", neg, &[b"ls"], &[]);
1186            assert_eq!(
1187                parse_procargs2_argv_64(&neg_buf, MAX_ARGUMENTS_RAW_BYTES),
1188                Err("negative-kern-procargs2-argc")
1189            );
1190        }
1191        // Empty or unterminated exec_path
1192        let empty_exec = build_procargs2_64(b"", 1, &[b"ls"], &[]);
1193        assert_eq!(
1194            parse_procargs2_argv_64(&empty_exec, MAX_ARGUMENTS_RAW_BYTES),
1195            Err("malformed-kern-procargs2-execpath")
1196        );
1197        assert_eq!(
1198            parse_procargs2_argv_64(
1199                b"\x01\x00\x00\x00/bin/unterminated",
1200                MAX_ARGUMENTS_RAW_BYTES
1201            ),
1202            Err("malformed-kern-procargs2-execpath")
1203        );
1204        // Truncated alignment padding (exec_path = "/a", len 2 -> path_with_nul 3 -> needs 5 extra NULs = 12 total)
1205        assert_eq!(
1206            parse_procargs2_argv_64(b"\x00\x00\x00\x00/a\x00\x00", MAX_ARGUMENTS_RAW_BYTES),
1207            Err("truncated-kern-procargs2-padding")
1208        );
1209        // Nonzero byte inside bounded alignment padding
1210        let mut bad_pad = build_procargs2_64(b"/a", 1, &[b"a"], &[]);
1211        bad_pad[8] = b'X'; // inside [6..12) padding region
1212        assert_eq!(
1213            parse_procargs2_argv_64(&bad_pad, MAX_ARGUMENTS_RAW_BYTES),
1214            Err("malformed-kern-procargs2-padding")
1215        );
1216        // Truncated argv (argc=2 but only 1 arg present)
1217        let trunc_argv = build_procargs2_64(b"/bin/ls", 2, &[b"ls"], &[]);
1218        assert_eq!(
1219            parse_procargs2_argv_64(&trunc_argv, MAX_ARGUMENTS_RAW_BYTES),
1220            Err("truncated-kern-procargs2-argv")
1221        );
1222        // Unterminated argument slice
1223        let mut unterm_arg = build_procargs2_64(b"/bin/ls", 1, &[b"ls"], &[]);
1224        unterm_arg.pop(); // remove final NUL
1225        assert_eq!(
1226            parse_procargs2_argv_64(&unterm_arg, MAX_ARGUMENTS_RAW_BYTES),
1227            Err("unterminated-kern-procargs2-arg")
1228        );
1229    }
1230}