Spaces:
Running
Running
feat: add autonomous AI runtime containment
Browse files- CHANGELOG.md +6 -0
- LIMITATIONS.md +7 -3
- QUALIFICATION.md +3 -7
- README.md +53 -24
- RELEASE_NOTES.md +3 -3
- SECURITY_MODEL.md +5 -3
- pyproject.toml +2 -2
- scripts/build_release.py +2 -0
- scripts/install.py +42 -9
- scripts/prepare_ai_smoke.py +1 -1
- scripts/run_autonomous_matrix.py +147 -0
- scripts/smoke_autonomous_ai.py +158 -0
- scripts/uninstall.py +24 -4
- scripts/verify_evidence.py +8 -6
- scripts/verify_release.py +2 -2
- src/lumi_eggcracker/__init__.py +2 -2
- src/lumi_eggcracker/adoption.py +239 -0
- src/lumi_eggcracker/approvals.py +98 -0
- src/lumi_eggcracker/cli.py +17 -1
- src/lumi_eggcracker/detector_catalogue.json +1 -0
- src/lumi_eggcracker/detectors.py +122 -0
- src/lumi_eggcracker/discovery.py +148 -0
- src/lumi_eggcracker/supervisor.py +160 -4
- tests/fixtures/discovery_fork_race.py +29 -0
- tests/test_adoption.py +27 -0
- tests/test_approvals.py +40 -0
- tests/test_cli.py +7 -2
- tests/test_detectors.py +38 -0
- tests/test_discovery.py +32 -0
CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
| 1 |
# Changelog
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
## 0.1.2
|
| 4 |
|
| 5 |
- Add a pinned, opt-in external asset preparation path and five-run real-AI smoke demonstration.
|
|
|
|
| 1 |
# Changelog
|
| 2 |
|
| 3 |
+
## 0.2.0
|
| 4 |
+
|
| 5 |
+
- Add deterministic autonomous discovery of unapproved supported AI runtimes.
|
| 6 |
+
- Add exact operator approvals, pidfd stop, quarantine cgroup capture and post-containment detection receipts.
|
| 7 |
+
- Preserve selected-workload cgroup containment and exclude N1 networking from the product release path.
|
| 8 |
+
|
| 9 |
## 0.1.2
|
| 10 |
|
| 11 |
- Add a pinned, opt-in external asset preparation path and five-run real-AI smoke demonstration.
|
LIMITATIONS.md
CHANGED
|
@@ -1,7 +1,11 @@
|
|
| 1 |
# Limitations
|
| 2 |
|
| 3 |
-
Lumi Eggcracker
|
| 4 |
|
| 5 |
-
|
| 6 |
|
| 7 |
-
The
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# Limitations
|
| 2 |
|
| 3 |
+
Lumi Eggcracker 0.2.0 autonomously acts only on a complete match from its installed deterministic AI-runtime catalogue. It does not recognise arbitrary, custom, obfuscated, containerised, remote or otherwise unlisted AI/agent workloads.
|
| 4 |
|
| 5 |
+
The observer uses bounded `/proc` polling. It has no kernel execution hook, eBPF programme or guarantee that a process which forks, daemonises or exits before discovery can be reconstructed as one complete historical tree. A successful receipt proves the exact captured quarantine cgroup is empty.
|
| 6 |
|
| 7 |
+
The product does not kill generic Python, Node.js, Java, shell, GPU-intensive, memory-intensive or networked processes based on those generic properties. It does not use behavioural modelling, telemetry upload, network isolation, credential isolation, filesystem isolation, malware prevention or EDR functions.
|
| 8 |
+
|
| 9 |
+
Approvals are exact: UID, resolved executable identity and complete argv digest must all match. Changing any argument requires a new approval. Revoking an approval affects future detections, not a workload already running under that approval.
|
| 10 |
+
|
| 11 |
+
The explicit `start` command remains non-interactive. It has no terminal attachment, current-working-directory forwarding, timeout, memory/CPU limit UX or output streaming. It supports one active selected workload globally. Detection receipts are bounded to 1000 entries.
|
QUALIFICATION.md
CHANGED
|
@@ -1,11 +1,7 @@
|
|
| 1 |
# Qualification
|
| 2 |
|
| 3 |
-
The 0.
|
| 4 |
|
| 5 |
-
|
| 6 |
|
| 7 |
-
|
| 8 |
-
sudo python3 scripts/run_native_matrix.py --fork-race-repetitions 100 --benign-repetitions 50 --restart-repetitions 20 --socket-attempts 100 --output ./native-matrix.json
|
| 9 |
-
```
|
| 10 |
-
|
| 11 |
-
The evidence establishes behavior only for the tested environment and commit. It does not establish universal Linux compatibility or any unsupported security claim.
|
|
|
|
| 1 |
# Qualification
|
| 2 |
|
| 3 |
+
The 0.2.0 candidate is releaseable only when its exact commit passes direct tests, the existing selected-workload matrix, and the native autonomous-discovery matrix on one Ubuntu VM.
|
| 4 |
|
| 5 |
+
Mandatory autonomous gates are: 100/100 unapproved fixture discoveries and complete tree kills, 100/100 unrelated-canary survivals, zero surviving bounded replacement attempts, zero reused-PID signals, 50/50 exact approved survivals, zero kills in the benign and partial-match matrices, zero workload policy/socket accesses, restart recovery, p95 qualifying-snapshot-to-stop below 100 ms, p95 fixture-start-to-stop below 500 ms, and p95 trigger-to-empty below 500 ms.
|
| 6 |
|
| 7 |
+
The candidate must also run five unapproved/approved/unapproved real llama.cpp/Qwen smoke sequences, cleanly install with discovery armed, and completely uninstall. Evidence is specific to the tested commit and host; it does not establish universal AI identification.
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -1,54 +1,83 @@
|
|
| 1 |
# Lumi Eggcracker
|
| 2 |
|
| 3 |
-
Lumi Eggcracker is a
|
| 4 |
|
| 5 |
-
>
|
| 6 |
|
| 7 |
-
|
| 8 |
|
| 9 |
-
##
|
| 10 |
|
| 11 |
-
-
|
| 12 |
-
-
|
| 13 |
-
-
|
| 14 |
-
-
|
| 15 |
-
-
|
|
|
|
| 16 |
|
| 17 |
-
##
|
| 18 |
|
| 19 |
-
|
|
|
|
|
|
|
| 20 |
|
| 21 |
## Requirements
|
| 22 |
|
| 23 |
-
- Linux with systemd and unified cgroup v2;
|
| 24 |
-
- `
|
| 25 |
-
- root for install/uninstall
|
| 26 |
- Python 3.11 or newer.
|
| 27 |
|
| 28 |
## Quick start
|
| 29 |
|
| 30 |
-
Download and extract `lumi-eggcracker-0.
|
| 31 |
|
| 32 |
```sh
|
| 33 |
-
cd lumi-eggcracker-0.
|
| 34 |
-
sudo python3 scripts/install.py --operator "$USER" --artifact ./lumi-eggcracker-0.
|
| 35 |
eggcracker doctor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
eggcracker start --name demo --max-pids 8 -- /bin/sleep 60
|
| 37 |
eggcracker kill --name demo --receipt ./demo-receipt.json
|
| 38 |
-
sudo python3 scripts/uninstall.py
|
| 39 |
```
|
| 40 |
|
| 41 |
-
The selected command is launched through a systemd transient unit. It does not attach an interactive terminal, preserve your current working directory, or stream output to the CLI in this preview. Use absolute paths and redirect output in a wrapper script when needed.
|
| 42 |
-
|
| 43 |
## Real local AI smoke
|
| 44 |
|
| 45 |
-
The release bundle can prepare
|
| 46 |
|
| 47 |
```sh
|
| 48 |
sudo python3 scripts/prepare_ai_smoke.py --workspace /opt/lumi-eggcracker-ai-smoke --accept-third-party-downloads
|
| 49 |
-
sudo python3 scripts/
|
|
|
|
|
|
|
| 50 |
```
|
| 51 |
|
| 52 |
-
The
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
See [SECURITY_MODEL.md](SECURITY_MODEL.md), [LIMITATIONS.md](LIMITATIONS.md), and [QUALIFICATION.md](QUALIFICATION.md) before using
|
|
|
|
| 1 |
# Lumi Eggcracker
|
| 2 |
|
| 3 |
+
Lumi Eggcracker is a local Linux kill switch for unapproved, supported AI and agent runtimes.
|
| 4 |
|
| 5 |
+
> Eggcracker monitors a Linux host for processes matching its published AI-runtime fingerprints. When a matching process has no exact operator approval, it automatically stops the process, captures its discovered process tree in a root-owned cgroup, and kills that cgroup.
|
| 6 |
|
| 7 |
+
There is no alert-only phase for an unapproved catalogue match. Containment begins with a pidfd stop signal; the explanation and receipt are written only after cgroup containment completes.
|
| 8 |
|
| 9 |
+
## What it does
|
| 10 |
|
| 11 |
+
- continuously scans host processes and performs a startup scan before accepting control commands;
|
| 12 |
+
- detects published local-runtime profiles including llama.cpp, Ollama, vLLM, Text Generation Inference, LocalAI, llamafile and selected agent CLIs;
|
| 13 |
+
- lets the configured operator approve one exact executable, UID and invocation before it is run;
|
| 14 |
+
- automatically stops, captures and kills unapproved matches with `pidfd_send_signal` and cgroup-v2 `cgroup.kill`;
|
| 15 |
+
- preserves the existing protected `start` and operator `kill` workflow;
|
| 16 |
+
- records bounded post-containment receipts, status and detection summaries.
|
| 17 |
|
| 18 |
+
## What it does not do
|
| 19 |
|
| 20 |
+
Eggcracker does not identify every possible AI implementation. It does not claim to detect custom, obfuscated, containerised or remote AI workloads, general malware or intrusions. It does not use a behavioural model, isolate host networking, credentials or filesystems, or replace EDR.
|
| 21 |
+
|
| 22 |
+
A successful receipt proves the captured quarantine cgroup is empty. It does not prove that a process which escaped before detection never existed.
|
| 23 |
|
| 24 |
## Requirements
|
| 25 |
|
| 26 |
+
- native Linux with systemd and unified cgroup v2;
|
| 27 |
+
- `cgroup.kill`, delegated child cgroups, `pidfd_open` and `pidfd_send_signal`;
|
| 28 |
+
- root for install/uninstall and one non-root local operator;
|
| 29 |
- Python 3.11 or newer.
|
| 30 |
|
| 31 |
## Quick start
|
| 32 |
|
| 33 |
+
Download and extract `lumi-eggcracker-0.2.0-linux.zip`, then run as root:
|
| 34 |
|
| 35 |
```sh
|
| 36 |
+
cd lumi-eggcracker-0.2.0
|
| 37 |
+
sudo python3 scripts/install.py --operator "$USER" --artifact ./lumi-eggcracker-0.2.0.pyz
|
| 38 |
eggcracker doctor
|
| 39 |
+
eggcracker approvals
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
An unapproved supported runtime is killed automatically when it starts. To allow a known invocation, approve it before launch. The approval stores hashes, not its raw arguments:
|
| 43 |
+
|
| 44 |
+
```sh
|
| 45 |
+
eggcracker approve --name local-qwen --uid "$(id -u)" -- \
|
| 46 |
+
/opt/llama.cpp/llama-cli -m /opt/models/qwen.gguf -p "Hello" -n 256
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Inspect autonomous containment summaries with:
|
| 50 |
+
|
| 51 |
+
```sh
|
| 52 |
+
eggcracker detections
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
Remove an approval for future launches with `eggcracker revoke --name local-qwen`. Revocation does not kill a workload that was already approved and running.
|
| 56 |
+
|
| 57 |
+
The selected-workload command remains available for controlled tests and explicit workloads:
|
| 58 |
+
|
| 59 |
+
```sh
|
| 60 |
eggcracker start --name demo --max-pids 8 -- /bin/sleep 60
|
| 61 |
eggcracker kill --name demo --receipt ./demo-receipt.json
|
|
|
|
| 62 |
```
|
| 63 |
|
|
|
|
|
|
|
| 64 |
## Real local AI smoke
|
| 65 |
|
| 66 |
+
The release bundle can prepare a pinned external llama.cpp runner and Qwen GGUF model in a separate workspace. The assets are downloaded only after explicit acceptance, verified by commit/revision and SHA-256, and never included in the release archive.
|
| 67 |
|
| 68 |
```sh
|
| 69 |
sudo python3 scripts/prepare_ai_smoke.py --workspace /opt/lumi-eggcracker-ai-smoke --accept-third-party-downloads
|
| 70 |
+
sudo python3 scripts/smoke_autonomous_ai.py \
|
| 71 |
+
--assets-manifest /opt/lumi-eggcracker-ai-smoke/ai-smoke-assets.json \
|
| 72 |
+
--user "$USER" --repetitions 5 --output ./autonomous-ai-smoke.json
|
| 73 |
```
|
| 74 |
|
| 75 |
+
The smoke launches the model directly, outside `eggcracker start`, verifies that Eggcracker kills the unapproved invocation, then proves that the same exact invocation survives only when approved.
|
| 76 |
+
|
| 77 |
+
To remove Eggcracker completely:
|
| 78 |
+
|
| 79 |
+
```sh
|
| 80 |
+
sudo python3 scripts/uninstall.py
|
| 81 |
+
```
|
| 82 |
|
| 83 |
+
See [SECURITY_MODEL.md](SECURITY_MODEL.md), [LIMITATIONS.md](LIMITATIONS.md), and [QUALIFICATION.md](QUALIFICATION.md) before using this engineering preview.
|
RELEASE_NOTES.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
-
# Lumi Eggcracker 0.
|
| 2 |
|
| 3 |
-
0.
|
| 4 |
|
| 5 |
-
The
|
|
|
|
| 1 |
+
# Lumi Eggcracker 0.2.0
|
| 2 |
|
| 3 |
+
0.2.0 adds autonomous catalogue-based discovery and termination of unapproved local AI-runtime processes. It uses deterministic fingerprints, exact pre-launch approvals, pidfd stop, cgroup capture and direct `cgroup.kill`.
|
| 4 |
|
| 5 |
+
The release remains a Linux engineering preview. It does not claim universal AI recognition, behavioural detection, network isolation, malware prevention or EDR replacement. The existing real-AI assets remain external and are not distributed in release archives.
|
SECURITY_MODEL.md
CHANGED
|
@@ -1,7 +1,9 @@
|
|
| 1 |
# Security model
|
| 2 |
|
| 3 |
-
The root-owned `lumi-eggcracker.service` is the only enforcement component. It accepts requests only from root or the configured operator UID over a root-owned Unix socket. A
|
| 4 |
|
| 5 |
-
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
|
|
| 1 |
# Security model
|
| 2 |
|
| 3 |
+
The root-owned `lumi-eggcracker.service` is the only enforcement component. It reads the root-owned detector catalogue, observes bounded process facts from `/proc`, and accepts control requests only from root or the configured operator UID over a root-owned Unix socket. A workload account remains a dedicated no-login unprivileged user with no supplementary groups and cannot access the control socket.
|
| 4 |
|
| 5 |
+
For an unapproved complete catalogue match, Eggcracker revalidates PID plus start-time identity, sends `SIGSTOP` through a pidfd, stops descendants, moves the discovered tree into an exact child cgroup delegated to the supervisor, and writes `1` to `cgroup.kill`. It proves that cgroup hierarchy is empty before writing the detection receipt. Individual pidfd signals are the initial stop/capture mechanism; direct cgroup-v2 `cgroup.kill` remains the authoritative complete-tree kill primitive.
|
| 6 |
|
| 7 |
+
An approval is an exact root-owned record of a UID, resolved executable device/inode and digest, plus complete argv digest. Raw process arguments and environment values are not written to approval or detection records.
|
| 8 |
+
|
| 9 |
+
This is not a general sandbox, universal AI detector, host intrusion detector, malware detector, network isolator, credential isolator or EDR replacement. An unapproved workload can evade a catalogue-based detector by using an unsupported or disguised runtime; that boundary is documented rather than hidden.
|
pyproject.toml
CHANGED
|
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
|
| 4 |
|
| 5 |
[project]
|
| 6 |
name = "lumi-eggcracker"
|
| 7 |
-
version = "0.
|
| 8 |
-
description = "A local Linux kill switch for
|
| 9 |
readme = "README.md"
|
| 10 |
requires-python = ">=3.11"
|
| 11 |
license = "Apache-2.0"
|
|
|
|
| 4 |
|
| 5 |
[project]
|
| 6 |
name = "lumi-eggcracker"
|
| 7 |
+
version = "0.2.0"
|
| 8 |
+
description = "A local Linux kill switch for unapproved supported AI and agent runtimes"
|
| 9 |
readme = "README.md"
|
| 10 |
requires-python = ">=3.11"
|
| 11 |
license = "Apache-2.0"
|
scripts/build_release.py
CHANGED
|
@@ -80,6 +80,8 @@ def main() -> int:
|
|
| 80 |
ROOT / "scripts" / "prepare_ai_smoke.py": "scripts/prepare_ai_smoke.py",
|
| 81 |
ROOT / "scripts" / "ai_smoke_worker.py": "scripts/ai_smoke_worker.py",
|
| 82 |
ROOT / "scripts" / "smoke_local_ai.py": "scripts/smoke_local_ai.py",
|
|
|
|
|
|
|
| 83 |
}
|
| 84 |
with zipfile.ZipFile(bundle, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
|
| 85 |
for path, name in release_files.items():
|
|
|
|
| 80 |
ROOT / "scripts" / "prepare_ai_smoke.py": "scripts/prepare_ai_smoke.py",
|
| 81 |
ROOT / "scripts" / "ai_smoke_worker.py": "scripts/ai_smoke_worker.py",
|
| 82 |
ROOT / "scripts" / "smoke_local_ai.py": "scripts/smoke_local_ai.py",
|
| 83 |
+
ROOT / "scripts" / "smoke_autonomous_ai.py": "scripts/smoke_autonomous_ai.py",
|
| 84 |
+
ROOT / "scripts" / "run_autonomous_matrix.py": "scripts/run_autonomous_matrix.py",
|
| 85 |
}
|
| 86 |
with zipfile.ZipFile(bundle, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
|
| 87 |
for path, name in release_files.items():
|
scripts/install.py
CHANGED
|
@@ -10,13 +10,15 @@ import os
|
|
| 10 |
import pwd
|
| 11 |
import secrets
|
| 12 |
import shutil
|
|
|
|
| 13 |
import stat
|
| 14 |
import subprocess
|
| 15 |
import time
|
|
|
|
| 16 |
from pathlib import Path
|
| 17 |
from typing import Any
|
| 18 |
|
| 19 |
-
VERSION = "0.
|
| 20 |
LIB = Path("/usr/local/lib/lumi-eggcracker")
|
| 21 |
BIN = Path("/usr/local/bin/eggcracker")
|
| 22 |
ETC = Path("/etc/lumi-eggcracker")
|
|
@@ -75,23 +77,51 @@ def workload_account() -> tuple[pwd.struct_passwd, bool]:
|
|
| 75 |
|
| 76 |
|
| 77 |
def service() -> bytes:
|
| 78 |
-
return b"""[Unit]\nDescription=Lumi Eggcracker
|
| 79 |
|
| 80 |
|
| 81 |
-
def
|
|
|
|
|
|
|
| 82 |
unit = f"lumi-eggcracker-preflight-{secrets.token_hex(8)}.service"
|
| 83 |
-
started = run(["/usr/bin/systemd-run", f"--unit={unit}", "--collect", "--property=Type=exec", "--", "/bin/sleep", "5"])
|
| 84 |
if started.returncode:
|
| 85 |
return False
|
| 86 |
try:
|
| 87 |
shown = run(["/usr/bin/systemctl", "show", unit, "--property=ControlGroup"])
|
| 88 |
values = dict(line.split("=", 1) for line in shown.stdout.splitlines() if "=" in line)
|
| 89 |
cgroup = values.get("ControlGroup", "")
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
finally:
|
| 92 |
run(["/usr/bin/systemctl", "stop", unit])
|
| 93 |
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
def cleanup(created: list[Path], created_user: bool, created_group: bool) -> None:
|
| 96 |
run(["/usr/bin/systemctl", "disable", "--now", "lumi-eggcracker.service"])
|
| 97 |
for path in reversed(created):
|
|
@@ -122,8 +152,8 @@ def main() -> int:
|
|
| 122 |
if any(path.exists() or path.is_symlink() for path in TARGETS):
|
| 123 |
raise SystemExit("refusing pre-existing Eggcracker installation target")
|
| 124 |
controllers = Path("/sys/fs/cgroup/cgroup.controllers")
|
| 125 |
-
if not controllers.is_file() or "pids" not in controllers.read_text(encoding="ascii").split() or not
|
| 126 |
-
raise SystemExit("unified cgroup v2
|
| 127 |
account, created_user = workload_account()
|
| 128 |
group = grp.getgrgid(account.pw_gid)
|
| 129 |
created_group = created_user and group.gr_name == WORKLOAD_NAME
|
|
@@ -139,10 +169,13 @@ def main() -> int:
|
|
| 139 |
shutil.copyfile(args.artifact, LIB / "lumi-eggcracker.pyz")
|
| 140 |
os.chmod(LIB / "lumi-eggcracker.pyz", 0o755)
|
| 141 |
write_new(BIN, b"#!/bin/sh\nexec /usr/bin/python3 /usr/local/lib/lumi-eggcracker/lumi-eggcracker.pyz \"$@\"\n", 0o755); created.append(BIN)
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
| 143 |
write_new(ETC / "policy.json", (json.dumps(policy, sort_keys=True) + "\n").encode(), 0o600)
|
| 144 |
write_new(UNIT, service(), 0o644); created.append(UNIT)
|
| 145 |
-
manifest = {"created_workload_group": created_group, "created_workload_user": created_user, "files": {str(BIN): digest(BIN), str(ETC / "policy.json"): digest(ETC / "policy.json"), str(LIB / "lumi-eggcracker.pyz"): digest(LIB / "lumi-eggcracker.pyz"), str(UNIT): digest(UNIT)}, "operator": operator.pw_name, "operator_uid": operator.pw_uid, "schema_version": "lumi-eggcracker.install.
|
| 146 |
write_new(STATE / "install-manifest.json", (json.dumps(manifest, sort_keys=True) + "\n").encode(), 0o600)
|
| 147 |
checked = run(["/usr/bin/systemctl", "daemon-reload"])
|
| 148 |
started = run(["/usr/bin/systemctl", "enable", "--now", "lumi-eggcracker.service"])
|
|
|
|
| 10 |
import pwd
|
| 11 |
import secrets
|
| 12 |
import shutil
|
| 13 |
+
import signal
|
| 14 |
import stat
|
| 15 |
import subprocess
|
| 16 |
import time
|
| 17 |
+
import zipfile
|
| 18 |
from pathlib import Path
|
| 19 |
from typing import Any
|
| 20 |
|
| 21 |
+
VERSION = "0.2.0"
|
| 22 |
LIB = Path("/usr/local/lib/lumi-eggcracker")
|
| 23 |
BIN = Path("/usr/local/bin/eggcracker")
|
| 24 |
ETC = Path("/etc/lumi-eggcracker")
|
|
|
|
| 77 |
|
| 78 |
|
| 79 |
def service() -> bytes:
|
| 80 |
+
return b"""[Unit]\nDescription=Lumi Eggcracker autonomous AI runtime supervisor\nAfter=multi-user.target\nStartLimitIntervalSec=60\nStartLimitBurst=60\n\n[Service]\nType=simple\nExecStart=/usr/bin/python3 /usr/local/lib/lumi-eggcracker/lumi-eggcracker.pyz _supervisor --policy /etc/lumi-eggcracker/policy.json\nRestart=always\nRestartSec=0.1\nRuntimeDirectory=lumi-eggcracker\nRuntimeDirectoryMode=0710\nUMask=0077\nNoNewPrivileges=yes\nDelegate=yes\n\n[Install]\nWantedBy=multi-user.target\n"""
|
| 81 |
|
| 82 |
|
| 83 |
+
def autonomous_primitives_available() -> bool:
|
| 84 |
+
if not hasattr(os, "pidfd_open") or not hasattr(signal, "pidfd_send_signal"):
|
| 85 |
+
return False
|
| 86 |
unit = f"lumi-eggcracker-preflight-{secrets.token_hex(8)}.service"
|
| 87 |
+
started = run(["/usr/bin/systemd-run", f"--unit={unit}", "--collect", "--property=Type=exec", "--property=Delegate=yes", "--", "/bin/sleep", "5"])
|
| 88 |
if started.returncode:
|
| 89 |
return False
|
| 90 |
try:
|
| 91 |
shown = run(["/usr/bin/systemctl", "show", unit, "--property=ControlGroup"])
|
| 92 |
values = dict(line.split("=", 1) for line in shown.stdout.splitlines() if "=" in line)
|
| 93 |
cgroup = values.get("ControlGroup", "")
|
| 94 |
+
root = Path("/sys/fs/cgroup").joinpath(*cgroup.lstrip("/").split("/"))
|
| 95 |
+
child = root / f"lumi-eggcracker-probe-{secrets.token_hex(4)}"
|
| 96 |
+
if not cgroup.startswith("/system.slice/") or not (root / "cgroup.kill").is_file():
|
| 97 |
+
return False
|
| 98 |
+
try:
|
| 99 |
+
child.mkdir(mode=0o700)
|
| 100 |
+
return (child / "cgroup.kill").is_file() and (child / "cgroup.procs").is_file()
|
| 101 |
+
finally:
|
| 102 |
+
if child.exists() and not child.is_symlink():
|
| 103 |
+
child.rmdir()
|
| 104 |
finally:
|
| 105 |
run(["/usr/bin/systemctl", "stop", unit])
|
| 106 |
|
| 107 |
|
| 108 |
+
def catalogue_from_artifact(artifact: Path) -> bytes:
|
| 109 |
+
try:
|
| 110 |
+
with zipfile.ZipFile(artifact) as bundle:
|
| 111 |
+
value = bundle.read("lumi_eggcracker/detector_catalogue.json")
|
| 112 |
+
except (KeyError, OSError, zipfile.BadZipFile) as error:
|
| 113 |
+
raise RuntimeError("release artifact lacks detector catalogue") from error
|
| 114 |
+
if not 1 <= len(value) <= 32 * 1024:
|
| 115 |
+
raise RuntimeError("detector catalogue size is invalid")
|
| 116 |
+
try:
|
| 117 |
+
parsed = json.loads(value.decode("utf-8"))
|
| 118 |
+
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
| 119 |
+
raise RuntimeError("detector catalogue is invalid") from error
|
| 120 |
+
if not isinstance(parsed, dict) or parsed.get("schema_version") != "lumi-eggcracker.detectors.v1":
|
| 121 |
+
raise RuntimeError("detector catalogue schema is invalid")
|
| 122 |
+
return value
|
| 123 |
+
|
| 124 |
+
|
| 125 |
def cleanup(created: list[Path], created_user: bool, created_group: bool) -> None:
|
| 126 |
run(["/usr/bin/systemctl", "disable", "--now", "lumi-eggcracker.service"])
|
| 127 |
for path in reversed(created):
|
|
|
|
| 152 |
if any(path.exists() or path.is_symlink() for path in TARGETS):
|
| 153 |
raise SystemExit("refusing pre-existing Eggcracker installation target")
|
| 154 |
controllers = Path("/sys/fs/cgroup/cgroup.controllers")
|
| 155 |
+
if not controllers.is_file() or "pids" not in controllers.read_text(encoding="ascii").split() or not autonomous_primitives_available():
|
| 156 |
+
raise SystemExit("unified cgroup v2, delegated child cgroups, cgroup.kill and pidfds are required")
|
| 157 |
account, created_user = workload_account()
|
| 158 |
group = grp.getgrgid(account.pw_gid)
|
| 159 |
created_group = created_user and group.gr_name == WORKLOAD_NAME
|
|
|
|
| 169 |
shutil.copyfile(args.artifact, LIB / "lumi-eggcracker.pyz")
|
| 170 |
os.chmod(LIB / "lumi-eggcracker.pyz", 0o755)
|
| 171 |
write_new(BIN, b"#!/bin/sh\nexec /usr/bin/python3 /usr/local/lib/lumi-eggcracker/lumi-eggcracker.pyz \"$@\"\n", 0o755); created.append(BIN)
|
| 172 |
+
catalogue = catalogue_from_artifact(args.artifact)
|
| 173 |
+
catalogue_path = ETC / "detector_catalogue.json"
|
| 174 |
+
write_new(catalogue_path, catalogue, 0o644)
|
| 175 |
+
policy = {"catalogue_path": str(catalogue_path), "catalogue_sha256": hashlib.sha256(catalogue).hexdigest(), "operator_gid": operator.pw_gid, "operator_uid": operator.pw_uid, "schema_version": "lumi-eggcracker.policy.v3", "socket_path": str(SOCKET), "source_commit": release["source_commit"], "state_dir": str(STATE), "unit_prefix": "lumi-eggcracker-workload-", "version": release["version"], "workload_gid": account.pw_gid, "workload_uid": account.pw_uid}
|
| 176 |
write_new(ETC / "policy.json", (json.dumps(policy, sort_keys=True) + "\n").encode(), 0o600)
|
| 177 |
write_new(UNIT, service(), 0o644); created.append(UNIT)
|
| 178 |
+
manifest = {"created_workload_group": created_group, "created_workload_user": created_user, "files": {str(BIN): digest(BIN), str(catalogue_path): digest(catalogue_path), str(ETC / "policy.json"): digest(ETC / "policy.json"), str(LIB / "lumi-eggcracker.pyz"): digest(LIB / "lumi-eggcracker.pyz"), str(UNIT): digest(UNIT)}, "operator": operator.pw_name, "operator_uid": operator.pw_uid, "schema_version": "lumi-eggcracker.install.v3", "targets": [str(path) for path in TARGETS], "workload_group": group.gr_name, "workload_uid": account.pw_uid, "workload_user": account.pw_name}
|
| 179 |
write_new(STATE / "install-manifest.json", (json.dumps(manifest, sort_keys=True) + "\n").encode(), 0o600)
|
| 180 |
checked = run(["/usr/bin/systemctl", "daemon-reload"])
|
| 181 |
started = run(["/usr/bin/systemctl", "enable", "--now", "lumi-eggcracker.service"])
|
scripts/prepare_ai_smoke.py
CHANGED
|
@@ -130,7 +130,7 @@ def download_model(destination: Path) -> None:
|
|
| 130 |
temporary.unlink(missing_ok=True)
|
| 131 |
value = hashlib.sha256()
|
| 132 |
size = 0
|
| 133 |
-
request = urllib.request.Request(MODEL_URL, headers={"User-Agent": "Lumi-Eggcracker-0.
|
| 134 |
try:
|
| 135 |
with urllib.request.urlopen(request, timeout=60) as response, temporary.open("xb") as handle:
|
| 136 |
if not response.url.startswith("https://"):
|
|
|
|
| 130 |
temporary.unlink(missing_ok=True)
|
| 131 |
value = hashlib.sha256()
|
| 132 |
size = 0
|
| 133 |
+
request = urllib.request.Request(MODEL_URL, headers={"User-Agent": "Lumi-Eggcracker-0.2.0"})
|
| 134 |
try:
|
| 135 |
with urllib.request.urlopen(request, timeout=60) as response, temporary.open("xb") as handle:
|
| 136 |
if not response.url.startswith("https://"):
|
scripts/run_autonomous_matrix.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Native root-only qualification of autonomous discovery and containment."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import pwd
|
| 9 |
+
import secrets
|
| 10 |
+
import shutil
|
| 11 |
+
import signal
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
import tempfile
|
| 15 |
+
import time
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 20 |
+
CLI = "/usr/local/bin/eggcracker"
|
| 21 |
+
DETECTIONS = Path("/var/lib/lumi-eggcracker/detections")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def run(argv: list[str], *, timeout: float = 30) -> subprocess.CompletedProcess[str]:
|
| 25 |
+
result = subprocess.run(argv, capture_output=True, text=True, check=False, timeout=timeout)
|
| 26 |
+
if result.returncode:
|
| 27 |
+
raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "command failed")
|
| 28 |
+
return result
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def call(operator: str, argv: list[str]) -> dict[str, Any]:
|
| 32 |
+
value = json.loads(run(["/usr/sbin/runuser", "-u", operator, "--", CLI, *argv]).stdout)
|
| 33 |
+
if not isinstance(value, dict):
|
| 34 |
+
raise TypeError("invalid Eggcracker response")
|
| 35 |
+
return value
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def stop(process: subprocess.Popen[bytes]) -> None:
|
| 39 |
+
if process.poll() is None:
|
| 40 |
+
os.killpg(process.pid, signal.SIGKILL)
|
| 41 |
+
process.wait(timeout=5)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def new_receipt(previous: set[Path], *, timeout: float = 8) -> dict[str, Any]:
|
| 45 |
+
deadline = time.monotonic() + timeout
|
| 46 |
+
while time.monotonic() < deadline:
|
| 47 |
+
created = set(DETECTIONS.glob("*.json")) - previous
|
| 48 |
+
if created:
|
| 49 |
+
value = json.loads(max(created, key=lambda item: item.stat().st_mtime_ns).read_text(encoding="utf-8"))
|
| 50 |
+
if value.get("result") != "TERMINATED":
|
| 51 |
+
raise RuntimeError(f"autonomous containment failed: {value.get('error', value.get('result'))}")
|
| 52 |
+
return value
|
| 53 |
+
time.sleep(0.01)
|
| 54 |
+
raise RuntimeError("autonomous receipt did not appear")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def percentile(values: list[float], percent: int) -> float:
|
| 58 |
+
ordered = sorted(values)
|
| 59 |
+
return ordered[max(0, (len(ordered) * percent + 99) // 100 - 1)]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def launch(user: str, runner: Path, fixture: Path, model: Path) -> subprocess.Popen[bytes]:
|
| 63 |
+
return subprocess.Popen(["/usr/sbin/runuser", "-u", user, "--", str(runner), str(fixture), "-m", str(model)], start_new_session=True)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def fixture_runner(root: Path) -> Path:
|
| 67 |
+
runner = root / "llama-cli"
|
| 68 |
+
shutil.copyfile(Path(sys.executable).resolve(), runner)
|
| 69 |
+
runner.chmod(0o755)
|
| 70 |
+
return runner
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def main() -> int:
|
| 74 |
+
if os.geteuid() != 0:
|
| 75 |
+
raise SystemExit("autonomous matrix must run as root")
|
| 76 |
+
parser = argparse.ArgumentParser()
|
| 77 |
+
parser.add_argument("--discoveries", required=True, type=int)
|
| 78 |
+
parser.add_argument("--approved", required=True, type=int)
|
| 79 |
+
parser.add_argument("--benign", required=True, type=int)
|
| 80 |
+
parser.add_argument("--output", required=True, type=Path)
|
| 81 |
+
args = parser.parse_args()
|
| 82 |
+
if args.discoveries != 100 or args.approved != 50 or args.benign < 200 or args.output.exists() or args.output.is_symlink() or not args.output.parent.is_dir():
|
| 83 |
+
raise SystemExit("qualification counts or output path are invalid")
|
| 84 |
+
install = json.loads(Path("/var/lib/lumi-eggcracker/install-manifest.json").read_text(encoding="utf-8"))
|
| 85 |
+
operator, user = str(install["operator"]), str(install["operator"])
|
| 86 |
+
uid = pwd.getpwnam(user).pw_uid
|
| 87 |
+
results: dict[str, Any] = {"approved": [], "benign": 0, "canary_survival": 0, "discoveries": [], "result": "FAIL"}
|
| 88 |
+
starts: list[float] = []
|
| 89 |
+
empties: list[float] = []
|
| 90 |
+
with tempfile.TemporaryDirectory(prefix="lumi-eggcracker-autonomous-", dir="/tmp") as raw:
|
| 91 |
+
root = Path(raw); runner = fixture_runner(root); model = root / "fixture.gguf"; model.write_bytes(b"fixture")
|
| 92 |
+
fixture = ROOT / "tests" / "fixtures" / "discovery_fork_race.py"
|
| 93 |
+
try:
|
| 94 |
+
doctor = call(operator, ["doctor"])
|
| 95 |
+
if doctor.get("result") != "PASS" or not doctor.get("autonomous_discovery"):
|
| 96 |
+
raise RuntimeError("autonomous discovery is not armed")
|
| 97 |
+
for index in range(args.discoveries):
|
| 98 |
+
canary = subprocess.Popen(["/bin/sleep", "30"], start_new_session=True)
|
| 99 |
+
process: subprocess.Popen[bytes] | None = None
|
| 100 |
+
try:
|
| 101 |
+
before = set(DETECTIONS.glob("*.json")); started = time.monotonic_ns()
|
| 102 |
+
process = launch(user, runner, fixture, model)
|
| 103 |
+
receipt = new_receipt(before)
|
| 104 |
+
process.wait(timeout=10)
|
| 105 |
+
if receipt.get("detector", {}).get("profile") != "llama.cpp" or canary.poll() is not None or receipt.get("containment", {}).get("surviving_pids"):
|
| 106 |
+
raise RuntimeError("autonomous fixture containment or canary proof failed")
|
| 107 |
+
starts.append((receipt["containment"]["first_stop_monotonic_ns"] - started) / 1_000_000)
|
| 108 |
+
empties.append(float(receipt["containment"]["trigger_to_empty_ms"]))
|
| 109 |
+
results["discoveries"].append(receipt["event_id"]); results["canary_survival"] += 1
|
| 110 |
+
finally:
|
| 111 |
+
if process is not None:
|
| 112 |
+
stop(process)
|
| 113 |
+
stop(canary)
|
| 114 |
+
for index in range(args.approved):
|
| 115 |
+
name = f"allow-{secrets.token_hex(6)}"
|
| 116 |
+
argv = [str(runner), str(fixture), "-m", str(model)]
|
| 117 |
+
call(operator, ["approve", "--name", name, "--uid", str(uid), "--", *argv])
|
| 118 |
+
process = launch(user, runner, fixture, model)
|
| 119 |
+
try:
|
| 120 |
+
time.sleep(0.2)
|
| 121 |
+
if process.poll() is not None:
|
| 122 |
+
raise RuntimeError("exact approved invocation was killed")
|
| 123 |
+
results["approved"].append(name)
|
| 124 |
+
finally:
|
| 125 |
+
stop(process)
|
| 126 |
+
call(operator, ["revoke", "--name", name])
|
| 127 |
+
for _ in range(args.benign):
|
| 128 |
+
process = subprocess.Popen(["/usr/sbin/runuser", "-u", user, "--", sys.executable, "-c", "import time; time.sleep(0.03)"], start_new_session=True)
|
| 129 |
+
process.wait(timeout=5)
|
| 130 |
+
if process.returncode != 0:
|
| 131 |
+
raise RuntimeError("benign process was interrupted")
|
| 132 |
+
results["benign"] += 1
|
| 133 |
+
if percentile(starts, 95) >= 500 or percentile(empties, 95) >= 500:
|
| 134 |
+
raise RuntimeError("autonomous latency gate failed")
|
| 135 |
+
results["latency_ms"] = {"process_start_to_first_stop_p95": percentile(starts, 95), "trigger_to_empty_p95": percentile(empties, 95)}
|
| 136 |
+
results["result"] = "PASS"
|
| 137 |
+
args.output.write_text(json.dumps(results, sort_keys=True) + "\n", encoding="utf-8")
|
| 138 |
+
return 0
|
| 139 |
+
except Exception as error:
|
| 140 |
+
results["error"] = str(error)
|
| 141 |
+
if not args.output.exists():
|
| 142 |
+
args.output.write_text(json.dumps(results, sort_keys=True) + "\n", encoding="utf-8")
|
| 143 |
+
raise
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
raise SystemExit(main())
|
scripts/smoke_autonomous_ai.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run a real unmanaged local AI invocation through autonomous Eggcracker containment."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import pwd
|
| 10 |
+
import signal
|
| 11 |
+
import subprocess
|
| 12 |
+
import tempfile
|
| 13 |
+
import time
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 18 |
+
DETECTIONS = Path("/var/lib/lumi-eggcracker/detections")
|
| 19 |
+
ASSET_SCHEMA = "lumi-eggcracker.ai-smoke-assets.v1"
|
| 20 |
+
CLI = "/usr/local/bin/eggcracker"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def digest(path: Path) -> str:
|
| 24 |
+
value = hashlib.sha256()
|
| 25 |
+
with path.open("rb") as handle:
|
| 26 |
+
for block in iter(lambda: handle.read(64 * 1024), b""):
|
| 27 |
+
value.update(block)
|
| 28 |
+
return value.hexdigest()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def assets_from_manifest(path: Path) -> tuple[Path, Path, dict[str, Any]]:
|
| 32 |
+
if path.is_symlink() or not path.is_file():
|
| 33 |
+
raise RuntimeError("asset manifest must be a regular file")
|
| 34 |
+
value = json.loads(path.read_text(encoding="utf-8"))
|
| 35 |
+
if set(value) != {"llama", "model", "platform", "schema_version"} or value.get("schema_version") != ASSET_SCHEMA:
|
| 36 |
+
raise RuntimeError("AI smoke asset manifest schema is invalid")
|
| 37 |
+
runner, model = Path(value["llama"]["path"]), Path(value["model"]["path"])
|
| 38 |
+
if any(path.is_symlink() or not path.is_file() for path in (runner, model)) or not os.access(runner, os.X_OK):
|
| 39 |
+
raise RuntimeError("AI smoke assets are invalid")
|
| 40 |
+
if digest(runner) != value["llama"]["sha256"] or digest(model) != value["model"]["sha256"]:
|
| 41 |
+
raise RuntimeError("AI smoke asset digest differs from manifest")
|
| 42 |
+
return runner, model, value
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def call(user: str, argv: list[str]) -> dict[str, Any]:
|
| 46 |
+
result = subprocess.run(["/usr/sbin/runuser", "-u", user, "--", CLI, *argv], capture_output=True, text=True, check=False, timeout=30)
|
| 47 |
+
if result.returncode:
|
| 48 |
+
raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "Eggcracker control command failed")
|
| 49 |
+
value = json.loads(result.stdout)
|
| 50 |
+
if not isinstance(value, dict):
|
| 51 |
+
raise TypeError("Eggcracker control command returned invalid JSON")
|
| 52 |
+
return value
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def stop(process: subprocess.Popen[bytes]) -> None:
|
| 56 |
+
if process.poll() is None:
|
| 57 |
+
os.killpg(process.pid, signal.SIGKILL)
|
| 58 |
+
process.wait(timeout=5)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def receipt_after(previous: set[Path], *, timeout: float = 90) -> dict[str, Any]:
|
| 62 |
+
deadline = time.monotonic() + timeout
|
| 63 |
+
while time.monotonic() < deadline:
|
| 64 |
+
paths = set(DETECTIONS.glob("*.json"))
|
| 65 |
+
created = paths - previous
|
| 66 |
+
if created:
|
| 67 |
+
path = max(created, key=lambda item: item.stat().st_mtime_ns)
|
| 68 |
+
value = json.loads(path.read_text(encoding="utf-8"))
|
| 69 |
+
if value.get("result") == "TERMINATED":
|
| 70 |
+
return value
|
| 71 |
+
raise RuntimeError(f"autonomous containment failed: {value.get('error', value.get('result'))}")
|
| 72 |
+
time.sleep(0.02)
|
| 73 |
+
raise RuntimeError("autonomous detection receipt did not appear")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def generated(path: Path) -> bool:
|
| 77 |
+
return path.is_file() and not path.is_symlink() and path.stat().st_size >= 32
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def runner_argv(runner: Path, model: Path) -> list[str]:
|
| 81 |
+
return [str(runner), "-m", str(model), "-p", "Explain one Linux cgroup property.", "-n", "4096", "-t", "12", "-tb", "12", "-c", "512", "--simple-io", "--single-turn", "--no-warmup", "--no-display-prompt", "--seed", "1234"]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def launch(user: str, argv: list[str], output: Path) -> subprocess.Popen[bytes]:
|
| 85 |
+
handle = output.open("wb")
|
| 86 |
+
try:
|
| 87 |
+
return subprocess.Popen(["/usr/sbin/runuser", "-u", user, "--", *argv], stdout=handle, stderr=subprocess.DEVNULL, start_new_session=True)
|
| 88 |
+
finally:
|
| 89 |
+
handle.close()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def one(*, runner: Path, model: Path, user: str, index: int, provenance: dict[str, Any]) -> dict[str, Any]:
|
| 93 |
+
argv = runner_argv(runner, model)
|
| 94 |
+
with tempfile.TemporaryDirectory(prefix="lumi-eggcracker-autonomous-", dir="/tmp") as raw:
|
| 95 |
+
root = Path(raw); output = root / "generated.txt"
|
| 96 |
+
os.chmod(root, 0o711)
|
| 97 |
+
canary = subprocess.Popen(["/bin/sleep", "180"], start_new_session=True)
|
| 98 |
+
unapproved: subprocess.Popen[bytes] | None = None
|
| 99 |
+
allowed: subprocess.Popen[bytes] | None = None
|
| 100 |
+
name = f"real-qwen-{index}"
|
| 101 |
+
try:
|
| 102 |
+
before = set(DETECTIONS.glob("*.json"))
|
| 103 |
+
unapproved = launch(user, argv, output)
|
| 104 |
+
receipt = receipt_after(before)
|
| 105 |
+
unapproved.wait(timeout=15)
|
| 106 |
+
if receipt.get("trigger", {}).get("kind") != "UNAPPROVED_AI_MATCH" or receipt.get("detector", {}).get("profile") != "llama.cpp" or canary.poll() is not None:
|
| 107 |
+
raise RuntimeError("unapproved real AI result or canary is invalid")
|
| 108 |
+
approval = call(user, ["approve", "--name", name, "--uid", str(pwd.getpwnam(user).pw_uid), "--", *argv])
|
| 109 |
+
if approval.get("result") != "APPROVED":
|
| 110 |
+
raise RuntimeError("exact real-AI approval failed")
|
| 111 |
+
allowed = launch(user, argv, output)
|
| 112 |
+
deadline = time.monotonic() + 120
|
| 113 |
+
while time.monotonic() < deadline and not generated(output):
|
| 114 |
+
time.sleep(0.05)
|
| 115 |
+
if not generated(output) or allowed.poll() is not None:
|
| 116 |
+
raise RuntimeError("approved real AI did not remain alive and generate output")
|
| 117 |
+
stop(allowed); allowed = None
|
| 118 |
+
call(user, ["revoke", "--name", name])
|
| 119 |
+
before = set(DETECTIONS.glob("*.json"))
|
| 120 |
+
unapproved = launch(user, argv, output)
|
| 121 |
+
receipt_after_revoke = receipt_after(before)
|
| 122 |
+
unapproved.wait(timeout=15)
|
| 123 |
+
if receipt_after_revoke.get("result") != "TERMINATED" or canary.poll() is not None:
|
| 124 |
+
raise RuntimeError("revoked real AI was not autonomously terminated")
|
| 125 |
+
return {"asset_model_sha256": provenance["model"]["sha256"], "asset_runner_sha256": provenance["llama"]["sha256"], "approved_generated_bytes": output.stat().st_size, "first_receipt": receipt, "result": "PASS", "second_receipt": receipt_after_revoke}
|
| 126 |
+
finally:
|
| 127 |
+
if unapproved is not None:
|
| 128 |
+
stop(unapproved)
|
| 129 |
+
if allowed is not None:
|
| 130 |
+
stop(allowed)
|
| 131 |
+
stop(canary)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def main() -> int:
|
| 135 |
+
if os.geteuid() != 0:
|
| 136 |
+
raise SystemExit("autonomous real-AI smoke must run as root")
|
| 137 |
+
parser = argparse.ArgumentParser()
|
| 138 |
+
parser.add_argument("--assets-manifest", required=True, type=Path)
|
| 139 |
+
parser.add_argument("--user", required=True)
|
| 140 |
+
parser.add_argument("--repetitions", required=True, type=int)
|
| 141 |
+
parser.add_argument("--output", required=True, type=Path)
|
| 142 |
+
args = parser.parse_args()
|
| 143 |
+
if args.output.exists() or args.output.is_symlink() or not args.output.parent.is_dir() or args.repetitions != 5:
|
| 144 |
+
raise SystemExit("output must be new and repetitions must equal five")
|
| 145 |
+
try:
|
| 146 |
+
pwd.getpwnam(args.user)
|
| 147 |
+
runner, model, provenance = assets_from_manifest(args.assets_manifest)
|
| 148 |
+
values = [one(runner=runner, model=model, user=args.user, index=index, provenance=provenance) for index in range(args.repetitions)]
|
| 149 |
+
args.output.write_text(json.dumps({"repetitions": values, "result": "PASS"}, sort_keys=True) + "\n", encoding="utf-8")
|
| 150 |
+
return 0
|
| 151 |
+
except (OSError, RuntimeError, TypeError, json.JSONDecodeError) as error:
|
| 152 |
+
if not args.output.exists():
|
| 153 |
+
args.output.write_text(json.dumps({"error": str(error), "result": "FAIL"}, sort_keys=True) + "\n", encoding="utf-8")
|
| 154 |
+
raise SystemExit(f"autonomous real-AI smoke failed: {error}") from error
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
if __name__ == "__main__":
|
| 158 |
+
raise SystemExit(main())
|
scripts/uninstall.py
CHANGED
|
@@ -18,6 +18,7 @@ UNIT = Path("/etc/systemd/system/lumi-eggcracker.service")
|
|
| 18 |
STATE = Path("/var/lib/lumi-eggcracker")
|
| 19 |
RUNTIME = Path("/run/lumi-eggcracker")
|
| 20 |
PREFIX = "lumi-eggcracker-workload-"
|
|
|
|
| 21 |
|
| 22 |
|
| 23 |
def digest(path: Path) -> str:
|
|
@@ -49,6 +50,25 @@ def owned_cgroups_empty() -> bool:
|
|
| 49 |
return True
|
| 50 |
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
def main() -> int:
|
| 53 |
if os.geteuid() != 0:
|
| 54 |
raise SystemExit("uninstaller must run as root")
|
|
@@ -56,16 +76,16 @@ def main() -> int:
|
|
| 56 |
if manifest_path.is_symlink() or not manifest_path.is_file():
|
| 57 |
raise SystemExit("installed manifest is missing")
|
| 58 |
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 59 |
-
if manifest.get("schema_version") != "lumi-eggcracker.install.
|
| 60 |
raise SystemExit("installed manifest schema is invalid")
|
| 61 |
for name, expected in manifest.get("files", {}).items():
|
| 62 |
path = Path(name)
|
| 63 |
if path.is_symlink() or not path.is_file() or digest(path) != expected:
|
| 64 |
raise SystemExit(f"refusing uninstall because installed file drifted: {path}")
|
| 65 |
-
|
|
|
|
| 66 |
raise SystemExit("refusing uninstall with populated or uncertain Eggcracker cgroups")
|
| 67 |
-
run(["/usr/bin/systemctl", "
|
| 68 |
-
run(["/usr/bin/systemctl", "reset-failed", "lumi-eggcracker.service"])
|
| 69 |
for path in (UNIT, BIN, LIB, ETC, STATE, RUNTIME):
|
| 70 |
if path.exists() and not path.is_symlink():
|
| 71 |
shutil.rmtree(path) if path.is_dir() else path.unlink()
|
|
|
|
| 18 |
STATE = Path("/var/lib/lumi-eggcracker")
|
| 19 |
RUNTIME = Path("/run/lumi-eggcracker")
|
| 20 |
PREFIX = "lumi-eggcracker-workload-"
|
| 21 |
+
SUPERVISOR = "lumi-eggcracker.service"
|
| 22 |
|
| 23 |
|
| 24 |
def digest(path: Path) -> str:
|
|
|
|
| 50 |
return True
|
| 51 |
|
| 52 |
|
| 53 |
+
def quarantine_empty() -> bool:
|
| 54 |
+
root = Path("/sys/fs/cgroup/system.slice/lumi-eggcracker.service/quarantine")
|
| 55 |
+
if not root.exists():
|
| 56 |
+
return True
|
| 57 |
+
if root.is_symlink() or not root.is_dir():
|
| 58 |
+
return False
|
| 59 |
+
for path in root.iterdir():
|
| 60 |
+
if path.is_symlink() or not path.is_dir() or len(path.name) != 24 or any(item not in "0123456789abcdef" for item in path.name):
|
| 61 |
+
return False
|
| 62 |
+
events = path / "cgroup.events"
|
| 63 |
+
try:
|
| 64 |
+
populated = dict(line.split(" ", 1) for line in events.read_text(encoding="ascii").splitlines()).get("populated")
|
| 65 |
+
except OSError:
|
| 66 |
+
return False
|
| 67 |
+
if populated != "0":
|
| 68 |
+
return False
|
| 69 |
+
return True
|
| 70 |
+
|
| 71 |
+
|
| 72 |
def main() -> int:
|
| 73 |
if os.geteuid() != 0:
|
| 74 |
raise SystemExit("uninstaller must run as root")
|
|
|
|
| 76 |
if manifest_path.is_symlink() or not manifest_path.is_file():
|
| 77 |
raise SystemExit("installed manifest is missing")
|
| 78 |
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 79 |
+
if manifest.get("schema_version") != "lumi-eggcracker.install.v3":
|
| 80 |
raise SystemExit("installed manifest schema is invalid")
|
| 81 |
for name, expected in manifest.get("files", {}).items():
|
| 82 |
path = Path(name)
|
| 83 |
if path.is_symlink() or not path.is_file() or digest(path) != expected:
|
| 84 |
raise SystemExit(f"refusing uninstall because installed file drifted: {path}")
|
| 85 |
+
run(["/usr/bin/systemctl", "disable", "--now", SUPERVISOR])
|
| 86 |
+
if not owned_cgroups_empty() or not quarantine_empty():
|
| 87 |
raise SystemExit("refusing uninstall with populated or uncertain Eggcracker cgroups")
|
| 88 |
+
run(["/usr/bin/systemctl", "reset-failed", SUPERVISOR])
|
|
|
|
| 89 |
for path in (UNIT, BIN, LIB, ETC, STATE, RUNTIME):
|
| 90 |
if path.exists() and not path.is_symlink():
|
| 91 |
shutil.rmtree(path) if path.is_dir() else path.unlink()
|
scripts/verify_evidence.py
CHANGED
|
@@ -7,8 +7,8 @@ import json
|
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
REQUIRED = {
|
| 10 |
-
"environment.json", "
|
| 11 |
-
"
|
| 12 |
"SHA256SUMS", "report.md",
|
| 13 |
}
|
| 14 |
|
|
@@ -22,14 +22,16 @@ def main() -> int:
|
|
| 22 |
if found != REQUIRED:
|
| 23 |
raise SystemExit(f"evidence pack files differ: {sorted(found)}")
|
| 24 |
manifest = json.loads((args.evidence / "release-manifest.json").read_text(encoding="utf-8"))
|
| 25 |
-
|
| 26 |
-
matrix = json.loads((args.evidence / "
|
| 27 |
-
smoke = json.loads((args.evidence / "ai-smoke.json").read_text(encoding="utf-8"))
|
|
|
|
| 28 |
if (
|
| 29 |
manifest.get("source_commit") != args.require_source_commit
|
| 30 |
or matrix.get("result") != "PASS"
|
| 31 |
or smoke.get("result") != "PASS"
|
| 32 |
-
or
|
|
|
|
| 33 |
or len(smoke.get("repetitions", [])) != 5
|
| 34 |
):
|
| 35 |
raise SystemExit("evidence does not meet release gate")
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
REQUIRED = {
|
| 10 |
+
"environment.json", "catalogue.json", "autonomous-matrix.json",
|
| 11 |
+
"real-ai-smoke.json", "benign-matrix.json", "install-cycle.json", "release-manifest.json",
|
| 12 |
"SHA256SUMS", "report.md",
|
| 13 |
}
|
| 14 |
|
|
|
|
| 22 |
if found != REQUIRED:
|
| 23 |
raise SystemExit(f"evidence pack files differ: {sorted(found)}")
|
| 24 |
manifest = json.loads((args.evidence / "release-manifest.json").read_text(encoding="utf-8"))
|
| 25 |
+
catalogue = json.loads((args.evidence / "catalogue.json").read_text(encoding="utf-8"))
|
| 26 |
+
matrix = json.loads((args.evidence / "autonomous-matrix.json").read_text(encoding="utf-8"))
|
| 27 |
+
smoke = json.loads((args.evidence / "real-ai-smoke.json").read_text(encoding="utf-8"))
|
| 28 |
+
benign = json.loads((args.evidence / "benign-matrix.json").read_text(encoding="utf-8"))
|
| 29 |
if (
|
| 30 |
manifest.get("source_commit") != args.require_source_commit
|
| 31 |
or matrix.get("result") != "PASS"
|
| 32 |
or smoke.get("result") != "PASS"
|
| 33 |
+
or not isinstance(catalogue.get("digest"), str)
|
| 34 |
+
or benign.get("result") != "PASS"
|
| 35 |
or len(smoke.get("repetitions", [])) != 5
|
| 36 |
):
|
| 37 |
raise SystemExit("evidence does not meet release gate")
|
scripts/verify_release.py
CHANGED
|
@@ -10,7 +10,7 @@ import sys
|
|
| 10 |
import zipfile
|
| 11 |
from pathlib import Path
|
| 12 |
|
| 13 |
-
VERSION = "0.
|
| 14 |
PREFIX = f"lumi-eggcracker-{VERSION}/"
|
| 15 |
FORBIDDEN = (
|
| 16 |
"/mnt/" + "f/", "f" + ":\\", "network" + "-deny", "network" + "_rule",
|
|
@@ -47,7 +47,7 @@ def main() -> int:
|
|
| 47 |
manifest = json.loads((args.artifact.parent / "release-manifest.json").read_text(encoding="utf-8"))
|
| 48 |
if manifest.get("version") != VERSION or manifest.get("artifact") != args.artifact.name:
|
| 49 |
raise SystemExit("release manifest is inconsistent")
|
| 50 |
-
expected = {PREFIX + name for name in (args.artifact.name, args.source_archive.name, "release-manifest.json", "SHA256SUMS", "README.md", "LICENSE", "LIMITATIONS.md", "SECURITY.md", "SECURITY_MODEL.md", "QUALIFICATION.md", "RELEASE_NOTES.md", "scripts/install.py", "scripts/uninstall.py", "scripts/verify_uninstalled.py", "scripts/prepare_ai_smoke.py", "scripts/ai_smoke_worker.py", "scripts/smoke_local_ai.py")}
|
| 51 |
with zipfile.ZipFile(args.release_bundle) as archive:
|
| 52 |
if set(archive.namelist()) != expected:
|
| 53 |
raise SystemExit("release bundle contents are inconsistent")
|
|
|
|
| 10 |
import zipfile
|
| 11 |
from pathlib import Path
|
| 12 |
|
| 13 |
+
VERSION = "0.2.0"
|
| 14 |
PREFIX = f"lumi-eggcracker-{VERSION}/"
|
| 15 |
FORBIDDEN = (
|
| 16 |
"/mnt/" + "f/", "f" + ":\\", "network" + "-deny", "network" + "_rule",
|
|
|
|
| 47 |
manifest = json.loads((args.artifact.parent / "release-manifest.json").read_text(encoding="utf-8"))
|
| 48 |
if manifest.get("version") != VERSION or manifest.get("artifact") != args.artifact.name:
|
| 49 |
raise SystemExit("release manifest is inconsistent")
|
| 50 |
+
expected = {PREFIX + name for name in (args.artifact.name, args.source_archive.name, "release-manifest.json", "SHA256SUMS", "README.md", "LICENSE", "LIMITATIONS.md", "SECURITY.md", "SECURITY_MODEL.md", "QUALIFICATION.md", "RELEASE_NOTES.md", "scripts/install.py", "scripts/uninstall.py", "scripts/verify_uninstalled.py", "scripts/prepare_ai_smoke.py", "scripts/ai_smoke_worker.py", "scripts/smoke_local_ai.py", "scripts/smoke_autonomous_ai.py", "scripts/run_autonomous_matrix.py")}
|
| 51 |
with zipfile.ZipFile(args.release_bundle) as archive:
|
| 52 |
if set(archive.namelist()) != expected:
|
| 53 |
raise SystemExit("release bundle contents are inconsistent")
|
src/lumi_eggcracker/__init__.py
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
-
"""Lumi Eggcracker:
|
| 2 |
|
| 3 |
-
__version__ = "0.
|
|
|
|
| 1 |
+
"""Lumi Eggcracker: autonomous Linux AI-runtime containment."""
|
| 2 |
|
| 3 |
+
__version__ = "0.2.0"
|
src/lumi_eggcracker/adoption.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stop, capture and cgroup-kill a discovered host process tree."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import errno
|
| 6 |
+
import os
|
| 7 |
+
import signal
|
| 8 |
+
import time
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from .containment import EmptyProof, events_from_fd, kill_path
|
| 13 |
+
from .discovery import PROC, ProcessIdentity, identity
|
| 14 |
+
from .jsonio import JsonInputError
|
| 15 |
+
|
| 16 |
+
MAX_CAPTURED = 4096
|
| 17 |
+
MAX_CAPTURE_SECONDS = 0.5
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass(frozen=True)
|
| 21 |
+
class QuarantineIdentity:
|
| 22 |
+
path: Path
|
| 23 |
+
device: int
|
| 24 |
+
inode: int
|
| 25 |
+
event_id: str
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass(frozen=True)
|
| 29 |
+
class AdoptionResult:
|
| 30 |
+
identity: QuarantineIdentity
|
| 31 |
+
captured: tuple[ProcessIdentity, ...]
|
| 32 |
+
fixed_point_scans: int
|
| 33 |
+
first_stop_ns: int
|
| 34 |
+
kill_started_ns: int
|
| 35 |
+
kill_complete_ns: int
|
| 36 |
+
empty_ns: int
|
| 37 |
+
proof: EmptyProof
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def pidfd_available() -> bool:
|
| 41 |
+
return hasattr(os, "pidfd_open") and hasattr(signal, "pidfd_send_signal")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _same(value: ProcessIdentity, *, proc: Path = PROC) -> bool:
|
| 45 |
+
return identity(value.pid, proc=proc) == value
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def stop(value: ProcessIdentity, *, proc: Path = PROC) -> int:
|
| 49 |
+
"""Stop one revalidated identity through a pidfd; return completion time."""
|
| 50 |
+
if not pidfd_available():
|
| 51 |
+
raise JsonInputError("pidfd_send_signal is unavailable")
|
| 52 |
+
if not _same(value, proc=proc):
|
| 53 |
+
raise ProcessLookupError(errno.ESRCH, "process identity vanished")
|
| 54 |
+
descriptor = os.pidfd_open(value.pid, 0)
|
| 55 |
+
try:
|
| 56 |
+
if not _same(value, proc=proc):
|
| 57 |
+
raise ProcessLookupError(errno.ESRCH, "process identity changed")
|
| 58 |
+
signal.pidfd_send_signal(descriptor, signal.SIGSTOP)
|
| 59 |
+
return time.monotonic_ns()
|
| 60 |
+
finally:
|
| 61 |
+
os.close(descriptor)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _kill(value: ProcessIdentity, *, proc: Path = PROC) -> None:
|
| 65 |
+
if not pidfd_available() or not _same(value, proc=proc):
|
| 66 |
+
return
|
| 67 |
+
try:
|
| 68 |
+
descriptor = os.pidfd_open(value.pid, 0)
|
| 69 |
+
except OSError:
|
| 70 |
+
return
|
| 71 |
+
try:
|
| 72 |
+
signal.pidfd_send_signal(descriptor, signal.SIGKILL)
|
| 73 |
+
except OSError:
|
| 74 |
+
return
|
| 75 |
+
finally:
|
| 76 |
+
os.close(descriptor)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def children(value: ProcessIdentity, *, proc: Path = PROC) -> set[ProcessIdentity]:
|
| 80 |
+
result: set[ProcessIdentity] = set()
|
| 81 |
+
tasks = proc / str(value.pid) / "task"
|
| 82 |
+
try:
|
| 83 |
+
entries = list(tasks.iterdir())
|
| 84 |
+
except OSError:
|
| 85 |
+
return result
|
| 86 |
+
for task in entries:
|
| 87 |
+
try:
|
| 88 |
+
raw = (task / "children").read_text(encoding="ascii", errors="strict")
|
| 89 |
+
except OSError:
|
| 90 |
+
continue
|
| 91 |
+
for field in raw.split():
|
| 92 |
+
if not field.isdigit():
|
| 93 |
+
raise JsonInputError("process children file is invalid")
|
| 94 |
+
item = identity(int(field), proc=proc)
|
| 95 |
+
if item is not None:
|
| 96 |
+
result.add(item)
|
| 97 |
+
return result
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def descendants(roots: set[ProcessIdentity], *, proc: Path = PROC, maximum: int = MAX_CAPTURED) -> set[ProcessIdentity]:
|
| 101 |
+
result = set(roots)
|
| 102 |
+
pending = list(roots)
|
| 103 |
+
while pending:
|
| 104 |
+
current = pending.pop()
|
| 105 |
+
for child in children(current, proc=proc):
|
| 106 |
+
if child not in result:
|
| 107 |
+
if len(result) >= maximum:
|
| 108 |
+
raise JsonInputError("discovered process tree exceeds capture limit")
|
| 109 |
+
result.add(child)
|
| 110 |
+
pending.append(child)
|
| 111 |
+
return result
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _events(path: Path) -> dict[str, int]:
|
| 115 |
+
with (path / "cgroup.events").open("rb", buffering=0) as handle:
|
| 116 |
+
return events_from_fd(handle.fileno())
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _validate(identity_value: QuarantineIdentity, root: Path) -> Path:
|
| 120 |
+
path = identity_value.path
|
| 121 |
+
if path.parent != root or path.name != identity_value.event_id or path.is_symlink() or not path.is_dir():
|
| 122 |
+
raise JsonInputError("quarantine cgroup is invalid")
|
| 123 |
+
metadata = path.stat(follow_symlinks=False)
|
| 124 |
+
if metadata.st_dev != identity_value.device or metadata.st_ino != identity_value.inode:
|
| 125 |
+
raise JsonInputError("quarantine cgroup identity drifted")
|
| 126 |
+
if not all((path / item).is_file() for item in ("cgroup.events", "cgroup.kill", "cgroup.procs")):
|
| 127 |
+
raise JsonInputError("quarantine cgroup lacks required controls")
|
| 128 |
+
return path
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def create_quarantine(root: Path, event_id: str) -> QuarantineIdentity:
|
| 132 |
+
if not root.is_dir() or root.is_symlink() or len(event_id) != 24 or any(character not in "0123456789abcdef" for character in event_id):
|
| 133 |
+
raise JsonInputError("quarantine root or event identity is invalid")
|
| 134 |
+
path = root / event_id
|
| 135 |
+
try:
|
| 136 |
+
path.mkdir(mode=0o700)
|
| 137 |
+
except FileExistsError as error:
|
| 138 |
+
raise JsonInputError("quarantine cgroup already exists") from error
|
| 139 |
+
metadata = path.stat(follow_symlinks=False)
|
| 140 |
+
value = QuarantineIdentity(path, metadata.st_dev, metadata.st_ino, event_id)
|
| 141 |
+
_validate(value, root)
|
| 142 |
+
return value
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _move(value: ProcessIdentity, destination: Path, *, proc: Path = PROC) -> bool:
|
| 146 |
+
if not _same(value, proc=proc):
|
| 147 |
+
return False
|
| 148 |
+
descriptor = os.open(destination / "cgroup.procs", os.O_WRONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0))
|
| 149 |
+
try:
|
| 150 |
+
os.write(descriptor, f"{value.pid}\n".encode("ascii"))
|
| 151 |
+
finally:
|
| 152 |
+
os.close(descriptor)
|
| 153 |
+
return True
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _survivors(path: Path) -> tuple[list[int], int]:
|
| 157 |
+
directories = [path, *(item for item in path.rglob("*") if item.is_dir() and not item.is_symlink())]
|
| 158 |
+
values: list[int] = []
|
| 159 |
+
for directory in directories:
|
| 160 |
+
for raw in (directory / "cgroup.procs").read_text(encoding="ascii").splitlines():
|
| 161 |
+
if not raw.isdigit():
|
| 162 |
+
raise JsonInputError("quarantine cgroup contains invalid PID")
|
| 163 |
+
values.append(int(raw))
|
| 164 |
+
return sorted(set(values)), len(directories)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def verify_empty(value: QuarantineIdentity, root: Path, *, deadline_seconds: float = 0.9) -> tuple[int, EmptyProof]:
|
| 168 |
+
deadline = time.monotonic() + deadline_seconds
|
| 169 |
+
last = EmptyProof(False, 0, -1, [])
|
| 170 |
+
while time.monotonic() <= deadline:
|
| 171 |
+
path = _validate(value, root)
|
| 172 |
+
state = _events(path)
|
| 173 |
+
survivors, count = _survivors(path)
|
| 174 |
+
populated = state.get("populated", -1)
|
| 175 |
+
last = EmptyProof(populated == 0 and not survivors, count, populated, survivors)
|
| 176 |
+
if last.complete:
|
| 177 |
+
return time.monotonic_ns(), last
|
| 178 |
+
kill_path(path)
|
| 179 |
+
time.sleep(0.002)
|
| 180 |
+
return time.monotonic_ns(), last
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _remove(value: QuarantineIdentity, root: Path) -> None:
|
| 184 |
+
path = _validate(value, root)
|
| 185 |
+
if _events(path).get("populated") != 0 or (path / "cgroup.procs").read_text(encoding="ascii").strip():
|
| 186 |
+
raise JsonInputError("cannot remove populated quarantine cgroup")
|
| 187 |
+
path.rmdir()
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def contain(target: ProcessIdentity, root: Path, event_id: str, *, proc: Path = PROC) -> AdoptionResult:
|
| 191 |
+
"""The first durable operation happens only after pidfd stop and cgroup kill."""
|
| 192 |
+
trigger_deadline = time.monotonic() + MAX_CAPTURE_SECONDS
|
| 193 |
+
first_stop = stop(target, proc=proc)
|
| 194 |
+
captured: set[ProcessIdentity] = {target}
|
| 195 |
+
fixed = 0
|
| 196 |
+
quarantine: QuarantineIdentity | None = None
|
| 197 |
+
try:
|
| 198 |
+
quarantine = create_quarantine(root, event_id)
|
| 199 |
+
while True:
|
| 200 |
+
captured = descendants(captured, proc=proc)
|
| 201 |
+
if len(captured) > MAX_CAPTURED:
|
| 202 |
+
raise JsonInputError("discovered process tree exceeds capture limit")
|
| 203 |
+
for current in sorted(captured):
|
| 204 |
+
try:
|
| 205 |
+
stop(current, proc=proc)
|
| 206 |
+
except ProcessLookupError:
|
| 207 |
+
continue
|
| 208 |
+
for current in sorted(captured):
|
| 209 |
+
_move(current, quarantine.path, proc=proc)
|
| 210 |
+
current_tree = descendants(captured, proc=proc)
|
| 211 |
+
if current_tree == captured:
|
| 212 |
+
fixed += 1
|
| 213 |
+
if fixed >= 2:
|
| 214 |
+
break
|
| 215 |
+
else:
|
| 216 |
+
captured = current_tree
|
| 217 |
+
fixed = 0
|
| 218 |
+
if time.monotonic() > trigger_deadline:
|
| 219 |
+
raise JsonInputError("discovered process tree did not reach capture fixed point")
|
| 220 |
+
time.sleep(0.002)
|
| 221 |
+
path = _validate(quarantine, root)
|
| 222 |
+
kill_started, kill_complete = kill_path(path)
|
| 223 |
+
empty_ns, proof = verify_empty(quarantine, root)
|
| 224 |
+
if not proof.complete:
|
| 225 |
+
raise JsonInputError("quarantine cgroup did not become empty")
|
| 226 |
+
result = AdoptionResult(quarantine, tuple(sorted(captured)), fixed, first_stop, kill_started, kill_complete, empty_ns, proof)
|
| 227 |
+
_remove(quarantine, root)
|
| 228 |
+
return result
|
| 229 |
+
except Exception:
|
| 230 |
+
for current in captured:
|
| 231 |
+
_kill(current, proc=proc)
|
| 232 |
+
try:
|
| 233 |
+
if quarantine is not None:
|
| 234 |
+
path = _validate(quarantine, root)
|
| 235 |
+
kill_path(path)
|
| 236 |
+
_remove(quarantine, root)
|
| 237 |
+
except (JsonInputError, OSError):
|
| 238 |
+
pass
|
| 239 |
+
raise
|
src/lumi_eggcracker/approvals.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact root-owned approval records for known AI invocations."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
import time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from .discovery import argv_digest, executable_digest
|
| 11 |
+
from .jsonio import JsonInputError, load_regular_json
|
| 12 |
+
from .records import write_atomic
|
| 13 |
+
|
| 14 |
+
SCHEMA = "lumi-eggcracker.approval.v1"
|
| 15 |
+
NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}\Z")
|
| 16 |
+
HEX = re.compile(r"[0-9a-f]{64}\Z")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _path(root: Path, name: str) -> Path:
|
| 20 |
+
if not isinstance(name, str) or not NAME.fullmatch(name):
|
| 21 |
+
raise JsonInputError("approval name is invalid")
|
| 22 |
+
return root / f"{name}.json"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def validate(value: dict[str, Any]) -> dict[str, Any]:
|
| 26 |
+
expected = {"argv_count", "argv_sha256", "created_monotonic_ns", "executable", "executable_device", "executable_inode", "executable_sha256", "name", "operator_uid", "schema_version", "uid"}
|
| 27 |
+
if set(value) != expected or value.get("schema_version") != SCHEMA:
|
| 28 |
+
raise JsonInputError("approval schema is invalid")
|
| 29 |
+
if not isinstance(value["name"], str) or not NAME.fullmatch(value["name"]):
|
| 30 |
+
raise JsonInputError("approval name is invalid")
|
| 31 |
+
for key in ("argv_sha256", "executable_sha256"):
|
| 32 |
+
if not isinstance(value[key], str) or not HEX.fullmatch(value[key]):
|
| 33 |
+
raise JsonInputError("approval digest is invalid")
|
| 34 |
+
if not isinstance(value["executable"], str) or not Path(value["executable"]).is_absolute():
|
| 35 |
+
raise JsonInputError("approval executable path is invalid")
|
| 36 |
+
for key in ("argv_count", "created_monotonic_ns", "executable_device", "executable_inode", "operator_uid", "uid"):
|
| 37 |
+
if isinstance(value[key], bool) or not isinstance(value[key], int) or value[key] < 0:
|
| 38 |
+
raise JsonInputError("approval integer field is invalid")
|
| 39 |
+
return value
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def create(root: Path, *, name: str, uid: int, argv: list[str], operator_uid: int) -> dict[str, Any]:
|
| 43 |
+
if isinstance(uid, bool) or not isinstance(uid, int) or uid < 1 or not argv or not all(isinstance(item, str) and item for item in argv):
|
| 44 |
+
raise JsonInputError("approval arguments are invalid")
|
| 45 |
+
supplied = Path(argv[0])
|
| 46 |
+
if not supplied.is_absolute():
|
| 47 |
+
raise JsonInputError("approval executable must be an absolute regular file")
|
| 48 |
+
try:
|
| 49 |
+
executable = supplied.resolve(strict=True)
|
| 50 |
+
except OSError as error:
|
| 51 |
+
raise JsonInputError("approval executable cannot be resolved") from error
|
| 52 |
+
metadata = executable.stat(follow_symlinks=False)
|
| 53 |
+
if executable.is_symlink() or not executable.is_file():
|
| 54 |
+
raise JsonInputError("approval executable must be regular")
|
| 55 |
+
destination = _path(root, name)
|
| 56 |
+
if destination.exists() or destination.is_symlink():
|
| 57 |
+
raise JsonInputError("approval name is unavailable")
|
| 58 |
+
value = validate({"argv_count": len(argv), "argv_sha256": argv_digest(argv), "created_monotonic_ns": time.monotonic_ns(), "executable": str(executable), "executable_device": metadata.st_dev, "executable_inode": metadata.st_ino, "executable_sha256": executable_digest(executable), "name": name, "operator_uid": operator_uid, "schema_version": SCHEMA, "uid": uid})
|
| 59 |
+
write_atomic(destination, value)
|
| 60 |
+
return value
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def load_all(root: Path) -> list[dict[str, Any]]:
|
| 64 |
+
if not root.exists():
|
| 65 |
+
return []
|
| 66 |
+
if root.is_symlink() or not root.is_dir():
|
| 67 |
+
raise JsonInputError("approval root is invalid")
|
| 68 |
+
values: list[dict[str, Any]] = []
|
| 69 |
+
for path in sorted(root.glob("*.json")):
|
| 70 |
+
if path.name != f"{path.stem}.json":
|
| 71 |
+
raise JsonInputError("approval filename is invalid")
|
| 72 |
+
value = validate(load_regular_json(path))
|
| 73 |
+
if value["name"] != path.stem:
|
| 74 |
+
raise JsonInputError("approval name/path mismatch")
|
| 75 |
+
values.append(value)
|
| 76 |
+
return values
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def approved(snapshot: Any, digest: str, approvals: list[dict[str, Any]]) -> bool:
|
| 80 |
+
command_hash = argv_digest(snapshot.argv)
|
| 81 |
+
try:
|
| 82 |
+
metadata = Path(snapshot.exe_path).stat(follow_symlinks=False)
|
| 83 |
+
except OSError:
|
| 84 |
+
return False
|
| 85 |
+
return any(item["uid"] == snapshot.uid and item["executable"] == snapshot.exe_path and item["executable_device"] == metadata.st_dev and item["executable_inode"] == metadata.st_ino and item["executable_sha256"] == digest and item["argv_count"] == len(snapshot.argv) and item["argv_sha256"] == command_hash for item in approvals)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def revoke(root: Path, name: str) -> dict[str, Any]:
|
| 89 |
+
path = _path(root, name)
|
| 90 |
+
value = validate(load_regular_json(path))
|
| 91 |
+
if value["name"] != name:
|
| 92 |
+
raise JsonInputError("approval name/path mismatch")
|
| 93 |
+
path.unlink()
|
| 94 |
+
return {"name": name, "result": "REVOKED"}
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def public(value: dict[str, Any]) -> dict[str, Any]:
|
| 98 |
+
return {key: value[key] for key in ("argv_count", "argv_sha256", "created_monotonic_ns", "executable", "executable_sha256", "name", "operator_uid", "uid")}
|
src/lumi_eggcracker/cli.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Public
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
@@ -27,6 +27,14 @@ def _parser() -> argparse.ArgumentParser:
|
|
| 27 |
status = commands.add_parser("status", help="show one protected workload")
|
| 28 |
status.add_argument("--name", required=True)
|
| 29 |
commands.add_parser("list", help="list protected workloads")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
commands.add_parser("doctor", help="check the installed protected supervisor")
|
| 31 |
commands.add_parser("version", help="print the public version")
|
| 32 |
return parser
|
|
@@ -57,6 +65,14 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 57 |
value = request("status", name=args.name)
|
| 58 |
elif args.command == "list":
|
| 59 |
value = request("list")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
else:
|
| 61 |
# This validation is deliberately read-only: no receipt reservation before kill.
|
| 62 |
if args.receipt.exists() or args.receipt.is_symlink() or not args.receipt.parent.is_dir():
|
|
|
|
| 1 |
+
"""Public CLI for protected workloads and autonomous AI-runtime enforcement."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 27 |
status = commands.add_parser("status", help="show one protected workload")
|
| 28 |
status.add_argument("--name", required=True)
|
| 29 |
commands.add_parser("list", help="list protected workloads")
|
| 30 |
+
approve = commands.add_parser("approve", help="approve one exact AI runtime invocation")
|
| 31 |
+
approve.add_argument("--name", required=True)
|
| 32 |
+
approve.add_argument("--uid", required=True, type=int)
|
| 33 |
+
approve.add_argument("argv", nargs=argparse.REMAINDER)
|
| 34 |
+
revoke = commands.add_parser("revoke", help="revoke one exact AI runtime approval")
|
| 35 |
+
revoke.add_argument("--name", required=True)
|
| 36 |
+
commands.add_parser("approvals", help="list exact AI runtime approvals")
|
| 37 |
+
commands.add_parser("detections", help="list autonomous containment summaries")
|
| 38 |
commands.add_parser("doctor", help="check the installed protected supervisor")
|
| 39 |
commands.add_parser("version", help="print the public version")
|
| 40 |
return parser
|
|
|
|
| 65 |
value = request("status", name=args.name)
|
| 66 |
elif args.command == "list":
|
| 67 |
value = request("list")
|
| 68 |
+
elif args.command == "approve":
|
| 69 |
+
value = request("approve", name=args.name, uid=args.uid, argv=_command(args.argv))
|
| 70 |
+
elif args.command == "revoke":
|
| 71 |
+
value = request("revoke", name=args.name)
|
| 72 |
+
elif args.command == "approvals":
|
| 73 |
+
value = request("approvals")
|
| 74 |
+
elif args.command == "detections":
|
| 75 |
+
value = request("detections")
|
| 76 |
else:
|
| 77 |
# This validation is deliberately read-only: no receipt reservation before kill.
|
| 78 |
if args.receipt.exists() or args.receipt.is_symlink() or not args.receipt.parent.is_dir():
|
src/lumi_eggcracker/detector_catalogue.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"profiles":[{"all":[{"kind":"exe_basename","values":["llama-cli","llama-server","main"]},{"kind":"argv_model_suffix","values":[".gguf"]}],"id":"llama.cpp"},{"all":[{"kind":"exe_basename","values":["ollama"]},{"kind":"argv_token","values":["serve","runner"]}],"id":"ollama"},{"all":[{"kind":"exe_basename","values":["python","python3","python3.11","python3.12"]},{"kind":"argv_token","values":["vllm"]}],"id":"vllm-python"},{"all":[{"kind":"exe_basename","values":["vllm"]}],"id":"vllm"},{"all":[{"kind":"exe_basename","values":["text-generation-launcher","text-generation-server"]}],"id":"text-generation-inference"},{"all":[{"kind":"exe_basename","values":["local-ai","localai"]},{"kind":"argv_token","values":["serve","run"]}],"id":"localai"},{"all":[{"kind":"exe_basename","values":["llamafile"]},{"kind":"argv_model_suffix","values":[".gguf"]}],"id":"llamafile"},{"all":[{"kind":"exe_basename","values":["crewai","autogenstudio","langgraph"]}],"id":"agent-cli"},{"all":[{"kind":"exe_basename","values":["python","python3","python3.11","python3.12"]},{"kind":"argv_token","values":["crewai","autogenstudio","langgraph"]}],"id":"agent-python"}],"schema_version":"lumi-eggcracker.detectors.v1"}
|
src/lumi_eggcracker/detectors.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Strict deterministic AI-runtime detector catalogue."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import importlib.resources
|
| 7 |
+
import json
|
| 8 |
+
import re
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from typing import Any, Protocol
|
| 11 |
+
|
| 12 |
+
from .jsonio import JsonInputError, canonical_bytes
|
| 13 |
+
|
| 14 |
+
SCHEMA = "lumi-eggcracker.detectors.v1"
|
| 15 |
+
HEX = re.compile(r"[0-9a-f]{64}\Z")
|
| 16 |
+
KINDS = {"exe_basename", "argv_token", "argv_model_suffix", "open_model_suffix", "map_basename"}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Snapshot(Protocol):
|
| 20 |
+
exe_basename: str
|
| 21 |
+
argv: tuple[str, ...]
|
| 22 |
+
fd_paths: tuple[str, ...]
|
| 23 |
+
map_basenames: tuple[str, ...]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass(frozen=True)
|
| 27 |
+
class Profile:
|
| 28 |
+
identifier: str
|
| 29 |
+
predicates: tuple[dict[str, Any], ...]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass(frozen=True)
|
| 33 |
+
class Catalogue:
|
| 34 |
+
digest: str
|
| 35 |
+
profiles: tuple[Profile, ...]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def bundled_bytes() -> bytes:
|
| 39 |
+
return importlib.resources.files("lumi_eggcracker").joinpath("detector_catalogue.json").read_bytes()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
| 43 |
+
result: dict[str, Any] = {}
|
| 44 |
+
for key, value in pairs:
|
| 45 |
+
if key in result:
|
| 46 |
+
raise JsonInputError("duplicate detector catalogue key")
|
| 47 |
+
result[key] = value
|
| 48 |
+
return result
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def load_catalogue(raw: bytes, *, expected_digest: str | None = None) -> Catalogue:
|
| 52 |
+
digest = hashlib.sha256(raw).hexdigest()
|
| 53 |
+
if expected_digest is not None and (not HEX.fullmatch(expected_digest) or digest != expected_digest):
|
| 54 |
+
raise JsonInputError("detector catalogue digest is invalid")
|
| 55 |
+
try:
|
| 56 |
+
value = json.loads(raw.decode("utf-8"), object_pairs_hook=_pairs)
|
| 57 |
+
except (UnicodeDecodeError, json.JSONDecodeError, JsonInputError) as error:
|
| 58 |
+
raise JsonInputError(f"detector catalogue is invalid: {error}") from error
|
| 59 |
+
if not isinstance(value, dict) or set(value) != {"profiles", "schema_version"} or value.get("schema_version") != SCHEMA:
|
| 60 |
+
raise JsonInputError("detector catalogue schema is invalid")
|
| 61 |
+
profiles = value["profiles"]
|
| 62 |
+
if not isinstance(profiles, list) or not profiles:
|
| 63 |
+
raise JsonInputError("detector catalogue profiles are invalid")
|
| 64 |
+
result: list[Profile] = []
|
| 65 |
+
seen: set[str] = set()
|
| 66 |
+
for item in profiles:
|
| 67 |
+
if not isinstance(item, dict) or set(item) != {"all", "id"}:
|
| 68 |
+
raise JsonInputError("detector profile schema is invalid")
|
| 69 |
+
identifier, predicates = item["id"], item["all"]
|
| 70 |
+
if not isinstance(identifier, str) or not re.fullmatch(r"[a-z][a-z0-9.-]{0,63}", identifier) or identifier in seen:
|
| 71 |
+
raise JsonInputError("detector profile identity is invalid")
|
| 72 |
+
if not isinstance(predicates, list) or not predicates:
|
| 73 |
+
raise JsonInputError("detector profile predicates are invalid")
|
| 74 |
+
clean: list[dict[str, Any]] = []
|
| 75 |
+
for predicate in predicates:
|
| 76 |
+
if not isinstance(predicate, dict) or set(predicate) != {"kind", "values"}:
|
| 77 |
+
raise JsonInputError("detector predicate schema is invalid")
|
| 78 |
+
kind, values = predicate["kind"], predicate["values"]
|
| 79 |
+
if kind not in KINDS or not isinstance(values, list) or not values or not all(isinstance(entry, str) and 1 <= len(entry) <= 128 for entry in values):
|
| 80 |
+
raise JsonInputError("detector predicate is invalid")
|
| 81 |
+
clean.append({"kind": kind, "values": tuple(values)})
|
| 82 |
+
seen.add(identifier)
|
| 83 |
+
result.append(Profile(identifier, tuple(clean)))
|
| 84 |
+
return Catalogue(digest, tuple(result))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def load_bundled(*, expected_digest: str | None = None) -> Catalogue:
|
| 88 |
+
return load_catalogue(bundled_bytes(), expected_digest=expected_digest)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _matches(snapshot: Snapshot, predicate: dict[str, Any]) -> bool:
|
| 92 |
+
values = tuple(predicate["values"])
|
| 93 |
+
kind = predicate["kind"]
|
| 94 |
+
if kind == "exe_basename":
|
| 95 |
+
return snapshot.exe_basename in values
|
| 96 |
+
if kind == "argv_token":
|
| 97 |
+
return any(token in values for token in snapshot.argv)
|
| 98 |
+
if kind == "argv_model_suffix":
|
| 99 |
+
return any(argument.lower().endswith(tuple(values)) for argument in snapshot.argv)
|
| 100 |
+
if kind == "open_model_suffix":
|
| 101 |
+
return any(path.lower().endswith(tuple(values)) for path in snapshot.fd_paths)
|
| 102 |
+
if kind == "map_basename":
|
| 103 |
+
return any(name in values for name in snapshot.map_basenames)
|
| 104 |
+
raise JsonInputError("unknown detector predicate")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def match(catalogue: Catalogue, snapshot: Snapshot) -> tuple[str, tuple[str, ...]] | None:
|
| 108 |
+
"""Return one complete profile match, never a partial or scored decision."""
|
| 109 |
+
for profile in catalogue.profiles:
|
| 110 |
+
matched = tuple(predicate["kind"] for predicate in profile.predicates if _matches(snapshot, predicate))
|
| 111 |
+
if len(matched) == len(profile.predicates):
|
| 112 |
+
return profile.identifier, matched
|
| 113 |
+
return None
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def public_catalogue(catalogue: Catalogue) -> dict[str, Any]:
|
| 117 |
+
return {"digest": catalogue.digest, "profiles": [{"id": profile.identifier, "predicates": [item["kind"] for item in profile.predicates]} for profile in catalogue.profiles], "schema_version": SCHEMA}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def canonical_catalogue_bytes(catalogue: Catalogue) -> bytes:
|
| 121 |
+
"""Small deterministic public representation used only by direct tests."""
|
| 122 |
+
return canonical_bytes(public_catalogue(catalogue))
|
src/lumi_eggcracker/discovery.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bounded `/proc` process identities and snapshots for autonomous discovery."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import os
|
| 7 |
+
import stat
|
| 8 |
+
from collections.abc import Callable
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from .jsonio import JsonInputError
|
| 13 |
+
|
| 14 |
+
PROC = Path("/proc")
|
| 15 |
+
MAX_READ = 64 * 1024
|
| 16 |
+
MAX_FDS = 256
|
| 17 |
+
MAX_MAPS = 512
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass(frozen=True, order=True)
|
| 21 |
+
class ProcessIdentity:
|
| 22 |
+
pid: int
|
| 23 |
+
start_time: int
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass(frozen=True)
|
| 27 |
+
class ProcessSnapshot:
|
| 28 |
+
identity: ProcessIdentity
|
| 29 |
+
uid: int
|
| 30 |
+
exe_path: str
|
| 31 |
+
exe_basename: str
|
| 32 |
+
argv: tuple[str, ...]
|
| 33 |
+
cgroups: tuple[str, ...]
|
| 34 |
+
fd_paths: tuple[str, ...]
|
| 35 |
+
map_basenames: tuple[str, ...]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _read(path: Path, limit: int = MAX_READ) -> bytes:
|
| 39 |
+
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0))
|
| 40 |
+
try:
|
| 41 |
+
value = os.read(descriptor, limit + 1)
|
| 42 |
+
finally:
|
| 43 |
+
os.close(descriptor)
|
| 44 |
+
if len(value) > limit:
|
| 45 |
+
raise JsonInputError(f"bounded proc read exceeded for {path.name}")
|
| 46 |
+
return value
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def parse_stat(raw: str) -> tuple[int, int]:
|
| 50 |
+
"""Return (parent PID, process start time) from a Linux stat record."""
|
| 51 |
+
end = raw.rfind(")")
|
| 52 |
+
fields = raw[end + 2 :].split()
|
| 53 |
+
if end < 1 or len(fields) < 20 or not fields[1].isdigit() or not fields[19].isdigit():
|
| 54 |
+
raise JsonInputError("process stat is invalid")
|
| 55 |
+
return int(fields[1]), int(fields[19])
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def identity(pid: int, *, proc: Path = PROC) -> ProcessIdentity | None:
|
| 59 |
+
if pid < 1:
|
| 60 |
+
return None
|
| 61 |
+
try:
|
| 62 |
+
_parent, start = parse_stat(_read(proc / str(pid) / "stat", 4096).decode("utf-8"))
|
| 63 |
+
except (OSError, UnicodeDecodeError, JsonInputError):
|
| 64 |
+
return None
|
| 65 |
+
return ProcessIdentity(pid, start)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def argv_digest(argv: tuple[str, ...] | list[str]) -> str:
|
| 69 |
+
return hashlib.sha256("\0".join(argv).encode("utf-8")).hexdigest()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def executable_digest(path: Path) -> str:
|
| 73 |
+
metadata = path.stat(follow_symlinks=False)
|
| 74 |
+
if not stat.S_ISREG(metadata.st_mode):
|
| 75 |
+
raise JsonInputError("detected executable is not a regular file")
|
| 76 |
+
value = hashlib.sha256()
|
| 77 |
+
with path.open("rb") as handle:
|
| 78 |
+
for block in iter(lambda: handle.read(64 * 1024), b""):
|
| 79 |
+
value.update(block)
|
| 80 |
+
return value.hexdigest()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _uid(raw: str) -> int:
|
| 84 |
+
for line in raw.splitlines():
|
| 85 |
+
if line.startswith("Uid:"):
|
| 86 |
+
fields = line.split()
|
| 87 |
+
if len(fields) >= 2 and fields[1].isdigit():
|
| 88 |
+
return int(fields[1])
|
| 89 |
+
raise JsonInputError("process status lacks UID")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _links(directory: Path, *, limit: int) -> tuple[str, ...]:
|
| 93 |
+
values: list[str] = []
|
| 94 |
+
for item in sorted(directory.iterdir(), key=lambda value: value.name)[:limit]:
|
| 95 |
+
try:
|
| 96 |
+
target = os.readlink(item)
|
| 97 |
+
except OSError:
|
| 98 |
+
continue
|
| 99 |
+
if len(target) <= 4096:
|
| 100 |
+
values.append(target.removesuffix(" (deleted)"))
|
| 101 |
+
return tuple(values)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _maps(path: Path) -> tuple[str, ...]:
|
| 105 |
+
try:
|
| 106 |
+
raw = _read(path).decode("utf-8", errors="replace")
|
| 107 |
+
except OSError:
|
| 108 |
+
return ()
|
| 109 |
+
values: list[str] = []
|
| 110 |
+
for line in raw.splitlines()[:MAX_MAPS]:
|
| 111 |
+
parts = line.split(maxsplit=5)
|
| 112 |
+
if len(parts) == 6 and parts[5].startswith("/"):
|
| 113 |
+
values.append(Path(parts[5].removesuffix(" (deleted)")).name)
|
| 114 |
+
return tuple(values)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def snapshot(value: ProcessIdentity, *, proc: Path = PROC) -> ProcessSnapshot | None:
|
| 118 |
+
current = identity(value.pid, proc=proc)
|
| 119 |
+
if current != value:
|
| 120 |
+
return None
|
| 121 |
+
root = proc / str(value.pid)
|
| 122 |
+
try:
|
| 123 |
+
exe = os.readlink(root / "exe")
|
| 124 |
+
command = tuple(item for item in _read(root / "cmdline").decode("utf-8").split("\0") if item)
|
| 125 |
+
cgroups = tuple(line for line in _read(root / "cgroup", 8192).decode("utf-8").splitlines() if line)
|
| 126 |
+
uid = _uid(_read(root / "status", 8192).decode("utf-8"))
|
| 127 |
+
fd_paths = _links(root / "fd", limit=MAX_FDS)
|
| 128 |
+
except (OSError, UnicodeDecodeError, JsonInputError):
|
| 129 |
+
return None
|
| 130 |
+
if not command or not exe or len(exe) > 4096:
|
| 131 |
+
return None
|
| 132 |
+
return ProcessSnapshot(value, uid, exe, Path(exe.removesuffix(" (deleted)")).name, command, cgroups, fd_paths, _maps(root / "maps"))
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def scan(*, proc: Path = PROC, exclude: Callable[[ProcessSnapshot], bool] | None = None) -> list[ProcessSnapshot]:
|
| 136 |
+
result: list[ProcessSnapshot] = []
|
| 137 |
+
try:
|
| 138 |
+
candidates = sorted(int(item.name) for item in proc.iterdir() if item.name.isdigit())
|
| 139 |
+
except OSError as error:
|
| 140 |
+
raise JsonInputError(f"cannot enumerate proc: {error}") from error
|
| 141 |
+
for pid in candidates:
|
| 142 |
+
item = identity(pid, proc=proc)
|
| 143 |
+
if item is None:
|
| 144 |
+
continue
|
| 145 |
+
current = snapshot(item, proc=proc)
|
| 146 |
+
if current is not None and not (exclude and exclude(current)):
|
| 147 |
+
result.append(current)
|
| 148 |
+
return result
|
src/lumi_eggcracker/supervisor.py
CHANGED
|
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|
| 5 |
import argparse
|
| 6 |
import datetime as dt
|
| 7 |
import errno
|
|
|
|
| 8 |
import json
|
| 9 |
import os
|
| 10 |
import re
|
|
@@ -20,6 +21,11 @@ from pathlib import Path
|
|
| 20 |
from typing import Any
|
| 21 |
|
| 22 |
from . import __version__
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
from .containment import (
|
| 24 |
capture_identity,
|
| 25 |
events_from_fd,
|
|
@@ -27,6 +33,8 @@ from .containment import (
|
|
| 27 |
validate_identity,
|
| 28 |
verify_empty,
|
| 29 |
)
|
|
|
|
|
|
|
| 30 |
from .jsonio import JsonInputError, load_regular_json
|
| 31 |
from .records import (
|
| 32 |
ACTIVE_STATES,
|
|
@@ -44,12 +52,13 @@ from .records import (
|
|
| 44 |
|
| 45 |
MAX_FRAME = 32 * 1024
|
| 46 |
NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}\Z")
|
| 47 |
-
POLICY_SCHEMA = "lumi-eggcracker.policy.
|
| 48 |
SOCKET_PATH = Path("/run/lumi-eggcracker/control.sock")
|
| 49 |
STATE_DIR = Path("/var/lib/lumi-eggcracker")
|
| 50 |
UNIT_PREFIX = "lumi-eggcracker-workload-"
|
| 51 |
GATES_DIR = Path("/run/lumi-eggcracker/gates")
|
| 52 |
MAX_TERMINAL_RECORDS = 128
|
|
|
|
| 53 |
|
| 54 |
|
| 55 |
def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
@@ -96,7 +105,7 @@ class Supervisor:
|
|
| 96 |
if os.geteuid() != 0:
|
| 97 |
raise JsonInputError("supervisor must run as root")
|
| 98 |
policy = load_regular_json(policy_path)
|
| 99 |
-
expected = {"operator_gid", "operator_uid", "schema_version", "socket_path", "source_commit", "state_dir", "unit_prefix", "version", "workload_gid", "workload_uid"}
|
| 100 |
if set(policy) != expected or policy["schema_version"] != POLICY_SCHEMA:
|
| 101 |
raise JsonInputError("supervisor policy schema is invalid")
|
| 102 |
for key in ("operator_gid", "operator_uid", "workload_gid", "workload_uid"):
|
|
@@ -108,16 +117,27 @@ class Supervisor:
|
|
| 108 |
raise JsonInputError("supervisor policy path is invalid")
|
| 109 |
if policy["version"] != __version__ or not isinstance(policy["source_commit"], str):
|
| 110 |
raise JsonInputError("supervisor build identity is invalid")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
self.policy = policy
|
| 112 |
self.runs = STATE_DIR / "runs"
|
| 113 |
self.names = STATE_DIR / "names"
|
| 114 |
self.receipts = STATE_DIR / "receipts"
|
|
|
|
|
|
|
|
|
|
| 115 |
self.stop_event = threading.Event()
|
| 116 |
self.locks: dict[str, threading.Lock] = {}
|
| 117 |
self.lock_guard = threading.Lock()
|
| 118 |
self.start_lock = threading.Lock()
|
| 119 |
self.completed: dict[str, dict[str, Any]] = {}
|
| 120 |
self.operations: list[str] = [] # Test-visible ordering only.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
@property
|
| 123 |
def operator_uid(self) -> int:
|
|
@@ -196,13 +216,130 @@ class Supervisor:
|
|
| 196 |
# Workloads need traversal only to their group-readable gate. The
|
| 197 |
# control socket remains a root/operator 0660 inode, so traversal does
|
| 198 |
# not grant control-socket access or directory listing.
|
| 199 |
-
for path, mode, gid in ((SOCKET_PATH.parent, 0o711, self.policy["operator_gid"]), (GATES_DIR, 0o710, self.policy["workload_gid"]), (STATE_DIR, 0o700, 0), (self.runs, 0o700, 0), (self.names, 0o700, 0), (self.receipts, 0o700, 0)):
|
| 200 |
path.mkdir(mode=mode, parents=True, exist_ok=True)
|
| 201 |
os.chown(path, 0, gid)
|
| 202 |
os.chmod(path, mode)
|
| 203 |
if SOCKET_PATH.exists() or SOCKET_PATH.is_symlink():
|
| 204 |
raise JsonInputError("control socket already exists")
|
| 205 |
self._recover()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
def _cleanup(self, unit: str) -> dict[str, Any]:
|
| 208 |
result = self._run(["/usr/bin/systemctl", "stop", unit])
|
|
@@ -438,7 +575,8 @@ class Supervisor:
|
|
| 438 |
action, args = value["action"], value["args"]
|
| 439 |
if action == "doctor" and not args:
|
| 440 |
available = Path("/sys/fs/cgroup/cgroup.controllers").is_file() and "pids" in Path("/sys/fs/cgroup/cgroup.controllers").read_text(encoding="ascii").split()
|
| 441 |
-
|
|
|
|
| 442 |
if action == "start":
|
| 443 |
return self._start(args)
|
| 444 |
if action == "status" and set(args) == {"name"}:
|
|
@@ -450,12 +588,30 @@ class Supervisor:
|
|
| 450 |
if action == "list" and not args:
|
| 451 |
runs = [self.handle({"action": "status", "args": {"name": path.stem}}) for path in sorted(self.names.glob("*.json"))]
|
| 452 |
return {"runs": runs}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
if action == "kill" and set(args) == {"name"}:
|
| 454 |
return self._contain(self._load(args["name"]), "OPERATOR")
|
| 455 |
raise JsonInputError("unsupported supervisor action")
|
| 456 |
|
| 457 |
def serve(self) -> int:
|
| 458 |
self._prepare()
|
|
|
|
|
|
|
| 459 |
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as listener:
|
| 460 |
listener.bind(str(SOCKET_PATH))
|
| 461 |
os.chown(SOCKET_PATH, 0, self.policy["operator_gid"])
|
|
|
|
| 5 |
import argparse
|
| 6 |
import datetime as dt
|
| 7 |
import errno
|
| 8 |
+
import hashlib
|
| 9 |
import json
|
| 10 |
import os
|
| 11 |
import re
|
|
|
|
| 21 |
from typing import Any
|
| 22 |
|
| 23 |
from . import __version__
|
| 24 |
+
from .adoption import AdoptionResult, contain, pidfd_available
|
| 25 |
+
from .approvals import approved, revoke
|
| 26 |
+
from .approvals import create as create_approval
|
| 27 |
+
from .approvals import load_all as load_approvals
|
| 28 |
+
from .approvals import public as public_approval
|
| 29 |
from .containment import (
|
| 30 |
capture_identity,
|
| 31 |
events_from_fd,
|
|
|
|
| 33 |
validate_identity,
|
| 34 |
verify_empty,
|
| 35 |
)
|
| 36 |
+
from .detectors import Catalogue, load_catalogue, match, public_catalogue
|
| 37 |
+
from .discovery import ProcessIdentity, ProcessSnapshot, executable_digest, scan
|
| 38 |
from .jsonio import JsonInputError, load_regular_json
|
| 39 |
from .records import (
|
| 40 |
ACTIVE_STATES,
|
|
|
|
| 52 |
|
| 53 |
MAX_FRAME = 32 * 1024
|
| 54 |
NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}\Z")
|
| 55 |
+
POLICY_SCHEMA = "lumi-eggcracker.policy.v3"
|
| 56 |
SOCKET_PATH = Path("/run/lumi-eggcracker/control.sock")
|
| 57 |
STATE_DIR = Path("/var/lib/lumi-eggcracker")
|
| 58 |
UNIT_PREFIX = "lumi-eggcracker-workload-"
|
| 59 |
GATES_DIR = Path("/run/lumi-eggcracker/gates")
|
| 60 |
MAX_TERMINAL_RECORDS = 128
|
| 61 |
+
DETECTION_LIMIT = 1000
|
| 62 |
|
| 63 |
|
| 64 |
def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
|
|
| 105 |
if os.geteuid() != 0:
|
| 106 |
raise JsonInputError("supervisor must run as root")
|
| 107 |
policy = load_regular_json(policy_path)
|
| 108 |
+
expected = {"catalogue_path", "catalogue_sha256", "operator_gid", "operator_uid", "schema_version", "socket_path", "source_commit", "state_dir", "unit_prefix", "version", "workload_gid", "workload_uid"}
|
| 109 |
if set(policy) != expected or policy["schema_version"] != POLICY_SCHEMA:
|
| 110 |
raise JsonInputError("supervisor policy schema is invalid")
|
| 111 |
for key in ("operator_gid", "operator_uid", "workload_gid", "workload_uid"):
|
|
|
|
| 117 |
raise JsonInputError("supervisor policy path is invalid")
|
| 118 |
if policy["version"] != __version__ or not isinstance(policy["source_commit"], str):
|
| 119 |
raise JsonInputError("supervisor build identity is invalid")
|
| 120 |
+
catalogue_path = Path(policy["catalogue_path"])
|
| 121 |
+
if catalogue_path != Path("/etc/lumi-eggcracker/detector_catalogue.json") or catalogue_path.is_symlink() or not catalogue_path.is_file():
|
| 122 |
+
raise JsonInputError("supervisor detector catalogue path is invalid")
|
| 123 |
+
self.catalogue: Catalogue = load_catalogue(catalogue_path.read_bytes(), expected_digest=policy["catalogue_sha256"])
|
| 124 |
self.policy = policy
|
| 125 |
self.runs = STATE_DIR / "runs"
|
| 126 |
self.names = STATE_DIR / "names"
|
| 127 |
self.receipts = STATE_DIR / "receipts"
|
| 128 |
+
self.approvals = STATE_DIR / "approvals"
|
| 129 |
+
self.detections = STATE_DIR / "detections"
|
| 130 |
+
self.quarantine_root: Path | None = None
|
| 131 |
self.stop_event = threading.Event()
|
| 132 |
self.locks: dict[str, threading.Lock] = {}
|
| 133 |
self.lock_guard = threading.Lock()
|
| 134 |
self.start_lock = threading.Lock()
|
| 135 |
self.completed: dict[str, dict[str, Any]] = {}
|
| 136 |
self.operations: list[str] = [] # Test-visible ordering only.
|
| 137 |
+
self.discovery_lock = threading.Lock()
|
| 138 |
+
self.discovery_active: set[ProcessIdentity] = set()
|
| 139 |
+
self.discovery_thread: threading.Thread | None = None
|
| 140 |
+
self.digest_cache: dict[tuple[int, int, int, int], str] = {}
|
| 141 |
|
| 142 |
@property
|
| 143 |
def operator_uid(self) -> int:
|
|
|
|
| 216 |
# Workloads need traversal only to their group-readable gate. The
|
| 217 |
# control socket remains a root/operator 0660 inode, so traversal does
|
| 218 |
# not grant control-socket access or directory listing.
|
| 219 |
+
for path, mode, gid in ((SOCKET_PATH.parent, 0o711, self.policy["operator_gid"]), (GATES_DIR, 0o710, self.policy["workload_gid"]), (STATE_DIR, 0o700, 0), (self.runs, 0o700, 0), (self.names, 0o700, 0), (self.receipts, 0o700, 0), (self.approvals, 0o700, 0), (self.detections, 0o700, 0)):
|
| 220 |
path.mkdir(mode=mode, parents=True, exist_ok=True)
|
| 221 |
os.chown(path, 0, gid)
|
| 222 |
os.chmod(path, mode)
|
| 223 |
if SOCKET_PATH.exists() or SOCKET_PATH.is_symlink():
|
| 224 |
raise JsonInputError("control socket already exists")
|
| 225 |
self._recover()
|
| 226 |
+
self.quarantine_root = self._prepare_quarantine()
|
| 227 |
+
self._scan_once(synchronous=True)
|
| 228 |
+
|
| 229 |
+
def _prepare_quarantine(self) -> Path:
|
| 230 |
+
"""Create only the delegated child cgroup root of this exact service."""
|
| 231 |
+
cgroup = ""
|
| 232 |
+
for line in Path("/proc/self/cgroup").read_text(encoding="ascii").splitlines():
|
| 233 |
+
if line.startswith("0::"):
|
| 234 |
+
cgroup = line.removeprefix("0::")
|
| 235 |
+
break
|
| 236 |
+
if not cgroup.startswith("/system.slice/lumi-eggcracker.service"):
|
| 237 |
+
raise JsonInputError("supervisor is outside its expected systemd cgroup")
|
| 238 |
+
parent = Path("/sys/fs/cgroup").joinpath(*cgroup.lstrip("/").split("/"))
|
| 239 |
+
if parent.is_symlink() or not parent.is_dir():
|
| 240 |
+
raise JsonInputError("supervisor cgroup is unavailable")
|
| 241 |
+
root = parent / "quarantine"
|
| 242 |
+
if root.is_symlink():
|
| 243 |
+
raise JsonInputError("quarantine root is a symlink")
|
| 244 |
+
root.mkdir(mode=0o700, exist_ok=True)
|
| 245 |
+
if not root.is_dir() or not all((root / name).is_file() for name in ("cgroup.events", "cgroup.procs")):
|
| 246 |
+
raise JsonInputError("delegated quarantine cgroup is unavailable")
|
| 247 |
+
return root
|
| 248 |
+
|
| 249 |
+
def _managed(self, snapshot: ProcessSnapshot) -> bool:
|
| 250 |
+
for path in self.runs.glob("*.json"):
|
| 251 |
+
try:
|
| 252 |
+
record = load_run(self.runs, path.stem)
|
| 253 |
+
except JsonInputError:
|
| 254 |
+
continue
|
| 255 |
+
if record["state"] in ACTIVE_STATES and any(line.endswith(":" + record["cgroup"]) for line in snapshot.cgroups):
|
| 256 |
+
return True
|
| 257 |
+
return False
|
| 258 |
+
|
| 259 |
+
def _cached_executable_digest(self, snapshot: ProcessSnapshot) -> str:
|
| 260 |
+
path = Path(snapshot.exe_path)
|
| 261 |
+
metadata = path.stat(follow_symlinks=False)
|
| 262 |
+
key = (metadata.st_dev, metadata.st_ino, metadata.st_size, metadata.st_mtime_ns)
|
| 263 |
+
value = self.digest_cache.get(key)
|
| 264 |
+
if value is None:
|
| 265 |
+
value = executable_digest(path)
|
| 266 |
+
self.digest_cache = {key: value}
|
| 267 |
+
return value
|
| 268 |
+
|
| 269 |
+
def _detection_path(self, event_id: str) -> Path:
|
| 270 |
+
if not RUN_ID.fullmatch(event_id):
|
| 271 |
+
raise JsonInputError("detection event identity is invalid")
|
| 272 |
+
return self.detections / f"{event_id}.json"
|
| 273 |
+
|
| 274 |
+
def _store_detection(self, value: dict[str, Any]) -> None:
|
| 275 |
+
write_atomic(self._detection_path(value["event_id"]), value)
|
| 276 |
+
records = sorted(self.detections.glob("*.json"), key=lambda item: item.stat().st_mtime_ns, reverse=True)
|
| 277 |
+
for path in records[DETECTION_LIMIT:]:
|
| 278 |
+
path.unlink(missing_ok=True)
|
| 279 |
+
|
| 280 |
+
def _detection_receipt(self, *, event_id: str, snapshot: ProcessSnapshot, profile: str, predicates: tuple[str, ...], executable_sha256: str, result: AdoptionResult | None, error: str | None) -> dict[str, Any]:
|
| 281 |
+
value: dict[str, Any] = {"catalogue_sha256": self.catalogue.digest, "detector": {"matched_predicates": list(predicates), "profile": profile}, "event_id": event_id, "executable": {"basename": snapshot.exe_basename, "sha256": executable_sha256}, "observed": {"argv_count": len(snapshot.argv), "argv_sha256": hashlib.sha256("\0".join(snapshot.argv).encode("utf-8")).hexdigest(), "pid": snapshot.identity.pid, "start_time": snapshot.identity.start_time, "uid": snapshot.uid}, "receipt_written_utc": None, "schema_version": "lumi-eggcracker.detection-receipt.v1", "source_commit": self.policy["source_commit"], "trigger": {"kind": "UNAPPROVED_AI_MATCH"}, "version": __version__}
|
| 282 |
+
if result is None:
|
| 283 |
+
value["result"] = "CONTAINMENT_FAILED"
|
| 284 |
+
value["error"] = (error or "containment failed")[:160]
|
| 285 |
+
return value
|
| 286 |
+
value.update({"result": "TERMINATED", "capture": {"captured_processes": len(result.captured), "fixed_point_scans": result.fixed_point_scans, "quarantine_cgroup": str(result.identity.path), "quarantine_device": result.identity.device, "quarantine_inode": result.identity.inode}, "containment": {"empty_verified_monotonic_ns": result.empty_ns, "first_stop_monotonic_ns": result.first_stop_ns, "kill_write_completed_monotonic_ns": result.kill_complete_ns, "kill_write_started_monotonic_ns": result.kill_started_ns, "primitive": "pidfd-stop+cgroup.kill", "root_populated": result.proof.root_populated, "surviving_pids": result.proof.surviving_pids, "trigger_to_empty_ms": (result.empty_ns - result.first_stop_ns) / 1_000_000}, "trigger": {"kind": "UNAPPROVED_AI_MATCH", "observed_monotonic_ns": result.first_stop_ns}})
|
| 287 |
+
return value
|
| 288 |
+
|
| 289 |
+
def _enforce_discovery(self, snapshot: ProcessSnapshot, profile: str, predicates: tuple[str, ...], executable_sha256: str, event_id: str) -> None:
|
| 290 |
+
try:
|
| 291 |
+
if self.quarantine_root is None:
|
| 292 |
+
raise JsonInputError("quarantine root is unavailable")
|
| 293 |
+
self.operations.append("pidfd.stop")
|
| 294 |
+
result = contain(snapshot.identity, self.quarantine_root, event_id)
|
| 295 |
+
self.operations.append("cgroup.kill")
|
| 296 |
+
receipt = self._detection_receipt(event_id=event_id, snapshot=snapshot, profile=profile, predicates=predicates, executable_sha256=executable_sha256, result=result, error=None)
|
| 297 |
+
receipt["receipt_written_utc"] = dt.datetime.now(dt.UTC).isoformat().replace("+00:00", "Z")
|
| 298 |
+
self._store_detection(receipt)
|
| 299 |
+
except (JsonInputError, OSError, RuntimeError, ProcessLookupError) as error:
|
| 300 |
+
receipt = self._detection_receipt(event_id=event_id, snapshot=snapshot, profile=profile, predicates=predicates, executable_sha256=executable_sha256, result=None, error=str(error))
|
| 301 |
+
receipt["receipt_written_utc"] = dt.datetime.now(dt.UTC).isoformat().replace("+00:00", "Z")
|
| 302 |
+
try:
|
| 303 |
+
self._store_detection(receipt)
|
| 304 |
+
except (JsonInputError, OSError):
|
| 305 |
+
pass
|
| 306 |
+
finally:
|
| 307 |
+
with self.discovery_lock:
|
| 308 |
+
self.discovery_active.discard(snapshot.identity)
|
| 309 |
+
|
| 310 |
+
def _scan_once(self, *, synchronous: bool = False) -> None:
|
| 311 |
+
try:
|
| 312 |
+
approvals = load_approvals(self.approvals)
|
| 313 |
+
except JsonInputError:
|
| 314 |
+
approvals = [] # A corrupt approval never authorizes a matching workload.
|
| 315 |
+
for snapshot in scan(exclude=lambda item: item.identity.pid == os.getpid() or self._managed(item)):
|
| 316 |
+
result = match(self.catalogue, snapshot)
|
| 317 |
+
if result is None:
|
| 318 |
+
continue
|
| 319 |
+
try:
|
| 320 |
+
executable_sha256 = self._cached_executable_digest(snapshot)
|
| 321 |
+
except (JsonInputError, OSError):
|
| 322 |
+
continue
|
| 323 |
+
if approved(snapshot, executable_sha256, approvals):
|
| 324 |
+
continue
|
| 325 |
+
with self.discovery_lock:
|
| 326 |
+
if snapshot.identity in self.discovery_active:
|
| 327 |
+
continue
|
| 328 |
+
self.discovery_active.add(snapshot.identity)
|
| 329 |
+
profile, predicates = result
|
| 330 |
+
event_id = os.urandom(12).hex()
|
| 331 |
+
if synchronous:
|
| 332 |
+
self._enforce_discovery(snapshot, profile, predicates, executable_sha256, event_id)
|
| 333 |
+
else:
|
| 334 |
+
threading.Thread(target=self._enforce_discovery, args=(snapshot, profile, predicates, executable_sha256, event_id), daemon=True).start()
|
| 335 |
+
|
| 336 |
+
def _discovery_loop(self) -> None:
|
| 337 |
+
while not self.stop_event.is_set():
|
| 338 |
+
try:
|
| 339 |
+
self._scan_once()
|
| 340 |
+
except (JsonInputError, OSError) as error:
|
| 341 |
+
print(f"eggcracker discovery scan failed: {error}", file=sys.stderr, flush=True)
|
| 342 |
+
self.stop_event.wait(0.1)
|
| 343 |
|
| 344 |
def _cleanup(self, unit: str) -> dict[str, Any]:
|
| 345 |
result = self._run(["/usr/bin/systemctl", "stop", unit])
|
|
|
|
| 575 |
action, args = value["action"], value["args"]
|
| 576 |
if action == "doctor" and not args:
|
| 577 |
available = Path("/sys/fs/cgroup/cgroup.controllers").is_file() and "pids" in Path("/sys/fs/cgroup/cgroup.controllers").read_text(encoding="ascii").split()
|
| 578 |
+
ready = available and pidfd_available() and self.quarantine_root is not None
|
| 579 |
+
return {"autonomous_discovery": ready, "backend": "root-supervisor", "catalogue": public_catalogue(self.catalogue), "cgroup_v2": available, "pidfd": pidfd_available(), "result": "PASS" if ready else "UNSUPPORTED", "version": __version__, "workload_uid": self.policy["workload_uid"]}
|
| 580 |
if action == "start":
|
| 581 |
return self._start(args)
|
| 582 |
if action == "status" and set(args) == {"name"}:
|
|
|
|
| 588 |
if action == "list" and not args:
|
| 589 |
runs = [self.handle({"action": "status", "args": {"name": path.stem}}) for path in sorted(self.names.glob("*.json"))]
|
| 590 |
return {"runs": runs}
|
| 591 |
+
if action == "approve" and set(args) == {"argv", "name", "uid"}:
|
| 592 |
+
value = create_approval(self.approvals, name=args["name"], uid=args["uid"], argv=args["argv"], operator_uid=self.operator_uid)
|
| 593 |
+
return {"approval": public_approval(value), "result": "APPROVED"}
|
| 594 |
+
if action == "revoke" and set(args) == {"name"}:
|
| 595 |
+
return revoke(self.approvals, args["name"])
|
| 596 |
+
if action == "approvals" and not args:
|
| 597 |
+
return {"approvals": [public_approval(value) for value in load_approvals(self.approvals)]}
|
| 598 |
+
if action == "detections" and not args:
|
| 599 |
+
values: list[dict[str, Any]] = []
|
| 600 |
+
for path in sorted(self.detections.glob("*.json"), reverse=True):
|
| 601 |
+
try:
|
| 602 |
+
value = load_regular_json(path)
|
| 603 |
+
values.append({key: value[key] for key in ("detector", "event_id", "result", "trigger", "version")})
|
| 604 |
+
except (JsonInputError, KeyError):
|
| 605 |
+
continue
|
| 606 |
+
return {"detections": values[:100]}
|
| 607 |
if action == "kill" and set(args) == {"name"}:
|
| 608 |
return self._contain(self._load(args["name"]), "OPERATOR")
|
| 609 |
raise JsonInputError("unsupported supervisor action")
|
| 610 |
|
| 611 |
def serve(self) -> int:
|
| 612 |
self._prepare()
|
| 613 |
+
self.discovery_thread = threading.Thread(target=self._discovery_loop, daemon=True)
|
| 614 |
+
self.discovery_thread.start()
|
| 615 |
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as listener:
|
| 616 |
listener.bind(str(SOCKET_PATH))
|
| 617 |
os.chown(SOCKET_PATH, 0, self.policy["operator_gid"])
|
tests/fixtures/discovery_fork_race.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bounded unmanaged fixture that presents as a llama.cpp-style invocation."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import signal
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
children: list[int] = []
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def stop(*_: object) -> None:
|
| 13 |
+
for child in children:
|
| 14 |
+
try:
|
| 15 |
+
os.kill(child, signal.SIGKILL)
|
| 16 |
+
except ProcessLookupError:
|
| 17 |
+
pass
|
| 18 |
+
raise SystemExit(0)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
signal.signal(signal.SIGTERM, stop)
|
| 22 |
+
for _ in range(32):
|
| 23 |
+
child = os.fork()
|
| 24 |
+
if child == 0:
|
| 25 |
+
while True:
|
| 26 |
+
time.sleep(1)
|
| 27 |
+
children.append(child)
|
| 28 |
+
while True:
|
| 29 |
+
time.sleep(1)
|
tests/test_adoption.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import tempfile
|
| 4 |
+
import unittest
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
from lumi_eggcracker.adoption import children, descendants
|
| 8 |
+
from lumi_eggcracker.discovery import ProcessIdentity
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def stat(pid: int, parent: int, start: int) -> str:
|
| 12 |
+
return f"{pid} (fixture) S {parent} " + "0 " * 17 + f"{start}\n"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class AdoptionTests(unittest.TestCase):
|
| 16 |
+
def test_descendant_walk_reads_every_task_children_file(self) -> None:
|
| 17 |
+
with tempfile.TemporaryDirectory() as raw:
|
| 18 |
+
proc = Path(raw)
|
| 19 |
+
for pid, parent, start in ((10, 1, 100), (11, 10, 101), (12, 10, 102)):
|
| 20 |
+
entry = proc / str(pid); (entry / "task" / str(pid)).mkdir(parents=True)
|
| 21 |
+
(entry / "stat").write_text(stat(pid, parent, start), encoding="ascii")
|
| 22 |
+
(proc / "10" / "task" / "10" / "children").write_text("11 12\n", encoding="ascii")
|
| 23 |
+
(proc / "11" / "task" / "11" / "children").write_text("", encoding="ascii")
|
| 24 |
+
(proc / "12" / "task" / "12" / "children").write_text("", encoding="ascii")
|
| 25 |
+
root = ProcessIdentity(10, 100)
|
| 26 |
+
self.assertEqual({ProcessIdentity(11, 101), ProcessIdentity(12, 102)}, children(root, proc=proc))
|
| 27 |
+
self.assertEqual({root, ProcessIdentity(11, 101), ProcessIdentity(12, 102)}, descendants({root}, proc=proc))
|
tests/test_approvals.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import tempfile
|
| 4 |
+
import unittest
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from lumi_eggcracker.approvals import approved, create, load_all, revoke
|
| 9 |
+
from lumi_eggcracker.discovery import argv_digest, executable_digest
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass(frozen=True)
|
| 13 |
+
class Sample:
|
| 14 |
+
uid: int
|
| 15 |
+
exe_path: str
|
| 16 |
+
argv: tuple[str, ...]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ApprovalTests(unittest.TestCase):
|
| 20 |
+
def test_exact_approval_matches_only_exact_uid_and_argv(self) -> None:
|
| 21 |
+
with tempfile.TemporaryDirectory() as raw:
|
| 22 |
+
root = Path(raw) / "approvals"; binary = Path(raw) / "runner"
|
| 23 |
+
binary.write_bytes(b"#!/bin/true\n")
|
| 24 |
+
binary.chmod(0o755)
|
| 25 |
+
record = create(root, name="qwen", uid=1001, argv=[str(binary), "-m", "/models/qwen.gguf"], operator_uid=1001)
|
| 26 |
+
values = load_all(root)
|
| 27 |
+
sample = Sample(1001, str(binary), (str(binary), "-m", "/models/qwen.gguf"))
|
| 28 |
+
self.assertTrue(approved(sample, executable_digest(binary), values))
|
| 29 |
+
self.assertFalse(approved(Sample(1002, str(binary), sample.argv), executable_digest(binary), values))
|
| 30 |
+
self.assertFalse(approved(Sample(1001, str(binary), (str(binary), "-m", "/models/other.gguf")), executable_digest(binary), values))
|
| 31 |
+
self.assertNotIn("/models/qwen.gguf", record.values())
|
| 32 |
+
self.assertEqual(argv_digest(sample.argv), record["argv_sha256"])
|
| 33 |
+
|
| 34 |
+
def test_revoke_removes_exact_record(self) -> None:
|
| 35 |
+
with tempfile.TemporaryDirectory() as raw:
|
| 36 |
+
root = Path(raw) / "approvals"; binary = Path(raw) / "runner"
|
| 37 |
+
binary.write_bytes(b"x"); binary.chmod(0o755)
|
| 38 |
+
create(root, name="qwen", uid=1001, argv=[str(binary)], operator_uid=1001)
|
| 39 |
+
self.assertEqual("REVOKED", revoke(root, "qwen")["result"])
|
| 40 |
+
self.assertEqual([], load_all(root))
|
tests/test_cli.py
CHANGED
|
@@ -13,12 +13,12 @@ class CliTests(unittest.TestCase):
|
|
| 13 |
output = io.StringIO()
|
| 14 |
with redirect_stdout(output):
|
| 15 |
self.assertEqual(0, main(["version"]))
|
| 16 |
-
self.assertEqual("0.
|
| 17 |
|
| 18 |
def test_public_help_has_only_supported_commands(self) -> None:
|
| 19 |
from lumi_eggcracker.cli import _parser
|
| 20 |
help_text = _parser().format_help()
|
| 21 |
-
for command in ("start", "kill", "status", "list", "doctor", "version"):
|
| 22 |
self.assertIn(command, help_text)
|
| 23 |
self.assertNotIn("_supervisor", help_text)
|
| 24 |
self.assertNotIn("network" + "-deny", help_text)
|
|
@@ -27,3 +27,8 @@ class CliTests(unittest.TestCase):
|
|
| 27 |
with patch("lumi_eggcracker.cli.supervisor_main", return_value=7) as supervisor:
|
| 28 |
self.assertEqual(main(["_supervisor", "--policy", "/tmp/policy.json"]), 7)
|
| 29 |
supervisor.assert_called_once_with(["--policy", "/tmp/policy.json"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
output = io.StringIO()
|
| 14 |
with redirect_stdout(output):
|
| 15 |
self.assertEqual(0, main(["version"]))
|
| 16 |
+
self.assertEqual("0.2.0", output.getvalue().strip())
|
| 17 |
|
| 18 |
def test_public_help_has_only_supported_commands(self) -> None:
|
| 19 |
from lumi_eggcracker.cli import _parser
|
| 20 |
help_text = _parser().format_help()
|
| 21 |
+
for command in ("start", "kill", "status", "list", "approve", "revoke", "approvals", "detections", "doctor", "version"):
|
| 22 |
self.assertIn(command, help_text)
|
| 23 |
self.assertNotIn("_supervisor", help_text)
|
| 24 |
self.assertNotIn("network" + "-deny", help_text)
|
|
|
|
| 27 |
with patch("lumi_eggcracker.cli.supervisor_main", return_value=7) as supervisor:
|
| 28 |
self.assertEqual(main(["_supervisor", "--policy", "/tmp/policy.json"]), 7)
|
| 29 |
supervisor.assert_called_once_with(["--policy", "/tmp/policy.json"])
|
| 30 |
+
|
| 31 |
+
def test_approve_forwards_only_exact_command_arguments(self) -> None:
|
| 32 |
+
with patch("lumi_eggcracker.cli.request", return_value={"result": "APPROVED"}) as request:
|
| 33 |
+
self.assertEqual(0, main(["approve", "--name", "qwen", "--uid", "1001", "--", "/opt/llama-cli", "-m", "/models/qwen.gguf"]))
|
| 34 |
+
request.assert_called_once_with("approve", name="qwen", uid=1001, argv=["/opt/llama-cli", "-m", "/models/qwen.gguf"])
|
tests/test_detectors.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import unittest
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
|
| 6 |
+
from lumi_eggcracker.detectors import load_bundled, load_catalogue, match
|
| 7 |
+
from lumi_eggcracker.jsonio import JsonInputError
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass(frozen=True)
|
| 11 |
+
class Sample:
|
| 12 |
+
exe_basename: str
|
| 13 |
+
argv: tuple[str, ...]
|
| 14 |
+
fd_paths: tuple[str, ...] = ()
|
| 15 |
+
map_basenames: tuple[str, ...] = ()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class DetectorTests(unittest.TestCase):
|
| 19 |
+
def test_llama_cpp_requires_model_argument(self) -> None:
|
| 20 |
+
catalogue = load_bundled()
|
| 21 |
+
self.assertIsNone(match(catalogue, Sample("llama-cli", ("/usr/bin/llama-cli", "--help"))))
|
| 22 |
+
value = match(catalogue, Sample("llama-cli", ("/usr/bin/llama-cli", "-m", "/models/tiny.gguf")))
|
| 23 |
+
self.assertEqual(("llama.cpp", ("exe_basename", "argv_model_suffix")), value)
|
| 24 |
+
|
| 25 |
+
def test_generic_language_runtime_is_not_a_match(self) -> None:
|
| 26 |
+
catalogue = load_bundled()
|
| 27 |
+
self.assertIsNone(match(catalogue, Sample("python3", ("/usr/bin/python3", "worker.py", "--model", "cat"))))
|
| 28 |
+
self.assertIsNone(match(catalogue, Sample("node", ("node", "agent.js"))))
|
| 29 |
+
|
| 30 |
+
def test_catalogue_rejects_unknown_predicate(self) -> None:
|
| 31 |
+
raw = b'{"schema_version":"lumi-eggcracker.detectors.v1","profiles":[{"id":"bad","all":[{"kind":"unknown","values":["x"]}]}]}'
|
| 32 |
+
with self.assertRaises(JsonInputError):
|
| 33 |
+
load_catalogue(raw)
|
| 34 |
+
|
| 35 |
+
def test_catalogue_digest_is_exact(self) -> None:
|
| 36 |
+
raw = b'{"schema_version":"lumi-eggcracker.detectors.v1","profiles":[{"id":"one","all":[{"kind":"exe_basename","values":["one"]}]}]}'
|
| 37 |
+
with self.assertRaises(JsonInputError):
|
| 38 |
+
load_catalogue(raw, expected_digest="0" * 64)
|
tests/test_discovery.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import tempfile
|
| 4 |
+
import unittest
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
from lumi_eggcracker.discovery import ProcessIdentity, argv_digest, identity, parse_stat
|
| 8 |
+
from lumi_eggcracker.jsonio import JsonInputError
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class DiscoveryTests(unittest.TestCase):
|
| 12 |
+
def test_stat_parser_handles_spaces_in_command_name(self) -> None:
|
| 13 |
+
raw = "77 (worker with spaces) S 4 " + "0 " * 17 + "901\n"
|
| 14 |
+
self.assertEqual((4, 901), parse_stat(raw))
|
| 15 |
+
|
| 16 |
+
def test_stat_parser_rejects_incomplete_record(self) -> None:
|
| 17 |
+
with self.assertRaises(JsonInputError):
|
| 18 |
+
parse_stat("1 (bad) S 2")
|
| 19 |
+
|
| 20 |
+
def test_argv_digest_does_not_retain_arguments(self) -> None:
|
| 21 |
+
digest = argv_digest(("/usr/bin/python3", "--token", "secret"))
|
| 22 |
+
self.assertEqual(64, len(digest))
|
| 23 |
+
self.assertNotIn("secret", digest)
|
| 24 |
+
|
| 25 |
+
def test_pid_identity_includes_start_time(self) -> None:
|
| 26 |
+
with tempfile.TemporaryDirectory() as raw:
|
| 27 |
+
proc = Path(raw)
|
| 28 |
+
entry = proc / "42"; entry.mkdir()
|
| 29 |
+
(entry / "stat").write_text("42 (x) S 1 " + "0 " * 17 + "100\n", encoding="utf-8")
|
| 30 |
+
self.assertEqual(ProcessIdentity(42, 100), identity(42, proc=proc))
|
| 31 |
+
(entry / "stat").write_text("42 (x) S 1 " + "0 " * 17 + "101\n", encoding="utf-8")
|
| 32 |
+
self.assertEqual(ProcessIdentity(42, 101), identity(42, proc=proc))
|