diff --git a/docs/C13-READINESS.md b/docs/C13-READINESS.md new file mode 100644 index 0000000..d01d9d0 --- /dev/null +++ b/docs/C13-READINESS.md @@ -0,0 +1,75 @@ +# C13 campaign and 80% band checks + +C13 measures usable charge from stock Full to a software reserve on the +internal meter. The natural 80% band and the guard crash inside that band each +need their own observations under the production guard. Schedule them outside +the calibration attempts. + +1. **Build on the host.** Run `python3 -B scripts/i14-calibration-launch.py + --build NEW_DIRECTORY`, then `--verify NEW_DIRECTORY` with the same script + and `sh -n NEW_DIRECTORY/wrapper.sh`. Independently review the exact package + and measurement hashes, runtime pins, retention budgets and launch gate. + Changed bytes need a fresh review and a grant bound to the new manifest. +2. **Reserve one operator and prove supervision.** The coordinator grants an + exclusive window up to 72 hours including restoration. Verify export and a + real unattended continuation through the deadline. The probe must be at + most 15 minutes old, the next checkpoint within one hour, with a boundary + check within five minutes. Retain the actual receipts behind the gate hashes. +3. **Preflight immediately before each launch.** Require fresh K1–K7, pinned + board, normal stock 3.18.19 boot ID, verified recovery routes, workload, + software/configuration and services. Require two valid same-boot guard + readings at least ten minutes apart, the latest and K at most 150 s old. + USB/AC must be online, voltage ≥3700 mV, stock capacity ≥10%, temperature + 0–40 °C, and the production guard valid with no drain or competing writer. + Read charging state from the approved cached getters and BCCT readback. + Reading `current_cmd` disables charging. +4. **Budget both cycles and all writers.** Verify actual userdata backing + and available bytes after any image staging. The start gate requires the + larger of 2 GiB and **3040 MiB + fixed observer bytes + background growth + bytes**. Fixed observer overhead includes at least 1 MiB. Background + growth includes at least 3,934,208 bytes for both guard logs plus the + reviewed ceilings of other writers. Verify quota and retention on each + backing filesystem through closure. Rows are capped at 128 KiB and each + sample trace at 480 MiB. Stop at ≤512 MiB free or on an unreadable budget. +5. **Attempt 1.** Place the reviewed bundle and newly bound gate in the + launcher's fixed code directory. From that directory the approved entry + point is `sh ./wrapper.sh gate-1.json`. Each attempt consumes a slot + before the child starts. Allow at most eight hours to reach the 300 s + stock Full anchor and 32 hours for the whole measurement. Keep the cable + attached. Stop discharge at 3550 mV or stock capacity 6%, whichever is + reached first. Use `python3 -B launcher.py --checkpoint` to inspect and + `--ack-checkpoint ACK_FILE` for a fresh matching scheduler receipt. + A missed checkpoint beyond its five-minute grace stops the attempt. + `--stop` targets the identified measurement process. Let the owning + supervisor finish teardown and restart production. +6. **Restore and review before attempt 2.** Export raw samples, state, + results or failure, wrapper receipts and hashes. Verify child and wrapper + exit, actual BCCT release, fresh production guard, services, unchanged + settings/hashes and full K1–K7. Recover to ≥3700 mV and ≥10% within four + hours. Incomplete teardown retains ownership. A safety abort ends the + campaign. For a complete accepted cycle, replay the trace and freeze the + cycle-1-only fit and input hashes in the independent review. With the + same boot, package and runtime, a fresh matching gate and at least + 32 h + 4 h + 30 s remaining, launch `sh ./wrapper.sh gate-2.json` + within the four-hour restoration/start window. Repeat restoration. +7. **Score the holdout offline.** The reviewer checks complete traces, + coverage, comparable workload, reset segments and the same reserve type. + Require reserve voltages within 50 mV, discharge median temperatures + within 3 °C, and usable-charge difference ≤5% of the pair's mean. + Unknown-interval charge must be ≤1% of usable charge per cycle. Evaluate + the frozen fit against cycle 2's own CAR reference at all common 10–90% + landmarks without extrapolation or refitting. Require mean absolute error + ≤5 percentage points and maximum ≤10. A result file or launcher success + only releases the data for review. A failed gate ends the campaign without + a profile or a third attempt. +8. **Production band and crash-in-band.** With a separate grant, normal + production ownership and unchanged 80% settings, capture the natural ZCV + rise to ≥4109 mV and verified BCCT pause, descent through the band, + release at ≤4003 mV and continued charging back inside the band. For the + crash check, first establish a fresh same-boot hardware pause strictly + inside 4003–4109 mV. Under the reviewed guard-crash procedure capture + the old and respawned guard PIDs, same-boot ZCV/status and matching BCCT + readbacks across the crash while still inside the band. Verify the pause + survives and the natural lower crossing releases it. Finish with full + restoration. A threshold crossing during the crash leaves hysteresis + unproven. Keep raw observations for both checks. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index fde29f0..0b8d3ea 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -40,10 +40,10 @@ Use an existing project virtual environment if one is configured. Some older experimental tests and C host tests under `tests/` depend on local firmware, captures, or optional C/host tooling and are not part of the default CI matrix. -The host-only M0 recovery-timing analyzer -(`scripts/i14-k70-recovery-timing.py`) reads normalized synthetic traces and -proves crash-to-return timing only, not device acceptance; see -[K70 recovery timing](K70-RECOVERY-TIMING.md) for usage and the trace schema. +The M0 analyzer reads normalized JSONL traces. The passive host capture writer +and analyzer are tested together using synthetic observations. Capture hooks, +the trace schema and the hardware gates are documented in +[K70 recovery timing](K70-RECOVERY-TIMING.md). See [ROADMAP.md](ROADMAP.md) for remaining device acceptance gates. ## Current route: Alpine with the stock kernel diff --git a/docs/K70-RECOVERY-TIMING.md b/docs/K70-RECOVERY-TIMING.md index 58d7b9b..dd51b24 100644 --- a/docs/K70-RECOVERY-TIMING.md +++ b/docs/K70-RECOVERY-TIMING.md @@ -4,10 +4,9 @@ interval for the Linux 7 recovery gate (M0) in [the roadmap](ROADMAP.md#3-linux-7-mainline-recovery-m0), section 3. The historical crash test returned in 70.6 s against the unchanged 40 s limit. -This tool is host-only: it reads a normalized saved JSON Lines trace and never -touches the phone, firmware or live evidence. Until a reviewed capture exists, -traces are generated only by the synthetic fixtures in -`tests/test_i14_k70_recovery_timing.py`. +The analyzer reads a saved JSON Lines trace. A passive writer, +`scripts/i14_k70_capture.py`, can record either terminal trigger inside a +host observer. Both paths have been exercised with synthetic observations. A within-limit result proves **timing only**. It does not establish M0 acceptance, pstore correspondence, restoration K, or a cause; those remain @@ -29,8 +28,8 @@ object; stderr stays empty and malformed input never produces a traceback. | 2 | `INCOMPLETE` | A required anchor is absent (contract, crash trigger, or confirmed return). Nothing is inferred. | | 2 | `INCONSISTENT` | Malformed, ambiguous or conflicting evidence, including bad usage or an unreadable trace. | -Durations are computed in one clock domain and reported at microsecond -resolution (`round(x, 6)`); the limit comparison uses that reported value. +The limit applies to the unrounded host interval (`duration_unrounded_s`). +`duration_s` is its display value rounded to six decimal places. ## Trace schema `i14-k70-recovery-trace/1` @@ -48,6 +47,11 @@ bounded by 2^53). File order is irrelevant; records are identified by `type`. | `production_return` | `clock: "host_monotonic"`, `session`, `boot_id`, `kernel`, `image`, `t_s`, `confirmed: true` | Exactly one confirmed record: the first confirmed production return. Unconfirmed records (`confirmed` absent or `false`) are counted as diagnostics, never anchors; several confirmed returns are ambiguous. | | `stage` | `stage`, `phase` (`start`/`end`), `clock: "boot_uptime"`, `boot_id`, `t_s` | Optional, paired. Timed on the returned production boot's uptime clock only. | +New captures also include `previous_production_boot_id` in the contract and +`method` (`sysrq-crash` or `keeper-stop`) in the trigger. Both methods use +the historical wire name `crash_trigger`. A confirmed return carrying the +pre-trial production boot ID invalidates the trace. Older traces remain readable. + ### Transition and identity rules The measurement requires a valid transition: the crash trigger sits on the @@ -80,7 +84,7 @@ Problematic stage records are called out separately in `stage_issues` (`{line, stage, reason}`) and are excluded from `stages`, so they cannot become measurement evidence: `malformed_stage`, `unknown_stage`, `stage_wrong_clock`, `stage_mixed_boot` (not the returned boot), `duplicate_stage_start`, -`duplicate_stage_end` (first occurrence kept), `unpaired_stage`, +`duplicate_stage_end` (the entire ambiguous pair is excluded), `unpaired_stage`, `reversed_stage`. Stage issues do not alter the timing verdict; `stage_evidence` reports `absent`, `valid`, `issues`, or `unevaluated` (when the core evidence is invalid). @@ -94,8 +98,46 @@ the core evidence is fully valid), `stages`, `stage_issues`, `stage_evidence`, (record counts, unconfirmed returns) and `scope_note` stating the timing-only scope. -## Limitations - -Synthetic fixtures only; no capture pipeline or device evidence exists yet. -The analyzer cannot verify pstore, restoration K, power state or the cause of -the slow return, and a within-limit fixture run is not a recovery acceptance. +## Capture and trial order + +1. **Commission the observer offline.** The live trip runner and returned-boot + stage producers are outside this checkout. Bind the writer to the reviewed + runner's dispatch and first identity-probe completion in one host process. + For each trial, open a new private JSONL file in exclusive creation mode. + Construct `RecoveryCapture(stream, previous_boot=..., experimental_boot=..., + kernel=..., image=...)` using the observed pre-trial and RAM-boot IDs and + the reviewed production pins. Wrap just the terminal dispatch in + `with capture.trigger(method):`. Raise if dispatch is refused or uncertain. + Call `observe_return(boot_id=..., kernel=..., image=...)` at probe completion + with observed identities. Preserve raw probe successes and failures. Reading + a saved log later cannot recreate either host timestamp. +2. Bind both edges of `early_init`, `sysinit_services` and `mdev_coldplug` to + the corresponding operations in the pinned production startup. Export each + observed edge with its original production boot ID and uptime through + `capture.stage(name, phase, boot_id, uptime_s)`. Exercise the entire path + with fixtures and review the exact runner, marker sources and artifact pins. + The writer performs no boot instrumentation. Missing edges leave that + interval unknown. Keep raw evidence, capture errors and restoration handling + independent so a logging failure cannot skip recovery. +3. **Fresh M0 grant and preflight.** Reserve one actor and a window clear of + calibration or soak. Verify the board, normal 3.18.19 boot ID, production + boot/rootfs and rollback hashes, serial recovery, healthy services and + fresh same-boot guard matching BCCT. Require USB power, 3800–4100 mV, + 10–40 °C, no drain or experiment, and the reviewed RAM image and keeper hashes. +4. **Crash trial first.** RAM-boot once. Confirm the 7.0 board/kernel and + experimental boot ID, no-touch settings, read-only eMMC, armed watchdog and + keeper, and its battery margin. Dispatch the reviewed `sysrq-crash` check. + Observe the first confirmed new production return. Run + `python3 scripts/i14-k70-recovery-timing.py TRACE.jsonl` on the host. Save + raw trace, exit code, last_kmsg/pstore evidence of the same trial and full + production restoration K1–K7, including guard/service continuity. +5. **Keeper-stop is conditional.** On missing evidence, a late return, a + pstore mismatch or failed restoration, stop and retain the failure. An + unconfirmed return goes to the authorized recovery procedure. Only after + independent crash acceptance and renewed preflight under a covering grant + run a separate RAM-only `keeper-stop` trial in a new directory. Apply the + same 40 s bound and full restoration checks. Require evidence of the keeper + stopping its feeds and the watchdog reset; a fallback reboot fails that check. + +Historical status remains 70.6 s for the crash trial, with no accepted +keeper-stop trial. The source of the delay remains unknown. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 23df997..988d3d7 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -30,6 +30,9 @@ firmware dumps, images, credentials and raw captures outside Git. ### Unattended collector & 48-hour Soak C (H2/H3) +The [H1, Soak C and H3 execution sequence](verification/H1-SOAK-C.md) lists +the commissioning steps, commands and evidence required for these gates. + - Commission a phone-local collector and export path with bounded retention and clean process teardown before starting a 48-hour acceptance window. - Freeze exact boot/rootfs identity, runtime hashes, sampler and probe settings, @@ -59,6 +62,7 @@ firmware dumps, images, credentials and raw captures outside Git. - Verify userdata free space, log retention budget and unattended supervision (`scripts/i14-calibration-launch.py`) before running a bounded two-cycle calibration campaign (fit on cycle 1, independent holdout on cycle 2). + See the [C13 and production charge-band sequence](C13-READINESS.md). ### Nearly-empty recovery (D) diff --git a/docs/ROOTFS-SWAP-ROLLBACK.md b/docs/ROOTFS-SWAP-ROLLBACK.md index 9183215..0e89e95 100644 --- a/docs/ROOTFS-SWAP-ROLLBACK.md +++ b/docs/ROOTFS-SWAP-ROLLBACK.md @@ -5,6 +5,13 @@ must have a matching `rootfs-trial.img` link, a previous image at `rootfs-prev.img`, and a 512-byte `rootfs-trial` record. Without the record, the normal boot follows the usual image checks. +Before releasing a staged trial for boot, check that `rootfs.img` and +`rootfs-trial.img` are regular files with the same device and inode, and that +`rootfs-prev.img` has the independently verified previous image on a different +inode. Reconcile old markers and receipts first. If the trial link is missing +or points elsewhere, rollback can replace the candidate's last name. Verify +the restored image independently of the `rollback` record. + The initramfs records each candidate boot before checking or mounting the image. It falls back after at most two starts, or immediately if the candidate fails the filesystem, mount or init check. If an image cannot be unmounted, the @@ -19,6 +26,17 @@ host's check. Confirmation also requires the configured services, SSH on port without confirmation is restarted by the watcher so the initramfs can roll back. Recovery login and power-off charging follow the existing boot paths. +The base rootfs builder seeds the packaged DNS trust anchor. Trial preparation +must carry the agreed baseline bytes, write their SHA-256 to +`/etc/i14-rootfs-root-key.sha256`, and write a fresh candidate stamp to +`/etc/i14-rootfs-id`. Verify the staged image after these writes. Before +acknowledging a trial, compare the retained `rootfs-trial-root-key.` +bytes and the receipt's boot ID, stamp and digest with the independent host +evidence. During the automatic rollback rehearsal, withhold the acknowledgement +on both starts and verify the subsequent boot against the restoration baseline. +`scripts/i14-r2-handoff-preflight.py` and `scripts/i14-r2-host-handoff.py` +manage a historical host supervisor. + Host tests exercise the decision and watcher logic with disposable files and fake system actions. Device acceptance follows the [R section of the roadmap](ROADMAP.md#restore-integrity-and-accept-the-new-rootfs-r). diff --git a/docs/verification/H1-SOAK-C.md b/docs/verification/H1-SOAK-C.md new file mode 100644 index 0000000..6e0944f --- /dev/null +++ b/docs/verification/H1-SOAK-C.md @@ -0,0 +1,156 @@ +# H1, Soak C and H3 execution sequence + +The acceptance evidence comes from the selected production image. The named +commands below are for its execution owner. Paths, dates, process IDs, grants +and digests must come from that run. Keep raw captures, manifests and settings +in a fresh private evidence directory outside Git. + +## Entry and H1 + +1. Obtain an exclusive grant with time for restoration. Record the phone, + installed boot and target partition, active rootfs, kernel, source revisions, + rollback disposition, selectors, runtime and helper SHA-256 values. Resolve + the image choice first. A B5 result applies to B5. Require the project's full + restoration/health check (K), closed E/R operations and no active soak, + calibration, drain or conflicting controller. Register H1 maintenance. +2. Stage the reviewed `i14-h1.py`, `i14-h1-input.py` and `i14-touch` exclusively + in `/run` as root, mode 0700. Check their hashes on the phone. The owner + supplies root-owned mode-0600 `/run/h1-freeze.json` and + `/run/i14-h1-permit.json` with the observed boot ID. Freeze both UI + entrypoints, Python UI modules, selector and helper as required by the + input harness. Bind any accepted rollback marker by digest. The permit + expires within 900 s of current uptime. Check the grant before each block. +3. Use the same workload, settings and observers across both arms. Record + brightness, CPU policy/frequency, USB, temperature and guard state. The owner + requires USB online, 0–35 °C, the pinned settings, fresh valid charge guard, + level 50–80, raw level ≤80, limit 80 enabled and matching BCCT state. + Keep the maintenance logger running. Never read `current_cmd`. +4. Send the hashed `scripts/i14-h1-owner.py` as stdin to the approved managed + transport for **one** `python3 -B - ACTION SERVICE IMPL [OUT]` at a time. + Preserve argv, input hash, UTC, exit status, stdout, stderr and raw result. + Use fresh `/run/h1-*.json` names for each case. Run in the following order. + + | Measurement | Order and invocation | Endpoint | + |---|---|---| + | Idle | For each of `ui`, `power`, `cpufreq`, `netwatch`, run `idle SERVICE rust OUT`, then `idle SERVICE python OUT`, then `select SERVICE rust`. Both arms start fresh and wait for natural screen-off. | 60 s at brightness zero. Record child PID/start ticks, actual uptime interval, CLK_TCK, CPU % of one core and ending RSS in KiB. Children excluded. The netwatch fallback is shell. | + | Taps | Select UI Rust, then Python. For each run `python3 -B /run/i14-h1-input.py taps --impl IMPL --freeze /run/h1-freeze.json --out OUT`. Restore `select ui rust`. | Ten Settings/back pairs. Keep each first CRC change across rows 0–79, ACK separately, timeout and cold first action. The 2 ms poll and 3 s deadline measure framebuffer observation. Optical latency is unknown. | + | Startup | From restored Rust OpenRC UI run `startup ui IMPL OUT` four times, Python, Rust, Python, Rust. Each action stops the UI, binds its measured child, tears it down and restores the Rust service. | Launch to first positive backlight, polled every 20 ms up to 10 s. Final pixels are unknown. | + | Terminal | Select UI Rust, then Python. For each run `python3 -B /run/i14-h1-input.py terminal --impl IMPL --freeze /run/h1-freeze.json --out TRACE --terminal-out RAW`. Use distinct fresh paths. | Direct UI child login shell and controlling PTY must be proven before typing. Time `seq 1 20000` through PTY writes and command exit. Final rendering is unknown. | + + Input blocks require the PIN gate, fresh helper, 60 s quiet interval, fresh + UI bound to that helper and the recorded display geometry. Keep partial data + on any refusal and stop dependent cases. Renew a still-current permit only + between blocks after rechecking the owner's grant and readiness. +5. Hash and export every result, including failed cases. Report per-pair Rust + minus fallback and relative change only with nonzero denominator. Restore + all five Rust selectors, services, guard and settings, stop owned helper + and verify its socket/injector and owned temporary files are accounted for. + Verify full K and close maintenance. H1 remains open for any missing arm. + +## Commission the collector before reserving the 48 hours + +1. Use a **short separate phase** to prove the production collection and export + path. Under a fresh grant take the read-only inventory + (`python3 -B i14-soak-observer-inventory.py`). Establish the boot, sampler + cron row/implementation, log rotation, real record sizes, available userdata + and host space. Verify the five-minute external DNS timer targets the + intended resolver and the minute sampler is already running once. Record + their exact deployed hashes and settings. Keep the existing sampler in place. +2. The owner supplies a fresh, private `phase-YYYYMMDDTHHMMSSZ` directory under + `/mnt/data/media/0/i14-linux/soak-c-observer-20261115`. Its `logs/` and + `receipts/` directories must be root-owned mode 0700. Stage + `i14-soak-local-collector.py`, `i14-soak-observer-inventory.py` and + `i14-soak-procs.sh` (installed name `procs.sh`) as root-owned mode 0700. + Record the original private root crontab as mode-0600 `root-crontab.before`. + Freeze mode-0600 `observer.json` with schema 2, actual `boot_id`, phase ID + in `grant_id`, future `expires_epoch`, `max_captures`, `max_bytes`, + `capture_bytes`, `reserve_bytes` and all three installed `source_sha256` + entries. Size the phase from observed growth and both boundary captures. + The export guard admits at most 80 captures and 1,281 MiB, 16 MiB per attempt + and a 512 MiB free-space reserve. Account separately for sample rotation, + filesystem allocation and background growth. A limit refusal stops the phase. +3. Using the owner's reviewed crontab installation procedure, add one hourly + row at the frozen minute running the following command with absolute paths. + Bound cron diagnostics too. Preserve all other crontab bytes, including the + existing sampler. Record the installed crontab and owned row hashes. + + ```sh + /usr/bin/python3 -B "$PHASE/i14-soak-local-collector.py" --run-dir "$PHASE" --origin cron + ``` + + Substitute the actual path before installing the row. Wait for **real root + cron**. Require a completed PASS/rc 0 receipt, cron ancestry, matching + boot/hashes, complete index entry, process roles and logs, closed helper + group and absent capture lock. Preserve missing, failed and timed-out attempts. +4. After the last needed capture, restore the byte-identical original crontab + using the owner's close procedure. Verify no collector/group or lock, + preserve `close-receipt.json` with `CRON_RESTORED_NO_ACTOR`, and bind the + phase, close grant, config/source/cron hashes and receipt digest. Stage the + verified phase-export program and its two pinned sibling modules outside the + phase evidence tree. The sender accepts a current, separate ≤900 s export + bundle on stdin. The receiver needs its four independently frozen binding + fields, `phase_id`, export `grant_id`, `boot_id`, `config_sha256`. +5. Use the approved foreground transport, with its exit status propagated and + diagnostics on stderr. The remote command is + `python3 -B /OWNER-STAGED-PATH/i14-soak-phase-export.py --stream`. Invoke it + from the host through the receiver with the owner's actual transport argv. + + ```sh + python3 -B scripts/i14-soak-receive.py --binding binding.json --out NEW_RECEIPT_DIR \ + --timeout REMAINING_SECONDS -- TRANSPORT_ARGV... < closed-phase.json + ``` + + Require receiver exit 0 and a complete `verified.json` with transport exit + 0, matching phase binding and locally verified per-file hashes. Preserve the + source and any partial transfer on failure. The installation, grants, close + receipt and managed transport come from the execution owner. Only a real + unattended capture, teardown and verified export completes commissioning. + +## Soak C and H3 + +1. After H1 restoration perform the single approved reboot, independently verify + the new boot and full K (at least ten minutes after startup), and allow at + least one unchanged hour. Prepare the final, separately bound collector on + the observed boot. Before the window, require actual scheduled capture and + freeze the exact image/boot, runtime files, root crontab, sampler/probe + versions, observer config/quotas, log timezone, audit command and future + UTC endpoints exactly 172,800 s apart. Close maintenance and reserve the + phone for the interval. Record the start baseline and pre-boundary samples, + DNS rounds, messages and process captures. +2. Run 48 uninterrupted hours. At/after the end obtain the matching baseline, + logs, process capture and post-boundary phone/DNS rounds. Close and export + the observer as commissioned. Acquire both retained sample generations + (rotated first, current second), external DNS CSV and maintenance file. + Keep samples and DNS separate from the observer log archive. Preserve raw + acquisition order, errors and boundary evidence. +3. On immutable private copies run the independent auditor with explicit Soak C + values. Supply each actual generation once. Put outputs outside the logs tree. + + ```sh + python3 -B scripts/i14-window-audit.py --samples samples.jsonl.1 samples.jsonl \ + --dns-csv dns.csv --maintenance maintenance.txt --baseline-start baseline-start.txt \ + --baseline-end baseline-end.txt --logs NEW_RECEIPT_DIR/raw/logs \ + --start "$START_UTC" --end "$END_UTC" --boot-id "$BOOT_ID" \ + --log-tz Europe/Amsterdam --max-log-gap 180 --json-out audit.json --summary-out audit.txt + ``` + + Require exit 0 and PASS on all six gates: schema/order, boundary coverage, + version/process/log continuity and maintenance, seven service statuses and + phone gaps ≤180 s, local DNS, five external DNS checks and gaps ≤450 s. + Battery condition 6 is informational. Check the predeclared 48-hour duration + explicitly because the auditor also supports shorter diagnostic intervals. +4. After final evidence acquisition and collector closure, take four separate + read-only Rust service measurements on the same boot and image. Keep all + selectors, services and clocks as found, let the screen turn off naturally, + and obtain a fresh post-window permit. Bind each supervised Rust process by + executable/hash, argv, parent, PID and start ticks. For each of `ui`, + `power`, `cpufreq`, `netwatch`, use the frozen measurement payload directly: + + ```sh + python3 -B /run/i14-h1.py idle --impl rust --service "$SERVICE" \ + --pid "$PID" --start-ticks "$START_TICKS" --out "/run/h1-postsoak-$SERVICE.json" + ``` + + The H1 **owner** idle action restarts the service and would invalidate H3. + Keep the raw before/after values and ambient conditions, compare with the + same-version Rust references, export/hash the results and verify cleanup. diff --git a/rust/crates/i14-fastboot/tests/differential.rs b/rust/crates/i14-fastboot/tests/differential.rs index b13d1ef..b2a4c35 100644 --- a/rust/crates/i14-fastboot/tests/differential.rs +++ b/rust/crates/i14-fastboot/tests/differential.rs @@ -1460,10 +1460,18 @@ fn differential_receipt_matches_v9_evidence_shape() { if !stock_present() { return; } - let evidence = std::fs::read_to_string(format!( - "{PROJECT}/evidence/2026-11-04/i14-boot-install/attempt-v9b.jsonl" - )) - .unwrap(); + let path = Path::new(PROJECT).join("evidence/2026-11-04/i14-boot-install/attempt-v9b.jsonl"); + let evidence = match std::fs::read_to_string(&path) { + Ok(evidence) => evidence, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + eprintln!( + "skipped receipt comparison: {} missing (local evidence)", + path.display() + ); + return; + } + Err(err) => panic!("reading {}: {err}", path.display()), + }; let dir = canonical_dir("v9shape"); let scenario = install( img(json!({})), diff --git a/scripts/i14-battery-calibrate.py b/scripts/i14-battery-calibrate.py index eb64b4c..c325ec7 100644 --- a/scripts/i14-battery-calibrate.py +++ b/scripts/i14-battery-calibrate.py @@ -297,6 +297,8 @@ def step(self, row): elif not step_ok: raise ValueError("fuel-gauge counter jump") if self.phase == "charge": + if now - self.started >= 8*3600: + raise ValueError("full-charge deadline reached") if row["capacity"] <= 6: raise ValueError("low-battery reserve before full anchor") full = (row["status"] == "Full" and row["voltage_mv"] >= 4300 and @@ -309,8 +311,6 @@ def step(self, row): self.phase = "discharge" self.anchor = self.stored(row) self.segments = [self.segment(row)] - if self.phase == "charge" and now - self.started >= 8*3600: - raise ValueError("full-charge deadline reached") elif self.phase == "discharge": self.points += 1 # Software cross-check: cached current (deci-mA) integrated over the same samples. diff --git a/scripts/i14-calibration-launch.py b/scripts/i14-calibration-launch.py index b4bb15e..da37097 100644 --- a/scripts/i14-calibration-launch.py +++ b/scripts/i14-calibration-launch.py @@ -18,7 +18,8 @@ BASE = Path('/mnt/data/media/0/i14-linux') CODE = BASE / ('battery-calibration-code-' + CAMPAIGN) CONTROL = BASE / ('battery-calibration-' + CAMPAIGN + '-control') -MEASURE_SHA = 'be92a25370ab8f0f97f89ee36a303a60822bd97bfca9e2b26e25c98508b455a6' +MEASUREMENT_LOCK = Path('/run/i14-battery-calibration.lock') +MEASURE_SHA = 'b6ffb1489e13f17096ceb3e4de88fb2d914a997beb0840562c925f3e3a5e985b' RUN_SECONDS, RECOVERY_SECONDS, CAMPAIGN_SECONDS = 32*3600, 4*3600, 72*3600 MIB = 1024**2 MAX_RECORD_BYTES, MAX_INPUT_BYTES, MAX_ACKS = 8*MIB, 256*1024, 80 @@ -119,10 +120,23 @@ def storage_required(gate): 'missing reviewed quota/retention proof') extra=[storage[key] for key in ('observer_fixed_bytes','background_growth_bytes')] require(all(type(value) is int and value>=0 for value in extra), 'invalid storage ceiling') + require(storage['observer_fixed_bytes'] >= MIB, 'insufficient fixed observer overhead') require(storage['background_growth_bytes']>=C13_GUARD_LOG_BYTES, 'insufficient C13 guard log allowance') return max(2*1024**3,C13_BYTES+OBSERVER_BYTES+COMMISSION_BYTES+ALLOCATION_BYTES+RESERVE_BYTES+sum(extra)) +def userdata_free_bytes(): + fd = os.open(BASE, os.O_RDONLY | os.O_DIRECTORY) + try: + device = os.fstat(fd).st_dev + uevent = Path('/sys/dev/block') / f'{os.major(device)}:{os.minor(device)}' / 'uevent' + require('PARTNAME=userdata' in uevent.read_text().splitlines(), 'campaign path is not on userdata') + space = os.fstatvfs(fd) + return space.f_bavail * space.f_frsize + finally: + os.close(fd) + + def validate_gate(gate, now): try: storage_required(gate) @@ -214,7 +228,8 @@ def finish_attempt(path, attempt, rc, result, restore_rc, ended_epoch, *, clock_ except (OSError,ValueError,KeyError,TypeError): pass success=rc==0 and restore_rc==0 and clock_ok and experiment_gone and result is not None and result.is_file() - if not clock_ok: rc=1 + if not success and rc == 0: + rc = 1 if checkpoint: if type(checkpoint.get('acknowledged_epoch')) is int: record['last_epoch']=max(record['last_epoch'],checkpoint['acknowledged_epoch']) @@ -313,7 +328,7 @@ def live_preflight(gate, package, directory): guard.get('online') is True, 'production guard not ready') require(all(service('status',name)==0 for name in SERVICES), 'service not started') - require(os.statvfs(BASE).f_bavail*os.statvfs(BASE).f_frsize>=storage_required(gate), + require(userdata_free_bytes()>=storage_required(gate), 'insufficient combined C13/observer/closure storage (2GiB floor retained)') spec=importlib.util.spec_from_file_location('measure',directory/'measure.py') measure=importlib.util.module_from_spec(spec); spec.loader.exec_module(measure) @@ -379,7 +394,7 @@ def stop(*_): stop_requested[0]=True exited=True except subprocess.TimeoutExpired: pass - if os.statvfs(BASE).f_bavail*os.statvfs(BASE).f_frsize<=512*1024**2: + if userdata_free_bytes()<=RESERVE_BYTES: stop_requested[0]=True wall,mono=int(time.time()),time.monotonic() if not supervision_valid(record,read_json(CONTROL/'checkpoint.json'),wall,mono, @@ -409,16 +424,24 @@ def stop(*_): stop_requested[0]=True # A live or uncertain experiment keeps ownership. Never start a second BCCT writer. gone=child is None or child.poll() is not None pid=measurement_pid(data,directory) - if gone and pid is None: - restore=service('start') - else: - rc=1 + gone = gone and pid is None + if gone: + # The measurement holds this lock for its entire lifetime, including cleanup. + # An unavailable PID file alone cannot rule out a surviving BCCT writer. + try: + with MEASUREMENT_LOCK.open('a') as measure_lock: + fcntl.flock(measure_lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + restore=service('start') + except OSError as exc: + supervisor_error=supervisor_error or exc + gone=False + if not gone: rc=1 if stop_requested[0]: rc=1 finished=finish_attempt(CONTROL/'campaign.json',attempt,rc,data/'result.json',restore,int(time.time()), - clock_floor=(seen_wall,seen_mono),experiment_gone=gone and pid is None) + clock_floor=(seen_wall,seen_mono),experiment_gone=gone) rc=finished['exit_code'] write_json(CONTROL/f'wrapper-result-{attempt}.json',dict(exit_code=rc, - production_start_rc=restore,experiment_gone=gone and pid is None, + production_start_rc=restore,experiment_gone=gone, supervisor_error=repr(supervisor_error) if supervisor_error else None, restoration_accepted=False,finished_epoch=int(time.time())),new=True) for sig,handler in old_handlers.items(): signal.signal(sig,handler) @@ -443,7 +466,7 @@ def optional(path): return read_json(path) if path.is_file() else None state=optional(data/'state.json'),failure=optional(data/'failure.json'), result=optional(data/'result.json'),wrapper=optional(CONTROL/f'wrapper-result-{attempt}.json'), guard=optional(Path('/run/i14-charge-status.json')),epoch=int(time.time()), - free_bytes=os.statvfs(BASE).f_bavail*os.statvfs(BASE).f_frsize),allow_nan=False)) + free_bytes=userdata_free_bytes()),allow_nan=False)) def ack_file(path): diff --git a/scripts/i14-dns-soak.py b/scripts/i14-dns-soak.py index ec6e7c7..1e35fc7 100644 --- a/scripts/i14-dns-soak.py +++ b/scripts/i14-dns-soak.py @@ -6,43 +6,130 @@ import datetime, os, random, socket, struct, time SERVER = os.environ.get("I14_DNS") -if not SERVER: - raise SystemExit("Set I14_DNS to the intended phone address before running this script.") OUT = os.path.expanduser("~/i14-soak/dns.csv") +def receive(s, size, deadline): + data = b"" + while len(data) < size: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("DNS deadline") + s.settimeout(remaining) + block = s.recv(size - len(data)) + if not block: + raise EOFError("incomplete DNS TCP frame") + data += block + return data + + +def dns_name(data, offset): + labels, seen, end, size = [], set(), None, 1 + while True: + if offset >= len(data) or offset in seen: + raise ValueError("short or cyclic DNS name") + seen.add(offset) + length = data[offset] + if length & 0xC0 == 0xC0: + if offset + 1 >= len(data): + raise ValueError("short DNS pointer") + if end is None: + end = offset + 2 + offset = (length & 0x3F) << 8 | data[offset + 1] + continue + offset += 1 + if length > 63 or offset + length > len(data): + raise ValueError("bad DNS label") + if length == 0: + return b".".join(labels).lower(), end if end is not None else offset + size += length + 1 + if size > 255: + raise ValueError("oversized DNS name") + labels.append(data[offset:offset + length]) + offset += length + + +def response(r, msg, name): + if len(r) < 12: + raise ValueError("short DNS header") + ident, fl, questions, answers, _, _ = struct.unpack(">HHHHHH", r[:12]) + # The request ends in an 11-byte OPT record; require the echoed A/IN question. + question = msg[12:-11] + if (ident != struct.unpack(">H", msg[:2])[0] or fl & 0xFA00 != 0x8000 or + questions != 1 or r[12:12 + len(question)] != question): + raise ValueError("unrelated or truncated DNS response") + offset, addresses, aliases = 12 + len(question), [], {} + for _ in range(answers): + owner, offset = dns_name(r, offset) + if offset + 10 > len(r): + raise ValueError("short DNS record") + kind, cls, _, size = struct.unpack(">HHIH", r[offset:offset + 10]) + offset += 10 + if offset + size > len(r): + raise ValueError("short DNS data") + if kind == 1 and cls == 1: + if size != 4: + raise ValueError("invalid A record length") + addresses.append((owner, socket.inet_ntoa(r[offset:offset + size]))) + elif kind == 5 and cls == 1: + target, end = dns_name(r, offset) + if end != offset + size or owner in aliases and aliases[owner] != target: + raise ValueError("invalid CNAME record") + aliases[owner] = target + offset += size + owners = {name.rstrip(".").encode("ascii").lower()} + if name != "i14-health.invalid": + # Real-name probes may legitimately reach their A records through CNAMEs. + while more := {target for owner, target in aliases.items() if owner in owners} - owners: + owners.update(more) + matching = [address for owner, address in addresses if owner in owners] + if fl & 15 == 0 and (not matching or name == "i14-health.invalid" and "192.0.2.1" not in matching): + raise ValueError("missing expected A answer") + return fl + + def query(name, tcp=False, do=False): msg = struct.pack(">HHHHHH", random.randint(0, 65535), 0x0100, 1, 0, 0, 1) msg += b"".join(bytes([len(p)]) + p.encode() for p in name.split(".")) + b"\0" + struct.pack(">HH", 1, 1) msg += b"\0" + struct.pack(">HHIH", 41, 1232, 0x8000 if do else 0, 0) - t = time.time() + t = time.monotonic() try: if tcp: with socket.create_connection((SERVER, 53), 5) as s: + remaining = t + 5 - time.monotonic() + if remaining <= 0: + raise TimeoutError("DNS deadline") + s.settimeout(remaining) s.sendall(struct.pack(">H", len(msg)) + msg) - n = struct.unpack(">H", s.recv(2))[0] - r = b"" - while len(r) < n: - r += s.recv(n - len(r)) + n = struct.unpack(">H", receive(s, 2, t + 5))[0] + r = receive(s, n, t + 5) else: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.settimeout(5) - s.sendto(msg, (SERVER, 53)) + s.connect((SERVER, 53)) + s.send(msg) r = s.recv(4096) - fl = struct.unpack(">H", r[2:4])[0] + fl = response(r, msg, name) code = {0: "NOERROR", 2: "SERVFAIL", 3: "NXDOMAIN", 5: "REFUSED"}.get(fl & 15, str(fl & 15)) if fl >> 5 & 1: code += "+AD" except Exception as e: code = "ERROR:" + type(e).__name__ - return f"{code},{(time.time() - t) * 1000:.0f}" + return f"{code},{(time.monotonic() - t) * 1000:.0f}" + + +def main(): + if not SERVER: + raise SystemExit("Set I14_DNS to the intended phone's IPv4 address") + checks = [("i14-health.invalid", False, False), ("i14-health.invalid", True, False), ("example.org", False, False), + ("cloudflare.com", False, True), ("dnssec-failed.org", False, True)] + line = ",".join([datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")] + [query(*c) for c in checks]) + new = not os.path.exists(OUT) + with open(OUT, "a") as f: + if new: + f.write("time,health_udp,ms,health_tcp,ms,example_udp,ms,signed_ad,ms,bogus,ms\n") + f.write(line + "\n") -checks = [("i14-health.invalid", False, False), ("i14-health.invalid", True, False), ("example.org", False, False), - ("cloudflare.com", False, True), ("dnssec-failed.org", False, True)] -line = ",".join([datetime.datetime.now().isoformat(timespec="seconds")] + [query(*c) for c in checks]) -new = not os.path.exists(OUT) -with open(OUT, "a") as f: - if new: - f.write("time,health_udp,ms,health_tcp,ms,example_udp,ms,signed_ad,ms,bogus,ms\n") - f.write(line + "\n") +if __name__ == "__main__": + main() diff --git a/scripts/i14-h1-owner.py b/scripts/i14-h1-owner.py index d6a436c..f7a14d1 100644 --- a/scripts/i14-h1-owner.py +++ b/scripts/i14-h1-owner.py @@ -206,7 +206,11 @@ def idle(self,service,impl,out): if time.monotonic()>=deadline:raise ValueError('natural screen timeout did not reach zero') time.sleep(1) self.ready() - payload(['python3','-B','/run/i14-h1.py','idle','--impl',impl,'--service',service,'--pid',str(binding['child']['pid']),'--out',str(out)],out,dict(identity=binding,light_before=self.h1.light(),clk_tck=os.sysconf('SC_CLK_TCK'))) + child = binding['child'] + argv = ['python3', '-B', '/run/i14-h1.py', 'idle', '--impl', impl, + '--service', service, '--pid', str(child['pid']), + '--start-ticks', str(child['start_ticks']), '--out', str(out)] + payload(argv, out, dict(identity=binding, light_before=self.h1.light(), clk_tck=os.sysconf('SC_CLK_TCK'))) def startup(self,impl,out): self.identify('ui','rust');command(['rc-service','i14-ui','stop']) try: diff --git a/scripts/i14-h1.py b/scripts/i14-h1.py index f92b512..f067da3 100644 --- a/scripts/i14-h1.py +++ b/scripts/i14-h1.py @@ -71,6 +71,14 @@ def idle_result(before, after, hz): rss_after_kib=after["rss_kib"], children_included=False) +def idle_sample(pid, expected_start, checked_light): + before = snapshot(pid) + if expected_start is not None and before["start_ticks"] != expected_start: + raise ValueError("idle process differs from the owner's bound child") + idle_wait(checked_light) + return idle_result(before, snapshot(pid), os.sysconf("SC_CLK_TCK")) + + def idle_wait(read_light, clock=time.monotonic, sleep=time.sleep): end = clock() + 60 while True: @@ -328,10 +336,13 @@ def main(): parser.add_argument("--impl", choices=("python", "rust"), required=True) parser.add_argument("--service", choices=("ui", "power", "cpufreq", "netwatch"), default="ui") parser.add_argument("--pid", type=int) + parser.add_argument("--start-ticks", type=int, help="expected idle child start time from owner binding") parser.add_argument("--settings", type=int, nargs=2, metavar=("X", "Y")) parser.add_argument("--back", type=int, nargs=2, metavar=("X", "Y")) parser.add_argument("--out", type=Path, required=True) args = parser.parse_args() + if args.start_ticks is not None and (args.mode != "idle" or args.start_ticks < 0): + parser.error("--start-ticks requires idle mode and a nonnegative value") if args.mode != "startup" and (args.pid is None or args.pid <= 1): parser.error("--pid must identify the verified measured process") if args.mode == "taps" and (args.settings is None or args.back is None): @@ -350,12 +361,10 @@ def interrupted(signum, frame): if args.out.exists(): raise FileExistsError("result path already exists") if args.mode == "idle": - before = snapshot(args.pid) def checked_light(): preflight() return light() - idle_wait(checked_light) - result["measurement"] = idle_result(before, snapshot(args.pid), os.sysconf("SC_CLK_TCK")) + result["measurement"] = idle_sample(args.pid, args.start_ticks, checked_light) elif args.mode == "taps": result["measurement"] = taps(args.pid, args.settings, args.back) elif args.mode == "startup": diff --git a/scripts/i14-k70-recovery-timing.py b/scripts/i14-k70-recovery-timing.py index c71dbf0..d8867c1 100644 --- a/scripts/i14-k70-recovery-timing.py +++ b/scripts/i14-k70-recovery-timing.py @@ -73,7 +73,7 @@ def load_records(path): lines.pop() records, problems = [], [] for number, line in enumerate(lines, 1): - if len(records) >= MAX_RECORDS: + if number > MAX_RECORDS: problems.append({"line": number, "reason": "too_many_records"}) break if line.strip() == "": @@ -106,6 +106,7 @@ def new_result(): def analyze_stages(records, boot_id): """Pair optional stage records on the returned boot's uptime clock only.""" starts, ends, issues, seen = {}, {}, [], False + ambiguous = set() for number, record in records: if record["type"] != "stage": continue @@ -130,10 +131,13 @@ def analyze_stages(records, boot_id): bucket = starts if record["phase"] == "start" else ends if name in bucket: issues.append(dict(issue, reason="duplicate_stage_" + record["phase"])) + ambiguous.add(name) continue bucket[name] = (record["t_s"], number) stages = [] for name in STAGE_ORDER: + if name in ambiguous: + continue if name in starts and name in ends: (start, _), (end, end_line) = starts[name], ends[name] if end < start: @@ -174,6 +178,9 @@ def single(kind, missing, duplicate): contract, contract_line = single("contract", "missing_contract", "duplicate_contract") if contract is not None and ( contract.get("schema") != SCHEMA + or ("previous_production_boot_id" in contract and + (not is_str(contract["previous_production_boot_id"]) or + contract["previous_production_boot_id"] == contract.get("experimental_boot_id"))) or not all(is_str(contract.get(key)) for key in ("host_clock_session", "experimental_boot_id", "expected_kernel", "expected_image"))): @@ -182,7 +189,9 @@ def single(kind, missing, duplicate): crash, crash_line = single("crash_trigger", "missing_crash_trigger", "duplicate_crash_trigger") if crash is not None: - if crash.get("clock") != "host_monotonic": + if "method" in crash and crash["method"] not in ("sysrq-crash", "keeper-stop"): + problem(crash_line, "unknown_trigger_method") + elif crash.get("clock") != "host_monotonic": problem(crash_line, "crash_clock_domain") elif not (is_str(crash.get("session")) and is_str(crash.get("boot_id")) and is_num(crash.get("t_s"))): @@ -225,6 +234,8 @@ def single(kind, missing, duplicate): problem(ret_line, "kernel_mismatch") if ret["image"] != contract["expected_image"]: problem(ret_line, "image_mismatch") + if ret["boot_id"] == contract.get("previous_production_boot_id"): + problem(ret_line, "previous_production_boot") experimental = (contract["experimental_boot_id"] if contract is not None else crash.get("boot_id") if crash is not None else None) if is_str(experimental) and ret["boot_id"] == experimental: @@ -239,14 +250,17 @@ def single(kind, missing, duplicate): result["exit_code"] = EXIT_CODES[result["verdict"]] return result - duration = round(ret["t_s"] - crash["t_s"], 6) + duration = ret["t_s"] - crash["t_s"] result["recovery"] = {"clock": "host_monotonic", "host_clock_session": contract["host_clock_session"], "crash_trigger_s": crash["t_s"], - "production_return_s": ret["t_s"], "duration_s": duration, + "production_return_s": ret["t_s"], "duration_s": round(duration, 6), + "duration_unrounded_s": duration, "from_boot_id": crash["boot_id"], "to_boot_id": ret["boot_id"], "kernel": ret["kernel"], "image": ret["image"], "kernel_confirmed": True, "image_confirmed": True} + if "method" in crash: + result["recovery"]["trigger_method"] = crash["method"] result["verdict"] = "WITHIN_LIMIT" if duration <= LIMIT_S else "OVER_LIMIT" stages, stage_issues, evidence = analyze_stages(records, ret["boot_id"]) result["stages"] = stages diff --git a/scripts/i14-rootfs-swap.py b/scripts/i14-rootfs-swap.py new file mode 100755 index 0000000..bcf9624 --- /dev/null +++ b/scripts/i14-rootfs-swap.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python3 +"""Stage and inspect an offline I14 trial on a quiescent local userdata filesystem. + +Supply the prepared rootfs.img.new, its independently verified SHA-256, and the +corresponding candidate root directory (including the carried key and stamp). +rootfs.img must still be B5, with a previously prepared hard link at rootfs-prev.img. +The previous image and carried key each need a separate trusted SHA-256. + +Keep --state on the host, outside userdata and the candidate root. It contains +the private ACK nonce. All verification commands are read-only. Use the same +filesystem for inode checks and an independently observed --boot-id for boot +checks. verify-rollback checks the B5 object identified before the trial. +Add --check-restored-sha256 for byte equality with a pristine offline B5 +image. A writable boot can legitimately change its raw filesystem bytes. +""" +import argparse +from contextlib import contextmanager +from dataclasses import asdict, dataclass +import fcntl +import hashlib +import json +import os +from pathlib import Path +import re +import secrets +import stat +import sys +import tempfile + + +ACTIVE = "rootfs.img" +PREV = "rootfs-prev.img" +NEW = "rootfs.img.new" +TRIAL = "rootfs-trial.img" +MARKER = "rootfs-trial" +ACK = "rootfs-trial-ack" +CONFIRMED = "rootfs-trial-confirmed" +RECEIPT = "rootfs-trial-root-key-receipt" +SIZE = 512 +FREE_FLOOR = 2 << 30 +SHA256 = r"[0-9a-f]{64}" +STAMP = r"src=[a-zA-Z0-9_.-]+ at=[a-zA-Z0-9_.:-]+" +BOOT_ID = r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}" +DATE = r"[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}" + + +class Refused(ValueError): + pass + + +def check(condition, reason): + if not condition: + raise Refused(reason) + + +def identity(info): + return (info.st_dev, info.st_ino) + + +@contextmanager +def regular(path): + info = path.lstat() + check(stat.S_ISREG(info.st_mode), f"{path}: expected a regular file") + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, "rb") as stream: + check(os.path.samestat(os.fstat(fd), info), f"{path}: changed while opening") + yield stream + + +def read(path, limit=4096): + with regular(path) as stream: + data = stream.read(limit + 1) + check(len(data) <= limit, f"{path}: oversized file") + return data + + +def digest(path): + with regular(path) as stream: + check(os.fstat(stream.fileno()).st_size > 0, f"{path}: empty file") + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def image_id(path): + info = path.lstat() + check(stat.S_ISREG(info.st_mode) and info.st_size > 0, f"{path}: expected a nonempty regular image") + return identity(info) + + +def directory(path): + check(stat.S_ISDIR(path.lstat().st_mode), f"{path}: expected a directory") + + +def root_path(root, name): + path = root + for part in Path(name).parts[:-1]: + directory(path) + path = path / part + directory(path) + return path / Path(name).name + + +def absent(path): + check(not os.path.lexists(path), f"{path}: unexpected existing entry") + + +def check_space(data, floor): + usage = os.statvfs(data) + check(usage.f_bavail * usage.f_frsize >= floor, f"userdata has less than {floor} bytes available") + + +def sync_dir(path): + fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def publish(path, contents): + """Publish complete, fsynced bytes without truncating or replacing an existing name.""" + with tempfile.NamedTemporaryFile(dir=path.parent, prefix="." + path.name + ".") as tmp: + tmp.write(contents) + tmp.flush() + os.fsync(tmp.fileno()) + os.link(tmp.name, path) + sync_dir(path.parent) + + +@dataclass(frozen=True) +class Evidence: + previous: tuple + candidate: tuple + previous_sha256: str + candidate_sha256: str + root_key_sha256: str + stamp: str + nonce: str + min_free_bytes: int + + def validate(self): + for pin in (self.previous_sha256, self.candidate_sha256, self.root_key_sha256, self.nonce): + check(isinstance(pin, str) and re.fullmatch(SHA256, pin), "invalid SHA-256 or nonce") + for obj in (self.previous, self.candidate): + check(isinstance(obj, (tuple, list)) and len(obj) == 2 and + all(type(n) is int and n >= 0 for n in obj), "invalid image identity") + check(self.previous[0] == self.candidate[0] and self.previous != self.candidate, + "images must be distinct inodes on the same filesystem") + check(type(self.min_free_bytes) is int and self.min_free_bytes >= FREE_FLOOR, "invalid userdata floor") + check(isinstance(self.stamp, str) and re.fullmatch(STAMP, self.stamp) and len(self.stamp) <= 220, + "expected a bounded 'src=SOURCE at=TIME' stamp") + + def line(self, count): + ack = hashlib.sha256(self.nonce.encode("ascii")).hexdigest() + return f"trial {count} {self.stamp} ack={ack}" + + @classmethod + def load(cls, path): + check(not path.lstat().st_mode & 0o077, "host nonce file must be private") + raw = json.loads(read(path)) + try: + result = cls(**raw) + except TypeError as exc: + raise Refused("invalid host state fields") from exc + result.validate() + return result + + +def root_metadata(root, evidence): + for name, value in (("etc/i14-rootfs-id", evidence.stamp), + ("etc/i14-rootfs-root-key.sha256", evidence.root_key_sha256)): + check(read(root_path(root, name)) == (value + "\n").encode(), f"{name}: host evidence mismatch") + + +def verify_images(data, evidence, rollback=False): + active = image_id(data / ACTIVE) + check(image_id(data / TRIAL) == tuple(evidence.candidate), "lost the recorded candidate inode") + if rollback: + absent(data / PREV) + check(active == tuple(evidence.previous), "B5 inode was not restored") + else: + check(image_id(data / PREV) == tuple(evidence.previous), "previous B5 inode changed") + check(active == tuple(evidence.candidate), "candidate inode is not active") + + +def marker(data): + value = read(data / MARKER, SIZE) + check(len(value) == SIZE and value.endswith(b"\n") and b"\n" not in value[:-1], + "expected one 512-byte trial record") + return value[:-1].rstrip(b" ").decode("ascii") + + +def check_stale_names(data, allowed=()): + for path in data.iterdir(): + if path.name in allowed: + continue + if path.name == MARKER + ".log": + info = path.lstat() + check(stat.S_ISREG(info.st_mode) and info.st_nlink == 1, f"{path}: unsafe watcher log") + elif path.name == MARKER or path.name.startswith((MARKER + "-", MARKER + ".")): + raise Refused(f"{path}: reconcile existing trial evidence first") + + +def stage(args): + data = args.data + floor = max(args.min_free_bytes, FREE_FLOOR) + check_space(data, floor) + check_stale_names(data) + absent(args.state) + old = image_id(data / PREV) + check(image_id(data / ACTIVE) == old, "active image is not the prepared B5 hard link") + new = image_id(data / NEW) + evidence = Evidence(old, new, args.previous_sha256, args.candidate_sha256, args.root_key_sha256, + args.stamp, secrets.token_hex(32), floor) + evidence.validate() + check(digest(data / PREV) == evidence.previous_sha256, "B5 SHA-256 mismatch") + check(digest(data / NEW) == evidence.candidate_sha256, "prepared candidate SHA-256 mismatch") + root_metadata(args.root, evidence) + check(digest(root_path(args.root, "var/lib/unbound/root.key")) == evidence.root_key_sha256, + "prepared root.key SHA-256 mismatch") + + # Flush the prepared image data before committing any names that depend on it. + for image in (PREV, NEW): + with regular(data / image) as stream: + os.fsync(stream.fileno()) + publish(args.state, (json.dumps(asdict(evidence), indent=2) + "\n").encode()) + os.link(data / NEW, data / TRIAL, follow_symlinks=False) + sync_dir(data) + check(image_id(data / TRIAL) == new and image_id(data / ACTIVE) == old, "links changed before swap") + publish(data / MARKER, evidence.line(0).encode().ljust(SIZE - 1) + b"\n") + check(marker(data) == evidence.line(0), "published trial record mismatch") + check_space(data, floor) + # Up to this rename B5 is still active. From here the record and both recovery + # names are durable. Keep all evidence after an error or an interrupted stage. + os.replace(data / NEW, data / ACTIVE) + sync_dir(data) + verify_images(data, evidence) + + +def key_receipt(args, evidence): + boot = args.boot_id + check(re.fullmatch(BOOT_ID, boot), "expected an independently observed Linux boot ID") + root_metadata(args.root, evidence) + expected = (f"root_key_boot={boot}\nroot_key_stamp={evidence.stamp}\n" + f"root_key_sha256={evidence.root_key_sha256}\n") + check(read(args.data / RECEIPT) == expected.encode(), "pre-Unbound receipt mismatch") + check(digest(args.data / f"rootfs-trial-root-key.{boot}") == evidence.root_key_sha256, + "pre-Unbound capture SHA-256 mismatch") + + +def verify(args): + data = args.data + evidence = Evidence.load(args.state) + rollback = args.command == "verify-rollback" + verify_images(data, evidence, rollback) + current = "|".join(re.escape(evidence.line(n)) for n in (1, 2)) + if rollback: + absent(data / CONFIRMED) + prior = f"{current}|{re.escape(evidence.line(0))}" + reason = r"[^\r\n]+" + if args.rehearsal: + absent(data / ACK) + prior = re.escape(evidence.line(2)) + reason = "not confirmed after 2 starts" + check(re.fullmatch(rf"rollback {reason} \({DATE}\); was: (?:{prior})", marker(data)), + "missing rollback record for this trial") + if args.check_restored_sha256: + check(digest(data / ACTIVE) == evidence.previous_sha256, "restored B5 SHA-256 mismatch") + return + if args.command == "verify-staged": + check_space(data, evidence.min_free_bytes) + check_stale_names(data, allowed=(TRIAL, MARKER)) + check(marker(data) == evidence.line(0), "not a fresh staged trial") + for path, pin in ((PREV, evidence.previous_sha256), (ACTIVE, evidence.candidate_sha256)): + check(digest(data / path) == pin, f"{path}: staged SHA-256 changed") + return + + key_receipt(args, evidence) + if args.command == "verify-confirmed": + absent(data / MARKER) + pattern = rf"confirmed {DATE} uptime=[0-9]+s ack-boot={args.boot_id} after: (?:{current})\n" + check(re.fullmatch(pattern, read(data / CONFIRMED).decode("ascii")), "invalid confirmation record") + else: + absent(data / CONFIRMED) + check(re.fullmatch(current, marker(data)), "not a counted start of this trial") + if args.command in ("verify-ack", "verify-confirmed"): + expected = f"ack {evidence.nonce} {args.boot_id}\n" + check(read(data / ACK) == expected.encode(), "ACK is not bound to this nonce and boot") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + commands = parser.add_subparsers(dest="command", required=True) + for name, description in ( + ("stage", "arm an offline candidate and save private host evidence"), + ("verify-staged", "check both pinned images, their names and the fresh record"), + ("verify-trial", "check a counted boot and its pre-Unbound receipt before ACK"), + ("verify-ack", "check a counted boot, its key receipt and the existing ACK"), + ("verify-confirmed", "check the watcher's completed confirmation and ACK"), + ("verify-rollback", "check the restored B5 inode, retained candidate and rollback record"), + ): + sub = commands.add_parser(name, aliases=["start"] if name == "stage" else [], help=description) + sub.add_argument("--data", type=Path, required=True, help="offline userdata image directory") + sub.add_argument("--state", type=Path, required=True, help="private host evidence file") + if name not in ("verify-staged", "verify-rollback"): + sub.add_argument("--root", type=Path, required=True, help="corresponding candidate root directory") + if name == "stage": + for pin in ("previous", "candidate", "root-key"): + sub.add_argument(f"--{pin}-sha256", required=True, help=f"independent {pin} SHA-256") + sub.add_argument("--stamp", required=True, help="independent candidate stamp, 'src=... at=...'") + sub.add_argument("--min-free-bytes", type=int, default=FREE_FLOOR, help="raise the 2 GiB userdata floor") + elif name not in ("verify-staged", "verify-rollback"): + sub.add_argument("--boot-id", required=True, help="independently observed current boot ID") + elif name == "verify-rollback": + sub.add_argument("--rehearsal", action="store_true", help="require two unconfirmed starts and no ACK") + sub.add_argument("--check-restored-sha256", action="store_true", help="also require original B5 bytes") + + args = parser.parse_args(argv) + staging = args.command in ("stage", "start") + try: + for root in (args.data, getattr(args, "root", None)): + if root is not None: + check(not args.state.resolve().is_relative_to(root.resolve()), "--state must be private host evidence") + fd = os.open(args.data, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + fcntl.flock(fd, (fcntl.LOCK_EX if staging else fcntl.LOCK_SH) | fcntl.LOCK_NB) + if staging: + stage(args) + else: + verify(args) + finally: + os.close(fd) + except (OSError, ValueError) as exc: + print(f"{args.command}: {exc}", file=sys.stderr) + return 1 + print(f"{args.command}: verified") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/i14-soak-local-collector.py b/scripts/i14-soak-local-collector.py new file mode 100644 index 0000000..c770c09 --- /dev/null +++ b/scripts/i14-soak-local-collector.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +"""Bounded local raw observer. Manual calls never establish cron origin.""" +import argparse +from datetime import datetime, timezone +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import resource +import signal +import stat +import subprocess +import time + +_spec = importlib.util.spec_from_file_location( + 'observer_inventory', Path(__file__).with_name('i14-soak-observer-inventory.py')) +_inventory = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_inventory) + +LOG_NAMES = ['messages' + suffix for suffix in ['', '.0', '.1', '.2', '.3', '.4']] + ['i14-battery.log'] +REQUIRED = {'messages', 'i14-battery.log'} +BASE = Path('/mnt/data/media/0/i14-linux/soak-c-observer-20261115') +LOG_ROOT = Path('/var/log') + + +class CaptureInterrupted(Exception): + """Deadline/cancellation must never be treated as a recoverable log read error.""" + + +def assert_source_location(root): + if (Path(__file__).resolve() != root/'i14-soak-local-collector.py' + or Path(_inventory.__file__).resolve() != root/'i14-soak-observer-inventory.py'): + raise ValueError('executing collector/helper do not match pinned run directory') + + +def digest(raw): + return hashlib.sha256(raw).hexdigest() + + +def copy_logs(source, target, budget): + result = {'ok': [], 'absent': [], 'failed': [], 'files': {}} + for name in LOG_NAMES: + try: + raw, metadata = _inventory.read_snapshot(source / name) + if raw is None: + result['failed' if name in REQUIRED else 'absent'].append( + name + '(absent)' if name in REQUIRED else name) + continue + if len(raw) > budget: + result['failed'].append(name + '(budget)') + continue + with (target / name).open('xb') as output: + output.write(raw) + budget -= len(raw) + result['ok'].append(name) + result['files'][name] = {'sha256': metadata['sha256'], 'bytes': len(raw)} + except (OSError, ValueError) as error: + result['failed'].append(name + '(read)') + with (target / (name + '.err')).open('xb') as output: + output.write((type(error).__name__ + '\n').encode()) + return result + + +def cron_origin(rows): + return any(row['uid'] == 0 and row['comm'] in ['crond', 'cron'] for row in rows) + + +def ancestry(pid): + rows = [] + seen = set() + while pid: + if pid in seen or len(rows) >= 32: + raise ValueError('invalid process ancestry') + seen.add(pid) + directory = Path('/proc') / str(pid) + fields = (directory / 'stat').read_text().rsplit(')', 1)[1].split() + uid = next(line for line in (directory / 'status').read_text().splitlines() + if line.startswith('Uid:')).split()[1] + row = {'pid': pid, 'ppid': int(fields[1]), 'uid': int(uid), + 'comm': (directory / 'comm').read_text().strip(), 'start_ticks': int(fields[19])} + rows.append(row) + if pid == 1: + break + pid = row['ppid'] + return rows + + +def check_limits(config, now, count, used, free): + if now >= config['expires_epoch']: + raise ValueError('observer expired') + if count >= config['max_captures']: + raise ValueError('observer capture count reached') + if used + config['capture_bytes'] > config['max_bytes']: + raise ValueError('observer storage quota reached') + if free < config['reserve_bytes'] + config['capture_bytes']: + raise ValueError('observer free-space reserve reached') + + +def usage(root): + used = 0 + for path in root.rglob('*'): + metadata = path.lstat() + if stat.S_ISLNK(metadata.st_mode): + raise ValueError('unexpected output symlink') + if stat.S_ISREG(metadata.st_mode): + used += max(metadata.st_size, metadata.st_blocks * 512) + count = sum(1 for path in (root/'logs').iterdir() if re.fullmatch(r'\d{8}T\d{6}Z', path.name)) + space = os.statvfs(root) + return count, used, space.f_bavail * space.f_frsize + + +def validate_procs(raw, boot): + lines = raw.decode().splitlines() + if len(lines) < 12 or lines[1] != boot: + raise ValueError('process capture incomplete or wrong boot') + datetime.strptime(lines[0], '%Y-%m-%dT%H:%M:%SZ') + seen = set() + for line in lines[2:]: + pid, ticks, command = line.split(None, 2) + pid, ticks = int(pid), int(ticks) + if pid <= 0 or ticks < 0 or pid in seen or not command: + raise ValueError('process row invalid') + seen.add(pid) + + +def append_index(path, stamp, ok, absent, failed): + datetime.strptime(stamp, '%Y%m%dT%H%M%SZ') + line = (stamp + ' ok: ' + ' '.join(ok) + ' absent: ' + (' '.join(absent) or 'none') + + ' failed: ' + (' '.join(failed) or 'none') + '\n') + if len(line.encode()) > 1024: + raise ValueError('index row exceeds metadata budget') + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'ab') as output: + if not stat.S_ISREG(os.fstat(output.fileno()).st_mode): + raise ValueError('index is not regular') + output.write(line.encode()) + output.flush() + os.fsync(output.fileno()) + + +def owned_file(path, mode): + raw, metadata = _inventory.read_snapshot(path) + if raw is None or metadata['uid'] != os.geteuid() or int(metadata['mode'], 8) != mode: + raise ValueError('observer source/config ownership differs') + return raw + + +def load_config(root): + assert_source_location(root) + raw = owned_file(root / 'observer.json', 0o600) + config = json.loads(raw) + keys = {'schema', 'grant_id', 'expires_epoch', 'max_captures', 'max_bytes', + 'reserve_bytes', 'capture_bytes', 'source_sha256'} + phase = root.name.startswith('phase-') + if phase: + keys.add('boot_id') + if set(config) != keys or config['schema'] != (2 if phase else 1): + raise ValueError('observer configuration schema differs') + for name in ['expires_epoch', 'max_captures', 'max_bytes', 'reserve_bytes', 'capture_bytes']: + if type(config[name]) is not int or config[name] <= 0: + raise ValueError('observer limit is not a positive integer') + if phase and (config['max_captures'] > 80 or config['max_bytes'] > 1281 << 20 + or config['capture_bytes'] != 16 << 20 or config['reserve_bytes'] != 512 << 20): + raise ValueError('phase limits differ from the closed-phase exporter') + if not isinstance(config['grant_id'], str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,120}', config['grant_id']): + raise ValueError('observer grant identifier malformed') + if config['max_captures'] > 1000 or not 131072 <= config['capture_bytes'] <= 16777216: + raise ValueError('observer capture bounds differ') + expected = {'i14-soak-local-collector.py', 'i14-soak-observer-inventory.py', 'procs.sh'} + if set(config['source_sha256']) != expected: + raise ValueError('observer source pin set differs') + for name, want in config['source_sha256'].items(): + if not isinstance(want, str) or not re.fullmatch('[0-9a-f]{64}', want): + raise ValueError('observer source pin is malformed') + if digest(owned_file(root / name, 0o700)) != want: + raise ValueError('observer source hash differs') + return config, digest(raw) + + +def write_json(path, value): + raw = (json.dumps(value, indent=2) + '\n').encode() + if len(raw) > 32768: + raise ValueError('receipt exceeds metadata budget') + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(raw) + output.flush() + os.fsync(output.fileno()) + + +def capture_procs(script, capture, timeout=10): + """Bound output in the child, and close the entire owned group on every exit.""" + numbers = {signal.SIGINT, signal.SIGTERM, signal.SIGALRM} + previous_mask = signal.pthread_sigmask(signal.SIG_BLOCK, numbers) + child = None + result = {'rc': None, 'group_closed': False} + def child_limits(): + resource.setrlimit(resource.RLIMIT_FSIZE, (32768, 32768)) + signal.pthread_sigmask(signal.SIG_SETMASK, previous_mask) + try: + with (capture/'procs.txt').open('xb') as stdout, (capture/'procs.err').open('xb') as stderr: + child = subprocess.Popen(['/bin/sh', str(script)], stdout=stdout, stderr=stderr, + start_new_session=True, preexec_fn=child_limits) + result['pid'] = child.pid + signal.pthread_sigmask(signal.SIG_SETMASK, previous_mask) + result['rc'] = child.wait(timeout=timeout) + finally: + signal.pthread_sigmask(signal.SIG_BLOCK, numbers) + try: + if child is not None: + try: + os.killpg(child.pid, signal.SIGKILL) + except ProcessLookupError: + pass + child.wait(timeout=3) + # The trusted helper has no background children. A surviving group is UNKNOWN. + try: + os.killpg(child.pid, 0) + except ProcessLookupError: + result['group_closed'] = True + finally: + signal.pthread_sigmask(signal.SIG_SETMASK, previous_mask) + return result + + +def runtime_identity(): + _inventory.check_identity(os.geteuid(), os.uname().nodename, os.uname().release, + Path('/proc/device-tree/compatible').read_bytes().decode()) + boot = Path('/proc/sys/kernel/random/boot_id').read_text().strip() + if not re.fullmatch(r'[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}', boot): + raise ValueError('invalid boot identity') + return boot + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--run-dir', type=Path, required=True) + parser.add_argument('--origin', choices=['manual', 'cron'], required=True) + args = parser.parse_args(argv) + os.umask(0o077) + root = args.run_dir.absolute() + if root.resolve() != root or not root.is_relative_to(BASE) or root == BASE: + raise ValueError('observer directory is not a dedicated userdata child') + info = root.stat() + if os.geteuid() != 0 or info.st_uid != 0 or stat.S_IMODE(info.st_mode) != 0o700: + raise ValueError('observer must run as root in own 0700 directory') + boot = runtime_identity() + config, config_sha = load_config(root) + if 'boot_id' in config and config['boot_id'] != boot: + raise ValueError('observer boot differs from frozen phase') + if os.path.lexists(root / 'STOPPED.json'): + return 3 + rows = ancestry(os.getppid()) + cron = cron_origin(rows) + if args.origin == 'cron' and not cron: + raise ValueError('actual root-cron ancestry not proven') + logs = root / 'logs' + receipts = root / 'receipts' + for directory in [logs, receipts]: + metadata = directory.lstat() + if not stat.S_ISDIR(metadata.st_mode) or metadata.st_uid != 0 or stat.S_IMODE(metadata.st_mode) != 0o700: + raise ValueError('observer output directory differs') + count, used, free = usage(root) + try: + check_limits(config, time.time(), count, used, free) + except ValueError as error: + try: + write_json(root / 'STOPPED.json', {'utc': datetime.now(timezone.utc).isoformat(), + 'reason': str(error), 'count': count, 'used_bytes': used}) + except FileExistsError: + pass + return 3 + lock = root / '.capture.lock' + previous_mask = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGALRM, signal.SIGINT, signal.SIGTERM}) + lock_fd = None + started = datetime.now(timezone.utc) + report = {'start_utc': started.isoformat(), 'monotonic_start': time.monotonic(), + 'boot_id': boot, 'pid': os.getpid(), 'origin': args.origin, + 'cron_origin_proven': args.origin == 'cron' and cron, 'ancestry': rows, + 'source_pins': config['source_sha256'], 'config_sha256': config_sha, + 'grant_id': config['grant_id'], 'result': 'FAIL', 'rc': 1} + previous_handlers = {} + def interrupted(signum, frame): + report['interruption_signal'] = signum + raise CaptureInterrupted('observer interrupted or timed out') + try: + lock_fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + lock_stat = os.fstat(lock_fd) + os.write(lock_fd, str(os.getpid()).encode()) + for number in [signal.SIGALRM, signal.SIGINT, signal.SIGTERM]: + previous_handlers[number] = signal.signal(number, interrupted) + signal.pthread_sigmask(signal.SIG_SETMASK, previous_mask) + signal.alarm(40) + # Existing minute probes may take 5s; collect after their initial write burst. + time.sleep(7) + # Refuse stale pre-lock count/space/expiry after a competing capture finishes. + if os.path.lexists(root / 'STOPPED.json'): + raise ValueError('observer phase already stopped') + check_limits(config, time.time(), *usage(root)) + stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ') + capture = logs / stamp + capture.mkdir(mode=0o700) + report['capture_directory'] = str(capture) + result = copy_logs(LOG_ROOT, capture, config['capture_bytes'] - 131072) + try: + process = capture_procs(root / 'procs.sh', capture) + report['process_actor'] = process + if process['rc'] != 0 or not process['group_closed']: + raise ValueError('process command returned nonzero') + raw = (capture / 'procs.txt').read_bytes() + validate_procs(raw, boot) + result['ok'].append('procs') + result['files']['procs.txt'] = {'sha256': digest(raw), 'bytes': len(raw)} + except (OSError, ValueError, subprocess.TimeoutExpired): + result['failed'].append('procs(read)') + append_index(logs / 'index.txt', stamp, result['ok'], result['absent'], result['failed']) + report.update(result) + if load_config(root)[1] != config_sha: + raise ValueError('observer configuration changed during capture') + if runtime_identity() != boot: + raise ValueError('boot changed during capture') + report['result'] = 'PASS' if not result['failed'] else 'FAIL' + report['rc'] = 0 if report['result'] == 'PASS' else 1 + except BaseException as error: + report['error_type'] = type(error).__name__ + finally: + signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGALRM, signal.SIGINT, signal.SIGTERM}) + signal.alarm(0) + try: + if lock_fd is not None: + current = lock.lstat() + if (current.st_dev, current.st_ino) != (lock_stat.st_dev, lock_stat.st_ino): + raise ValueError('observer lock identity changed; retain for reconciliation') + lock.unlink() + report['end_utc'] = datetime.now(timezone.utc).isoformat() + report['monotonic_end'] = time.monotonic() + path = receipts / (started.strftime('%Y%m%dT%H%M%S.%fZ') + '-' + str(os.getpid()) + '.json') + write_json(path, report) + print(json.dumps({'result': report['result'], 'rc': report['rc'], 'receipt': str(path)})) + finally: + if lock_fd is not None: + os.close(lock_fd) + for number, handler in previous_handlers.items(): + signal.signal(number, handler) + signal.pthread_sigmask(signal.SIG_SETMASK, previous_mask) + return report['rc'] + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/scripts/i14-soak-observer-export.py b/scripts/i14-soak-observer-export.py new file mode 100644 index 0000000..1bd8f4e --- /dev/null +++ b/scripts/i14-soak-observer-export.py @@ -0,0 +1,350 @@ +#!/usr/bin/env python3 +"""Streaming export primitive only; no transport, device main or cleanup permission. + +The phase caller must first restore cron, close actors and validate its exact +owned destination/identity. A successful export alone never authorizes cleanup. +""" +from contextlib import contextmanager +import hashlib +import io +import json +import os +from pathlib import Path +import re +import stat +import tarfile + +MAX_FILE = 16 << 20 +MAX_BYTES = 1281 << 20 +MAX_FILES = 1024 +MAX_META = 1 << 20 +CHUNK = 1 << 20 +FIRST = 'EXPORT-MANIFEST.json' +LAST = 'EXPORT-COMPLETE.json' + + +def safe_name(name): + if (not isinstance(name, str) or len(name.encode()) > 100 + or not 1 <= len(name.split('/')) <= 3 + or any(not re.fullmatch(r'[A-Za-z0-9_.-]+', p) or p in ['.', '..'] + for p in name.split('/')) or name in [FIRST, LAST]): + raise ValueError('unsafe export name') + return name + + +@contextmanager +def directory(path): + inherited = type(path) is int + if inherited: + fd = os.dup(path) + else: + path = Path(path).absolute() + if path.anchor != '/' or '..' in path.parts: + raise ValueError('unexpected export directory') + fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY) + try: + if not inherited: + for part in path.parts[1:]: + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd) + os.close(fd) + fd = child + yield fd + except OSError as error: + raise ValueError('export directory unavailable or symlinked') from error + finally: + os.close(fd) + + +@contextmanager +def parent_descriptor(root, name, create=False): + parts = safe_name(name).split('/') + with directory(root) as initial: + fd = os.dup(initial) + try: + for part in parts[:-1]: + if create: + try: + os.mkdir(part, 0o700, dir_fd=fd) + except FileExistsError: + pass + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd) + os.close(fd) + fd = child + info = os.fstat(fd) + if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o700: + raise ValueError('export parent directory owner/mode differs') + yield fd, parts[-1] + finally: + os.close(fd) + + +def metadata(info): + return {'dev': info.st_dev, 'inode': info.st_ino, 'bytes': info.st_size, + 'mode': stat.S_IMODE(info.st_mode), 'uid': info.st_uid, 'gid': info.st_gid, + 'mtime_ns': info.st_mtime_ns, 'ctime_ns': info.st_ctime_ns, 'nlink': info.st_nlink} + + +def regular(info): + if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() + or stat.S_IMODE(info.st_mode) not in [0o600, 0o700] + or info.st_nlink != 1 or not 0 <= info.st_size <= MAX_FILE): + raise ValueError('unexpected export file type/owner/mode/links/size') + + +def tree(root): + result = {} + directories = 0 + + def visit(fd, prefix): + nonlocal directories + directories += 1 + info = os.fstat(fd) + if (directories > 256 or info.st_uid != os.geteuid() + or stat.S_IMODE(info.st_mode) != 0o700): + raise ValueError('unexpected export directory owner/mode/count') + with os.scandir(fd) as entries: + for entry in entries: + name = safe_name(prefix + entry.name) + info = entry.stat(follow_symlinks=False) + if stat.S_ISDIR(info.st_mode): + child = os.open(entry.name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd) + try: + visit(child, name + '/') + finally: + os.close(child) + else: + regular(info) + result[name] = metadata(info) + if len(result) > MAX_FILES or sum(v['bytes'] for v in result.values()) > MAX_BYTES: + raise ValueError('export file count/total quota exceeded') + + with directory(root) as fd: + visit(fd, '') + if not result: + raise ValueError('empty export') + return dict(sorted(result.items())) + + +@contextmanager +def opened(root, name, expected): + with parent_descriptor(root, name) as (parent, basename): + fd = os.open(basename, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + with os.fdopen(fd, 'rb') as stream: + info = os.fstat(stream.fileno()) + regular(info) + if metadata(info) != expected: + raise ValueError('export file metadata changed') + yield stream + after = os.fstat(stream.fileno()) + current = os.stat(basename, dir_fd=parent, follow_symlinks=False) + if metadata(after) != expected or metadata(current) != expected or not stat.S_ISREG(current.st_mode): + raise ValueError('export file changed during read') + + +def inventory(root): + files = tree(root) + for name, info in files.items(): + digest = hashlib.sha256() + with opened(root, name, info) as stream: + remaining = info['bytes'] + while remaining: + raw = stream.read(min(CHUNK, remaining)) + if not raw: + raise ValueError('short export file') + digest.update(raw) + remaining -= len(raw) + if stream.read(1): + raise ValueError('export file grew') + info['sha256'] = digest.hexdigest() + return {'files': files, 'total_bytes': sum(v['bytes'] for v in files.values())} + + +def validate_manifest(value): + if not isinstance(value, dict) or set(value) != {'files', 'total_bytes'}: + raise ValueError('unexpected export manifest') + files = value['files'] + if not isinstance(files, dict) or not 1 <= len(files) <= MAX_FILES: + raise ValueError('export manifest count outside bound') + for name, info in files.items(): + safe_name(name) + if (not isinstance(info, dict) or type(info.get('bytes')) is not int + or not 0 <= info['bytes'] <= MAX_FILE + or not re.fullmatch('[0-9a-f]{64}', str(info.get('sha256', '')))): + raise ValueError('invalid export size/hash') + total = sum(v['bytes'] for v in files.values()) + if type(value['total_bytes']) is not int or value['total_bytes'] != total or total > MAX_BYTES: + raise ValueError('invalid export total quota') + + +def binding_bytes(binding): + if (not isinstance(binding, dict) + or set(binding) != {'phase_id', 'grant_id', 'boot_id', 'config_sha256'} + or any(not isinstance(binding[k], str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,120}', binding[k]) + for k in ['phase_id', 'grant_id']) + or not re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', str(binding['boot_id'])) + or not re.fullmatch('[0-9a-f]{64}', str(binding['config_sha256']))): + raise ValueError('invalid export binding') + return binding + + +def encoded(value): + raw = (json.dumps(value, sort_keys=True, separators=(',', ':')) + '\n').encode() + if len(raw) > MAX_META: + raise ValueError('export metadata exceeds bound') + return raw + + +def add_bytes(archive, name, raw): + item = tarfile.TarInfo(name) + item.size = len(raw) + item.mode = 0o600 + archive.addfile(item, io.BytesIO(raw)) + + +class HashReader: + def __init__(self, stream): + self.stream = stream + self.digest = hashlib.sha256() + + def read(self, size): + if not 0 <= size <= CHUNK: + raise ValueError('unbounded archive read request') + raw = self.stream.read(size) + self.digest.update(raw) + return raw + + +def export_tar(root, manifest, binding, stream): + validate_manifest(manifest) + binding_bytes(binding) + wanted = {n: {k: v for k, v in info.items() if k != 'sha256'} for n, info in manifest['files'].items()} + if tree(root) != wanted: + raise ValueError('export namespace/metadata changed') + first = encoded({'schema': 1, 'binding': binding, 'manifest': manifest}) + with tarfile.open(fileobj=stream, mode='w|', format=tarfile.USTAR_FORMAT) as archive: + add_bytes(archive, FIRST, first) + for name, info in manifest['files'].items(): + item = tarfile.TarInfo(name) + item.size = info['bytes'] + item.mode = 0o600 + with opened(root, name, wanted[name]) as source: + reader = HashReader(source) + archive.addfile(item, reader) + if reader.digest.hexdigest() != info['sha256'] or source.read(1): + raise ValueError('export content changed') + if tree(root) != wanted: + raise ValueError('export namespace changed during stream') + add_bytes(archive, LAST, encoded({'manifest_sha256': hashlib.sha256(first).hexdigest(), + 'files': len(wanted), 'total_bytes': manifest['total_bytes']})) + + +def read_metadata(archive, member): + if not member or not member.isreg() or not 0 < member.size <= MAX_META: + raise ValueError('invalid export metadata member') + return archive.extractfile(member).read(MAX_META + 1) + + +class PlainTarInfo(tarfile.TarInfo): + @classmethod + def fromtarfile(cls, archive): + raw = archive.fileobj.read(tarfile.BLOCKSIZE) + member = cls.frombuf(raw, archive.encoding, archive.errors) + # Reject PAX/GNU extended headers before tarfile reads their declared body. + if member.type not in [tarfile.REGTYPE, tarfile.AREGTYPE] or not 0 <= member.size <= MAX_FILE: + raise ValueError('only bounded regular tar members are permitted') + member.offset = archive.fileobj.tell() - tarfile.BLOCKSIZE + member.offset_data = archive.fileobj.tell() + archive.offset = member.offset_data + ((member.size + 511) // 512) * 512 + return member + + +def verify_end(archive): + padding = archive.offset - archive.fileobj.tell() + if not 0 <= padding < tarfile.BLOCKSIZE: + raise ValueError('invalid final member alignment') + # Our USTAR writer emits member padding, two zero blocks and one full record. + size = padding + 2 * tarfile.BLOCKSIZE + raw = archive.fileobj.read(size) + if len(raw) != size or any(raw): + raise ValueError('missing or damaged tar zero terminators') + size = (-archive.fileobj.tell()) % tarfile.RECORDSIZE + raw = archive.fileobj.read(size) + if len(raw) != size or any(raw) or archive.fileobj.read(1): + raise ValueError('truncated padding or trailing tar bytes') + + +def unpack_files(archive, root_fd, manifest, manifest_raw): + seen = set() + while True: + member = archive.next() + if member is None: + raise ValueError('missing export completion receipt') + if member.name == LAST: + complete = json.loads(read_metadata(archive, member)) + wanted = {'manifest_sha256': hashlib.sha256(manifest_raw).hexdigest(), + 'files': len(manifest['files']), 'total_bytes': manifest['total_bytes']} + if complete != wanted or seen != set(manifest['files']): + raise ValueError('incomplete export') + verify_end(archive) + persisted = inventory(root_fd) + if any(persisted['files'].get(name, {}).get('sha256') != info['sha256'] + or persisted['files'][name]['bytes'] != info['bytes'] + for name, info in manifest['files'].items()) or set(persisted['files']) != seen: + raise ValueError('persisted export readback differs') + return manifest + name = safe_name(member.name) + if (not member.isreg() or name in seen or name not in manifest['files'] + or member.size != manifest['files'][name]['bytes']): + raise ValueError('unexpected/duplicate export member') + seen.add(name) + digest = hashlib.sha256() + with parent_descriptor(root_fd, name, create=True) as (parent, basename): + fd = os.open(basename, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, + 0o600, dir_fd=parent) + with os.fdopen(fd, 'wb') as output: + source = archive.extractfile(member) + remaining = member.size + while remaining: + block = source.read(min(CHUNK, remaining)) + if not block: + raise ValueError('short archive member') + output.write(block) + digest.update(block) + remaining -= len(block) + output.flush() + os.fsync(output.fileno()) + if digest.hexdigest() != manifest['files'][name]['sha256']: + raise ValueError('archive content hash differs') + + +def unpack_tar(stream, destination, expected_binding): + binding_bytes(expected_binding) + target = Path(destination).absolute() + try: + with tarfile.open(fileobj=stream, mode='r|', tarinfo=PlainTarInfo) as archive: + first = archive.next() + if not first or first.name != FIRST: + raise ValueError('missing export manifest') + raw = read_metadata(archive, first) + value = json.loads(raw) + if (set(value) != {'schema', 'binding', 'manifest'} or value['schema'] != 1 + or value['binding'] != expected_binding): + raise ValueError('foreign export binding/schema') + manifest = value['manifest'] + validate_manifest(manifest) + with directory(target.parent) as parent: + os.mkdir(target.name, 0o700, dir_fd=parent) + root_fd = os.open(target.name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=parent) + try: + result = unpack_files(archive, root_fd, manifest, raw) + # A substituted name must not turn descriptor-local success into acceptance. + with directory(target) as current: + a, b = os.fstat(root_fd), os.fstat(current) + if (a.st_dev, a.st_ino) != (b.st_dev, b.st_ino): + raise ValueError('destination namespace changed') + return result + finally: + os.close(root_fd) + except (tarfile.TarError, EOFError, OSError) as error: + raise ValueError('invalid or truncated export archive') from error diff --git a/scripts/i14-soak-observer-inventory.py b/scripts/i14-soak-observer-inventory.py new file mode 100644 index 0000000..93f8be2 --- /dev/null +++ b/scripts/i14-soak-observer-inventory.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Read-only phone collector inventory; no environment, secrets or log bodies.""" +from datetime import datetime, timezone +import errno +import hashlib +import json +import os +from pathlib import Path +import re +import stat +import time + + +BASE = Path('/mnt/data/media/0/i14-linux') +SAMPLER = '/mnt/data/media/0/i14-linux/soak/i14-soak-sample' + + +def check_identity(uid, hostname, kernel, compatible): + if (uid != 0 or hostname != 'i14' or kernel != '3.18.19' + or 'mediatek,MT6735' not in compatible.split('\0')): + raise ValueError('unexpected device identity; stop without retry') + + +def cron_summary(raw): + lines = [line for line in raw.decode().splitlines() + if line.strip() and not line.lstrip().startswith('#')] + commands = {f"{quote}{path}{quote}" for path in (SAMPLER, SAMPLER + "-rs") + for quote in ("", "'", '"')} + commands.add(f"/bin/sh '{SAMPLER}'") + expected = {f"* * * * * {cmd} # i14-soak-sample" for cmd in commands} + sampler = [line for line in lines if line in expected] + return {'sha256': hashlib.sha256(raw).hexdigest(), 'bytes': len(raw), + 'sampler_lines': len(sampler), 'other_command_count': len(lines) - len(sampler), + 'other_line_sha256': [hashlib.sha256(line.encode()).hexdigest() + for line in lines if line not in sampler]} + + +def read_snapshot(path): + """One bounded descriptor snapshot; every directory and file refuses symlinks.""" + path = path.absolute() + if path.anchor != '/' or '..' in path.parts: + raise ValueError('unexpected input path') + parent = os.open('/', os.O_RDONLY | os.O_DIRECTORY) + descriptor = None + try: + for part in path.parts[1:-1]: + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + os.close(parent) + parent = child + descriptor = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode): + raise ValueError('inventory path is not regular') + if before.st_size > 64 * 1024 * 1024: + raise ValueError('unexpected inventory input size') + blocks = [] + size = 0 + while size <= before.st_size: + block = os.read(descriptor, min(65536, before.st_size + 1 - size)) + if not block: + break + blocks.append(block) + size += len(block) + after = os.fstat(descriptor) + current = os.stat(path.name, dir_fd=parent, follow_symlinks=False) + if (size != before.st_size or before.st_size != after.st_size + or before.st_mtime_ns != after.st_mtime_ns + or (current.st_dev, current.st_ino) != (before.st_dev, before.st_ino) + or (current.st_size, current.st_mtime_ns) != (after.st_size, after.st_mtime_ns) + or not stat.S_ISREG(current.st_mode)): + raise ValueError('input changed during bounded snapshot') + raw = b''.join(blocks) + return raw, {'present': True, 'bytes': size, 'bytes_read': size, + 'sha256': hashlib.sha256(raw).hexdigest(), 'inode': before.st_ino, + 'dev': before.st_dev, 'mode': oct(stat.S_IMODE(before.st_mode)), + 'uid': before.st_uid, 'mtime_ns': before.st_mtime_ns, 'symlink': False} + except FileNotFoundError: + if descriptor is not None: + raise ValueError('input disappeared during bounded snapshot') from None + return None, {'present': False} + except OSError as error: + if error.errno in [errno.ELOOP, errno.ENOTDIR]: + raise ValueError('unexpected symlink or ancestor type; no target read') from None + raise + finally: + if descriptor is not None: + os.close(descriptor) + os.close(parent) + + +def file_info(path, log=False): + raw, info = read_snapshot(path) + if raw is None: + return info + if log: + first = last = None + lines = raw.splitlines() + for line in lines: + match = re.match(rb'^(?:[A-Z][a-z]{2}\s+\d+ \d\d:\d\d:\d\d|' + rb'\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)', line) + if match: + last = match[0].decode('ascii') + if first is None: + first = last + info.update(first_stamp=first, last_stamp=last, lines=len(lines), + newline_terminated=not raw or raw.endswith(b'\n')) + return info + + +def main(): + compatible = Path('/proc/device-tree/compatible').read_bytes().decode() + identity = dict(uid=os.geteuid(), hostname=os.uname().nodename, + kernel=os.uname().release, compatible=compatible) + check_identity(identity['uid'], identity['hostname'], identity['kernel'], compatible) + boot = Path('/proc/sys/kernel/random/boot_id').read_text().strip() + if not re.fullmatch(r'[0-9a-f-]{36}', boot): + raise ValueError('invalid boot identity') + cron_raw, cron_info = read_snapshot(Path('/etc/crontabs/root')) + syslog_raw, syslog_info = read_snapshot(Path('/etc/conf.d/syslog')) + if cron_raw is None or syslog_raw is None: + raise ValueError('required cron/syslog configuration missing') + sources = ['/etc/periodic/daily/i14-logtrim', SAMPLER, SAMPLER + '-rs'] + logs = ['/var/log/messages' + suffix for suffix in ['', '.0', '.1', '.2', '.3', '.4']] + logs.append('/var/log/i14-battery.log') + files = {name: file_info(Path(name), log=name in logs) for name in sources + logs} + files.update({'/etc/crontabs/root': cron_info, '/etc/conf.d/syslog': syslog_info}) + processes = [] + for proc in Path('/proc').glob('[0-9]*'): + try: + command = (proc / 'comm').read_text().strip() + if command in ['crond', 'syslogd']: + processes.append({'pid': int(proc.name), 'comm': command, + 'stat': (proc / 'stat').read_text().strip(), + 'cmdline_sha256': hashlib.sha256((proc / 'cmdline').read_bytes()).hexdigest()}) + except (FileNotFoundError, ProcessLookupError): + continue + storage = os.statvfs(BASE) + samples = {str(BASE / 'soak' / name): file_info(BASE / 'soak' / name) + for name in ['samples.jsonl.1', 'samples.jsonl']} + print(json.dumps({'utc': datetime.now(timezone.utc).isoformat(), + 'epoch': time.time(), 'monotonic': time.monotonic(), + 'uptime': float(Path('/proc/uptime').read_text().split()[0]), + 'identity': identity, 'boot_id': boot, 'files': files, + 'sample_files': samples, 'cron': cron_summary(cron_raw), + 'processes': processes, 'userdata_available_bytes': storage.f_bavail * storage.f_frsize, + 'syslog_expected_options': any(line.strip() == 'SYSLOGD_OPTS="-t -s 2048 -b 4"' + for line in syslog_raw.decode().splitlines()), + 'scope': 'Inventory only; no write, environment dump, secret or log-body output'}, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/scripts/i14-soak-phase-export.py b/scripts/i14-soak-phase-export.py new file mode 100644 index 0000000..28fc4a7 --- /dev/null +++ b/scripts/i14-soak-phase-export.py @@ -0,0 +1,226 @@ +"""Stream a closed phase to stdout after validating its owner-supplied bundle.""" +import hashlib +import json +import math +import os +from pathlib import Path +import re +import stat +import sys +import time +import types + +BASE = Path('/mnt/data/media/0/i14-linux/soak-c-observer-20261115') +CRON = Path('/etc/crontabs/root') +OWNER = 0 +DEPS = { + 'i14-soak-observer-export.py': '1382cd4e2e450f7c43c3e4b85e6203e1673ab08195309df7e1b7b7dc1051f660', + 'i14-soak-observer-inventory.py': '4a7973e96c1e3063e45def3e0efb2ef69c919f3384aad19caa9a2d00e6f5891c', +} +SOURCES = { + 'i14-soak-local-collector.py': 'bd202328ed4cc6611d6fa5e72d99159eaabc4f6127d96105203768b3090a6b0c', + 'i14-soak-observer-inventory.py': DEPS['i14-soak-observer-inventory.py'], + 'procs.sh': '32bc698ce56a958045bf6b63ff0588a0c1287e9f47007c6789d1314aa80def9d', +} + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + +def dependencies(raws): + if set(raws) != set(DEPS): + raise ValueError('exact approved dependencies required') + result = {} + for name, raw in raws.items(): + if len(raw) > 65536 or sha(raw) != DEPS[name]: + raise ValueError('approved export/inventory dependency differs') + module = types.ModuleType('pinned_closed_phase_dependency') + module.__file__ = name + exec(compile(raw, name, 'exec'), module.__dict__) + result[name] = module + return result['i14-soak-observer-export.py'], result['i14-soak-observer-inventory.py'] + +def fixed(path, limit): + with Path(path).open('rb') as stream: + raw = stream.read(limit + 1) + if len(raw) > limit: + raise ValueError('fixed identity/proc input exceeds bound') + return raw + +def native(expected_boot): + u = os.uname() + if (os.geteuid(), u.nodename, u.release, u.machine) != (0, 'i14', '3.18.19', 'aarch64'): + raise ValueError('native phone identity differs') + if b'mediatek,MT6735' not in fixed('/proc/device-tree/compatible', 4096).split(b'\0'): + raise ValueError('native board differs') + actual = fixed('/proc/sys/kernel/random/boot_id', 64).decode().strip() + if actual != expected_boot: + raise ValueError('expected closed-phase boot differs') + return actual + +def actors(root): + script = 'i14-soak-local-collector.py' + expected = str(root/script) + found = [] + with os.scandir('/proc') as entries: + for i, entry in enumerate(entries): + if i >= 4096: + raise ValueError('process enumeration exceeds 4096') + if entry.name.isdigit(): + try: + parts = fixed(Path(entry.path)/'cmdline', 65536).split(b'\0') + if parts[-1] == b'': + parts.pop() # Only the final separator; empty arguments retain their positions. + argv = [os.fsdecode(a) for a in parts] + run_dirs = [] + run_option = False + for j,argument in enumerate(argv): + option,separator,value = argument.partition('=') + # The unchanged collector accepts argparse's unambiguous --r... prefixes. + if len(option)>=3 and '--run-dir'.startswith(option): + run_option = True + if separator: + run_dirs.append(value) + elif j+14096 or not os.path.isabs(cwd) or cwd.endswith(' (deleted)'): + raise ValueError('ambiguous relevant collector cwd') + return os.path.normpath(os.path.join(cwd,argument)) + candidates = [a for a in argv if os.path.basename(a)==script] + if any(normalized(a)==expected for a in candidates): + found.append(int(entry.name)) + continue + if (not candidates and not run_dirs) or any(normalized(a)==str(root) for a in run_dirs): + raise ValueError('unresolved relevant collector invocation') + except (FileNotFoundError, ProcessLookupError): + pass + return found + +def stream_phase(bundle, dependency_sources, stream, clock): + """Require caller/grant proof, stream bounded tar, and return ONLY after final checks. + + The future host caller must require this function's normal remote exit as well + as B3a tar verification; an earlier tar completion member alone is insufficient. + """ + keys = {'phase_id', 'grant_id', 'close_grant_id', 'run_dir', 'boot_id', + 'config_sha256', 'source_sha256', 'cronline_sha256', 'original_cron_sha256', + 'close_receipt_sha256', 'start_epoch', 'deadline_epoch'} + if set(bundle) != keys or bundle['source_sha256'] != SOURCES: + raise ValueError('unexpected closed-phase binding/source set') + for name in ['phase_id', 'grant_id', 'close_grant_id']: + if not isinstance(bundle[name], str) or not re.fullmatch('[A-Za-z0-9_.-]{1,120}', bundle[name]): + raise ValueError('invalid phase/grant identifier') + for name in ['config_sha256', 'cronline_sha256', 'original_cron_sha256', 'close_receipt_sha256']: + if not re.fullmatch('[0-9a-f]{64}', str(bundle[name])): + raise ValueError('missing exact provenance pin') + if not re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', str(bundle['boot_id'])): + raise ValueError('invalid expected boot') + start, end = bundle['start_epoch'], bundle['deadline_epoch'] + if any(type(x) not in (int, float) or not math.isfinite(x) for x in [start, end]) or not 0 < end-start <= 900: + raise ValueError('export grant exceeds 0..900s') + def time_guard(): + now = clock() + if not math.isfinite(now) or not start <= now < end: + raise ValueError('export grant not current; no retry') + time_guard() + root = Path(bundle['run_dir']) + if root.parent != BASE or not re.fullmatch('phase-[0-9]{8}T[0-9]{6}Z', root.name): + raise ValueError('not the exact owned phase destination') + export, inventory = dependencies(dependency_sources) + binding = {k:bundle[k] for k in ['phase_id', 'grant_id', 'boot_id', 'config_sha256']} + export.binding_bytes(binding) + def checked(path, digest, mode): + raw, meta = inventory.read_snapshot(path) + if raw is None or len(raw) > 65536 or sha(raw) != digest or meta['uid'] != OWNER or int(meta['mode'],8) != mode: + raise ValueError('closed-phase pinned file/metadata differs: '+path.name) + return raw + def invariants(): + time_guard(); native(bundle['boot_id']) + checked(CRON, bundle['original_cron_sha256'], 0o600) + checked(root/'root-crontab.before', bundle['original_cron_sha256'], 0o600) + config = json.loads(checked(root/'observer.json', bundle['config_sha256'], 0o600)) + if (set(config) != {'schema','boot_id','grant_id','expires_epoch','max_captures','max_bytes','capture_bytes','reserve_bytes','source_sha256'} + or config['schema'] != 2 or config['boot_id'] != bundle['boot_id'] + or config['grant_id'] != bundle['phase_id'] or config['source_sha256'] != SOURCES + or type(config['max_captures']) is not int or not 1 <= config['max_captures'] <= 80 + or type(config['max_bytes']) is not int or not 0 < config['max_bytes'] <= 1281 << 20 + or config['capture_bytes'] != 16 << 20 or config['reserve_bytes'] != 512 << 20): + raise ValueError('closed-phase config outside reviewed export scope') + for name, digest in SOURCES.items(): + checked(root/name, digest, 0o700) + report = json.loads(checked(root/'close-receipt.json', bundle['close_receipt_sha256'], 0o600)) + expected = dict(result='CRON_RESTORED_NO_ACTOR',grant_id=bundle['close_grant_id'],run_dir=str(root), + boot_id=bundle['boot_id'],source_sha256=SOURCES,config_sha256=bundle['config_sha256'], + cronline_sha256=bundle['cronline_sha256'],restored_cron_sha256=bundle['original_cron_sha256']) + if any(report.get(k) != v for k,v in expected.items()): + raise ValueError('close receipt belongs to a different phase/grant/provenance') + try: + os.stat('.capture.lock', dir_fd=fd, follow_symlinks=False) + locked = True + except FileNotFoundError: + locked = False + if actors(root) or locked: + raise ValueError('collector actor/lock still present') + with export.directory(root) as fd: + before = os.fstat(fd) + if before.st_uid != OWNER or stat.S_IMODE(before.st_mode) != 0o700: + raise ValueError('phase directory is not private and owned') + invariants() + manifest = export.inventory(fd) + if any(v['uid'] != OWNER for v in manifest['files'].values()): + raise ValueError('foreign owner in phase evidence') + required = {name:(digest,0o700) for name,digest in SOURCES.items()} + required.update({'observer.json':(bundle['config_sha256'],0o600), + 'root-crontab.before':(bundle['original_cron_sha256'],0o600), + 'close-receipt.json':(bundle['close_receipt_sha256'],0o600)}) + for name,(digest,mode) in required.items(): + row = manifest['files'].get(name,{}) + if (row.get('sha256'),row.get('uid'),row.get('mode'),row.get('nlink')) != (digest,OWNER,mode,1): + raise ValueError('export manifest differs from validated provenance: '+name) + time_guard() + class DeadlineSink: + written = 0 + def write(self, raw): + time_guard() + self.written += len(raw) + if self.written > export.MAX_BYTES + 2*export.MAX_META + (export.MAX_FILES+4)*1024 + 10240: + raise ValueError('stream envelope exceeds bounded tar overhead') + count = stream.write(raw) + if count != len(raw): + raise ValueError('short export stream write') + return count + sink = DeadlineSink() + export.export_tar(fd, manifest, binding, sink) + invariants() + with export.directory(root) as current: + after = os.fstat(current) + if (before.st_dev,before.st_ino) != (after.st_dev,after.st_ino): + raise ValueError('phase namespace changed') + time_guard() + return dict(result='CLOSED_PHASE_STREAMED_NOT_CLEANUP_AUTHORIZED',binding=binding, + files=len(manifest['files']),bytes=manifest['total_bytes'],tar_bytes=sink.written, + cleanup_authorized=False) + + +if __name__ == '__main__': + if sys.argv[1:] != ['--stream']: + raise SystemExit('usage: i14-soak-phase-export.py --stream < closed-phase.json') + raw = sys.stdin.buffer.read(65537) + if len(raw) > 65536: + raise SystemExit('phase bundle too large') + sources = {name: fixed(Path(__file__).with_name(name), 65536) for name in DEPS} + stream_phase(json.loads(raw), sources, sys.stdout.buffer, time.time) + sys.stdout.buffer.flush() diff --git a/scripts/i14-soak-procs.sh b/scripts/i14-soak-procs.sh new file mode 100644 index 0000000..ef42e9f --- /dev/null +++ b/scripts/i14-soak-procs.sh @@ -0,0 +1,19 @@ +# Runs on the phone via `sh -s`. Prints boot id and the start time (clock ticks since boot, +# /proc//stat field 22) of each monitored process. Exits nonzero on any incomplete capture. +date -u +%FT%TZ || exit 2 +cat /proc/sys/kernel/random/boot_id || exit 2 +pids=$(pgrep -f 'supervise-daemon|i14-rs|unbound|wpa_supplicant|sshd|chronyd|crond|syslogd') || exit 3 +[ -n "$pids" ] || exit 3 +n=0 +for p in $pids; do + # Skip only a process that has exited meanwhile; a failed read of a live one is an error. + if ! st=$(cat /proc/$p/stat) || ! cmd=$(tr '\0' ' ' &2; exit 5; } + continue + fi + set -- $st + shift 21 + echo "$p $1 $cmd" + n=$((n + 1)) +done +[ "$n" -ge 10 ] || exit 4 # fewer than the supervised services + daemons: incomplete diff --git a/scripts/i14-soak-receive.py b/scripts/i14-soak-receive.py new file mode 100644 index 0000000..e86ece2 --- /dev/null +++ b/scripts/i14-soak-receive.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Receive one closed-phase export through an owner-supplied foreground transport.""" +import argparse +import importlib.util +import json +import os +from pathlib import Path +import selectors +import signal +import subprocess +import time + + +spec = importlib.util.spec_from_file_location("soak_export", Path(__file__).with_name("i14-soak-observer-export.py")) +export = importlib.util.module_from_spec(spec) +spec.loader.exec_module(export) + + +class TransportStream: + def __init__(self, pipe, selector, deadline): + self.pipe = pipe + self.selector = selector + self.deadline = deadline + + def remaining(self): + left = self.deadline - time.monotonic() + if left <= 0: + raise TimeoutError("phase transport deadline") + return left + + def read(self, size): + if not 0 < size <= export.CHUNK: + raise ValueError("invalid transport read size") + if not self.selector.select(self.remaining()): + raise TimeoutError("phase transport stalled") + return os.read(self.pipe.fileno(), size) + + +def receive(command, destination, binding, seconds): + export.binding_bytes(binding) + if not command or not 0 < seconds <= 900: + raise ValueError("foreground command and timeout (0, 900] required") + destination.mkdir(mode=0o700) + deadline = time.monotonic() + seconds + # The transport inherits stdin (reviewed producer inputs) and stderr (owner's private log). + with selectors.DefaultSelector() as selector, subprocess.Popen( + command, stdout=subprocess.PIPE, start_new_session=True) as child: + try: + selector.register(child.stdout, selectors.EVENT_READ) + stream = TransportStream(child.stdout, selector, deadline) + manifest = export.unpack_tar(stream, destination / "raw", binding) + if child.wait(timeout=stream.remaining()) != 0: + raise ValueError(f"export transport exited {child.returncode}") + try: + os.killpg(child.pid, 0) + except ProcessLookupError: + pass + else: + raise ValueError("export transport left a process group") + except BaseException: + child.poll() # Reap an already-exited leader before examining its group. + try: + os.killpg(child.pid, signal.SIGKILL) + except ProcessLookupError: + pass + except PermissionError: + # Darwin may report EPERM for a leader that just became a zombie. + if child.poll() is None: + raise + try: + os.killpg(child.pid, 0) + except ProcessLookupError: + pass + else: + raise + child.wait() + raise + receipt = dict(binding=binding, transport_exit=0, files=len(manifest["files"]), + bytes=manifest["total_bytes"], manifest=manifest) + pending = destination / "receipt.partial" + with pending.open("x") as output: + json.dump(receipt, output, allow_nan=False) + output.flush() + os.fsync(output.fileno()) + pending.rename(destination / "verified.json") + return receipt + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binding", required=True, type=Path) + parser.add_argument("--out", required=True, type=Path) + parser.add_argument("--timeout", required=True, type=int) + parser.add_argument("command", nargs="+") + args = parser.parse_args() + def interrupted(signum, frame): + raise KeyboardInterrupt + signal.signal(signal.SIGTERM, interrupted) + receive(args.command, args.out, json.loads(args.binding.read_text()), args.timeout) + + +if __name__ == "__main__": + main() diff --git a/scripts/i14_k70_capture.py b/scripts/i14_k70_capture.py new file mode 100644 index 0000000..7dfecd4 --- /dev/null +++ b/scripts/i14_k70_capture.py @@ -0,0 +1,65 @@ +"""Passive JSONL writer for one M0 trial inside a single host observer process.""" + +from contextlib import contextmanager +import json +import time +import uuid + + +class RecoveryCapture: + """The observer supplies verified identities and owns the exclusively opened stream.""" + + def __init__(self, stream, *, previous_boot, experimental_boot, kernel, image): + if not all(isinstance(v, str) and v.strip() for v in + (previous_boot, experimental_boot, kernel, image)) or previous_boot == experimental_boot: + raise ValueError("distinct boot IDs and verified production pins required") + self.stream = stream + self.records = 0 + self.session = str(uuid.uuid4()) + self.experimental = experimental_boot + self.previous = previous_boot + self.kernel = kernel + self.image = image + self.started = False + self.dispatched = False + self.returned = False + self._write(type="contract", schema="i14-k70-recovery-trace/1", + host_clock_session=self.session, previous_production_boot_id=previous_boot, + experimental_boot_id=experimental_boot, expected_kernel=kernel, expected_image=image) + + def _write(self, **record): + line = json.dumps(record, allow_nan=False) + "\n" + if self.records >= 4096 or self.stream.tell() + len(line) > 1024**2: + raise ValueError("trace limit exceeded") + self.records += 1 + self.stream.write(line) + self.stream.flush() + + @contextmanager + def trigger(self, method): + if self.started or method not in ("sysrq-crash", "keeper-stop"): + raise ValueError("expected one named terminal trigger") + self.started = True + stamp = time.monotonic() + yield # The caller raises on a refused or uncertain dispatch. + self._write(type="crash_trigger", method=method, clock="host_monotonic", + session=self.session, boot_id=self.experimental, t_s=stamp) + self.dispatched = True + + def observe_return(self, *, boot_id, kernel, image): + """Call at identity-probe completion with observed values. Keep failed probes separately.""" + stamp = time.monotonic() + if not self.dispatched or self.returned: + raise ValueError("expected a dispatched trigger and no prior confirmed return") + confirmed = (isinstance(boot_id, str) and bool(boot_id.strip()) + and boot_id not in (self.experimental, self.previous) + and kernel == self.kernel and image == self.image) + self._write(type="production_return", confirmed=confirmed, clock="host_monotonic", + session=self.session, boot_id=boot_id, kernel=kernel, image=image, t_s=stamp) + self.returned = confirmed + return confirmed + + def stage(self, name, phase, boot_id, uptime_s): + """Preserve the boot ID and uptime recorded by the stage producer.""" + self._write(type="stage", stage=name, phase=phase, boot_id=boot_id, + clock="boot_uptime", t_s=uptime_s) diff --git a/scripts/install_boot_usb.py b/scripts/install_boot_usb.py index 8d33251..68cf66b 100644 --- a/scripts/install_boot_usb.py +++ b/scripts/install_boot_usb.py @@ -23,8 +23,10 @@ def validate_install_cmdline(data): """Check both NUL-terminated command-line fields of the legacy v0 header.""" for start, end in ((64, 576), (608, 1632)): for word in data[start:end].split(b"\0", 1)[0].split(): - if word.startswith(TEST_CMDLINE_PREFIXES): - raise FastbootError("RAM-boot-only test image; never install it") + for prefix in TEST_CMDLINE_PREFIXES: + if word.startswith(prefix): + shown = word if len(word) <= 64 and all(33 <= c <= 126 for c in word) else prefix + raise FastbootError(f"RAM-boot-only test image ({shown.decode('ascii')}); never install it") def validate_stock(data): diff --git a/tests/test_boot_install.py b/tests/test_boot_install.py index bba636d..730625e 100644 --- a/tests/test_boot_install.py +++ b/tests/test_boot_install.py @@ -78,7 +78,8 @@ def test_ram_only_cmdline_is_refused_before_connect_or_device_io(self): hashlib.sha256(data).hexdigest(), "--stock-backup", str(stock), "--attempt", str(attempt)]) self.assertEqual(status, 1) - self.assertIn("RAM-boot-only", error.getvalue()) + self.assertIn(f"RAM-boot-only test image ({word.decode('ascii')}); never install it", + error.getvalue()) connector.assert_not_called() self.assertFalse(attempt.exists()) device = Device([]) @@ -87,6 +88,19 @@ def test_ram_only_cmdline_is_refused_before_connect_or_device_io(self): installer.install_boot(fb.Fastboot(device), data, lambda *_a, **_kw: None) self.assertEqual(device.writes, []) + def test_ram_only_diagnostic_limits_the_displayed_word(self): + prefix = b"i14.test=" + limit = prefix.ljust(64, b"x") + for word, shown in ((limit, limit), (limit + b"x", prefix), + (prefix + b"\x1b", prefix), (prefix + b"\xff", prefix)): + data = bytearray(image()) + data[64:64 + len(word)] = word + with self.subTest(word=word): + with self.assertRaises(fb.FastbootError) as error: + installer.validate_install_cmdline(data) + self.assertEqual(str(error.exception), + f"RAM-boot-only test image ({shown.decode('ascii')}); never install it") + def test_stock_backup_must_match_pinned_full_partition(self): for stock in (b"", b"x" * 16384, b"\0" * 0x1000000): with self.subTest(size=len(stock)), self.assertRaises(fb.FastbootError): diff --git a/tests/test_i14_battery_calibrate.py b/tests/test_i14_battery_calibrate.py index 80b3194..7f9ce2c 100644 --- a/tests/test_i14_battery_calibrate.py +++ b/tests/test_i14_battery_calibrate.py @@ -254,6 +254,13 @@ def test_gap_and_deadline_cannot_be_treated_as_continuous_calibration(self): with self.assertRaisesRegex(ValueError, "deadline"): cal.Cycle("boot-a", 0).step(self.sample(32*3600)) + def test_full_window_completed_after_eight_hours_cannot_start_discharge(self): + deadline = 8 * 3600 + for now in range(deadline - 299, deadline, 30): + self.cycle.step(self.sample(now)) + with self.assertRaisesRegex(ValueError, "full-charge deadline"): + self.cycle.step(self.sample(deadline + 1)) + def test_bcct_pause_must_be_in_force_during_discharge(self): self.full() with self.assertRaisesRegex(ValueError, "BCCT"): diff --git a/tests/test_i14_calibration_launch.py b/tests/test_i14_calibration_launch.py index 78bce0e..92b4195 100644 --- a/tests/test_i14_calibration_launch.py +++ b/tests/test_i14_calibration_launch.py @@ -57,6 +57,24 @@ def test_background_allowance_covers_hard_c13_guard_log_bound_before_other_write with self.assertRaisesRegex(ValueError,'C13 guard log allowance'): launch.validate_gate(value,NOW) + def test_fixed_observer_overhead_must_be_funded(self): + value = gate() + value['storage']['observer_fixed_bytes'] = launch.MIB - 1 + with self.assertRaisesRegex(ValueError, 'observer'): + launch.validate_gate(value, NOW) + + def test_free_space_must_come_from_the_userdata_backing_device(self): + with mock.patch.object(launch, 'BASE', self.root), \ + mock.patch.object(Path, 'read_text', autospec=True) as uevent, \ + mock.patch.object(launch.os, 'fstatvfs', return_value=SimpleNamespace(f_bavail=3, f_frsize=4096)): + uevent.return_value = 'PARTNAME=userdata\n' + self.assertEqual(launch.userdata_free_bytes(), 12288) + dev = self.root.stat().st_dev + uevent.assert_called_once_with(Path(f'/sys/dev/block/{launch.os.major(dev)}:{launch.os.minor(dev)}/uevent')) + uevent.return_value = 'PARTNAME=other\n' + with self.assertRaisesRegex(ValueError, 'userdata'): + launch.userdata_free_bytes() + def test_record_and_gate_limits_refuse_before_replacing_or_reading(self): path=self.root/'record.json'; path.write_text('{}') with mock.patch.object(launch,'MAX_RECORD_BYTES',8): @@ -193,6 +211,14 @@ def test_wrapper_restoration_receipt_never_equals_full_restoration_acceptance(se self.assertEqual(record['attempts'],1) self.assertFalse(receipt['restoration_accepted']) self.assertEqual(receipt['production_start_rc'],restore_rc) + self.assertEqual(receipt['exit_code'] == 0, want == 'awaiting_review') + + def test_missing_result_cannot_exit_successfully(self): + state = self.root / 'campaign.json' + launch.reserve_attempt(state, gate(), NOW, 'a'*64) + finished = launch.finish_attempt(state, 1, 0, self.root/'result.json', 0, NOW+1) + self.assertEqual(finished['state'], 'stopped') + self.assertNotEqual(finished['exit_code'], 0) def test_supervision_exception_terminates_verified_child_and_restores_after_reap(self): control=self.root/'held' @@ -252,6 +278,24 @@ def test_unreapable_child_is_an_explicit_owned_hold_not_restored_or_retryable(se self.assertFalse(receipt['experiment_gone']) self.assertIsNone(receipt['production_start_rc']) + def test_reaped_timeout_and_missing_pid_do_not_override_a_live_measurement_lock(self): + control = self.root / 'lock-held' + with (self.root/'measurement.lock').open('a') as lock: + launch.fcntl.flock(lock, launch.fcntl.LOCK_EX) + with self.assertRaises(BlockingIOError): + self.run_wrapper(control, 0, 0) + record = json.loads((control/'campaign.json').read_text()) + self.assertEqual(record['state'], 'stopping') + self.assertIsNone(record['production_start_rc']) + self.assertNotEqual(record['exit_code'], 0) + + def test_userdata_at_reserve_stops_even_if_child_returns_zero(self): + control = self.root / 'space-floor' + self.run_wrapper(control, 0, 0, scenario='space-floor') + record = json.loads((control/'campaign.json').read_text()) + self.assertEqual(record['state'], 'stopped') + self.assertNotEqual(record['exit_code'], 0) + def run_wrapper(self,control,child_rc,restore_rc,live=False,missed=False,scenario=None): bundle=self.root/('bundle-'+control.name) launch.build_bundle(bundle) @@ -301,11 +345,13 @@ def restore(*args): with mock.patch.object(launch,'__file__',str(bundle/'launcher.py')), \ mock.patch.object(launch,'CODE',bundle),mock.patch.object(launch,'CONTROL',control), \ mock.patch.object(launch,'BASE',base), \ + mock.patch.object(launch,'MEASUREMENT_LOCK',self.root/'measurement.lock'), \ mock.patch.object(launch,'live_preflight',return_value={'boot_id':BOOT}), \ mock.patch.object(launch.time,'time',side_effect=lambda:clock['wall']), \ mock.patch.object(launch.time,'monotonic',side_effect=lambda:clock['mono']), \ mock.patch.object(launch.subprocess,'Popen',side_effect=spawn), \ - mock.patch.object(launch.os,'statvfs',return_value=SimpleNamespace(f_bavail=10**9,f_frsize=4096)), \ + mock.patch.object(launch,'userdata_free_bytes',return_value=launch.RESERVE_BYTES + + (0 if scenario == 'space-floor' else 1)), \ mock.patch.object(launch,'measurement_pid',side_effect=lambda *a:123456 if not done[0] else None), \ mock.patch.object(launch.os,'kill',side_effect=lambda *args:signals.append(args)), \ mock.patch.object(launch,'service',side_effect=restore): diff --git a/tests/test_i14_dns_probe.py b/tests/test_i14_dns_probe.py new file mode 100644 index 0000000..2665da2 --- /dev/null +++ b/tests/test_i14_dns_probe.py @@ -0,0 +1,142 @@ +"""DNS wire fixtures: invalid replies must never become successful soak samples.""" +import importlib.util +from pathlib import Path +import struct +import unittest +from unittest.mock import patch + + +def load_probe(): + path = Path(__file__).resolve().parents[1] / 'scripts/i14-dns-soak.py' + spec = importlib.util.spec_from_file_location('probe', path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + module.SERVER = '192.0.2.10' + return module + + +probe = load_probe() +QUESTION = b'\x0ai14-health\x07invalid\0\0\x01\0\x01' +ANSWER = b'\xc0\x0c\0\x01\0\x01\0\0\0\x3c\0\x04\xc0\0\x02\x01' + + +def reply(*, flags=0x8180, ident=0x1234, answers=1, answer=ANSWER, question=QUESTION): + return struct.pack('>HHHHHH', ident, flags, 1, answers, 0, 0) + question + answer + + +class Socket: + def __init__(self, packets): + self.packets = iter(packets) + + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + def settimeout(self, value): + pass + + def connect(self, address): + pass + + def send(self, data): + return len(data) + + def sendto(self, data, address): + return len(data) + + def sendall(self, data): + pass + + def recv(self, count): + # Bound an old EOF loop in the RED test without leaving a hanging test. + try: + return next(self.packets) + except StopIteration: + raise TimeoutError('fixture exhausted after EOF') + + +class ProbeTests(unittest.TestCase): + def query(self, packets, tcp=False, name='i14-health.invalid'): + sock = Socket(packets) + with patch.object(probe.socket, 'socket', return_value=sock), \ + patch.object(probe.socket, 'create_connection', return_value=sock), \ + patch.object(probe.random, 'randint', return_value=0x1234): + return probe.query(name, tcp=tcp).split(',')[0] + + def test_health_answer(self): + self.assertEqual(self.query([reply()]), 'NOERROR') + + def test_empty_noerror_is_not_health(self): + self.assertEqual(self.query([reply(answers=0, answer=b'')]), 'ERROR:ValueError') + + def test_wrong_health_address(self): + self.assertEqual(self.query([reply(answer=ANSWER[:-1] + b'\x02')]), 'ERROR:ValueError') + + def test_unrelated_owner_with_expected_health_address_is_rejected(self): + answer = b'\x05other\x07invalid\0' + ANSWER[2:] + self.assertEqual(self.query([reply(answer=answer)]), 'ERROR:ValueError') + + def test_self_referencing_owner_pointer_is_rejected(self): + self.assertEqual(self.query([reply(answer=b'\xc0\x24' + ANSWER[2:])]), 'ERROR:ValueError') + + def test_out_of_bounds_owner_pointer_is_rejected(self): + self.assertEqual(self.query([reply(answer=b'\xff\xff' + ANSWER[2:])]), 'ERROR:ValueError') + + def test_nested_owner_compression_is_accepted(self): + answers = ANSWER + b'\xc0\x24' + ANSWER[2:] + self.assertEqual(self.query([reply(answers=2, answer=answers)]), 'NOERROR') + + def test_owner_names_are_case_insensitive(self): + answer = b'\x0aI14-HEALTH\x07INVALID\0' + ANSWER[2:] + self.assertEqual(self.query([reply(answer=answer)]), 'NOERROR') + + def test_real_name_probe_rejects_an_unrelated_a_record(self): + answer = b'\x05other\x07invalid\0' + ANSWER[2:] + question = b'\x05alias\x07invalid\0\0\x01\0\x01' + self.assertEqual(self.query([reply(question=question, answer=answer)], name='alias.invalid'), 'ERROR:ValueError') + + def test_real_name_probe_accepts_a_cname_chain(self): + question = b'\x05alias\x07invalid\0\0\x01\0\x01' + target = b'\x06target\x07invalid\0' + cname = b'\xc0\x0c\0\x05\0\x01\0\0\0\x3c\0\x10' + target + answer = target + ANSWER[2:] + self.assertEqual(self.query([reply(question=question, answers=2, answer=cname + answer)], name='alias.invalid'), 'NOERROR') + + def test_wrong_transaction(self): + self.assertEqual(self.query([reply(ident=0x5678)]), 'ERROR:ValueError') + + def test_query_packet_is_not_a_response(self): + self.assertEqual(self.query([reply(flags=0x0100)]), 'ERROR:ValueError') + + def test_truncated_udp_reply(self): + self.assertEqual(self.query([reply(flags=0x8380)]), 'ERROR:ValueError') + + def test_incomplete_answer(self): + self.assertEqual(self.query([reply(answer=ANSWER[:-1])]), 'ERROR:ValueError') + + def test_tcp_fragmented_length_and_body(self): + data = reply() + size = struct.pack('>H', len(data)) + self.assertEqual(self.query([size[:1], size[1:], data[:7], data[7:]], tcp=True), 'NOERROR') + + def test_tcp_eof_during_body_is_terminal(self): + self.assertEqual(self.query([b'\0\x3c', b'\x12\x34', b'', b''], tcp=True), 'ERROR:EOFError') + + def test_tcp_eof_during_length_is_terminal(self): + self.assertEqual(self.query([b''], tcp=True), 'ERROR:EOFError') + + def test_servfail_without_answer_is_preserved(self): + self.assertEqual(self.query([reply(flags=0x8182, answers=0, answer=b'')]), 'SERVFAIL') + + def test_ad_flag_is_preserved(self): + self.assertEqual(self.query([reply(flags=0x81A0)]), 'NOERROR+AD') + + def test_tcp_deadline_is_shared_across_fragments(self): + with patch.object(probe.time, 'monotonic', side_effect=[0, 0, 4, 6, 6]): + self.assertEqual(self.query([b'\0', b'\x3c', b'\x12'], tcp=True), 'ERROR:TimeoutError') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_i14_h1.py b/tests/test_i14_h1.py index 9b282cf..ead7732 100644 --- a/tests/test_i14_h1.py +++ b/tests/test_i14_h1.py @@ -51,6 +51,12 @@ def test_reused_pid_and_reversed_cpu_are_rejected(self): with self.subTest(delta=delta), self.assertRaises(ValueError): h1.idle_result(before, after, 100) + def test_idle_rejects_pid_reused_since_owner_selected_child(self): + with mock.patch.object(h1, "snapshot", return_value={"start_ticks": 901}), \ + mock.patch.object(h1, "idle_wait") as wait, self.assertRaises(ValueError): + h1.idle_sample(42, 900, lambda: 0) + wait.assert_not_called() + def test_idle_waits_sixty_seconds_and_refuses_screen_on(self): clock = Clock() h1.idle_wait(lambda: 0, clock.now, clock.sleep) diff --git a/tests/test_i14_h1_owner.py b/tests/test_i14_h1_owner.py index df13e81..80a0b54 100644 --- a/tests/test_i14_h1_owner.py +++ b/tests/test_i14_h1_owner.py @@ -154,10 +154,12 @@ def test_timeout_preserves_child_frames_and_existing_result_before_raising(self) def test_idle_always_requests_fresh_process_for_both_implementations(self): instance=owner.Owner.__new__(owner.Owner);instance.h1=SimpleNamespace(light=lambda:0) - instance.ready=mock.Mock();instance.select=mock.Mock(return_value={'child':{'pid':42}}) - with mock.patch.object(owner,'payload'): + instance.ready=mock.Mock();instance.select=mock.Mock(return_value={'child':{'pid':42,'start_ticks':912}}) + with mock.patch.object(owner,'payload') as measure: instance.idle('ui','rust',Path('/run/h1-idle.json')) instance.select.assert_called_once_with('ui','rust',restart=True) + argv = measure.call_args.args[0] + self.assertEqual(argv[argv.index('--start-ticks') + 1], '912') def test_measurement_failure_stops_after_logging_payload_status(self): self.assertIsNotNone(owner) diff --git a/tests/test_i14_hardening.py b/tests/test_i14_hardening.py index 451ec9b..9f1b5f7 100644 --- a/tests/test_i14_hardening.py +++ b/tests/test_i14_hardening.py @@ -127,27 +127,49 @@ def test_isolation_failure_quiesces_interfaces_and_services(self): self.assertIn(f"rc-service -D {service} stop", log) self.assertNotIn("--dport", log) + +class DnsClientPolicy(unittest.TestCase): + paths = ("etc/i14/firewall.rules", "etc/unbound/unbound.conf") + + def render(self, contents): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + root = pathlib.Path(directory.name) + for path in self.paths: + (root / path).parent.mkdir(parents=True) + (root / path).write_bytes((O / path).read_bytes()) + clients = root / "clients" + if contents is not None: + clients.write_text(contents) + result = subprocess.run([sys.executable, ROOT / "rootfs/configure-dns.py", root, clients], + capture_output=True, text=True) + return result, [(root / path).read_text() for path in self.paths] + def test_dns_sources_render_to_both_services(self): - with tempfile.TemporaryDirectory() as directory: - d = pathlib.Path(directory) - for path in ("etc/i14/firewall.rules", "etc/unbound/unbound.conf"): - (d / path).parent.mkdir(parents=True, exist_ok=True) - (d / path).write_bytes((O / path).read_bytes()) - clients = d / "clients" - clients.write_text("192.0.2.20/32 # example\n198.51.100.8/29\n") - tool = ROOT / "rootfs/configure-dns.py" - result = subprocess.run([sys.executable, tool, d, clients], capture_output=True, text=True) - self.assertEqual(result.returncode, 0, result.stderr) - firewall = (d / "etc/i14/firewall.rules").read_text() - unbound = (d / "etc/unbound/unbound.conf").read_text() - for cidr in ("192.0.2.20/32", "198.51.100.8/29"): - self.assertIn(f"-A I14_DNS -s {cidr} -j ACCEPT", firewall) - self.assertIn(f"access-control: {cidr} allow", unbound) - for invalid in ("0.0.0.0/0", "2001:db8::1/128", "192.0.2.7/24", "x; echo ignored"): - clients.write_text(invalid) - result = subprocess.run([sys.executable, tool, d, clients], capture_output=True) - self.assertNotEqual(result.returncode, 0, invalid) - self.assertEqual((d / "etc/i14/firewall.rules").read_text(), firewall) + result, (firewall, unbound) = self.render("192.0.2.20/32 # example\n198.51.100.8/29\n") + self.assertEqual(result.returncode, 0, result.stderr) + for cidr in ("192.0.2.20/32", "198.51.100.8/29"): + self.assertIn(f"-A I14_DNS -s {cidr} -j ACCEPT", firewall) + self.assertIn(f"access-control: {cidr} allow", unbound) + + def test_invalid_dns_clients_leave_both_templates_unchanged(self): + for invalid in ("0.0.0.0/0", "127.0.0.0/8", "2001:db8::1/128", "192.0.2.7/24", "x; echo ignored"): + with self.subTest(invalid=invalid): + result, configs = self.render(invalid) + self.assertNotEqual(result.returncode, 0) + self.assertIn("Invalid IPv4 client network at line 1", result.stderr) + self.assertEqual(configs, [(O / path).read_text() for path in self.paths]) + + def test_empty_dns_clients_allow_only_local_queries(self): + for contents in (None, "", "\n # no clients\n"): + with self.subTest(contents=contents): + result, (firewall, unbound) = self.render(contents) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("# I14_DNS_CLIENTS", firewall + unbound) + self.assertNotIn("-A I14_DNS ", firewall) + self.assertEqual([line.strip() for line in unbound.splitlines() + if line.strip().startswith("access-control:")], + ["access-control: 0.0.0.0/0 refuse", "access-control: 127.0.0.0/8 allow"]) class Dns(unittest.TestCase): diff --git a/tests/test_i14_k70_recovery_timing.py b/tests/test_i14_k70_recovery_timing.py index 2aa28c7..8853ce9 100644 --- a/tests/test_i14_k70_recovery_timing.py +++ b/tests/test_i14_k70_recovery_timing.py @@ -23,8 +23,8 @@ IMAGE = "alpine-v10c-img" -def load_module(): - spec = importlib.util.spec_from_file_location("i14_k70_recovery_timing_test", SCRIPT) +def load_module(path=SCRIPT): + spec = importlib.util.spec_from_file_location(path.stem, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module @@ -123,6 +123,55 @@ def test_just_over_40_seconds_is_over_limit(self): self.assertEqual(output["verdict"], "OVER_LIMIT") self.assertEqual(output["recovery"]["duration_s"], 40.001) + def test_submicrosecond_overrun_is_over_limit(self): + code, output = self.run_main(records(1000, 1040.0000004)) + self.assertEqual(code, 1) + self.assertGreater(output["recovery"]["duration_unrounded_s"], 40) + + def test_captures_both_triggers_and_first_confirmed_new_boot(self): + writer = load_module(SCRIPT.with_name("i14_k70_capture.py")) + for method in ("sysrq-crash", "keeper-stop"): + with self.subTest(method=method), (self.root/method).open("x") as trace: + capture = writer.RecoveryCapture(trace, previous_boot="previous", experimental_boot=EXP_BOOT, + kernel=KERNEL, image=IMAGE) + with mock.patch.object(writer.time, "monotonic", side_effect=[100, 110, 120, 125, 130, 140]): + with capture.trigger(method): + pass + for boot, kernel, image in (("previous", KERNEL, IMAGE), (EXP_BOOT, KERNEL, IMAGE), + (PROD_BOOT, "other", IMAGE), (PROD_BOOT, KERNEL, "other")): + self.assertFalse(capture.observe_return(boot_id=boot, kernel=kernel, image=image)) + self.assertTrue(capture.observe_return(boot_id=PROD_BOOT, kernel=KERNEL, image=IMAGE)) + for item in valid_stages(): + capture.stage(item["stage"], item["phase"], item["boot_id"], item["t_s"]) + code, output = self.run_main(Path(trace.name).read_text()) + self.assertEqual(code, 0) + self.assertEqual(output["recovery"]["trigger_method"], method) + self.assertEqual(output["recovery"]["duration_s"], 40) + self.assertEqual(output["diagnostics"]["unconfirmed_returns"], 4) + self.assertEqual(output["stage_evidence"], "valid") + + def test_refused_dispatch_leaves_an_incomplete_trace_and_disallows_retry(self): + writer = load_module(SCRIPT.with_name("i14_k70_capture.py")) + stream = io.StringIO() + capture = writer.RecoveryCapture(stream, previous_boot="previous", experimental_boot=EXP_BOOT, + kernel=KERNEL, image=IMAGE) + with self.assertRaises(OSError), capture.trigger("sysrq-crash"): + raise OSError("dispatch unconfirmed") + with self.assertRaises(ValueError), capture.trigger("sysrq-crash"): + self.fail("retried") + with self.assertRaises(ValueError): + capture.observe_return(boot_id=PROD_BOOT, kernel=KERNEL, image=IMAGE) + self.assertEqual(self.run_main(stream.getvalue())[1]["verdict"], "INCOMPLETE") + + def test_external_trace_rejects_old_production_boot_and_unknown_trigger(self): + trace = records() + trace[0]["previous_production_boot_id"] = PROD_BOOT + trace[1]["method"] = "reboot" + code, output = self.run_main(trace) + self.assertEqual(code, 2) + self.assertIn("previous_production_boot", self.reasons(output)) + self.assertIn("unknown_trigger_method", self.reasons(output)) + def test_historical_70_6_seconds_is_over_limit(self): code, output = self.run_main(records(1000.0, 1070.6)) self.assertEqual(code, 1) @@ -356,8 +405,11 @@ def test_missing_and_malformed_evidence_together_is_inconsistent(self): def test_record_limits_are_enforced(self): with mock.patch.object(self.module, "MAX_RECORDS", 2): code, output = self.run_main(records()) - self.assertEqual(code, 2) - self.assertIn("too_many_records", self.reasons(output)) + self.assertEqual(code, 2) + self.assertIn("too_many_records", self.reasons(output)) + code, output = self.run_main("\n\n\n") + self.assertEqual(code, 2) + self.assertIn("too_many_records", self.reasons(output)) with mock.patch.object(self.module, "MAX_TRACE_BYTES", 16): code, output = self.run_main(records()) self.assertEqual(code, 2) @@ -408,8 +460,7 @@ def test_duplicate_stage_endpoints_are_called_out_separately(self): self.assertEqual(code, 0) self.assertIn("duplicate_stage_start", self.stage_reasons(output)) self.assertIn("duplicate_stage_end", self.stage_reasons(output)) - self.assertEqual(output["stages"][0]["start_uptime_s"], 0.2) - self.assertEqual(output["stages"][1]["end_uptime_s"], 6.5) + self.assertEqual([item["stage"] for item in output["stages"]], ["mdev_coldplug"]) def test_unpaired_stages_are_called_out_and_never_measured(self): trace = records() + [stage("early_init", "start", 0.2), diff --git a/tests/test_i14_rootfs_swap.py b/tests/test_i14_rootfs_swap.py new file mode 100644 index 0000000..7737c67 --- /dev/null +++ b/tests/test_i14_rootfs_swap.py @@ -0,0 +1,334 @@ +"""Local files only. Exercise the host CLI against the actual initramfs and watcher records.""" +import fcntl +import hashlib +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +from test_i14_rootfs_rollback import ROOT, WATCHER, boot + +SCRIPT = ROOT / "scripts/i14-rootfs-swap.py" +BOOT = "02fc6e24-8d75-462a-8865-21f3ffeaa305" +OTHER_BOOT = "247c7dbb-7624-45f7-b7de-3842ef789d32" +STAMP = "src=abc123 at=20261123T123456Z" +KEY = b";;last_queried: 1\n. IN DNSKEY 257 3 8 PUBLIC\n" +OLD, NEW = b"OLD image\n", b"NEW image\n" + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +class TrialFiles(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.base = Path(self.tmp.name) + self.data = self.base / "data" + self.data.mkdir() + self.state = self.base / "state.json" + self.root = self.base / "candidate-root" + (self.root / "etc").mkdir(parents=True) + self.live_key = self.root / "var/lib/unbound/root.key" + self.live_key.parent.mkdir(parents=True) + self.live_key.write_bytes(KEY) + self.stamp = self.root / "etc/i14-rootfs-id" + self.stamp.write_text(STAMP + "\n") + self.digest = self.root / "etc/i14-rootfs-root-key.sha256" + self.digest.write_text(sha(KEY) + "\n") + self.active = self.data / "rootfs.img" + self.prev = self.data / "rootfs-prev.img" + self.new = self.data / "rootfs.img.new" + self.trial = self.data / "rootfs-trial.img" + self.marker = self.data / "rootfs-trial" + self.ack = self.data / "rootfs-trial-ack" + self.confirmed = self.data / "rootfs-trial-confirmed" + self.receipt = self.data / "rootfs-trial-root-key-receipt" + self.capture = self.data / f"rootfs-trial-root-key.{BOOT}" + self.active.write_bytes(OLD) + os.link(self.active, self.prev) + self.new.write_bytes(NEW) + + def cli(self, command, *extra, ok=True): + self.assertTrue(SCRIPT.is_file(), "host swap CLI is missing") + args = [sys.executable, "-B", str(SCRIPT), command, "--data", str(self.data), + "--state", str(self.state)] + if command in ("stage", "start"): + args += ["--previous-sha256", sha(OLD), "--candidate-sha256", sha(NEW), + "--root-key-sha256", sha(KEY), "--stamp", STAMP, "--root", str(self.root)] + elif command in ("verify-trial", "verify-ack", "verify-confirmed"): + args += ["--root", str(self.root), "--boot-id", BOOT] + r = subprocess.run([*args, *extra], capture_output=True, text=True, timeout=8) + if ok: + self.assertEqual(r.returncode, 0, r.stderr) + else: + self.assertNotEqual(r.returncode, 0, r.stdout) + self.assertNotIn("Traceback", r.stderr) + return r.stdout + + def started(self): + self.cli("stage") + self.cli("verify-staged") + self.assertEqual(boot(self.base)[0], ["mounted NEW", "booted"]) + (self.base / "boot-id").write_text(BOOT + "\n") + # Use the watcher's own pre-OpenRC capture, including its three-line receipt. + self.watcher('root_key_capture') + self.live_key.write_bytes(b"Unbound advanced its RFC5011 state\n") + + def watcher(self, action): + source = WATCHER.read_text().split('\ncase "$1" in\nstart)')[0] + env = dict(os.environ, I14_TRIAL_DIR=str(self.data), I14_TRIAL_ROOT=str(self.root), + I14_BOOT_ID=str(self.base / "boot-id"), I14_UPTIME=str(self.base / "uptime"), + I14_TRIAL_CONF=str(self.base / "test.conf")) + # Portable sha256sum for macOS. No logging or global sync during a fixture. + (self.base / "uptime").write_text("620.00 0\n") + action = ('\nsha256sum() { shasum -a 256 "$@"; }\nsync() { :; }\n' + 'log() { :; }\n' + action) + r = subprocess.run(["sh", "-c", source + action], env=env, capture_output=True, text=True, timeout=8) + self.assertEqual(r.returncode, 0, r.stderr) + + def acknowledge(self): + nonce = json.loads(self.state.read_bytes())["nonce"] + self.ack.write_text(f"ack {nonce} {BOOT}\n") + + def rolled_back(self): + self.cli("stage") + for _ in range(2): + self.assertEqual(boot(self.base)[0], ["mounted NEW", "booted"]) + self.assertEqual(boot(self.base)[0], ["mounted OLD", "booted"]) + + def refused_stage(self, *args): + self.cli("stage", *args, ok=False) + self.assertEqual(self.active.read_bytes(), OLD) + self.assertFalse(self.marker.exists()) + self.assertFalse(self.state.exists()) + + def test_stage_links_images_and_writes_exact_initramfs_record(self): + previous, candidate = self.active.stat().st_ino, self.new.stat().st_ino + self.cli("start") + self.assertEqual(self.prev.stat().st_ino, previous) + self.assertEqual(self.active.stat().st_ino, candidate) + self.assertTrue(self.active.samefile(self.trial)) + self.assertFalse(self.new.exists()) + nonce = json.loads(self.state.read_bytes())["nonce"] + self.assertEqual(self.state.stat().st_mode & 0o777, 0o600) + text = f"trial 0 {STAMP} ack={sha(nonce.encode())}".encode() + self.assertEqual(self.marker.read_bytes(), text.ljust(511) + b"\n") + self.cli("verify-staged") + self.cli("stage", ok=False) + self.cli("verify-staged") + + def test_free_floor_leaves_active_image_untouched(self): + self.refused_stage("--min-free-bytes", str(2**63)) + + def test_concurrent_stage_is_refused(self): + fd = os.open(self.data, os.O_RDONLY) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + self.refused_stage() + finally: + os.close(fd) + + def test_interrupted_final_rename_keeps_recoverable_trial(self): + swap = runpy.run_path(str(SCRIPT)) + args = ["stage", "--data", str(self.data), "--state", str(self.state), "--root", str(self.root), + "--stamp", STAMP, "--previous-sha256", sha(OLD), "--candidate-sha256", sha(NEW), + "--root-key-sha256", sha(KEY)] + with patch("os.replace", side_effect=OSError("interrupted final rename")): + with patch("sys.stderr") as stderr: + self.assertEqual(swap["main"](args), 1) + self.assertIn("interrupted final rename", str(stderr.write.call_args_list)) + self.assertTrue(self.active.samefile(self.prev)) + self.assertTrue(self.new.samefile(self.trial)) + self.assertEqual(self.marker.stat().st_size, 512) + self.cli("verify-staged", ok=False) + self.assertEqual(boot(self.base)[0], ["mounted OLD", "booted"]) + self.cli("verify-rollback") + self.cli("verify-rollback", "--rehearsal", ok=False) + + def test_missing_previous_image(self): + self.prev.unlink() + self.refused_stage() + + def test_candidate_colliding_with_b5(self): + self.new.unlink() + os.link(self.prev, self.new) + self.refused_stage("--candidate-sha256", sha(OLD)) + + def test_previous_must_be_the_active_b5_inode(self): + self.prev.unlink() + self.prev.write_bytes(OLD) + self.refused_stage() + + def test_independent_image_or_key_pin_mismatch(self): + for arg in ("--previous-sha256", "--candidate-sha256", "--root-key-sha256"): + with self.subTest(arg=arg): + self.refused_stage(arg, "0" * 64) + + def test_wrong_staged_key_or_stamp(self): + self.live_key.write_bytes(b"changed") + self.refused_stage() + self.live_key.write_bytes(KEY) + self.refused_stage("--stamp", "src=other at=T") + + def test_symlink_inputs_and_intermediate_root_directories(self): + for path in (self.active, self.new, self.prev, self.live_key, self.root / "etc"): + with self.subTest(path=path): + original = path.with_name(path.name + ".saved") + path.rename(original) + path.symlink_to(original) + self.refused_stage() + path.unlink() + original.rename(path) + + def test_refuses_old_trial_names_including_dangling_links(self): + for path in (self.trial, self.ack, self.confirmed, self.receipt, self.capture, + self.data / "rootfs-trial-ack.new", self.data / "rootfs-trial.new", + self.data / "rootfs-trial.log"): + with self.subTest(path=path): + path.symlink_to(self.base / "missing-target") + self.refused_stage() + path.unlink() + + def test_evidence_cannot_be_stored_on_userdata_or_overwritten(self): + self.cli("stage", "--state", str(self.data / "secret"), ok=False) + self.assertFalse((self.data / "secret").exists()) + self.state.write_bytes(b"previous trial\n") + self.cli("stage", ok=False) + self.assertEqual(self.state.read_bytes(), b"previous trial\n") + self.assertEqual(self.active.read_bytes(), OLD) + + def test_staged_verification_rejects_replaced_trial_and_modified_candidate(self): + self.cli("stage") + self.trial.unlink() + self.trial.write_bytes(NEW) + self.cli("verify-staged", ok=False) + self.trial.unlink() + os.link(self.active, self.trial) + self.active.write_bytes(b"wrong") + self.cli("verify-staged", ok=False) + + def test_verify_staged_refuses_stale_boot_receipt_and_short_record(self): + self.cli("stage") + self.receipt.write_bytes(b"stale\n") + self.cli("verify-staged", ok=False) + self.receipt.unlink() + self.marker.write_bytes(self.marker.read_bytes().rstrip() + b"\n") + self.cli("verify-staged", ok=False) + + def test_dangling_active_record_or_symlinked_key_cannot_confirm(self): + self.started() + self.acknowledge() + self.watcher('confirm "$(marker)"') + self.marker.symlink_to(self.base / "missing-target") + self.cli("verify-confirmed", ok=False) + self.marker.unlink() + saved = self.base / "saved-key" + self.capture.rename(saved) + self.capture.symlink_to(saved) + self.cli("verify-confirmed", ok=False) + + def test_real_init_rollback_preserves_both_original_inodes(self): + self.rolled_back() + self.cli("verify-rollback", "--rehearsal", "--check-restored-sha256") + self.active.write_bytes(b"changed after boot\n") + self.cli("verify-rollback", "--check-restored-sha256", ok=False) + self.acknowledge() + self.cli("verify-rollback", "--rehearsal", ok=False) + + def test_verify_requires_independent_private_evidence(self): + self.cli("stage") + counterfeit = self.data / "copied-state" + counterfeit.write_bytes(self.state.read_bytes()) + counterfeit.chmod(0o600) + self.cli("verify-staged", "--state", str(counterfeit), ok=False) + self.state.chmod(0o644) + self.cli("verify-staged", ok=False) + + def test_rollback_record_with_candidate_still_active(self): + self.rolled_back() + self.active.unlink() + os.link(self.trial, self.active) + self.cli("verify-rollback", ok=False) + + def test_rollback_without_original_failed_candidate_inode(self): + self.rolled_back() + self.trial.rename(self.data / "kept-for-test") + self.cli("verify-rollback", ok=False) + self.trial.write_bytes(NEW) + self.cli("verify-rollback", ok=False) + + def test_rollback_with_copied_previous_inode(self): + self.rolled_back() + self.active.rename(self.data / "kept-for-test") + self.active.write_bytes(OLD) + self.cli("verify-rollback", ok=False) + + def test_rollback_requires_current_trial_record_and_consumed_prev(self): + self.rolled_back() + os.link(self.active, self.prev) + self.cli("verify-rollback", ok=False) + self.prev.unlink() + self.marker.write_bytes(self.marker.read_bytes().replace(b"ack=", b"old=")) + self.cli("verify-rollback", ok=False) + + def test_boot_receipt_and_ack_match_real_watcher(self): + self.started() + self.cli("verify-trial") + self.cli("verify-staged", ok=False) + self.cli("verify-ack", ok=False) + self.acknowledge() + self.cli("verify-ack") + self.watcher('ack_ok "$(marker)" && root_key_ok && confirm "$(marker)"') + self.cli("verify-confirmed") + self.cli("verify-trial", ok=False) + + def test_incorrect_receipt_or_boot_metadata(self): + self.started() + for path in (self.capture, self.receipt, self.digest, self.stamp): + with self.subTest(path=path): + saved = path.read_bytes() + path.unlink() + self.cli("verify-trial", ok=False) + path.write_bytes(b"tampered\n") + self.cli("verify-trial", ok=False) + path.write_bytes(saved) + self.cli("verify-trial", "--boot-id", OTHER_BOOT, ok=False) + self.cli("verify-trial", "--boot-id", "../escape", ok=False) + for field in ("root_key_boot", "root_key_stamp", "root_key_sha256"): + with self.subTest(field=field): + saved = self.receipt.read_bytes() + self.receipt.write_bytes(saved.replace((field + "=").encode(), (field + "=old").encode())) + self.cli("verify-trial", ok=False) + self.receipt.write_bytes(saved) + + def test_ack_must_match_independent_boot_and_nonce(self): + self.started() + self.acknowledge() + saved = self.ack.read_text() + for invalid in (saved.replace(BOOT, OTHER_BOOT), saved.replace("ack ", "ack wrong"), saved + saved): + self.ack.write_text(invalid) + self.cli("verify-ack", ok=False) + self.ack.write_text(saved) + self.marker.write_bytes(self.marker.read_bytes().replace(b"ack=", b"bad=")) + self.cli("verify-ack", ok=False) + + def test_incomplete_or_replayed_confirmation(self): + self.started() + self.acknowledge() + old = self.marker.read_bytes() + self.watcher('confirm "$(marker)"') + self.marker.write_bytes(old) + self.cli("verify-confirmed", ok=False) + self.marker.unlink() + record = self.confirmed.read_text() + for invalid in (record.replace(BOOT, OTHER_BOOT), record.replace("trial 1", "trial 0"), + record.replace("ack=", "old="), record + record): + self.confirmed.write_text(invalid) + self.cli("verify-confirmed", ok=False) diff --git a/tests/test_i14_soak_local_collector.py b/tests/test_i14_soak_local_collector.py new file mode 100644 index 0000000..b38cd2a --- /dev/null +++ b/tests/test_i14_soak_local_collector.py @@ -0,0 +1,265 @@ +"""Local fixtures only; no phone, real cron, network or live logs.""" +import importlib.util +from pathlib import Path +import tempfile +import unittest +import os +import stat +import json +import hashlib +import time +import signal +from datetime import timedelta +from unittest.mock import patch + +SOURCE = Path(__file__).resolve().parents[1] / "scripts/i14-soak-local-collector.py" +collector = None +if SOURCE.is_file(): + spec = importlib.util.spec_from_file_location("local_collector", SOURCE) + collector = importlib.util.module_from_spec(spec) + spec.loader.exec_module(collector) + +BOOT = "00000000-0000-4000-8000-000000000014" + + +class LocalCollector(unittest.TestCase): + def setUp(self): + self.assertIsNotNone(collector, "local collector not implemented") + + def test_copy_preserves_required_bytes_and_optional_absence(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + source = root / "source" + target = root / "capture" + source.mkdir() + target.mkdir() + (source / "messages").write_bytes(b"Nov 15 18:00:00 i14 raw\n") + (source / "i14-battery.log").write_bytes(b"2026-11-15 18:00:00 raw\n") + result = collector.copy_logs(source, target, 4096) + self.assertFalse(result["failed"]) + self.assertEqual((target / "messages").read_bytes(), (source / "messages").read_bytes()) + self.assertIn("messages.4", result["absent"]) + self.assertFalse((target / "messages.4").exists()) + + def test_missing_required_log_is_failure_not_empty_success(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + source = root / "source" + target = root / "capture" + source.mkdir() + target.mkdir() + result = collector.copy_logs(source, target, 4096) + self.assertIn("messages(absent)", result["failed"]) + self.assertFalse((target / "messages").exists()) + + def test_unexpected_symlink_and_budget_are_refused_without_copy(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + source = root / "source" + target = root / "capture" + source.mkdir() + target.mkdir() + private = root / "private" + private.write_bytes(b"must not copy\n") + (source / "messages").symlink_to(private) + (source / "i14-battery.log").write_bytes(b"x" * 100) + result = collector.copy_logs(source, target, 20) + self.assertIn("messages(read)", result["failed"]) + self.assertIn("i14-battery.log(budget)", result["failed"]) + self.assertFalse((target / "messages").exists()) + self.assertFalse((target / "i14-battery.log").exists()) + + def test_manual_flag_cannot_prove_root_cron(self): + rows = [{"pid": 2, "uid": 0, "comm": "sshd"}] + self.assertFalse(collector.cron_origin(rows)) + self.assertFalse(collector.cron_origin([{"pid": 2, "uid": 1000, "comm": "crond"}])) + self.assertTrue(collector.cron_origin([{"pid": 2, "uid": 0, "comm": "crond"}])) + + def test_expiry_count_and_storage_limits_are_terminal(self): + config = {"expires_epoch": 200, "max_captures": 2, "max_bytes": 1000, + "reserve_bytes": 100, "capture_bytes": 200} + collector.check_limits(config, 100, 0, 0, 1000) + for now, count, used, free in [(200, 0, 0, 1000), (100, 2, 0, 1000), + (100, 0, 900, 1000), (100, 0, 0, 299)]: + with self.assertRaises(ValueError): + collector.check_limits(config, now, count, used, free) + + def test_process_capture_requires_expected_boot_and_unique_rows(self): + raw = ("2026-11-15T18:00:00Z\n" + BOOT + "\n" + + "".join(f"{pid} 100 /service\n" for pid in range(10, 20))).encode() + collector.validate_procs(raw, BOOT) + with self.assertRaises(ValueError): + collector.validate_procs(raw.replace(BOOT.encode(), b"other"), BOOT) + with self.assertRaises(ValueError): + collector.validate_procs(raw + b"10 100 /service\n", BOOT) + + def test_index_preserves_old_bytes_and_explicit_failure(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp).resolve() / "index.txt" + path.write_bytes(b"prior evidence\n") + collector.append_index(path, "20261115T180000Z", ["procs"], ["messages.4"], ["messages(read)"]) + self.assertTrue(path.read_bytes().startswith(b"prior evidence\n")) + self.assertIn(b"failed: messages(read)", path.read_bytes()) + + def test_index_refuses_symlink(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + evidence = root / 'evidence' + evidence.write_bytes(b'unchanged') + index = root / 'index.txt' + index.symlink_to(evidence) + with self.assertRaises(OSError): + collector.append_index(index, '20261115T180000Z', [], [], []) + self.assertEqual(evidence.read_bytes(), b'unchanged') + + def test_process_capture_has_output_limit_and_reaps_own_group(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + script = root / 'procs.sh' + script.write_text('yes x\n') + result = collector.capture_procs(script, root, timeout=1) + self.assertNotEqual(result['rc'], 0) + self.assertTrue(result['group_closed']) + for name in ['procs.txt', 'procs.err']: + self.assertLessEqual((root/name).stat().st_size, 32768) + + def test_json_receipt_is_private_and_bounded(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp).resolve()/'receipt.json' + collector.write_json(path, {'result': 'PASS'}) + self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600) + with self.assertRaises(ValueError): + collector.write_json(path.with_name('oversized.json'), {'raw': 'x'*32768}) + + def test_interruption_propagates_without_reading_subsequent_logs(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + calls=[] + def cancelled(path): + calls.append(path.name) + raise collector.CaptureInterrupted('real capture cancellation') + with patch.object(collector._inventory,'read_snapshot',side_effect=cancelled): + with self.assertRaises(collector.CaptureInterrupted): + collector.copy_logs(root,root,4096) + self.assertEqual(calls,['messages']) + + def test_source_location_must_match_executing_modules(self): + collector.assert_source_location(SOURCE.parent) + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp).resolve() + with self.assertRaises(ValueError): + collector.assert_source_location(root) + pins={} + for name in ['i14-soak-local-collector.py','i14-soak-observer-inventory.py','procs.sh']: + (root/name).write_bytes(b'not executing code') + (root/name).chmod(0o700) + pins[name]=hashlib.sha256(b'not executing code').hexdigest() + config={'schema':1,'grant_id':'fixture','expires_epoch':200,'max_captures':1, + 'max_bytes':1<<20,'reserve_bytes':1<<20,'capture_bytes':1<<19,'source_sha256':pins} + (root/'observer.json').write_text(json.dumps(config));(root/'observer.json').chmod(0o600) + with self.assertRaises(ValueError): + collector.load_config(root) + + def test_main_fixture_captures_raw_and_real_ancestry_flag_and_closes_lock(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp).resolve() + root = base/'phase-20261115T180000Z' + root.mkdir(mode=0o700) + for name in ['logs', 'receipts']: + (root/name).mkdir(mode=0o700) + source = base/'varlog' + source.mkdir() + for name in ['messages', 'i14-battery.log']: + (source/name).write_bytes(b'raw original\n') + procs = 'printf "2026-11-15T18:00:00Z\\n' + BOOT + '\\n"\n' + procs += ''.join(f'echo "{pid} 100 /service"\n' for pid in range(10, 20)) + pins = {} + for name, body in [('i14-soak-local-collector.py', SOURCE.read_bytes()), + ('i14-soak-observer-inventory.py', SOURCE.with_name('i14-soak-observer-inventory.py').read_bytes()), + ('procs.sh', procs.encode())]: + (root/name).write_bytes(body) + (root/name).chmod(0o700) + pins[name] = hashlib.sha256(body).hexdigest() + config = {'schema':2, 'boot_id':BOOT, 'grant_id':'fixture-only', 'expires_epoch':int(time.time())+120, + 'max_captures':3, 'max_bytes':50<<20, 'reserve_bytes':512<<20, + 'capture_bytes':16<<20, 'source_sha256':pins} + (root/'observer.json').write_text(json.dumps(config)) + (root/'observer.json').chmod(0o600) + # Load the exact pinned source from its real fixture destination. + global collector + previous_collector = collector + spec=importlib.util.spec_from_file_location('installed_fixture_collector',root/'i14-soak-local-collector.py') + collector=importlib.util.module_from_spec(spec) + spec.loader.exec_module(collector) + self.addCleanup(lambda:globals().__setitem__('collector',previous_collector)) + ancestry = [{'pid':2,'ppid':1,'uid':0,'comm':'crond','start_ticks':10}] + original_datetime=collector.datetime + class AdvancingDateTime(original_datetime): + counter=0 + @classmethod + def now(cls,tz): + cls.counter+=1 + return original_datetime.now(tz)+timedelta(seconds=cls.counter) + # All identity/cron facts are local fixtures, never device acceptance. + with patch.object(collector, 'BASE', base), patch.object(collector, 'LOG_ROOT', source), \ + patch.object(collector, 'runtime_identity', return_value=BOOT), \ + patch.object(collector, 'ancestry', return_value=ancestry), \ + patch.object(collector, 'datetime', AdvancingDateTime), \ + patch.object(collector.os, 'geteuid', return_value=0), \ + patch.object(collector.time, 'sleep'): + # macOS fixtures are owned by the current uid; emulate target uid0 metadata gates. + original_stat = Path.stat + original_lstat = Path.lstat + def root_stat(path, *args, **kwargs): + value = original_stat(path, *args, **kwargs) + if path in [root, root/'logs', root/'receipts']: + fields = list(value); fields[4] = 0 + return os.stat_result(fields) + return value + def root_lstat(path): + return root_stat(path, follow_symlinks=False) + with patch.object(Path, 'stat', root_stat), patch.object(Path, 'lstat', root_lstat), \ + patch.object(collector, 'owned_file', side_effect=lambda p, m:p.read_bytes()): + self.addCleanup(os.umask, os.umask(0o077)) + (root/'observer.json').write_text(json.dumps(dict(config, max_captures=81))) + with self.assertRaisesRegex(ValueError, 'exporter'): + collector.main(['--run-dir',str(root),'--origin','cron']) + (root/'observer.json').write_text(json.dumps(config)) + with patch.object(collector, 'runtime_identity', return_value='different'), \ + self.assertRaisesRegex(ValueError, 'boot differs'): + collector.main(['--run-dir',str(root),'--origin','cron']) + self.assertEqual(collector.main(['--run-dir',str(root),'--origin','cron']),0) + # Real local signals during the first read must skip all later reads/helper. + for number in [signal.SIGALRM,signal.SIGTERM]: + calls=[] + def cancel_at_first_read(source,target,budget): + original_read=collector._inventory.read_snapshot + def raise_signal(path): + calls.append(path.name) + signal.raise_signal(number) + return original_read(path) + with patch.object(collector._inventory,'read_snapshot',side_effect=raise_signal): + return collector.copy_logs_original(source,target,budget) + collector.copy_logs_original=collector.copy_logs + with patch.object(collector,'copy_logs',side_effect=cancel_at_first_read), \ + patch.object(collector,'capture_procs',return_value={'rc':0,'group_closed':True}) as procs: + self.assertEqual(collector.main(['--run-dir',str(root),'--origin','cron']),1) + procs.assert_not_called() + self.assertEqual(calls,['messages']) + self.assertEqual(collector.main(['--run-dir',str(root),'--origin','cron']),3) + with patch.object(collector, 'usage', side_effect=AssertionError('resumed stopped phase')): + self.assertEqual(collector.main(['--run-dir',str(root),'--origin','cron']),3) + receipts=[json.loads(p.read_text()) for p in (root/'receipts').iterdir()] + receipt=next(p for p in receipts if p['result']=='PASS') + self.assertEqual(sorted(p['interruption_signal'] for p in receipts if 'interruption_signal' in p), + sorted([signal.SIGALRM,signal.SIGTERM])) + self.assertEqual(receipt['result'], 'PASS') + self.assertTrue(receipt['cron_origin_proven']) + self.assertTrue(receipt['process_actor']['group_closed']) + self.assertFalse((root/'.capture.lock').exists()) + capture = next(p for p in (root/'logs').iterdir() if p.is_dir() and (p/'messages').exists()) + self.assertEqual((capture/'messages').read_bytes(), b'raw original\n') + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_i14_soak_observer_export.py b/tests/test_i14_soak_observer_export.py new file mode 100644 index 0000000..4172b78 --- /dev/null +++ b/tests/test_i14_soak_observer_export.py @@ -0,0 +1,220 @@ +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path +import tarfile +import tempfile +import unittest +from unittest import mock + +SPEC = importlib.util.spec_from_file_location('observer_export', + Path(__file__).resolve().parents[1]/'scripts/i14-soak-observer-export.py') +export = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(export) + + +class ObserverExportTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.base = Path(self.temp.name).resolve() + self.root = self.base/'raw' + self.root.mkdir(mode=0o700) + (self.root/'logs').mkdir(mode=0o700) + self.body = b'raw\x00bytes\xff\n'*1000 + (self.root/'logs'/'messages').write_bytes(self.body) + (self.root/'logs'/'messages').chmod(0o600) + self.binding = {'phase_id':'D-example', 'grant_id':'export-example', + 'boot_id':'00000000-0000-4000-8000-000000000014', + 'config_sha256':'a'*64} + + def tearDown(self): + self.temp.cleanup() + + def archive(self): + output = io.BytesIO() + export.export_tar(self.root, export.inventory(self.root), self.binding, output) + return output.getvalue() + + def test_roundtrip_preserves_exact_bytes_and_private_files(self): + raw = self.archive() + self.assertGreater(len(raw), len(self.body)) + target = self.base/'received' + result = export.unpack_tar(io.BytesIO(raw), target, self.binding) + self.assertEqual((target/'logs/messages').read_bytes(), self.body) + self.assertEqual((target/'logs/messages').stat().st_mode & 0o777, 0o600) + self.assertEqual(target.stat().st_mode & 0o777, 0o700) + self.assertEqual(result['files']['logs/messages']['sha256'], hashlib.sha256(self.body).hexdigest()) + + def test_changed_source_is_refused_without_complete_receipt(self): + manifest = export.inventory(self.root) + (self.root/'logs/messages').write_bytes(b'changed') + with self.assertRaises(ValueError): + export.export_tar(self.root, manifest, self.binding, io.BytesIO()) + + def test_symlink_root_or_ancestor_is_refused(self): + (self.base/'link').symlink_to(self.root, target_is_directory=True) + for path in [self.base/'link', self.base/'link/logs']: + with self.subTest(path=path), self.assertRaises(ValueError): + export.inventory(path) + + def test_symlink_inside_tree_is_refused(self): + (self.root/'logs/linked').symlink_to(self.root/'logs/messages') + with self.assertRaises(ValueError): + export.inventory(self.root) + + def test_oversized_file_is_refused_before_read(self): + with (self.root/'large').open('wb') as f: + f.truncate(16*1024*1024+1) + with self.assertRaises(ValueError): + export.inventory(self.root) + + def test_foreign_binding_is_refused_before_destination_creation(self): + raw = self.archive() + target = self.base/'received' + with self.assertRaises(ValueError): + export.unpack_tar(io.BytesIO(raw), target, {**self.binding,'phase_id':'other'}) + self.assertFalse(target.exists()) + + def test_partial_archive_is_not_accepted(self): + raw = self.archive() + with self.assertRaises(ValueError): + export.unpack_tar(io.BytesIO(raw[:len(self.body)]), self.base/'received', self.binding) + + def test_unsafe_tar_name_is_refused(self): + raw = io.BytesIO() + with tarfile.open(fileobj=raw,mode='w') as archive: + item = tarfile.TarInfo('../escape'); item.size=3 + archive.addfile(item,io.BytesIO(b'bad')) + with self.assertRaises(ValueError): + export.unpack_tar(io.BytesIO(raw.getvalue()),self.base/'received',self.binding) + self.assertFalse((self.base/'escape').exists()) + + def crafted(self, members): + manifest = export.inventory(self.root) + first = json.dumps({'schema':1,'binding':self.binding,'manifest':manifest}).encode() + raw = io.BytesIO() + with tarfile.open(fileobj=raw,mode='w') as archive: + item=tarfile.TarInfo('EXPORT-MANIFEST.json');item.size=len(first) + archive.addfile(item,io.BytesIO(first)) + for name, data, kind in members: + item=tarfile.TarInfo(name) + if kind == 'link': + item.type=tarfile.SYMTYPE; item.linkname='/etc/passwd' + archive.addfile(item) + else: + item.size=len(data);archive.addfile(item,io.BytesIO(data)) + return raw.getvalue() + + def test_duplicate_or_symlink_member_is_refused(self): + for members in [[('logs/messages',self.body,'file')]*2, + [('logs/messages',b'','link')]]: + with self.subTest(members=len(members)), tempfile.TemporaryDirectory(dir=self.base) as tmp: + with self.assertRaises(ValueError): + export.unpack_tar(io.BytesIO(self.crafted(members)),Path(tmp)/'received',self.binding) + + def test_corrupted_member_is_refused(self): + corrupted = b'x' + self.body[1:] + with self.assertRaisesRegex(ValueError,'hash'): + export.unpack_tar(io.BytesIO(self.crafted([('logs/messages',corrupted,'file')])), + self.base/'received',self.binding) + + def test_existing_destination_is_never_overwritten(self): + target=self.base/'received';target.mkdir(mode=0o700) + (target/'keep').write_bytes(b'original') + with self.assertRaises(ValueError): + export.unpack_tar(io.BytesIO(self.archive()),target,self.binding) + self.assertEqual((target/'keep').read_bytes(),b'original') + + def test_change_during_stream_is_refused(self): + test=self + class ChangingSink(io.BytesIO): + def write(self,data): + (test.root/'logs/messages').write_bytes(b'x'*len(test.body)) + return super().write(data) + with self.assertRaises(ValueError): + export.export_tar(self.root,export.inventory(self.root),self.binding,ChangingSink()) + + def test_total_quota_is_checked_before_any_file_read(self): + value={'files':{str(i):{'bytes':16<<20,'sha256':'a'*64} for i in range(81)}, + 'total_bytes':81*(16<<20)} + with self.assertRaisesRegex(ValueError,'quota'): + export.validate_manifest(value) + + def test_extended_header_is_refused_before_its_body(self): + item=tarfile.TarInfo('extended') + item.type=tarfile.XHDTYPE;item.size=2<<20 + raw=item.tobuf(format=tarfile.USTAR_FORMAT) + with self.assertRaisesRegex(ValueError,'regular'): + export.unpack_tar(io.BytesIO(raw),self.base/'received',self.binding) + + def test_persisted_output_is_rehashed_before_acceptance(self): + raw=self.archive() + def corrupt_after_flush(fd): + os.pwrite(fd,b'X',0) + with mock.patch.object(export.os,'fsync',side_effect=corrupt_after_flush): + with self.assertRaisesRegex(ValueError,'persisted'): + export.unpack_tar(io.BytesIO(raw),self.base/'received',self.binding) + + def test_nested_capture_directories_are_private(self): + nested=self.root/'logs/20261115T193308Z';nested.mkdir(mode=0o700) + (self.root/'logs/messages').rename(nested/'messages') + target=self.base/'received' + try: + export.unpack_tar(io.BytesIO(self.archive()),target,self.binding) + except ValueError as error: + self.fail('nested roundtrip must stay private and succeed: '+str(error)) + self.assertEqual((target/'logs/20261115T193308Z/messages').read_bytes(),self.body) + for path in [target/'logs',target/'logs/20261115T193308Z']: + self.assertEqual(path.stat().st_mode & 0o777,0o700) + + def test_truncated_damaged_or_trailing_tar_end_is_refused(self): + raw=self.archive() + with tarfile.open(fileobj=io.BytesIO(raw),mode='r:') as archive: + last=archive.getmember('EXPORT-COMPLETE.json') + end=last.offset_data+((last.size+511)//512)*512 + cases=[raw[:end],raw[:end]+b'X'*512+raw[end+512:],raw+b'trailing'] + for i,data in enumerate(cases): + with self.subTest(case=i),self.assertRaises(ValueError): + export.unpack_tar(io.BytesIO(data),self.base/('received'+str(i)),self.binding) + + def test_parent_replacement_cannot_create_in_foreign_tree(self): + parent=self.base/'parent';parent.mkdir(mode=0o700) + foreign=self.base/'foreign';foreign.mkdir(mode=0o700) + target=parent/'received';original=os.mkdir;changed=False + def substitute(path,mode=0o777,*,dir_fd=None): + nonlocal changed + if not changed and (str(path)==str(target) or str(path)=='received'): + changed=True + parent.rename(self.base/'parked-parent') + parent.symlink_to(foreign,target_is_directory=True) + return original(path,mode,dir_fd=dir_fd) + raw=self.archive() + with mock.patch.object(export.os,'mkdir',side_effect=substitute): + with self.assertRaises(ValueError): + export.unpack_tar(io.BytesIO(raw),target,self.binding) + self.assertTrue(changed) + self.assertFalse((foreign/'received').exists()) + + def test_nested_replacement_cannot_create_in_foreign_tree(self): + target=self.base/'received' + foreign=self.base/'foreign';foreign.mkdir(mode=0o700) + original=os.mkdir;changed=False + def substitute(path,mode=0o777,*,dir_fd=None): + nonlocal changed + if not changed and (str(path)==str(target/'logs') or str(path)=='logs'): + changed=True + target.rename(self.base/'parked-received') + target.symlink_to(foreign,target_is_directory=True) + return original(path,mode,dir_fd=dir_fd) + raw=self.archive() + with mock.patch.object(export.os,'mkdir',side_effect=substitute): + with self.assertRaises(ValueError): + export.unpack_tar(io.BytesIO(raw),target,self.binding) + self.assertTrue(changed) + self.assertFalse((foreign/'logs').exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_i14_soak_observer_inventory.py b/tests/test_i14_soak_observer_inventory.py new file mode 100644 index 0000000..828eb26 --- /dev/null +++ b/tests/test_i14_soak_observer_inventory.py @@ -0,0 +1,144 @@ +"""Host-only privacy and identity checks for the read-only inventory payload.""" +import hashlib +import importlib.util +from pathlib import Path +import tempfile +import unittest +from unittest import mock +import os + + +SOURCE = Path(os.environ.get("I14_OBSERVER_INVENTORY", + Path(__file__).resolve().parents[1] / "scripts/i14-soak-observer-inventory.py")) +inventory = None +if SOURCE.is_file(): + spec = importlib.util.spec_from_file_location("observer_inventory", SOURCE) + inventory = importlib.util.module_from_spec(spec) + spec.loader.exec_module(inventory) + + +class Inventory(unittest.TestCase): + def setUp(self): + self.assertIsNotNone(inventory, "read-only observer inventory is not implemented") + + def test_identity_accepts_nul_separated_exact_platform_only(self): + inventory.check_identity(0, "i14", "3.18.19", "mediatek,MT6735\0other\0") + for value in [(1, "i14", "3.18.19", "mediatek,MT6735"), + (0, "other", "3.18.19", "mediatek,MT6735"), + (0, "i14", "7.0", "mediatek,MT6735"), + (0, "i14", "3.18.19", "mediatek,MT6737")]: + with self.assertRaises(ValueError): + inventory.check_identity(*value) + + def test_shell_installer_cron_line_is_recognised(self): + line = f"* * * * * /bin/sh '{inventory.SAMPLER}' # i14-soak-sample\n" + self.assertEqual(inventory.cron_summary(line.encode())["sampler_lines"], 1) + + def test_cron_summarises_known_sampler_without_exposing_other_commands(self): + raw = (b"* * * * * '/mnt/data/media/0/i14-linux/soak/i14-soak-sample' # i14-soak-sample\n" + b"0 1 * * * tool SECRET_TOKEN=do-not-output\n") + info = inventory.cron_summary(raw) + self.assertEqual(info["sha256"], hashlib.sha256(raw).hexdigest()) + self.assertEqual(info["sampler_lines"], 1) + self.assertEqual(info["other_command_count"], 1) + self.assertNotIn("SECRET_TOKEN", repr(info)) + self.assertNotIn("do-not-output", repr(info)) + + def test_cron_recognises_actual_existing_rust_sampler_row(self): + raw = b"* * * * * '/mnt/data/media/0/i14-linux/soak/i14-soak-sample-rs' # i14-soak-sample\n" + info = inventory.cron_summary(raw) + self.assertEqual(info["sampler_lines"], 1) + self.assertEqual(info["other_command_count"], 0) + + def test_log_metadata_retains_hash_and_stamp_boundaries_without_log_text(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory).resolve() / "messages" + raw = b"Nov 15 17:00:00 i14 secret=hidden\nNov 15 17:01:00 i14 other-secret\n" + path.write_bytes(raw) + info = inventory.file_info(path, log=True) + self.assertEqual(info["sha256"], hashlib.sha256(raw).hexdigest()) + self.assertEqual(info["first_stamp"], "Nov 15 17:00:00") + self.assertEqual(info["last_stamp"], "Nov 15 17:01:00") + self.assertTrue(info["newline_terminated"]) + self.assertNotIn("hidden", repr(info)) + self.assertNotIn("other-secret", repr(info)) + + def test_missing_log_is_explicit_and_not_an_empty_success(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory).resolve() / "messages.4" + self.assertFalse(path.exists()) + info = inventory.file_info(path, log=True) + self.assertEqual(info, {"present": False}) + + def test_unexpected_symlink_is_refused_before_reading_target(self): + with tempfile.TemporaryDirectory() as directory: + target = Path(directory).resolve() / "private-target" + target.write_text("not an inventory input") + path = Path(directory).resolve() / "messages" + path.symlink_to(target) + with self.assertRaises(ValueError): + inventory.file_info(path, log=True) + + def test_unexpected_large_input_is_refused_without_hashing_it(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory).resolve() / "samples.jsonl" + with path.open("wb") as stream: + stream.truncate(64 * 1024 * 1024 + 1) + with self.assertRaises(ValueError): + inventory.file_info(path) + + def test_growth_after_size_check_is_refused(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory).resolve() / "messages" + path.write_bytes(b"original\n") + real_read = os.read + changed = False + def grow_then_read(fd, size): + nonlocal changed + if not changed: + changed = True + with path.open("ab") as stream: + stream.write(b"grew\n") + return real_read(fd, size) + with mock.patch.object(inventory.os, "read", side_effect=grow_then_read): + with self.assertRaises(ValueError): + inventory.file_info(path, log=True) + + def test_symlinked_ancestor_is_refused(self): + with tempfile.TemporaryDirectory() as directory: + target = Path(directory).resolve() / "outside" + target.mkdir() + (target / "samples.jsonl").write_bytes(b"private\n") + link = Path(directory).resolve() / "soak" + link.symlink_to(target, target_is_directory=True) + with self.assertRaises(ValueError): + inventory.file_info(link / "samples.jsonl") + + def test_battery_iso_boundaries_do_not_expose_body(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory).resolve() / "battery" + path.write_bytes(b"2026-11-15 17:00:00 private=hidden\n2026-11-15 17:01:00 hidden\n") + info = inventory.file_info(path, log=True) + self.assertEqual(info["first_stamp"], "2026-11-15 17:00:00") + self.assertEqual(info["last_stamp"], "2026-11-15 17:01:00") + self.assertNotIn("hidden", repr(info)) + + def test_log_summary_uses_same_snapshot_as_hash(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory).resolve() / "messages" + original = b"Nov 15 17:00:00 i14 original\n" + replacement = b"Nov 15 17:59:00 i14 changed\n" + path.write_bytes(original) + real_read_bytes = Path.read_bytes + def replace_on_reread(value): + if value == path: + path.write_bytes(replacement) + return real_read_bytes(value) + with mock.patch.object(Path, "read_bytes", replace_on_reread): + info = inventory.file_info(path, log=True) + self.assertEqual(info["sha256"], hashlib.sha256(original).hexdigest()) + self.assertEqual(info["first_stamp"], "Nov 15 17:00:00") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_i14_soak_phase_export.py b/tests/test_i14_soak_phase_export.py new file mode 100644 index 0000000..a9c503b --- /dev/null +++ b/tests/test_i14_soak_phase_export.py @@ -0,0 +1,279 @@ +"""Synthetic files only. Native identity/process inputs are mocked; no transport.""" +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch, MagicMock + +ROOT = Path(__file__).resolve().parents[1] +def load(path): + spec = importlib.util.spec_from_file_location(path.stem.replace('-', '_'), path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module +guard = load(ROOT/'scripts/i14-soak-phase-export.py') +export = load(ROOT/'scripts/i14-soak-observer-export.py') +inventory = load(ROOT/'scripts/i14-soak-observer-inventory.py') +real_actors = guard.actors +sha = lambda raw: hashlib.sha256(raw).hexdigest() +BOOT = '00000000-0000-4000-8000-000000000014' + +class PhaseExportTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.base = Path(self.temp.name).resolve() + self.data = self.base/'observer'; self.data.mkdir(mode=0o700) + self.run = self.data/'phase-20261116T020000Z'; self.run.mkdir(mode=0o700) + self.cron = self.base/'root-cron' + self.original = b'*/1 * * * * existing-sampler\n' + self.write(self.cron, self.original) + self.sources = { + 'i14-soak-local-collector.py': (ROOT/'scripts/i14-soak-local-collector.py').read_bytes(), + 'i14-soak-observer-inventory.py': (ROOT/'scripts/i14-soak-observer-inventory.py').read_bytes(), + 'procs.sh': (ROOT/'scripts/i14-soak-procs.sh').read_bytes(), + } + self.deps = {name: (ROOT/'scripts'/name).read_bytes() for name in + ['i14-soak-observer-export.py', 'i14-soak-observer-inventory.py']} + for name, raw in self.sources.items(): self.write(self.run/name, raw, 0o700) + config = dict(schema=2, boot_id=BOOT, grant_id='phase-one', expires_epoch=2000, + max_captures=80, max_bytes=1281<<20, capture_bytes=16<<20, + reserve_bytes=512<<20, source_sha256={n:sha(b) for n,b in self.sources.items()}) + self.config = json.dumps(config, sort_keys=True).encode() + self.write(self.run/'observer.json', self.config) + self.write(self.run/'root-crontab.before', self.original) + self.close = dict(result='CRON_RESTORED_NO_ACTOR', grant_id='close-one', run_dir=str(self.run), + boot_id=BOOT, config_sha256=sha(self.config), + source_sha256=config['source_sha256'], cronline_sha256='b'*64, + restored_cron_sha256=sha(self.original)) + self.close_raw = json.dumps(self.close, sort_keys=True).encode() + self.write(self.run/'close-receipt.json', self.close_raw) + self.bundle = dict(phase_id='phase-one', grant_id='export-one', close_grant_id='close-one', + run_dir=str(self.run), boot_id=BOOT, config_sha256=sha(self.config), + source_sha256=config['source_sha256'], cronline_sha256='b'*64, + original_cron_sha256=sha(self.original), close_receipt_sha256=sha(self.close_raw), + start_epoch=1000, deadline_epoch=1800) + # Only fixture filesystem/owner/native-proc inputs differ from production constants. + self.addCleanup(patch.stopall) + patch.object(guard, 'BASE', self.data, create=True).start() + patch.object(guard, 'CRON', self.cron, create=True).start() + patch.object(guard, 'OWNER', os.getuid(), create=True).start() + self.native = patch.object(guard, 'native', return_value=BOOT, create=True).start() + self.actors = patch.object(guard, 'actors', return_value=[], create=True).start() + + def write(self, path, raw, mode=0o600): + path.write_bytes(raw); path.chmod(mode) + + def call(self, bundle=None, deps=None, clock=None, stream=None): + return guard.stream_phase(bundle or self.bundle, deps or self.deps, + stream or io.BytesIO(), clock or (lambda: 1100)) + + def test_complete_bound_tar_roundtrip(self): + target = io.BytesIO(); result = self.call(stream=target) + self.assertEqual(result.get('result'), 'CLOSED_PHASE_STREAMED_NOT_CLEANUP_AUTHORIZED') + manifest = export.unpack_tar(io.BytesIO(target.getvalue()), self.base/'received', + {k:self.bundle[k] for k in ['phase_id','grant_id','boot_id','config_sha256']}) + self.assertEqual((self.base/'received'/'observer.json').read_bytes(), self.config) + self.assertEqual(manifest['total_bytes'], sum(p.stat().st_size for p in self.run.iterdir())) + + def test_foreign_close_provenance_is_refused(self): + changed = {**self.close, 'grant_id':'foreign-close'} + raw = json.dumps(changed).encode(); self.write(self.run/'close-receipt.json', raw) + bundle = {**self.bundle, 'close_receipt_sha256':sha(raw)} + with self.assertRaises(ValueError): self.call(bundle=bundle) + + def test_active_collector_refused_before_archive(self): + self.actors.return_value = [88] + target = io.BytesIO() + with self.assertRaises(ValueError): self.call(stream=target) + self.assertEqual(target.getvalue(), b'') + + def test_cron_modified_after_restoration_refused(self): + self.write(self.cron, self.original+b'foreign\n') + with self.assertRaises(ValueError): self.call() + + def test_config_bytes_refused(self): + self.write(self.run/'observer.json', self.config+b' ') + with self.assertRaises(ValueError): self.call() + + def test_source_bytes_refused(self): + self.write(self.run/'procs.sh', b'changed', 0o700) + with self.assertRaises(ValueError): self.call() + + def test_dependency_pin_refused(self): + deps = dict(self.deps); deps['i14-soak-observer-export.py'] += b'\n' + with self.assertRaises(ValueError): self.call(deps=deps) + + def test_future_expired_overlong_lease_refused(self): + for times in [(1200,1800),(100,1050),(1000,1901)]: + with self.subTest(times=times), self.assertRaises(ValueError): + self.call(bundle={**self.bundle,'start_epoch':times[0],'deadline_epoch':times[1]}) + + def test_lock_and_foreign_namespace_refused(self): + self.write(self.run/'.capture.lock', b'') + with self.assertRaises(ValueError): self.call() + (self.run/'.capture.lock').unlink() + with self.assertRaises(ValueError): self.call(bundle={**self.bundle,'run_dir':str(self.base)}) + + def test_late_lease_midstream_refused(self): + class Late(io.BytesIO): + pass + target=Late(); state={'now':1100} + original=target.write + def write(raw): + n=original(raw); state['now']=1800; return n + target.write=write + with self.assertRaises(ValueError): self.call(clock=lambda:state['now'], stream=target) + + def test_after_stream_identity_change_refused(self): + self.native.side_effect=[BOOT,ValueError('changed boot')] + with self.assertRaises(ValueError): self.call() + + def test_actor_appearing_after_stream_refused(self): + self.actors.side_effect = [[], [88]] + with self.assertRaises(ValueError): self.call() + + def test_cron_change_during_stream_refused_even_with_complete_tar(self): + class Changed(io.BytesIO): + pass + target = Changed(); original = target.write + def write(raw): + self.write(self.cron, self.original+b'foreign\n') + return original(raw) + target.write = write + with self.assertRaises(ValueError): self.call(stream=target) + # Complete tar bytes do not imply caller rc0 or permission to clean up. + self.assertGreater(len(target.getvalue()), 0) + + def test_short_output_write_refused(self): + class Short(io.BytesIO): + def write(self, raw): + return max(0, len(raw)-1) + with self.assertRaises(ValueError): self.call(stream=Short()) + + def test_inexact_schema_or_phase_config_refused(self): + with self.assertRaises(ValueError): self.call(bundle={**self.bundle, 'extra': True}) + with self.assertRaises(ValueError): self.call(bundle={**self.bundle, 'phase_id': 'foreign'}) + + def test_private_root_mode_refused(self): + self.run.chmod(0o755) + target = io.BytesIO() + with self.assertRaises(ValueError): self.call(stream=target) + self.assertEqual(target.getvalue(), b'') + + def test_symlink_phase_refused_without_touching_foreign_files(self): + foreign=self.base/'foreign'; foreign.mkdir(); link=self.data/'phase-20261116T030000Z';link.symlink_to(foreign) + with self.assertRaises(ValueError): self.call(bundle={**self.bundle,'run_dir':str(link)}) + self.assertEqual(list(foreign.iterdir()),[]) + + def test_R1_manifest_provenance_swap_restored_after_tar_refused(self): + original_inventory = export.inventory + original_export = export.export_tar + target = io.BytesIO() + def swapped(fd): + self.write(self.run/'observer.json', self.config+b' ') + return original_inventory(fd) + def restore_after_tar(*args): + result = original_export(*args) + self.write(self.run/'observer.json', self.config) + return result + with patch.object(guard, 'dependencies', return_value=(export,inventory)), \ + patch.object(export, 'inventory', side_effect=swapped), \ + patch.object(export, 'export_tar', side_effect=restore_after_tar): + with self.assertRaises(ValueError): self.call(stream=target) + self.assertEqual(target.getvalue(), b'') + + def test_R1_manifest_required_mode_swap_refused(self): + original_inventory = export.inventory + original_export = export.export_tar + target = io.BytesIO() + def swapped(fd): + (self.run/'observer.json').chmod(0o700) + return original_inventory(fd) + def restore_after_tar(*args): + result = original_export(*args) + (self.run/'observer.json').chmod(0o600) + return result + with patch.object(guard, 'dependencies', return_value=(export,inventory)), \ + patch.object(export, 'inventory', side_effect=swapped), \ + patch.object(export, 'export_tar', side_effect=restore_after_tar): + with self.assertRaises(ValueError): self.call(stream=target) + self.assertEqual(target.getvalue(), b'') + + def actor_fixture(self, argv, cwd=None, error=None): + context = MagicMock() + context.__enter__.return_value = iter([SimpleNamespace(name='47',path='/fixture/proc/47')]) + with patch.object(guard.os, 'scandir', return_value=context), \ + patch.object(guard, 'fixed', return_value=b'\0'.join(a.encode() for a in argv)+b'\0'), \ + patch.object(guard.os, 'readlink', return_value=cwd, side_effect=error) as readlink: + found = real_actors(self.run) + return found, readlink.call_count + + def test_R2_relative_collector_actor_found(self): + found, _ = self.actor_fixture(['python3','i14-soak-local-collector.py', + '--run-dir',str(self.run),'--origin','manual'], str(self.run)) + self.assertEqual(found, [47]) + + def test_R2_normalized_absolute_collector_actor_found(self): + found, _ = self.actor_fixture(['python3',str(self.run)+'/./i14-soak-local-collector.py', + '--run-dir='+str(self.run),'--origin','manual']) + self.assertEqual(found, [47]) + + def test_R2_unresolved_relevant_cwd_refused(self): + with self.assertRaises(ValueError): + self.actor_fixture(['python3','i14-soak-local-collector.py','--run-dir',str(self.run)], + error=PermissionError('fixture cwd denied')) + + def test_R2_unknown_script_alias_for_this_phase_refused(self): + with self.assertRaises(ValueError): + self.actor_fixture(['python3','alias.py','--run-dir',str(self.run)],str(self.run)) + + def test_R2_external_alias_relative_run_directory_refused(self): + with self.assertRaises(ValueError): + self.actor_fixture(['python3','/fixture/external-alias.py','--run-dir','.','--origin','manual'], + str(self.run)) + + def test_R2_external_alias_equals_relative_run_directory_refused(self): + with self.assertRaises(ValueError): + self.actor_fixture(['python3','/fixture/external-alias.py','--run-dir=.','--origin','manual'], + str(self.run)) + + def test_R2_external_alias_empty_run_directory_refused(self): + with self.assertRaises(ValueError): + self.actor_fixture(['python3','/fixture/external-alias.py','--run-dir','','--origin','manual'], + str(self.run)) + + def test_external_alias_for_foreign_run_directory_is_irrelevant(self): + found, _ = self.actor_fixture(['python3','/fixture/external-alias.py','--run-dir','other'], + str(self.base/'foreign')) + self.assertEqual(found, []) + + def test_R2_external_alias_abbreviated_run_directory_refused(self): + for option in ['--r','--run-d','--run-di=.']: + args=[option] if '=' in option else [option,'.'] + with self.subTest(option=option), self.assertRaises(ValueError): + self.actor_fixture(['python3','/fixture/external-alias.py',*args,'--origin','manual'], + str(self.run)) + + def test_unrelated_actor_does_not_read_cwd(self): + found, reads = self.actor_fixture(['unrelated','--ordinary']) + self.assertEqual((found,reads), ([],0)) + + def test_R3_deadline_during_final_actor_check_refused(self): + state = {'now':1100} + def final_actor_check(root): + state['now'] = 1800 + return [] + calls=[] + def actors(root): + calls.append(root) + return final_actor_check(root) if len(calls)==2 else [] + self.actors.side_effect = actors + with self.assertRaises(ValueError): self.call(clock=lambda:state['now']) + +if __name__ == '__main__': unittest.main() diff --git a/tests/test_i14_soak_receive.py b/tests/test_i14_soak_receive.py new file mode 100644 index 0000000..69ec17d --- /dev/null +++ b/tests/test_i14_soak_receive.py @@ -0,0 +1,75 @@ +"""Exercise the host transport boundary with a local fixture process.""" +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/i14-soak-receive.py" +spec = importlib.util.spec_from_file_location("receiver", SCRIPT) +receiver = importlib.util.module_from_spec(spec) +spec.loader.exec_module(receiver) + + +class ReceiveTests(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name).resolve() + source = self.root / "source" + source.mkdir(mode=0o700) + (source / "messages").write_bytes(b"fixture\n") + (source / "messages").chmod(0o600) + self.binding = dict(phase_id="fixture", grant_id="fixture-export", + boot_id="00000000-0000-4000-8000-000000000014", config_sha256="a" * 64) + self.archive = self.root / "fixture.tar" + with self.archive.open("xb") as output: + receiver.export.export_tar(source, receiver.export.inventory(source), self.binding, output) + self.destination = self.root / "received" + + def send(self, body, seconds=5): + program = ("import os, sys, time\nfrom pathlib import Path\n" + "Path(sys.argv[2]).write_text(str(os.getpid()))\n" + body) + return receiver.receive([sys.executable, "-c", program, str(self.archive), str(self.root / "pid")], + self.destination, self.binding, seconds) + + send_archive = "sys.stdout.buffer.write(Path(sys.argv[1]).read_bytes()); sys.stdout.buffer.flush()\n" + + def test_normal_exit_and_persisted_bytes(self): + self.send(self.send_archive) + self.assertEqual((self.destination / "raw/messages").read_bytes(), b"fixture\n") + self.assertEqual(json.loads((self.destination / "verified.json").read_text())["transport_exit"], 0) + + def test_cli_passes_owner_stdin_through_foreground_transport(self): + binding_file = self.root / "binding.json" + binding_file.write_text(json.dumps(self.binding)) + with self.archive.open("rb") as fixture_stream: + subprocess.run([sys.executable, "-B", str(SCRIPT), "--binding", str(binding_file), + "--out", str(self.destination), "--timeout", "5", "--", "/bin/cat"], + stdin=fixture_stream, check=True, timeout=10) + self.assertEqual((self.destination / "raw/messages").read_bytes(), b"fixture\n") + + def test_full_valid_archive_followed_by_nonzero_exit(self): + with self.assertRaisesRegex(ValueError, "exited 7"): + self.send(self.send_archive + "sys.exit(7)") + self.assertFalse((self.destination / "verified.json").exists()) + + def test_missing_and_partial_output(self): + for index, body in enumerate(["pass", "sys.stdout.buffer.write(b'partial')"]): + self.destination = self.root / f"incomplete-{index}" + with self.subTest(body=body), self.assertRaises(ValueError): + self.send(body) + self.assertFalse((self.destination / "verified.json").exists()) + + def test_timeout_before_output_and_after_complete_archive_reaps_transport(self): + for index, prefix in enumerate(["", self.send_archive + "os.close(1)\n"]): + self.destination = self.root / f"timeout-{index}" + with self.subTest(prefix=prefix), self.assertRaises((ValueError, TimeoutError, subprocess.TimeoutExpired)): + self.send(prefix + "time.sleep(30)", seconds=1) + with self.assertRaises(ProcessLookupError): + os.killpg(int((self.root / "pid").read_text()), 0) + self.assertFalse((self.destination / "verified.json").exists())