diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..770c7aa --- /dev/null +++ b/.dockerignore @@ -0,0 +1,14 @@ +# Whitelist: only what the Dockerfile copies. +* +!deploy/docker/requirements.txt +!deploy/snapshot/nt2102-snapshot.tar.gz +!src/live/live_server.py +!src/live/repository.py +!src/live/history.py +!src/live/file_store.py +!src/live/snapshot.py +!src/live/playback.py +!src/live/static/index.html +!src/pipeline/alg1.py +!src/pipeline/alg2.py +!src/pipeline/cmdlines.py diff --git a/.github/workflows/demo-image.yml b/.github/workflows/demo-image.yml new file mode 100644 index 0000000..aa86dd2 --- /dev/null +++ b/.github/workflows/demo-image.yml @@ -0,0 +1,91 @@ +# main -> ghcr.io/uitprojects/nt2102-demo:sha-, :edge +# vX.Y.Z -> ghcr.io/uitprojects/nt2102-demo:X.Y.Z, :latest +# Make the GHCR package public once; the cluster pulls without a secret. +name: demo-image + +on: + push: + branches: [main] + tags: ['v*.*.*'] + paths: + - 'src/live/**' + - 'src/pipeline/alg1.py' + - 'src/pipeline/alg2.py' + - 'src/pipeline/cmdlines.py' + - 'deploy/**' + - '.dockerignore' + - '.github/workflows/demo-image.yml' + pull_request: + paths: + - 'src/live/**' + - 'deploy/**' + - '.github/workflows/demo-image.yml' + workflow_dispatch: + +permissions: + contents: read + packages: write + +concurrency: + group: demo-image-${{ github.ref }} + cancel-in-progress: true + +env: + IMAGE: ghcr.io/uitprojects/nt2102-demo + +jobs: + selftest: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: | + pip install --require-hashes -r deploy/docker/requirements.txt + pip install httpx==0.28.1 # fastapi.testclient only + - name: selftests (snapshot path) + run: | + for t in repository file_store snapshot playback; do python src/live/$t.py --selftest; done + python -c "import sys; sys.path.insert(0, 'src/live'); import live_server; live_server.selftest_snapshot()" + + image: + needs: selftest + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-buildx-action@v3 + - uses: docker/metadata-action@v5 + id: meta + with: + images: ${{ env.IMAGE }} + tags: | + type=semver,pattern={{version}} + type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') }} + type=sha,prefix=sha-,format=short + type=raw,value=edge,enable={{is_default_branch}} + - uses: docker/login-action@v3 + if: github.event_name != 'pull_request' + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - uses: docker/build-push-action@v6 + with: + context: . + file: deploy/docker/Dockerfile + platforms: linux/amd64 + push: ${{ github.event_name != 'pull_request' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + build-args: NT2102_CODE_SHA=${{ github.sha }} + cache-from: type=gha + cache-to: type=gha,mode=max + - name: smoke test the built image + if: github.event_name != 'pull_request' + run: | + ref=$(echo "${{ steps.meta.outputs.tags }}" | head -1) + docker run -d --name demo -p 8000:8000 --read-only --tmpfs /data --tmpfs /tmp --memory 256m "$ref" + for i in $(seq 1 30); do curl -sf localhost:8000/healthz && break; sleep 1; done + curl -sf localhost:8000/api/status | python3 -c "import json,sys; d=json.load(sys.stdin); assert d['snapshot']['counts']['windows'] > 0, d" + test "$(curl -s -o /dev/null -w '%{http_code}' -X POST localhost:8000/ingest -d '{}')" = 403 diff --git a/CLAUDE.md b/CLAUDE.md index a7e820a..5d9f6bd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -148,6 +148,13 @@ numbers. If ambiguous, answer the most likely interpretation and state the assum scores red on each host before any claim (D6 risk: DC auth blends into legit AD traffic). Network-flow note for the teammate (the user's imagined path): `docs/notes/cross-host-attack-flow.md`. Also owed: `ws-etw-1` D14 rollout, merge the branch to `main`, 24 h two-VM soak. Details: PROGRESS top. Then concepts 2–4. +- **Project done (user, 2026-11-16) → CV phase: a public, read-only demo for employers** on the user's k8s homelab + (`projects.datrollout.dev/nt2102/`, path-routed on the shared host `projects.datrollout.dev`, few and rare visitors). Built 2026-11-16 on branch `things-need-to-close-project`, **uncommitted, pending the user's + review** (NT2102 + the `/home/akira/code/home-lab` repo): repository-layer refactor of `src/live/`, recorded snapshot + `deploy/snapshot/nt2102-snapshot.tar.gz`, snapshot mode of `live_server.py`, image + CI, `deploy/k8s/`. Verified locally: all 24 + `./selftest.sh` steps pass, the container serves the snapshot, 30-user load test OK, manifests pass a server-side dry run on the cluster. + **Not yet deployed.** User steps left: commit + merge to `main` → tag `v1.0.0` → make the GHCR package public → `terraform apply` (DNS) → + Argo sync → cluster load test, then fill the cluster numbers into `deploy/README.md`. Decisions: section 9 "Public demo"; guide: `deploy/README.md`. - SG-Det: code default = the **paper's level scale** (user, 2026-11-03): Moderate from 10, [PAPER] §7.2.1. **Live `ocr-live` runs [OURS] Moderate from 4.5 on both hosts since 2026-11-15** (user; `live_sg_moderate_from` in `proxmox.ini`) **with the NET rule OFF** (user, 2026-11-15 05:03Z, `live_sg_require_types=none`; accepts ~5 benign red/day per host): the teammate's 11-15 react2shell run (up to 19.9) @@ -167,8 +174,51 @@ history of earlier progress) and, if relevant, this section. ## 9. Decisions already made (with rationale) - Environment: Python deps are managed with uv (`pyproject.toml` + `uv.lock`), not containers. Docker is used only on the Ubuntu trainer, - for Loki + Grafana and the Prometheus monitoring stack (installed by Ansible). No RDF / GraphDB (user, 2026-10-17): edges stay CSV and - Alg. 1 runs in memory. + for Loki + Grafana and the Prometheus monitoring stack (installed by Ansible). The one exception is the public demo image + (`deploy/docker/`, see "Public demo" below). No RDF / GraphDB (user, 2026-10-17): edges stay CSV and Alg. 1 runs in memory. +- Persistence behind repository ports (user, 2026-11-16, for the CV demo): `src/live/repository.py` defines three ABCs, used like Spring Data + interfaces. `HistoryRepository` holds window history + detail; its shared query/dedup/detail-merge logic and path guard live in the base. + `CrosshostRepository` holds cross-host findings. `SessionStore` holds the engine's session/window files + the daily LLM budget. + `open_repositories("files"|"snapshot")` is the only place an implementation is picked. The file implementations + (`history.FileHistoryRepository`, alias `HistoryStore`; `file_store.py`) write the same bytes as before the refactor. + `engine.py`, `correlate.py` and `live_server.py` persist only through the ports (constructor args `store=`, `history=`, `repo=`). Why: + the same HTTP/UI code serves live data and a read-only snapshot, and the user wanted the abstraction for the CV. +- **Public demo (user, 2026-11-16)**, all of it [OURS] engineering, not a method change: + - **Snapshot, not live scoring.** The container replays recorded results. Why: the raw ETW of 11-15 afternoon is gone (12 h retention), + so it cannot be re-scored, and a recorded snapshot needs no torch, no Loki and no LLM key. Every score / level / verdict shown is the + one computed live at the time, with that session's model + settings. The UI banner says so, and also that the 4.5 cut-off + NET rule + off were tuned on the 11-15 react2shell run (in-sample, D8). Never present the demo as fresh detection. + - **Range (user):** "from start to the last real LLM attack + 3 windows". That is 2026-11-02 23:10Z (first `history.jsonl` row) → + 2026-11-15 20:15Z: the last LLM `attack` verdict is ws-etw-1 19:55Z (teammate's enumeration), followed by 20:00/20:05/20:10Z. + Result: 4,658 windows, 63 red, 17 LLM `attack`. + - **Snapshot content:** only the History winner per (host, window start); `.rN` restart duplicates and replays are left out. Per window + only `detail.json` is kept, rebuilt from `scores.csv` when missing; it already carries top nodes, Sysmon command lines and the LLM + summary + report. Also each `session.json` (paths cut to names), `history.jsonl` and `crosshost.jsonl`. No raw, edges, features or + `calls.jsonl`. Redaction covers the `proxmox.ini` passwords, `$LAB_TOKEN` and password-like arguments, followed by a re-scan that + fails the build. The tar.gz is deterministic, with a sha256 per file in `manifest.json`. + - **Compressed in the image, unpacked at start (user):** 5.6 MB archive committed in git → `SnapshotArchive.open` extracts with tarfile + `filter="data"` into an emptyDir and verifies every sha256 before serving (~1 s). Built with `lab snapshot build` (`src/live/snapshot.py`). + The committed one was built on the trainer from a scratch copy of the builder, because the trainer runs `main`. + - **Playback, no torch (user):** `live_server.py --snapshot` imports no `engine`/torch. `playback.SnapshotMember` stands in for `Engine` + behind the same routes, and `Player` replays 2026-11-15 15:10Z → 20:15Z, one window per 3 s, looping. History covers the whole + range. `POST /ingest` returns 403, and History presets use the snapshot end as "now". + - **Image:** `python:3.12.16-slim-trixie` with fastapi/uvicorn/pandas/networkx only, hash-pinned in `deploy/docker/requirements.txt` + (constrained by `uv.lock`); 239 MB, uid 10001, read-only rootfs. CI `.github/workflows/demo-image.yml` runs the snapshot selftests + → builds → pushes `ghcr.io/uitprojects/nt2102-demo` (`:sha-*`/`:edge` on main, `:X.Y.Z` on a `vX.Y.Z` tag) → smoke test. + `deploy/k8s/deployment.yaml` pins `:1.0.0`. + - **Homelab fit:** plain YAML in `deploy/k8s/`, deployed by an Argo Application `nt2102-demo` kept in this repo (`deploy/argocd/`, applied with kubectl; no home-lab change, user 2026-11-17; manual sync, + `CreateNamespace`, namespace `nt2102-demo`). The Ingress uses the `traefik` class, websecure + `letsencrypt` resolver, and middlewares + `traefik-crowdsec`, no rate limit (user, 2026-11-17). Path routing (user, 2026-11-17): every project demo lives on the shared host + `projects.datrollout.dev`, this one at `/nt2102/`; Traefik redirects `/nt2102` → `/nt2102/` and strips the prefix, so the app stays + prefix-agnostic as long as its UI uses relative URLs (`deploy/k8s/middleware-path.yaml`); `/` is 404 for now. + The VN geo filter is deliberately off, since employers may be abroad. DNS `projects` + is a CNAME **not proxied**, so crowdsec sees visitor IPs (the websecure entrypoint trusts no forwarded headers; Traefik + runs with `externalTrafficPolicy: Local`). No Grafana dashboard (user, 2026-11-17: not needed). + - **Sizing from the local load test** (`deploy/loadtest.py`, 30 users: 61 req/s, 0 errors, p95 ≤ 56 ms, 0.57 core, RSS 134 MiB flat): + requests 50m / 160Mi, limits 1 CPU / 256Mi. Cluster numbers are still owed. + - **Cluster access:** `~/.kube/merged_kubeconfig` fails to load because the `it2003-admin` client key is corrupt (not our file to fix). + For kubectl, extract only the `kubernetes-super-admin@cluster.local` context into a temp file (mode 600) and delete it after. + On 2026-11-16 `master-nodes-2` and `worker-nodes-2` were NotReady. - Log transport: our collector (`src/etw-python`, `etwcollect`) pushes SilkETW-format JSON lines to Loki (Docker, host network) on the trainer, from its own run files with saved offsets. Labels: job (`silketw`, it names the line format), host, split, run, provider; event/pid/process as structured metadata. Training pulls from Loki by run or time range (`loki_pull.py`); the live server follows Loki (`--loki-url`). All @@ -263,6 +313,11 @@ history of earlier progress) and, if relevant, this section. explanations go to the report and speaker notes. Deck redesigned 2026-11-08 (user structure: intro → core concept → demo → thanks; results + limits live in the report; one Windows VM; no source-tag chips; ≤3 bullets/group; one "3 · Demo" slide with the teammate's attack-flow diagram, videos added by hand). Slides cross-reference by name ("slide ② Behavior feature"), not number. +- Persistence (2026-11-16): `src/live/repository.py` ABCs (`HistoryRepository`, `CrosshostRepository`, `SessionStore`) + + `open_repositories("files"|"snapshot")`; files = `history.FileHistoryRepository` / `file_store.py`, snapshot = `snapshot.py` (read-only). +- Public demo (2026-11-16): `lab snapshot build` → `deploy/snapshot/*.tar.gz` → `live_server.py --snapshot` + `playback.py` (no torch) + → `deploy/docker/Dockerfile` (CI `.github/workflows/demo-image.yml`, `ghcr.io/uitprojects/nt2102-demo`) → `deploy/k8s/` (Argo app + `deploy/argocd/nt2102-demo.yaml`, `projects.datrollout.dev/nt2102/`). Guide: `deploy/README.md`. - Root shortcuts: `selftest.sh`, `serve.sh`, `replay.sh`, `rejudge.sh` (wrap the documented commands). - Root `README.md`: front door (project, quick start, layout, references). `src/README.md`: map of `src/` and the new-member start path. diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 0000000..73b7cc6 --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,140 @@ +# Public demo: OCR-APT live detector, recorded snapshot + +`https://projects.datrollout.dev/nt2102/`: a read-only, explorable copy of what the live detector showed from +**2026-11-02 23:10Z to 2026-11-15 20:15Z**. That range runs up to the last real attack that got an LLM `attack` verdict +(teammate on `ws-etw-1`, window 19:55Z) plus the three windows after it. Employers can open any window, see the +anomalous subgraph, the top nodes per type and the LLM report, while the live panels replay the attack session +(2026-11-15 15:10Z → 20:15Z) at one 5-min window every 3 s, in a loop. + +**What it is and is not.** Every score, alert level and LLM verdict shown is the one the live server computed at the +time, with the model and settings recorded in that session's `session.json`. Nothing is re-scored in the container: +there is no model, no torch, no Loki and no LLM key. The raw ETW logs of 11-15 afternoon are gone (12 h retention), so +re-scoring would not be possible anyway. The 4.5 alert cut-off and the NET rule being off (since 2026-11-15) were tuned +on the 2026-11-15 react2shell run, so that run is in-sample evidence, not an independent test (docs/DEVIATIONS.md D8). +The UI banner says the same. + +``` +trainer: src/live/sessions/ (3.2 GB, raw logs included) + │ lab snapshot build --until 2026-11-15T20:15Z (src/live/snapshot.py: winners only, redacted, sha256 manifest) + ▼ +deploy/snapshot/nt2102-snapshot.tar.gz 5.6 MB, 4,658 windows, 4,583 details, 63 red, 17 LLM "attack" + │ .github/workflows/demo-image.yml (selftests → buildx → ghcr.io/uitprojects/nt2102-demo:X.Y.Z → smoke test) + ▼ +image 239 MB (python:3.12-slim + fastapi/uvicorn/pandas/networkx; no torch) + │ Argo CD (home-lab app-of-app → this repo's deploy/k8s, manual sync) + ▼ +pod: unpack + verify into an emptyDir (~1 s) → live_server.py --snapshot → Traefik (crowdsec, path strip) → visitors +``` + +## The persistence layer (why the same server can serve live data and a snapshot) + +The live server's storage is behind three abstract repositories in `src/live/repository.py`. They play the role of +Spring Data repository interfaces: the engine, the cross-host correlator and the HTTP layer only know the interface. + +| Port (ABC) | What it stores | Live implementation | Snapshot implementation | +|---|---|---|---| +| `HistoryRepository` | every window state, queryable by time range; the UI detail of a window | `history.FileHistoryRepository` (`history.jsonl` + `detail.json`) | `snapshot.SnapshotHistoryRepository` (read-only) | +| `CrosshostRepository` | cross-host findings | `file_store.FileCrosshostRepository` (`crosshost.jsonl`) | `snapshot.SnapshotCrosshostRepository` (read-only) | +| `SessionStore` | the engine's own files: `session.json`, raw lines, per-window CSV/JSON, `windows.csv`, LLM verdicts, daily LLM budget | `file_store.FileSessionStore` (`sessions/` folder) | `snapshot.SnapshotSessionStore`: reads work, writes raise `ReadOnlyRepositoryError` | + +`repository.open_repositories("files" | "snapshot", ...)` is the only place that picks an implementation. Shared +logic lives in the abstract base: the History query (dedup of restart copies, alerts-only, per-host), the detail merge +and the path-traversal guard. This is a template-method base class, like a Java abstract class with concrete methods. +In live mode `live_server.py` wires the `files` implementations into `Engine` and `Correlator`. The bytes on disk +are unchanged by the refactor, and `engine.py` / `correlate.py` selftests still pass. In snapshot mode +`playback.SnapshotMember` stands in for `Engine` behind the same HTTP routes, so the UI is the same file. + +## Run it locally + +```bash +# straight from the repo (no Docker): needs only the torch-free deps +uv run python src/live/live_server.py --snapshot deploy/snapshot/nt2102-snapshot.tar.gz --data-dir /tmp/nt2102-demo \ + --port 8000 --playback-from 2026-11-15T15:10:00Z +# or the image, with the same hardening as in the cluster +docker build -f deploy/docker/Dockerfile -t nt2102-demo:local . +docker run --rm -p 8000:8000 --read-only --tmpfs /data --tmpfs /tmp --memory 256m --cap-drop ALL nt2102-demo:local +``` + +## Rebuild the snapshot + +On the trainer, after `main` with this code is deployed there (or from a scratch copy of `src/live/{repository,history, +file_store,snapshot}.py` + `src/pipeline/{alg2,cmdlines}.py`, which is how the committed one was built on 2026-11-16): + +```bash +source .venv/bin/activate +lab snapshot build --until 2026-11-15T20:15Z --out /tmp/nt2102-snapshot.tar.gz +``` + +- **Which windows are kept:** the History winner per host and window start. Restart duplicates (`.rN`) and replay + sessions are left out. +- **What is copied per window:** `detail.json`, rebuilt from `scores.csv` where it is missing, plus `session.json` + with absolute paths cut to names. Raw lines, edges, features and LLM prompt logs (`calls.jsonl`) stay behind. +- **Redaction:** the passwords in `src/ansible/proxmox.ini`, `$LAB_TOKEN`, and password-looking arguments in + command lines. The output is then re-scanned, and the build fails if a known secret is still in it. +- **Deterministic:** the same input gives the same files and hashes. + +Copy the archive to `deploy/snapshot/` and release a new image tag. + +## Release and deploy + +1. Merge to `main`. CI runs the snapshot-path selftests, builds and pushes `:sha-` and `:edge`, then smoke-tests + the image (`/healthz`, snapshot counts, `POST /ingest` → 403). +2. `git tag v1.0.0 && git push origin v1.0.0` builds `ghcr.io/uitprojects/nt2102-demo:1.0.0`. + **Once:** make the package public in the UITProjects org (Packages → nt2102-demo → settings), because the + homelab pulls without a secret. +3. Argo CD Application (kept in this repo, no home-lab change): `kubectl apply -f deploy/argocd/nt2102-demo.yaml`. + No DNS change: `projects.datrollout.dev` already resolves to the DDNS host (checked 2026-11-17), shared by all project + demos (see "Path routing"). The uncommitted home-lab drafts (app-of-app template `nt2102-demo.yaml`, DNS record `nt2102`) + are not needed; keep only one Application definition. +4. Argo CD: sync `nt2102-demo` (manual sync, the homelab convention; `CreateNamespace` makes `nt2102-demo`). +5. Check: + ```bash + kubectl -n nt2102-demo get pods + curl -sI https://projects.datrollout.dev/nt2102 # 308, Location: …/nt2102/ + curl -sI https://projects.datrollout.dev/nt2102/healthz + curl -sI https://projects.datrollout.dev/ # 404 (no landing page yet) + python deploy/loadtest.py --url https://projects.datrollout.dev/nt2102 --users 10 --duration 300 + ``` + +New code or a new snapshot: release `v1.0.1`, bump the tag in `deploy/k8s/deployment.yaml`, sync. + +## Kubernetes objects (`deploy/k8s/`, plain YAML in the homelab style) + +| File | What | +|---|---| +| `deployment.yaml` | 1 replica; non-root uid 10001, read-only root FS, all capabilities dropped, seccomp RuntimeDefault, no SA token; emptyDir `/data` (unpacked snapshot) + `/tmp`; startup/readiness/liveness on `/healthz` | +| `service.yaml` | ClusterIP :8000 (`http`) | +| `middleware-path.yaml` | Traefik `RedirectRegex` `slash` (`/nt2102` → `/nt2102/`) + `StripPrefix` `strip` (`/nt2102`) | +| `ingress.yaml` | `projects.datrollout.dev`, path `/nt2102`, websecure + `letsencrypt` resolver, middlewares `traefik-crowdsec` → slash → strip; no rate limit (user, 2026-11-17); no VN geo filter (employers abroad) | + +All four (deployment, service, middleware-path, ingress) pass `kubectl apply --dry-run=server` on the homelab cluster (2026-11-17). + +## Path routing + +One path per project on the shared host `projects.datrollout.dev`. Traefik redirects `/nt2102` → `/nt2102/` and strips the +prefix, so the app serves at `/`. Keep UI URLs relative: `grep -nE '(fetch|EventSource)\(["`]/|(href|src)="/' src/live/static/index.html` +must print nothing. `/` has no router (404). + +## Measured resources (local container, 2026-11-16) + +Load from `deploy/loadtest.py`. Each virtual user keeps one SSE stream open and loops: status → windows of both hosts → +History 6 h → History 7 d alerts-only → 3 window details, with 2–5 s think time. This is far busier than a real visitor. +Container: `--read-only --memory 256m --cap-drop ALL`, snapshot unpacked to tmpfs. + +| Load | Throughput | p95 latency (worst endpoint) | CPU peak | Process RSS | Errors | +|---|---|---|---|---|---| +| idle (playback only) | – | – | ~1 % | 132 MiB | – | +| 10 users, 120 s | 22 req/s | 50 ms (History 7 d) | 0.35 core | 133 MiB | 0 | +| 30 users, 60 s | 61 req/s | 56 ms (History 7 d) | 0.57 core | 134 MiB | 0 | + +Hence `requests: cpu 50m, memory 160Mi` and `limits: cpu 1, memory 256Mi`. Memory is flat under load, because +the whole history (~5k rows) is loaded once at start. The headroom covers the unpack at start. The cluster numbers will +come from `kubectl top pod -n nt2102-demo` after the first sync. Re-run the load test against the public URL then and update this +table. + +## Tests + +`./selftest.sh` runs every module's `--selftest`, including the new `repository`, `file_store`, `snapshot` and +`playback` ones and the snapshot-mode HTTP test in `live_server.py`. They prove the code runs (cut-off, dedup, +redaction, tamper and traversal refused, read-only writes refused, playback over HTTP, no torch import). They say +nothing about how well the detector detects attacks. diff --git a/deploy/argocd/nt2102-demo.yaml b/deploy/argocd/nt2102-demo.yaml new file mode 100644 index 0000000..91b0689 --- /dev/null +++ b/deploy/argocd/nt2102-demo.yaml @@ -0,0 +1,27 @@ +# Apply once, manual sync, tracks deploy/k8s on main. Don't also enable the home-lab app-of-app template. +apiVersion: argoproj.io/v1alpha1 +kind: Application +metadata: + name: nt2102-demo + namespace: argocd + labels: + applicationType: stateless + finalizers: + - resources-finalizer.argocd.argoproj.io +spec: + project: default + destination: + namespace: nt2102-demo + name: in-cluster + syncPolicy: + syncOptions: + - CreateNamespace=true + - ServerSideApply=true + automated: + enabled: true + source: + repoURL: https://github.com/UITProjects/NT2102.git + targetRevision: main + path: deploy/k8s + directory: + recurse: false diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile new file mode 100644 index 0000000..b61a8a1 --- /dev/null +++ b/deploy/docker/Dockerfile @@ -0,0 +1,39 @@ +# syntax=docker/dockerfile:1 +# Snapshot-mode live server (no torch / Loki / LLM). See deploy/README.md. +# +# docker build -f deploy/docker/Dockerfile -t nt2102-demo . (repo root) +# docker run --rm -p 8000:8000 --read-only --tmpfs /data --tmpfs /tmp nt2102-demo + +FROM python:3.12.16-slim-trixie AS deps +COPY --from=ghcr.io/astral-sh/uv:0.9.3 /uv /bin/uv +COPY deploy/docker/requirements.txt /tmp/requirements.txt +RUN uv pip install --no-cache --require-hashes --target /opt/deps -r /tmp/requirements.txt + +FROM python:3.12.16-slim-trixie +ARG NT2102_CODE_SHA=unknown +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONPATH=/opt/deps \ + NT2102_CODE_SHA=${NT2102_CODE_SHA} \ + TZ=Asia/Ho_Chi_Minh +LABEL org.opencontainers.image.title="nt2102-demo" \ + org.opencontainers.image.description="OCR-APT live detector, recorded snapshot demo (read-only)" \ + org.opencontainers.image.source="https://github.com/UITProjects/NT2102" \ + org.opencontainers.image.revision="${NT2102_CODE_SHA}" +RUN useradd --uid 10001 --no-create-home --shell /usr/sbin/nologin demo +COPY --from=deps /opt/deps /opt/deps +WORKDIR /app +# only the modules snapshot mode imports +COPY src/live/live_server.py src/live/repository.py src/live/history.py src/live/file_store.py \ + src/live/snapshot.py src/live/playback.py src/live/ +COPY src/live/static/index.html src/live/static/ +COPY src/pipeline/alg1.py src/pipeline/alg2.py src/pipeline/cmdlines.py src/pipeline/ +COPY deploy/snapshot/nt2102-snapshot.tar.gz /app/snapshot/ +USER 10001 +EXPOSE 8000 +HEALTHCHECK --interval=30s --timeout=3s --start-period=20s \ + CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2).status == 200 else 1)" +# loops 2026-11-15 15:10Z -> 20:15Z +ENTRYPOINT ["python", "src/live/live_server.py", "--snapshot", "/app/snapshot/nt2102-snapshot.tar.gz", \ + "--data-dir", "/data", "--bind", "0.0.0.0", "--port", "8000", \ + "--playback-from", "2026-11-15T15:10:00Z", "--playback-interval-s", "3", "--playback-pause-s", "30"] diff --git a/deploy/docker/requirements.in b/deploy/docker/requirements.in new file mode 100644 index 0000000..6217bb8 --- /dev/null +++ b/deploy/docker/requirements.in @@ -0,0 +1,8 @@ +# Demo image runtime (no torch / PyG / LLM SDKs). +# Versions match uv.lock; regenerate requirements.txt with: +# uv export --format requirements-txt --no-hashes --no-emit-project > /tmp/lock.txt +# uv pip compile deploy/docker/requirements.in -c /tmp/lock.txt --python-version 3.12 --python-platform x86_64-unknown-linux-gnu --generate-hashes -o deploy/docker/requirements.txt +fastapi==0.143.0 +uvicorn==0.54.0 +pandas==3.0.6 +networkx==3.7 diff --git a/deploy/docker/requirements.txt b/deploy/docker/requirements.txt new file mode 100644 index 0000000..db97caf --- /dev/null +++ b/deploy/docker/requirements.txt @@ -0,0 +1,378 @@ +# This file was autogenerated by uv via the following command: +# uv pip compile deploy/docker/requirements.in -c /tmp/lock.txt --python-version 3.12 --python-platform x86_64-unknown-linux-gnu --generate-hashes -o deploy/docker/requirements.txt +annotated-doc==0.0.5 \ + --hash=sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101 \ + --hash=sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb + # via + # -c /tmp/lock.txt + # fastapi +annotated-types==0.8.0 \ + --hash=sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7 \ + --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0 + # via + # -c /tmp/lock.txt + # pydantic +anyio==4.15.1 \ + --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101 \ + --hash=sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94 + # via + # -c /tmp/lock.txt + # starlette +click==8.5.0 \ + --hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \ + --hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34 + # via + # -c /tmp/lock.txt + # uvicorn +fastapi==0.143.0 \ + --hash=sha256:1acffe48206a80917cf7dac21992b5c44b25384e8902bf745c1fd9dabcf6c51f \ + --hash=sha256:3e9395fd35276425b61b516a31fdd7c77fe2af83e41b4da22e30696fb1304c5d + # via + # -c /tmp/lock.txt + # -r deploy/docker/requirements.in +h11==0.16.0 \ + --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \ + --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86 + # via + # -c /tmp/lock.txt + # uvicorn +idna==3.20 \ + --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \ + --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c + # via + # -c /tmp/lock.txt + # anyio +networkx==3.7 \ + --hash=sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0 \ + --hash=sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a + # via + # -c /tmp/lock.txt + # -r deploy/docker/requirements.in +numpy==2.5.3 \ + --hash=sha256:012e66aca395d795496446e52aeeb5866312a5d4d3f27da270e5a0b43f70dc5c \ + --hash=sha256:09d5a423c71ad5feb5625844ad58050e35df43871004b52ac9c0ad44a56775be \ + --hash=sha256:09ffa5d903faeaa5c4dd05009cf81c8bab9f2cb37c548b8d39b65b4cfa7c97f7 \ + --hash=sha256:0a59a421a32580a009e8a1751345bf829631b990dc1794b80514ab722b435def \ + --hash=sha256:116f96cadd935c6122e9228d676fe7ede19e741f5c8bb1c3cddbe0c51ccebea2 \ + --hash=sha256:1302b90c0e52281681b2975adfe8a860cb7b12216a27b4b0b4207c44bf7bccf0 \ + --hash=sha256:15aa985ac73a8db02db7663381aa109510449d3819d37206caed27b33a65a8a6 \ + --hash=sha256:1aad64d99730d013cfc6debafed22783b4fc5a7f4b8bc744d2d8cf7dcc880551 \ + --hash=sha256:1c80eabb4035ecf4ca9cd49cde8a9fdd69a729e63e6474887d1523ade7aa277f \ + --hash=sha256:1f3ed25271581281f2fccb1adcedfcde4c07362eec69189b50baf6f90e3ae159 \ + --hash=sha256:1fb6f8fb9ff0b3a69f52c66ce397b0246583e9f28616231b0e32ca49259a5fa6 \ + --hash=sha256:214045a5bf00113a146ab9ee9730c44501af6723cdf1f6830932f7b5ef2e7af0 \ + --hash=sha256:26e15e4aecd8617dfbaecb37d223e365d7b39411fba20454be2670a96aa74cb5 \ + --hash=sha256:2c25dfa72943e4336ddb6b0ee4277b47a0c85bede0807530ec68103bf58e2c10 \ + --hash=sha256:2d8240cb4c16fd831074aa2b2cf9fc54664d826341d61c372245b96a74a49a9a \ + --hash=sha256:350ba9783ce969cf9f7ce6e6a9a58e1a6e2a19ca025b7ee448c4db727706212a \ + --hash=sha256:4c8a6d2ebce6305fd82fbefca827775437147052a976ee7c94b36a0c1b52ac6c \ + --hash=sha256:4f8929ee6c96bfbd7b4ed2032e0c03af86fe1826740ab61ddabf9072d06e57ff \ + --hash=sha256:536f963710a4e63934d80ac0dc4f478804a83e9a84b6828018f25d09953ada33 \ + --hash=sha256:54a115e5a73b8fc44f0cebef486365a1894b5c9760685d4558b72b7c3eb846e0 \ + --hash=sha256:595d020938c84e320bcf40ad71089e108eac0d377cd018e14a8c094f39e98d85 \ + --hash=sha256:66a78fe4556c60aceda5916f9eacd638b18e9e681016ec302dcb4682d6d4d034 \ + --hash=sha256:6b05c171afb3aa07adbd20abc00aea86fe375beb0fdb9ef780ec5b7f63bab1c0 \ + --hash=sha256:6cef4bb1706dfec49243c05d921eefb4e190d41e2528b30d8035ea1f36b4c24a \ + --hash=sha256:6f24021b9f22bc6301c37b196974a92c1c18dccedb6fef3dd252e95f2d6adbe4 \ + --hash=sha256:71b39d9f935b6ec0f8753e3e2afb51e3efba6f2e05b68b32a40754d24bcd4a3c \ + --hash=sha256:71cad2b2a7451ab79d8f5e71b453485b6775963d5cf794179144a7463fe6e8ec \ + --hash=sha256:76c2c1e6bfa5c84adc6434dfbf013aa92096a7985221762c8f11fedfd20fff58 \ + --hash=sha256:8617bbfae4486cf99c9f899966699428d19da931d06ca94ad3da986c76e15997 \ + --hash=sha256:86bff898a431c0fb71f7610b75726e75a54d47b37edc9d537f48de63bb3c0b90 \ + --hash=sha256:8e4dd766076855b5ff7ea52fa5f07ce26286726e0f8bff446b7739d02e6ea204 \ + --hash=sha256:92f30e89b8ee0ecf363033576c422b2f58fed6a80bed0aa48dff6d14c654663e \ + --hash=sha256:93e1f5447e2b1e479d7bd74701e84746b86450cff1fc368b132d195e2b8f8211 \ + --hash=sha256:9a37475425b431b4d060f23b4f52cd2f3aef6bc7c654bd760adf0040eec9d435 \ + --hash=sha256:9deb49575e5b0b94ed72c8a64ec4d033381adc27e9060ae842971f697ba96104 \ + --hash=sha256:a5fa86b80fd24bcd1aff83ad23be44ea323de3f787be8f8b15d4a65621e25321 \ + --hash=sha256:a6391fafaba97500887132cd582abc6e19452b1ac775a47caa7b24490e152058 \ + --hash=sha256:a72f874bc9e10e4b8f80426fb49716d5141f64442a0c8418065093ec8017fbb0 \ + --hash=sha256:ac7bb1c52d445bd4f8f7f97fefe6abc3a084dc4d63df50d79b17fa2b78e89297 \ + --hash=sha256:adc1ada2662f8a5f960b8a10d9986897e7499ef07e06d4cfe7197f8cce923c07 \ + --hash=sha256:b00eefbcf0f292945c4b4dec2ae845389ef5bcdcd596e6e4328051db5b5ba694 \ + --hash=sha256:b0521d0f4aebb6e06189451025fa17a913287b13c03d5fe05c017333b654ea5b \ + --hash=sha256:b5d93cf48f687479941d12b69c873ad2cc76bbd487f0091c2200636497f34034 \ + --hash=sha256:b7e18c623bb5c95acb3b3328861272816ba199fb531921c5d6d0b675f1fde9e3 \ + --hash=sha256:bd4cb9ad3c7889b9b3fe0a9a9fb5d2ed26f9879bff2608d9f01aed147a20d231 \ + --hash=sha256:be5a8381859b6da607c84f4f7d6847725f1cf1853ef8a2c9e115b7d58bef47dc \ + --hash=sha256:befa1ae5bd6030b3f512b43ff3fa5290bbed6b84411a44244b14adf835f5b89d \ + --hash=sha256:bf63afbe037eb5d2fe87fbcc7778e61da53ebaf21d938a4515aa73b62532a5d4 \ + --hash=sha256:c00abe94c1a69d75d827dcf1c025b25c8a45d230b3bcd77a9020883a1b047653 \ + --hash=sha256:c2381f82999704f818e2c987a865050e285ec3621262c66d40f5a96c8f899f8e \ + --hash=sha256:c76d5dde9f445058f83d0c02af00557a4db91de9a9a57c0df87d1535001d654b \ + --hash=sha256:cb189f09db39283b26bfd061ec16189e14f71c6755207f72a0f7540867afe5b9 \ + --hash=sha256:ccb32e0525d29e8b0572eb84c9a57af0e7a4e615726927506f55063c62414034 \ + --hash=sha256:ccbc4665079665c3cf3bab4db9f6b095370cd6437d66be549b6c2a1fd19e1958 \ + --hash=sha256:d1c89973648c85069c5046ad460f7b8a00218b29a2e42359ac8cc63e9ab94832 \ + --hash=sha256:df2d5874ff183595a4ba404edd04f6bd9b5505c1d7708573f6a6c17489a67563 \ + --hash=sha256:e01c918ac3d48e18a927cf7b14a26a3e29ff2bdf2eacb976da0aecd6a43ed034 \ + --hash=sha256:e6ab667ba76450084eb64013762c438ea76d9d29cc676dcd6c2e9892ba37f841 \ + --hash=sha256:e931e4f499e0dc7ef29d269a8e5b35dd722e5d14be07df6240166ea7c6532fae \ + --hash=sha256:f54660b0eb6b0b9f36e7fe1cdfdff472028dd0d14acd9b9b65098efbad059469 \ + --hash=sha256:f59a878c33d6b88122d80d239bb3b845d58708750b0cb06a09aebb9b18ec696c \ + --hash=sha256:f7fabeb6cea87d65f3b926de33d03fb016cfdc29314c90974383b5582ae72891 \ + --hash=sha256:f9579f383d1bf9df80081e72760e84960a7fd4f88cf0c9e535a8597c9bb646f5 \ + --hash=sha256:f9a2353b37a1a9e78fd82b27ad7e2a32a2d036604d18f02b05e3136c62ca3b09 \ + --hash=sha256:fc36dc566135b5eceec4cf89758fcb719266a019ef07dae1754ae7c9f617ef3e \ + --hash=sha256:ffdc76bfcae6b255dff75202c5e7feaf95b40246bc0a17944facc1fecf9f79ab + # via + # -c /tmp/lock.txt + # pandas +opentelemetry-api==1.45.1 \ + --hash=sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75 \ + --hash=sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb + # via + # -c /tmp/lock.txt + # fastapi +pandas==3.0.6 \ + --hash=sha256:0704044b676496b8350e023b09f174a26772456c974a2b11c36bebb558c9490d \ + --hash=sha256:085e3786ae6b2e82b406266bce36690f72b9dc1421903ba9296b2981a9fcf586 \ + --hash=sha256:097090508a1dd335013d39106fc10b20f4fd4a171638e47b77d55798ed9dab6c \ + --hash=sha256:1bcb3e9ed29e74a7439cedff9e2aefd3ea65de84d7de9ccb6c194192541bd60e \ + --hash=sha256:1e7c0afdcaf6661d795fcefc2f647ddd1136f62cdc153fba177c685d97a87808 \ + --hash=sha256:1e92d9fa834c7d877130027cddc0cad8dcff97c1f6cca26bd6310f847228b658 \ + --hash=sha256:22172a92e7ee678ec0140c7af4fc9366b55413834a1cd86af78b3caa0b0574de \ + --hash=sha256:253e12cb9081b0afbac607920f6142975966bc315135e09de275fdbaa415d2de \ + --hash=sha256:265f562fdd1079f69f3de96dd425c3405224038c0af4f920c54bd240ee2c4640 \ + --hash=sha256:2a8fc94be2ee5f1d86f97aacd8cc566f81680b6498e76f3007421bb5d98151bf \ + --hash=sha256:2e5fa32ff162dfdbc280157d664f44d23049ae414725af9676df339c501d82cd \ + --hash=sha256:3ef908d28590b3f42d7070e7ad8f9b34b442b260b7f3c1afb57e0040c58cdb1b \ + --hash=sha256:429d9df32731ab01383ed98f2baa7a60368090d1a94fc06019a12062510e8630 \ + --hash=sha256:47121f9571503f724c9b93e297ab6254ac99c77adf5e9ed085ea419fd585c258 \ + --hash=sha256:4e25e2e1adee99ddfada6f7206a79ae8e9c8a8861b0e3eaaba165006d3eef18e \ + --hash=sha256:4ff44b2cb51cbd691c91f92c4ea6c71e34003f239ebd67c2e857dc898466b49c \ + --hash=sha256:50c44cbf5820b6b91a5f74aae04972472aefadd3cd9fbd1010409d85528bd570 \ + --hash=sha256:569e114072b24fc4970c12e2b4bab252671668a40b324318903380cab0254c0c \ + --hash=sha256:583be68728a31d0d750d5b8d9e00f02b153df0d4655f858bde93cb84cfc4227c \ + --hash=sha256:5e75072773c1b2f7cb63faa3a6f562aede11f3976f68ed34cb538bc091a28171 \ + --hash=sha256:5edd0a7abb0986ecce1ac81f56d99b6763f86aa6946dceb6c661224f90af5a19 \ + --hash=sha256:60d81f9e1799b36f3739e7fff44d1fbb2e8fd5a271b3863e03de9715fccda0fa \ + --hash=sha256:62f51d7f651c8054c5e82a69265c98082e795d1442df7ca6edc3a545d61214b1 \ + --hash=sha256:654aae059295dbba6ecd2328ca12712a2cf1676214c8699f1c29213f7ccf9c34 \ + --hash=sha256:66b07ef7315a31bfe1089cd3d71a7de781c9dca986762d0b4fe7c0ef17465d10 \ + --hash=sha256:6ff482fa91fa2bafd92e8fe66ce3645c851824310f295c1f0a2f96e928fc4541 \ + --hash=sha256:77ccbe5057aece6fc172b9b77f19c04335af6882bc2e10c8f3ee4e6bfb3da553 \ + --hash=sha256:7dac2d65e9087e8e7b5a45fe15c4920911a221df061ab629943ce016489145c7 \ + --hash=sha256:83e91d15738d7783c050197cef2f2cf82fc6353dae9865aa87ed1fa16aa4d55a \ + --hash=sha256:86fa853a12e0b70927e2b1ee00d56d2224ec9cbb4b9d58348b5ad52d2f21150e \ + --hash=sha256:8fe77b408d82e2615674dfed62533b95e18a03610573877422aada4f625d4947 \ + --hash=sha256:963ca21199097a84c7827c4678b04e30833084fbf8ef44fde3fa7180a29f8fa0 \ + --hash=sha256:97274c9adf6255bb48c620cd6959805efa7f09ea2167f0e0ae006a448cd2fca7 \ + --hash=sha256:994a79608263fe1c14cc48ffa7300e2b834b7d1cb406ffe96a08828cb0cdd79b \ + --hash=sha256:9ae8073aed8e21d1a7fe263dcdc6840743549722a6738198a0a46000fa9476f2 \ + --hash=sha256:9dab635a549e58a053c7b0fa054dc0bd7be22f0ed9a720f4a85d5fb993276172 \ + --hash=sha256:9e492cd4bdba6778de4fe0df7f4590c012161ebcf9902dce01b01dc683105514 \ + --hash=sha256:a3a22e07fe75347eaacc75b0e85297947af4fba6b4aae23916bd8b6828d0bba3 \ + --hash=sha256:a4dbd4dc65cbe645b92b8785d0f96dd7311010dc6606cf620e51b07b8788a12a \ + --hash=sha256:a77a1a44e4d88f1c6a2a64d3eb12efec8420875722e14279800b173a7c7c2804 \ + --hash=sha256:b27c8d890e4aa2171437ae2a39de1d215e674158e4865c4023a8b31c932513b2 \ + --hash=sha256:bd75ed0c840f709fc2ae26ddd9534ac77ca1a48ac0cce521a74acaa85f3340a7 \ + --hash=sha256:c6e4aae3e9bea26c6c9a20d88d96c86ec4a99b4db5fd516bcb4e829ab2c0ee36 \ + --hash=sha256:c826e9babb7790142c399f58599d8de679bea059d7b39c5b6efa2096fac37266 \ + --hash=sha256:cc39303913e2ea129915670de5d1c9fbd647f543bb72e5543bac8baa94e9e42f \ + --hash=sha256:d7564d86a94c2eb8ab290b07f63ddaae5c032fa53897c29a2ff2197d43aee8af \ + --hash=sha256:d7dcd21238cbb4828ff148481ba01cac8946dc5121457b5aeba28636f8f99a60 \ + --hash=sha256:db7ec631f26223beee8e5c9e0b8f23c24d8197bbd1d982421d4e3188bea51965 \ + --hash=sha256:e3dccb584123b399c07562ac4d62543e90ede49ddf8ce3c13ffc64cbe828c281 \ + --hash=sha256:e7c1905ef02c3d6d43d9dbd5b6ccb4da4870a0b0c821bbc103fbdb6f3ad2707b \ + --hash=sha256:eb6900de08ac85f93ac4948aa6b80842eba555875337b8359035ac9c43e92d34 \ + --hash=sha256:ee913a91669056c1de1a6b733fbfeab711de9e54e3bee2dfa5fe79d9457247d1 \ + --hash=sha256:ef738d71d1059245b6bb03e312be06d8b3821326a83486c1ad03b9aba3710e44 \ + --hash=sha256:f3ce8a6968045481e91a3990e797e348ce13db45ee164a7095bbc824e26c09dd \ + --hash=sha256:f4e7c52eb108d752e7592268108fd3e98efd76d83a3125cdd06c621c2e44359b \ + --hash=sha256:f8029ec0f1f89e4f985929ce1f6626dabf3140d61a4e9c1215afdab34eaf9a5d \ + --hash=sha256:fb625f426b375bcc96e3a04c5d5d266cd7be6ae5d6866e0e703382ab5164068c \ + --hash=sha256:ff51a4459ed036e93d1eb1bb5e6e7b28685d3cb6b7c12b91c05b31024e234729 + # via + # -c /tmp/lock.txt + # -r deploy/docker/requirements.in +pydantic==2.14.0 \ + --hash=sha256:15fab1bea6f1dc5003b54fc2ecab230c1fd1dbade2acd4addc52d81e32416d4b \ + --hash=sha256:8a51a7aaddd60f55566d1f07bdd87b92b463903f39a8f26b71a06314cd1548ae + # via + # -c /tmp/lock.txt + # fastapi +pydantic-core==2.50.0 \ + --hash=sha256:00963fde61cf8880d9e7b5635a9830e0591edfa45168447fdc5b47635c0f6437 \ + --hash=sha256:01340f4fbb4f854b1f36a6fe9dcd2b26c8936aead4e4ad1205624ac025c875fc \ + --hash=sha256:02ec3675d606a355523e1c52bf5aa4116776f8d273dba03d8336a5a3ae984e15 \ + --hash=sha256:031867348c98ab49c6d3a16ad39738369ea48da59900d76d71c1e64de71fe79b \ + --hash=sha256:0393763d66f6f61715488d074a2cefac04aeb3ee281e36fb4925dd44deaf9e17 \ + --hash=sha256:049b0404792dcb942f1092bfdae5f819ef30445b0d174782e1909fbdd91bb48b \ + --hash=sha256:0abe1b44d361b948404b6b2ed80be2583e0077340572e071afa6e0eda4e1de30 \ + --hash=sha256:0def1dc09802a790e4a1b3cbc4401f0b53c58f273ce3671df9867f7bdf1fbe20 \ + --hash=sha256:0fdeda6272d60b1f6fb63f6a3dade55e274af62e1514d24a6549a12150c385cc \ + --hash=sha256:1541c334af5d42cb9eb03862a9b4d2cfbfc670fd05172ec51f3ce02d704550f1 \ + --hash=sha256:158749408ee19682b8a2a7e7135cced7f41d6f2f9de96088b1b1609858a6a158 \ + --hash=sha256:1751e92d56fbb623b937d73985e500b1a2b1053e56f718a6c564660d99bb9cb0 \ + --hash=sha256:1773001198030e16f946a7ff7760fc3ebd45b12150f66fd0f433780043dc13d8 \ + --hash=sha256:17a5ca9c197788a6424749a09a3dce824cb2c17b72f835f8a5e330935b973609 \ + --hash=sha256:1bbd7da16d8b2912cc56c9d0b85c4998a6cbf39b220f81c0d8c397c64672ae0e \ + --hash=sha256:2092ce156f92aff17e3345baba2b7c0c1701f32ba922c5de71bd6248fbe164e3 \ + --hash=sha256:21b62d45f327eb0802f842c132fda6d01a8376a8077922dc4dda69011c64d34a \ + --hash=sha256:21e38a011783d8afc8b9d79928e273d06f349b52ae84edf63ec18ad07f077484 \ + --hash=sha256:23e0940b7d73f405d92e98b2a05b93b16db163be13b7478bb19e1db2e486ade6 \ + --hash=sha256:24302bf47319a64e5c5c7c29e971d2b7a20a190c64e59035a3df9582dec636fa \ + --hash=sha256:243088c95e23b12db9f2cd7661d584a3f00814e087489f40cde7f9feac56b694 \ + --hash=sha256:2568b190075acd058513dca34f7fddc7252fc958c1591cb67a554338fc9a81b2 \ + --hash=sha256:2918547195ffb20118b829fdb8938e9dc92c9527fe6cbe58572594c96362880e \ + --hash=sha256:2f28a5a299d4cefd1066a6883d22600b9ae3606f881c3015d255784634647580 \ + --hash=sha256:34a4a0938eb30931baca56e55786c5a6871ac7aa891a38c8cabcdb7e49dab91b \ + --hash=sha256:350001f5573451150d919722ee095aa28bec037d6e23b86d7f04581a910fe924 \ + --hash=sha256:364f62d8024997536e57865cb1c8b36effad3249bf392a29a2379ea69db28238 \ + --hash=sha256:36c49d4e1769127461b609f110d91963790091ffcc2de401ac1d3b2f6a63bd54 \ + --hash=sha256:36f9ed6ae1069913e4f6e86d8233e119e83e00a20c54f88faf9c81292f2fecc0 \ + --hash=sha256:38b03c5439c6a7a952f56e3e6596dae44bc78c3fb6a69df46cabfb2f888e5f0c \ + --hash=sha256:3b2f3e44af4c6512dd73557621385a71b18094c8be81d60e5a8e73a8ce96b7f4 \ + --hash=sha256:3fce74add1099da1ea09473268950270071fd56773e2968604efb3ab1d240e02 \ + --hash=sha256:41b9f2821f0a105f88cd54ad03fe1392ec600618ffa8610f7c5e466ecd98c531 \ + --hash=sha256:42a56b0052ac11d9d0d87b1c94a1ce52e31914fd133f269585e0f63a4ed988f2 \ + --hash=sha256:42fff617cb0b08505d8123d71e6e7a8e54210d9007498f564855bd843ce984b1 \ + --hash=sha256:468f7e67cfbd8231f442af6726449efe46f2be0e5a57b44fba7ccd92c6f121c4 \ + --hash=sha256:4b1bae96f41806b14dd8bb1568d39b5e33b5af7fb27f7be36c78b8fa84708917 \ + --hash=sha256:4f31af62efd1fd0257735b72e6716b32d4f207654adeabfe524d44baf1bb6bed \ + --hash=sha256:4f96ccd9368ecbf6685d8f6981584ab72b4f0ffd20685e747737e7e340277b8d \ + --hash=sha256:4faa766450ef44d9eabed5b65a280f63f903d1e1ed6d2e278961eb22345ec49f \ + --hash=sha256:50920d66aaab60dbc6023c3035d55fbabfa58b6d205d0b39d47d820c4a7a13a8 \ + --hash=sha256:5307a8bd49158b57a0ca4e10950d31085aa35d9007e934047043ccc6d28eea97 \ + --hash=sha256:55684bc850059fc85ff8dc21a3e342b722d3178993c49ebdfdee8b698a432720 \ + --hash=sha256:56178c4116fc0c859786875ff4acc1c8d52678f095c312b0eff2a2dd9d6f8d5f \ + --hash=sha256:57c0e5b26d82bf31ab2b044781527b1b1a36e9ed400856b6aca5097eb1abb909 \ + --hash=sha256:586699b43066ca6038f96bd71d0eff0b6c292929e3d66ff63d5dc79d0f06d589 \ + --hash=sha256:588d309ce5c85448379556d72011b191c0414ee2e80d7c3f1ebe2ceb2d9027b1 \ + --hash=sha256:593dd4f24abeb3ed90222f98bc6eefcac68cd5aa96fc7745f93862a802952bce \ + --hash=sha256:59f816dc04e99627a5a6352ae51dfb30e603f2cb0b7009c91dc640c533def014 \ + --hash=sha256:5a07c644047f5abc268b4c39f8cb5a30e08a3c349228cb70142c7d3ed87587c0 \ + --hash=sha256:5a8403eef4a66743e339102fb3cdd8c8b9016b8bd67924685893d062c88896f9 \ + --hash=sha256:5d0b210c871486f5acb56d87bf00e3c5d83aab6a1ef3042629fa6ae0172fcf47 \ + --hash=sha256:5dbf9f18c8af11db719e67633be0af556d7d765bee0ca9419bd706fe4b7ed9fe \ + --hash=sha256:610e9f483ac53c5cc59c2d3687224029b54eb494feec2d40a2bcfdd187635192 \ + --hash=sha256:62a93a9d206a3580c975c3c1f65a869cd063844d016c004f8d786a9309b3c591 \ + --hash=sha256:62ec6568896e0abf258cbcd22c406c1c8bf27d16224b21bec8f75c4ae88a8173 \ + --hash=sha256:63263d64884688554fb025a3906c7b00573980cfee75f9afeb86239d577384bc \ + --hash=sha256:68421ba548f6d86c7dededd70bfe530b4faf67eb811c53c70a1be69438d3ce99 \ + --hash=sha256:6e1ec4176c3b56017745937dfd4a3ec6df55f7f0e66991124499f3f79f8f8d1f \ + --hash=sha256:70df7ff903aea05383298715ea53551c8f27c8f70cbe54ba7f05606cd822e7e4 \ + --hash=sha256:71061800a3c225e730f7997f8a7fad6e0d0dcbe36609cdc7e60576a099a2832b \ + --hash=sha256:718d05d4e078c7828f40ad3e310870fe4b837d93a32e7e8497a080c1f1040490 \ + --hash=sha256:732efbb50977ab7cf18f01d4c255834aeb14cb2425459f7bff681a1ba3a4ffa1 \ + --hash=sha256:74cbb6cbd74445ca279668790e0c10eccac0428fd79fe061fce6c9e3982ad3fe \ + --hash=sha256:753863dd4317ec8cc9eb3e6d9d01a8ef1a1726a8003b4354658d68a1ae05f9db \ + --hash=sha256:75b451ec5e64a1d4b803317f34710131742ff2e42f4bf5403f597d0af857d7d8 \ + --hash=sha256:779b6c74526596a86d38248dedaecfb7851bbaf319c234be042c57acddd2c8c4 \ + --hash=sha256:7987866a2569396e6765c54d643fd6a7b3b234e89ee8d45a3729a7b4b2726145 \ + --hash=sha256:79e8fc9c135ef628c45cb8aa5deef8d21de13d33bb4c59a859fa73d335ceb40a \ + --hash=sha256:7eee44c3f1f8acc220a743a5ed5588949a4f18b33df4cfbef2b1277470285401 \ + --hash=sha256:8447678b49412294801c9ea15ae31ea3bae7da65425268c92d40e032c38eac6f \ + --hash=sha256:84d2d38f7d163c4dec292f379e9de1960c661795442aca6c90d706436cb3749e \ + --hash=sha256:8ab9e74878172948e0426e3d27fba333fd6a1c3f9456d8e75643e8e6868ac1a1 \ + --hash=sha256:8ad8dad549cd1645be591a50b4573995ee7e018f6619ddc2bc6ea44b2ad9f694 \ + --hash=sha256:8b16e164205a90b1050d2f5469f8a7829db7698ad198c69e6aab6cbfb5648b87 \ + --hash=sha256:8f16bc5bb12f4c581b0f40facc28dbf286db32d1bf4e7e4f4c4e0f7f4e34ecf9 \ + --hash=sha256:8facaf0a16121ac82cc403a71399a061b74624c1ae2034eec9ed6169c5d16ecb \ + --hash=sha256:90874428bc6678b26434336c77931c9734ecebedf50132c179205e5a9908761d \ + --hash=sha256:92016718bcf3e6f35a6bd986880191a8da7a35aa1f5b1e97544582ef938464cf \ + --hash=sha256:9279f4be22bc3765dd9f61f5b4d38d9cb219d167bbd6f2e0ffa3368b1b71b4d1 \ + --hash=sha256:933f2d639eb81a3e1f145aec415453cc00983236629933f028d9507222583a2e \ + --hash=sha256:93502b3c762149a5904316ef52f0ed1ea721e0f4c8431f964f140ed15fa61926 \ + --hash=sha256:955d7878130dfc124d6a5343e1b87d2933244fe14a4a0a3e98787e8e660a8eb4 \ + --hash=sha256:980c81c2ec53ea9eb2227c14b3e6de35670b2de163b638f2a803e90a3bd5bbb0 \ + --hash=sha256:99e203d5c2a814facef78dcd993b0fb7a933124a3475a38979fc09cceae210b7 \ + --hash=sha256:a2b88f9f9fa52e1c34938ff1a18ee7fbffe482df0bb43c087a9a60578d273d68 \ + --hash=sha256:a3e8ee6386f6b68e2f818ccf422ccfafc59bcff10862b52c7819db3aa0352dfc \ + --hash=sha256:a7080928078ff56c07da393392f772054e93a39c8033dc9c04547bd949f9b614 \ + --hash=sha256:a8ee3965e01f10e4ff92ba1727626328ab7ba93bcd5674ff2b78ea1048ee0cea \ + --hash=sha256:ab3f95f737fc1b258b8210308fc02ce1442cf5950cf6d30b09ad89ab9e8afebd \ + --hash=sha256:ac223ea031905319a64d0df116979ae438b42d6265862a3d63c9f9808c2905a7 \ + --hash=sha256:ad3532291deedfdfcad3cf5d351d0076d646c68a0c63869a1bebf87c22159600 \ + --hash=sha256:ad9185366893714cd4514ae5e1a098227704fa395cb41a7855d75968ecedc826 \ + --hash=sha256:ae45853d25a23fba56681d2f9ed41f3e3f12f0a3b2393fefa08ff6406320a1f5 \ + --hash=sha256:af2b808a79bb04075e87c81a5b6179365b93f9a851f29dafd67abff72085d0c8 \ + --hash=sha256:b123f9d8702106f39dc3af63a031ca8b5279862a3747ec6c03ca49dbe78b71b9 \ + --hash=sha256:b1399f918aea8fb76ffa99b474c9b768accea1f079fde407ee538bec89f20fa7 \ + --hash=sha256:b916ff828d604d4311a5639b7b3da51eaea3923833ec3e300a5ee35eade99691 \ + --hash=sha256:b9be297ffe1015bfb2db4a23b6e1fec7e48361cf7c7b4f4f6bbdd008451b0a7b \ + --hash=sha256:bc87bd34239835c8d73171acd039e591cea0a2ca8615e6188044ad170a40fca1 \ + --hash=sha256:bd841dcf394ff261c26763a9d7be754176d4f1e6d26cb2a5d5331e91b6b56a5f \ + --hash=sha256:bdd70c2d9e73bca09fad54605dfeaae2b4e770b2800c65f5f5342901ed567b9f \ + --hash=sha256:c05b75ef3574c9ee4e05bbcf8513f7ccb155d426514be9efef5f6f53152d5f5c \ + --hash=sha256:c05d035e72530f6b00297941b0162218601542b76870c3bf2756bd87f16fc538 \ + --hash=sha256:c19500343957f254ecf3e60174f4a4cdd21690e0e1677740a8017d28ab2a2a4b \ + --hash=sha256:c21e6a6e4e6d32fb6acbc4f0fa69e8319cac0d65eeaa8298d757371cc2a9c687 \ + --hash=sha256:c2b246fa7cbdf9918488d1542a82bbb928cf71bcba66905c24131981e759ff0b \ + --hash=sha256:c2e97985641fe53ad7824d1b5bfeb7990a5ff788c4559ee44d7522642560ddc2 \ + --hash=sha256:c3ae59461625518449f800acc4f874753ae96fcf993c47a27be07beb651371fd \ + --hash=sha256:c4abc425789f8540e86ca4cfdbc8dc650433cc2ac7c6136fee9bcb29d5665a02 \ + --hash=sha256:cb4fcaabb28cabf21396a9b816b9afe091f8c776805fdf03e2cbc606b64dfa7c \ + --hash=sha256:cbce1b5a2a88a465d7865df61b7e4f8829ddc49b4fa841e9b241815c9d67c3b2 \ + --hash=sha256:cf150693a51ca21e8288cd08a9de05e5ab331776dfcfd0537b14523338f0502a \ + --hash=sha256:cf81432281af66ba3285b26b09c2d478d84730dc50ff90926c1bdcef54048a33 \ + --hash=sha256:d01029d54ff1f45c195b1f7e6fbf6e58fb7e7e12cda9a6e639570d9c581decb2 \ + --hash=sha256:d06dbbfe8da01a0574de27afc19915bb3e7dddfbd184bb97e958f94051d8531b \ + --hash=sha256:d14d04058923d526a552fc3ebe8b0b0353c19516431cee196502b53119278fd9 \ + --hash=sha256:d187f43d1c5b844adc871c5b8c22b4aa12a116aaca4e9bd1521bc9ce479aae1f \ + --hash=sha256:d1d084e92d0f4a096a5155b23d1ac603db8073ef98a3d1384badf1455e5ae742 \ + --hash=sha256:d8354fbbe2abf0fb724b9303bef43bfd9b7a2779332813fa6d6559983954e7d8 \ + --hash=sha256:dcbd1fe5083315243447c13f7252ae9fe9d128b1ae2857e3a916c609235dd863 \ + --hash=sha256:dec0dafc116ac29a84d143fdbc3b83fdb5d4ed339276be2251154537ab30e14d \ + --hash=sha256:e15bb1535f68a27f28e579ba3a8f74e7b05d350c45f5622b76a311d5a19ae48a \ + --hash=sha256:e41f9d1d9240e8e0d8a670ad3e66c0c00f0b1f7150a31bc6c445a4f87c1cb3ba \ + --hash=sha256:e58acd43ac8d3905659c1d5309318dd576243e723dd7c3b5dd4f555479b77d4b \ + --hash=sha256:eadf95aab7301ac651628f097e521d742d0fb5f732155ebfd00d07933045d81c \ + --hash=sha256:ec786cb9d597dd75d993f8c1273e31bb2114c9bc22f67fba611e654e8347701b \ + --hash=sha256:ed557fa2744617eac3e34dd39b85037efbf23cd33f06851c00fdb8f18ad8f4c2 \ + --hash=sha256:ee9913fa2b5bfa6111c11158cf481bb13544f8bd5d10382fb6ee2612b16fcf28 \ + --hash=sha256:f0af2d2f745ec00a6616c4dfba4477f9156ccfb45690f6ffa5fd34f42e871ed4 \ + --hash=sha256:f12d9690634414fc04b1a7072fdc35c34a9242232c1851fe4518383578bb09d4 \ + --hash=sha256:f187030fc3d62c668feb0f09e92852e0eb414d7fcefc4748f2e67d245aade37e \ + --hash=sha256:f3abcabb04503023e1053add24472e78878de0bfd5c8a93686be01f4032c363c \ + --hash=sha256:f44107b5fdfecc03438feb165431652c8006650471326e53dd86d4c19124f5c5 \ + --hash=sha256:f517a417cd02aa8fb05b603a0ac6d87b7b004c3ba4fcd279cad25cab7229043b \ + --hash=sha256:f8cc61ad94215ab98e5cbcdea2cfde45e11bb0136ee980e1240b721635e55790 \ + --hash=sha256:f8df36f964c21168e345f914855e3b428e2cb6e1f739c8ef5963b77d86dd84ae + # via + # -c /tmp/lock.txt + # pydantic +python-dateutil==2.9.0.post0 \ + --hash=sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3 \ + --hash=sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427 + # via + # -c /tmp/lock.txt + # pandas +six==1.17.0 \ + --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \ + --hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81 + # via + # -c /tmp/lock.txt + # python-dateutil +starlette==1.7.0 \ + --hash=sha256:67f8e99895493dd2911a03f11314af6ceebeae4e704bb9f43dfc6a9db151c93e \ + --hash=sha256:c79f74ea63cff761804fbbfb182f1e0b440c2d07b164d24700c5a1bab5d6ff5d + # via + # -c /tmp/lock.txt + # fastapi +typing-extensions==4.16.0 \ + --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \ + --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5 + # via + # -c /tmp/lock.txt + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 \ + --hash=sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47 \ + --hash=sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147 + # via + # -c /tmp/lock.txt + # fastapi + # pydantic +uvicorn==0.54.0 \ + --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \ + --hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620 + # via + # -c /tmp/lock.txt + # -r deploy/docker/requirements.in diff --git a/deploy/k8s/deployment.yaml b/deploy/k8s/deployment.yaml new file mode 100644 index 0000000..d26ff48 --- /dev/null +++ b/deploy/k8s/deployment.yaml @@ -0,0 +1,84 @@ +# Snapshot-mode server, stateless. Sizing: deploy/README.md. +apiVersion: apps/v1 +kind: Deployment +metadata: + name: nt2102-demo + labels: + app: nt2102-demo +spec: + replicas: 1 + revisionHistoryLimit: 3 + strategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 1 + maxUnavailable: 0 + selector: + matchLabels: + app: nt2102-demo + template: + metadata: + labels: + app: nt2102-demo + spec: + automountServiceAccountToken: false + enableServiceLinks: false + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + fsGroup: 10001 + seccompProfile: + type: RuntimeDefault + containers: + - name: demo + # CI builds :X.Y.Z from tag vX.Y.Z + image: ghcr.io/uitprojects/nt2102-demo:1.0.0 + imagePullPolicy: IfNotPresent + ports: + - name: http + containerPort: 8000 + env: + - name: TZ + value: Asia/Ho_Chi_Minh + resources: + requests: + cpu: 50m + memory: 160Mi + limits: + cpu: "1" + memory: 256Mi + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + startupProbe: # snapshot unpack + sha256 check + httpGet: + path: /healthz + port: http + periodSeconds: 2 + failureThreshold: 30 + readinessProbe: + httpGet: + path: /healthz + port: http + periodSeconds: 10 + livenessProbe: + httpGet: + path: /healthz + port: http + periodSeconds: 20 + failureThreshold: 3 + volumeMounts: + - name: data + mountPath: /data + - name: tmp + mountPath: /tmp + volumes: + - name: data # unpacked snapshot, ~75 MB + emptyDir: + sizeLimit: 256Mi + - name: tmp + emptyDir: + sizeLimit: 16Mi diff --git a/deploy/k8s/ingress.yaml b/deploy/k8s/ingress.yaml new file mode 100644 index 0000000..0780d87 --- /dev/null +++ b/deploy/k8s/ingress.yaml @@ -0,0 +1,25 @@ +# https://projects.datrollout.dev/nt2102/ — crowdsec, slash redirect, strip prefix. No geo filter. +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: nt2102-demo + labels: + app: nt2102-demo + annotations: + traefik.ingress.kubernetes.io/router.entrypoints: websecure + traefik.ingress.kubernetes.io/router.tls: "true" + traefik.ingress.kubernetes.io/router.tls.certresolver: letsencrypt + traefik.ingress.kubernetes.io/router.middlewares: "traefik-crowdsec@kubernetescrd,nt2102-demo-slash@kubernetescrd,nt2102-demo-strip@kubernetescrd" +spec: + ingressClassName: traefik + rules: + - host: projects.datrollout.dev + http: + paths: + - path: /nt2102 + pathType: Prefix + backend: + service: + name: nt2102-demo + port: + name: http diff --git a/deploy/k8s/middleware-path.yaml b/deploy/k8s/middleware-path.yaml new file mode 100644 index 0000000..3806443 --- /dev/null +++ b/deploy/k8s/middleware-path.yaml @@ -0,0 +1,19 @@ +# /nt2102 -> /nt2102/ (UI uses relative URLs), then strip /nt2102. +apiVersion: traefik.io/v1alpha1 +kind: Middleware +metadata: + name: slash +spec: + redirectRegex: + regex: ^(https?://[^/]+/nt2102)$ + replacement: ${1}/ + permanent: true +--- +apiVersion: traefik.io/v1alpha1 +kind: Middleware +metadata: + name: strip +spec: + stripPrefix: + prefixes: + - /nt2102 diff --git a/deploy/k8s/service.yaml b/deploy/k8s/service.yaml new file mode 100644 index 0000000..1284657 --- /dev/null +++ b/deploy/k8s/service.yaml @@ -0,0 +1,14 @@ +apiVersion: v1 +kind: Service +metadata: + name: nt2102-demo + labels: + app: nt2102-demo +spec: + type: ClusterIP + selector: + app: nt2102-demo + ports: + - name: http + port: 8000 + targetPort: http diff --git a/deploy/loadtest.py b/deploy/loadtest.py new file mode 100644 index 0000000..035b9cf --- /dev/null +++ b/deploy/loadtest.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +""" +loadtest.py - a small, realistic load on the demo (a handful of employers browsing at once), standard library only. + +Each virtual user does what a visitor does in the UI: opens the page, keeps ONE SSE stream open (the live panels), +then loops: status, the window list of both hosts, a History query (6 h, then 7 d alerts-only), and 3 window +details picked from the History result, with a 2-5 s think time. Reports latency percentiles per request type, +errors, and HTTP 429s (none expected: the Ingress has no rate limit since 2026-11-17). + + python deploy/loadtest.py --url http://localhost:8766 --users 10 --duration 300 + python deploy/loadtest.py --url https://projects.datrollout.dev/nt2102 --users 10 --duration 300 + +Measure resources meanwhile: `docker stats nt2102-demo` locally, `kubectl top pod -n nt2102-demo` on the cluster. +""" +from __future__ import annotations + +import argparse +import json +import random +import statistics +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +from collections import defaultdict + +UA = {"User-Agent": "nt2102-loadtest/1"} + + +class Stats: + def __init__(self): + self.lock = threading.Lock() + self.ms = defaultdict(list) + self.codes = defaultdict(lambda: defaultdict(int)) + self.sse_events = 0 + + def add(self, name, ms, code): + with self.lock: + self.ms[name].append(ms) + self.codes[name][code] += 1 + + +def get(base, path, stats, name, timeout=15): + t0 = time.perf_counter() + try: + with urllib.request.urlopen(urllib.request.Request(base + path, headers=UA), timeout=timeout) as r: + body = r.read() + code = r.status + except urllib.error.HTTPError as e: + body, code = b"", e.code + except Exception as e: # timeouts, resets + body, code = b"", type(e).__name__ + stats.add(name, (time.perf_counter() - t0) * 1000, code) + return json.loads(body) if code == 200 and body[:1] in (b"{", b"[") else None + + +def sse(base, stats, stop): + """One open event stream per user, like the browser tab.""" + while not stop.is_set(): + try: + with urllib.request.urlopen(urllib.request.Request(base + "/api/stream", headers=UA), timeout=30) as r: + for line in r: + if stop.is_set(): + return + if line.startswith(b"event:"): + with stats.lock: + stats.sse_events += 1 + except Exception: + time.sleep(1) + + +def user(base, stats, stop, seed): + rnd = random.Random(seed) + threading.Thread(target=sse, args=(base, stats, stop), daemon=True).start() + get(base, "/", stats, "page") + st = get(base, "/api/status", stats, "status") or {} + snap = st.get("snapshot") or {} + end = snap.get("to_ms") or int(time.time() * 1000) + hosts = [h["host"] for h in st.get("hosts", []) if h.get("host")] + while not stop.is_set(): + get(base, "/api/status", stats, "status") + for h in hosts: + get(base, "/api/windows?host=" + urllib.parse.quote(h), stats, "windows") + q = {"from": str(end - 6 * 3600_000), "to": str(end)} + hist = get(base, "/api/history?" + urllib.parse.urlencode(q), stats, "history_6h") or {} + get(base, "/api/history?" + urllib.parse.urlencode({"from": str(end - 7 * 86400_000), "to": str(end), + "alert": "1"}), stats, "history_7d_alerts") + rows = hist.get("windows") or [] + for w in rnd.sample(rows, min(3, len(rows))): + get(base, f"/api/history/{w['sdir']}/{w['window']}", stats, "detail") + stop.wait(rnd.uniform(2, 5)) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--url", default="http://localhost:8766") + ap.add_argument("--users", type=int, default=10) + ap.add_argument("--duration", type=float, default=300, help="seconds") + a = ap.parse_args() + base = a.url.rstrip("/") + stats, stop = Stats(), threading.Event() + threads = [threading.Thread(target=user, args=(base, stats, stop, i), daemon=True) for i in range(a.users)] + t0 = time.time() + for t in threads: + t.start() + time.sleep(0.5) # staggered arrivals + try: + while time.time() - t0 < a.duration: + time.sleep(5) + n = sum(len(v) for v in stats.ms.values()) + print(f"[loadtest] {time.time() - t0:5.0f}s {n} requests {stats.sse_events} SSE events", flush=True) + finally: + stop.set() + el = time.time() - t0 + print(f"\n{a.users} users, {el:.0f}s, {sum(len(v) for v in stats.ms.values()) / el:.1f} req/s, " + f"{stats.sse_events} SSE events") + print(f"{'request':<20}{'n':>7}{'p50 ms':>9}{'p95 ms':>9}{'max ms':>9} codes") + for name, v in sorted(stats.ms.items()): + v = sorted(v) + p95 = v[min(len(v) - 1, int(len(v) * 0.95))] + print(f"{name:<20}{len(v):>7}{statistics.median(v):>9.1f}{p95:>9.1f}{v[-1]:>9.1f} {dict(stats.codes[name])}") + bad = {n: {c: k for c, k in cs.items() if c != 200} for n, cs in stats.codes.items()} + bad = {n: cs for n, cs in bad.items() if cs} + print("non-200:", bad or "none") + + +if __name__ == "__main__": + main() diff --git a/deploy/snapshot/nt2102-snapshot.tar.gz b/deploy/snapshot/nt2102-snapshot.tar.gz new file mode 100644 index 0000000..c6bcc98 Binary files /dev/null and b/deploy/snapshot/nt2102-snapshot.tar.gz differ diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index dcd02dd..adac1f8 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1,4 +1,4 @@ -# PROGRESS (status as of 2026-11-15) +# PROGRESS (status as of 2026-11-16) Replace lines in place when status changes; no history. "Verified" = checked in code/data. Branch: **`test-train-with-two-window-vm`** (from `main`). All work on the Proxmox VMs. The trainer checkout is @@ -6,6 +6,23 @@ Branch: **`test-train-with-two-window-vm`** (from `main`). All work on the Proxm This deploy also brought `a788fc8` live: anomaly-first `correlate.py` (`/api/crosshost` 200) and the projector-friendly UI (collapsible LLM card, Present toggle / `#present=1`, Parameters = [OURS] + τ only). +## 2026-11-16 CV demo: repository layer + recorded snapshot + container + k8s (branch `things-need-to-close-project`, uncommitted) + +User: project done; publish a read-only demo for employers on the k8s homelab. Details: `deploy/README.md`. +- **Repository refactor (verified, selftests pass):** `src/live/repository.py` = 3 ABCs (`HistoryRepository`, `CrosshostRepository`, + `SessionStore`) + `open_repositories()`; file implementations in `history.py` / `file_store.py` (same bytes on disk); `engine.py`, + `correlate.py`, `live_server.py` now persist only through them. `HistoryStore` kept as an alias. +- **Snapshot (verified):** `deploy/snapshot/nt2102-snapshot.tar.gz` (5.6 MB) built on the trainer 2026-11-16 from a scratch copy of the + builder: 11-02 23:10Z → 11-15 20:15Z (last real LLM `attack` = ws-etw-1 19:55Z + 3 windows), 4,658 windows, 63 red, 17 LLM attack, + redaction scan clean. `lab snapshot build` / `src/live/snapshot.py`. +- **Snapshot mode (verified locally):** `live_server.py --snapshot` (no torch import) + `playback.py` replays 11-15 15:10Z → 20:15Z; + UI banner + in-sample note. Image `deploy/docker/Dockerfile` 239 MB; 30-user load test: 0 errors, p95 ≤ 56 ms, 0.57 core, RSS 134 MiB. +- **k8s (`deploy/k8s/`, server dry-run OK on the homelab):** Deployment/Service/Ingress (`projects.datrollout.dev/nt2102/`, path-routed: slash redirect + StripPrefix, crowdsec, no rate limit). CI `.github/workflows/demo-image.yml` → `ghcr.io/uitprojects/nt2102-demo`. home-lab repo (uncommitted, optional): Argo app + `nt2102-demo`, `nt2102Demo.enabled`; its DNS `nt2102` record is not needed. +- **Committed `things-need-to-close-project` (2026-11-17).** Not done: push + merge to `main`; tag `v1.0.0` (CI builds + `:1.0.0`); make the GHCR package public; `kubectl apply -f deploy/argocd/nt2102-demo.yaml` + manual Argo sync (Application + kept in this repo, no home-lab change: user 2026-11-17); cluster load test. DNS needs nothing: `projects.datrollout.dev` already resolves. `master-nodes-2` NotReady (11-17). + ## 2026-11-15 False-positive review + `ws-etw-0` retrain → `exp17-ws0` (LIVE) Details: `docs/notes/fp-review-20261115.md`. Plan: `~/.claude/plans/i-need-to-check-wondrous-chipmunk.md`. diff --git a/selftest.sh b/selftest.sh index 3800140..d722e0e 100755 --- a/selftest.sh +++ b/selftest.sh @@ -12,7 +12,11 @@ steps=( "src/pipeline/score_window.py --selftest" "src/pipeline/alg1.py --selftest" "src/pipeline/alg2.py --selftest" + "src/live/repository.py --selftest" "src/live/history.py --selftest" + "src/live/file_store.py --selftest" + "src/live/snapshot.py --selftest" + "src/live/playback.py --selftest" "src/live/engine.py --selftest" "src/live/etwship.py --selftest" "src/pipeline/etw2nodlink.py --selftest" diff --git a/src/lab/cli.py b/src/lab/cli.py index 105c955..b058b94 100644 --- a/src/lab/cli.py +++ b/src/lab/cli.py @@ -20,6 +20,7 @@ lab hosts [VM ...] show or set which VMs are scored live: one VM or both lab compare two models on the same replayed windows: red counts per label lab current print the current model's paths + lab snapshot build --until T --out F recorded live history -> read-only demo snapshot (deploy/README.md) lab selftest prove the plumbing runs (fake Loki, tiny model) Typical session on the trainer: @@ -957,6 +958,17 @@ def build_parser(): "Print which model the live server loads (used by serve.sh and rejudge.sh).") c.add_argument("--field", choices=["run", "run_dir", "scaler", "experiment"], help="print just this path") + sn = _parser(sub, "snapshot", "live history -> read-only demo snapshot (.tar.gz)", + "Pack the live server's recorded windows (history.jsonl + each window's detail.json + session.json\n" + "+ cross-host findings) up to --until into one deterministic, redacted .tar.gz that\n" + "`live_server.py --snapshot` serves without a model (src/live/snapshot.py, deploy/README.md).", + "example:\n lab snapshot build --until 2026-11-15T20:15Z --out deploy/snapshot/nt2102-snapshot.tar.gz") + sn.add_argument("action", choices=["build"]) + sn.add_argument("--until", required=True, metavar="TIME", help="keep windows that end by this time (naive = UTC)") + sn.add_argument("--from", dest="start", metavar="TIME", help="first window (default: the first recorded)") + sn.add_argument("--out", required=True, metavar="TAR_GZ") + sn.add_argument("--sessions-dir", default=os.path.join(SRC, "live", "sessions")) + _parser(sub, "selftest", "prove the plumbing runs (fake Loki, tiny model)", "Fake Loki <- synthetic capture -> pull -> train (1 seed, 3 epochs) -> promote. Proves it RUNS,\n" "not that it detects attacks.") @@ -1010,6 +1022,9 @@ def main(argv=None): return 1 print(cur.get(a.field) or "" if a.field else json.dumps(cur, indent=1)) return 0 + if a.cmd == "snapshot": + return run([os.path.join(SRC, "live", "snapshot.py"), "build", "--sessions-dir", a.sessions_dir, + "--until", a.until, "--out", os.path.abspath(a.out), *(["--from", a.start] if a.start else [])]) if a.cmd == "selftest": return selftest() return 1 diff --git a/src/live/correlate.py b/src/live/correlate.py index 31dec5e..2bf2392 100644 --- a/src/live/correlate.py +++ b/src/live/correlate.py @@ -146,10 +146,14 @@ def _kept_subgraphs(wdir: str) -> list: class Correlator: - def __init__(self, ips: dict, sessions_dir: str, window_ms: int = 300_000, llm=None, take_budget=None, log=print): + def __init__(self, ips: dict, sessions_dir: str, window_ms: int = 300_000, llm=None, take_budget=None, log=print, + repo=None): + """sessions_dir: where the window folders are read from; repo: where findings are kept + (repository.CrosshostRepository, default sessions/crosshost.jsonl).""" + from file_store import FileCrosshostRepository self.ips, self.dir, self.w_ms = ips, sessions_dir, int(window_ms) self.llm, self.take_budget, self.log = llm, take_budget, log - self.path = os.path.join(sessions_dir, "crosshost.jsonl") + self.repo = repo or FileCrosshostRepository(sessions_dir) self.lock = threading.Lock() self.conns: dict[int, dict] = {} # window start -> {5-tuple: connection record} self.wins: dict[str, dict] = {h: {} for h in ips} # host -> {window start: state} @@ -163,23 +167,14 @@ def __init__(self, ips: dict, sessions_dir: str, window_ms: int = 300_000, llm=N # ---------------------------------------------------------------- persistence def _load(self): - if not os.path.exists(self.path): - return - with open(self.path, encoding="utf-8") as fh: - for line in fh: - try: - f = json.loads(line) - self.findings[f["id"]] = f - except (ValueError, KeyError): - pass # a line torn by a crash + self.findings.update(self.repo.load()) for f in self.findings.values(): # the window table is gone: a pending one cannot finish f.pop("dirty", None) if f["level"] == "pending": f["level"], f["note"] = "one-sided", "server restarted before the peer windows closed; peer side not read" def _save(self, f: dict): - with open(self.path, "a", encoding="utf-8") as fh: - fh.write(json.dumps(f) + "\n") + self.repo.append(f) def _emit(self, f: dict): for cb in list(self.listeners): diff --git a/src/live/engine.py b/src/live/engine.py index 644044a..8a5e26b 100644 --- a/src/live/engine.py +++ b/src/live/engine.py @@ -28,7 +28,6 @@ import base64 import bisect -import csv import hashlib import heapq import json @@ -54,12 +53,16 @@ import lab_filters # noqa: E402 (post-conversion lab-labels node drop; outside the converter hash, D9) import score_window as sw # noqa: E402 sys.path.insert(0, HERE) -from history import HistoryStore, _f, display_attrs, make_detail, write_json_atomic # noqa: E402,F401 +from history import (FileHistoryRepository, _f, display_attrs, make_detail, train_summary, # noqa: E402,F401 + write_json_atomic) +from file_store import FileSessionStore # noqa: E402 +from repository import HistoryRepository, SessionStore # noqa: E402,F401 +INDEX_HEADER = ["window", "start_ms", "end_ms", "start_utc", "status", "edges", "nodes", "flagged", "subgraphs", + "subgraphs_kept", "max_sg_score", "max_level", "alert", "edges_dropped_relation", "llm"] EDGE_HEADER = ["source-id", "source-type", "destination-id", "destination-type", "edge-type", "timestamp"] DEFAULT_CONVERTER = os.path.join(SRC, "pipeline", "etw2nodlink.py") MAX_FLAGGED_FOR_SUBGRAPHS = 300 # a broken model flags everything; keep the UI usable -BUDGET_LOCK = threading.Lock() # one llm_budget.json, shared by every host's engine and the correlator # --------------------------------------------------------------------------- converter reuse @@ -120,26 +123,6 @@ def utc_iso(ms: int) -> str: return datetime.fromtimestamp(ms / 1000, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") -TRAIN_KEYS = ("layers", "hidden", "lr", "beta", "epochs", "dropout", "contamination", "patience", "tnr_tolerance", - "seed", "val_split") - - -def train_summary(run_dir: str) -> dict: - """The training hyperparameters of a run, from its train_meta.json (train_gnn_models.py writes `args`). - Keys a run does not record are left out (older runs); a missing / unreadable file gives {}.""" - try: - meta = json.load(open(os.path.join(run_dir, "train_meta.json"))) - except (OSError, ValueError): - return {} - args = meta.get("args") or {} - out = {k: args[k] for k in TRAIN_KEYS if k in args} - if "relations" in meta: - out["n_relations"] = len(meta["relations"]) - if "label_source" in meta: - out["label_source"] = meta["label_source"] - return out - - # --------------------------------------------------------------------------- engine class Engine: def __init__(self, run_dir, scaler_path, sessions_dir, window_min=5, stride_min=None, lateness_s=20, @@ -147,10 +130,13 @@ def __init__(self, run_dir, scaler_path, sessions_dir, window_min=5, stride_min= n_seed=15, min_nodes=3, max_edges=5000, sg_min_level="Moderate", sg_min_score=None, sg_moderate_from=alg1.MODERATE_FROM, sg_require_types=alg1.REQUIRE_TYPES, llm_provider=None, llm_model=None, llm_base_url=None, llm_api_key=None, llm_client=None, llm_max_subgraphs=5, llm_reasoning_effort=None, - llm_debug=False, llm_max_per_day=10, today=None, host=None, history=None, flow_sink=None): + llm_debug=False, llm_max_per_day=10, today=None, host=None, history=None, flow_sink=None, + store=None): # two-host scoring (D12): one Engine per host. host names its session folders, history = the store they # share, flow_sink(host, event, ts_ms) gets every raw knet line for the cross-host correlator (correlate.py). # All three default off, and then nothing below behaves differently from one engine. + # Persistence goes through the repository ports (repository.py): store = this engine's session / window + # files, history = the window history. Both default to the sessions/ folder implementations. self.host, self.flow_sink = host, flow_sink self.conv, self.conv_sha = load_converter(converter_path) self.conv_check = "not checked (no --experiment)" @@ -189,12 +175,12 @@ def __init__(self, run_dir, scaler_path, sessions_dir, window_min=5, stride_min= # [OURS] daily LLM budget (user, 2026-11-02: token spend on a 24/7 server): at most llm_max_per_day red # windows investigated per local calendar day (each = 1 triage per kept subgraph up to max_subgraphs, 3 for # an attack subgraph, +9 with >= 2 attack subgraphs: <= 24 requests); - # 0 = unlimited. Kept in sessions/llm_budget.json so restarts and new sessions do not reset it. + # 0 = unlimited. Kept by the store (sessions/llm_budget.json) so restarts and new sessions do not reset it. self.llm_max_per_day = int(llm_max_per_day or 0) self.today = today or (lambda: datetime.now().astimezone().strftime("%Y-%m-%d")) - self.budget_path = os.path.join(sessions_dir, "llm_budget.json") + self.store: SessionStore = store or FileSessionStore(sessions_dir) # persistent window history (history.py): loaded / backfilled from disk here, appended on every change - self.history = history or HistoryStore(sessions_dir) + self.history: HistoryRepository = history or FileHistoryRepository(sessions_dir) self.lock = threading.RLock() self.listeners = [] # callables(event_dict), called from any thread @@ -209,15 +195,7 @@ def __init__(self, run_dir, scaler_path, sessions_dir, window_min=5, stride_min= # ---------------------------------------------------------------- session def _new_session(self, sid, payload): name = f"{sid}-{self.host}" if self.host else sid # two hosts could start a run in the same second - base = os.path.join(self.sessions_dir, re.sub(r"[^A-Za-z0-9._-]", "_", name)) - # a restart mid-run re-reads the run from Loki: a fresh folder .r2, .r3, ... instead of appending a - # second copy of the raw lines to the old one (that would corrupt replay / re-judge of the session) - sdir, n = base, 1 - while os.path.exists(os.path.join(sdir, "session.json")): - n += 1 - sdir = f"{base}.r{n}" - os.makedirs(os.path.join(sdir, "raw"), exist_ok=True) - os.makedirs(os.path.join(sdir, "windows"), exist_ok=True) + name = re.sub(r"[^A-Za-z0-9._-]", "_", name).lstrip(".") or "session" dmap = {str(k).lower(): str(v).lower() for k, v in (payload.get("dos_map") or {}).items()} dmap = dict(sorted(dmap.items(), key=lambda kv: -len(kv[0]))) # longest device prefix first stats = {k: Counter() for k in ("events", "edges", "excluded", "unresolved", "unmapped", "bad_lines", @@ -228,8 +206,18 @@ def _new_session(self, sid, payload): # run name goes into ids of processes started before the capture ("p_pre_"); the # shipper sends the capture folder name, as etw2nodlink.convert uses, so replayed ids match training g.new_run(str(payload.get("run") or sid)) + mode = payload.get("mode", "live") + meta = {"session": sid, "mode": mode, "host": payload.get("host", ""), + "dos_map": dmap, "exclude_pids": sorted(exclude), "run_dir": self.run_dir, + "scaler": self.scaler_path, "converter_sha256": self.conv_sha, "converter_check": self.conv_check, + "window_min": self.w_ms / 60000, "stride_min": self.s_ms / 60000, + "lateness_s": self.lateness_ms / 1000, "origin_ms": self.origin_ms, + "tau": self.run.tau, "score_range": self.run.score_range, "alg1": self.sg, "llm": self.llm_cfg, + "created_utc": utc_iso(int(time.time() * 1000))} + # store: a fresh .rN folder when a restart re-reads the run, session.json (+ restart_of), windows.csv + sdir = self.store.create_session(name, meta, INDEX_HEADER) self.session = { - "id": sid, "dir": sdir, "mode": payload.get("mode", "live"), "host": payload.get("host", ""), + "id": sid, "sdir": sdir, "dir": self.store.path(sdir), "mode": payload.get("mode", "live"), "host": payload.get("host", ""), "dmap": dmap, "exclude_pids": sorted(exclude), "graph": g, "sink": sink, "stats": stats, "offsets": {}, "heap": [], "released_wm": None, "first_t": None, "max_event_t": None, "clock_ms": None, "last_seen": None, "late_dropped": 0, "next_k": None, "edge_base": 0, @@ -237,20 +225,7 @@ def _new_session(self, sid, payload): "raw_fh": {}, "started": time.time(), "cmd": cmdlines.CmdlineIndex(), # Sysmon EID 1 records of this session (D14) } - meta = {"session": sid, "mode": self.session["mode"], "host": self.session["host"], - "dos_map": dmap, "exclude_pids": sorted(exclude), "run_dir": self.run_dir, - "scaler": self.scaler_path, "converter_sha256": self.conv_sha, "converter_check": self.conv_check, - "window_min": self.w_ms / 60000, "stride_min": self.s_ms / 60000, - "lateness_s": self.lateness_ms / 1000, "origin_ms": self.origin_ms, - "tau": self.run.tau, "score_range": self.run.score_range, "alg1": self.sg, "llm": self.llm_cfg, - "created_utc": utc_iso(int(time.time() * 1000)), - "restart_of": os.path.basename(base) if sdir != base else None} - json.dump(meta, open(os.path.join(sdir, "session.json"), "w"), indent=2) - with open(os.path.join(sdir, "windows.csv"), "w", newline="") as fh: - csv.writer(fh).writerow(["window", "start_ms", "end_ms", "start_utc", "status", "edges", "nodes", - "flagged", "subgraphs", "subgraphs_kept", "max_sg_score", "max_level", - "alert", "edges_dropped_relation", "llm"]) - print(f"[engine] new session {sid} ({self.session['mode']}) -> {sdir} dos_map={dmap} exclude={exclude}") + print(f"[engine] new session {sid} ({self.session['mode']}) -> {self.session['dir']} dos_map={dmap} exclude={exclude}") self._emit({"type": "session", "session": sid}) # ---------------------------------------------------------------- ingest @@ -297,7 +272,7 @@ def ingest(self, payload: dict) -> tuple[int, dict]: def _accept_line(self, S, stream, line, end): fh = S["raw_fh"].get(stream) if fh is None: - fh = S["raw_fh"][stream] = open(os.path.join(S["dir"], "raw", stream + ".json"), "a", encoding="utf-8") + fh = S["raw_fh"][stream] = self.store.open_raw(S["sdir"], stream) fh.write(line + "\n") S["lines_total"][stream] += 1 if stream == cmdlines.SYSMON_STREAM: # command lines only: never an event for the converter / graph (D14) @@ -435,8 +410,7 @@ def _score(self, sid, wid, w_rows, attrs): S = self.session if S is None or S["id"] != sid: return - wdir = os.path.join(S["dir"], "windows", wid) - os.makedirs(wdir, exist_ok=True) + sdir = S["sdir"] # [OURS] command lines (Sysmon EID 1) for the UI + LLM document, never for scoring (D14). Looked up # under the lock: ingest feeds S["cmd"] under the same lock. procs = nodes.loc[nodes["node_type"].str.upper() == "PROCESS", "node_uuid"] @@ -447,19 +421,18 @@ def _score(self, sid, wid, w_rows, attrs): for g in subgraphs: for n in g["nodes"]: n.update(cmd.get(n["id"], {})) - cmdlines.write_csv(os.path.join(wdir, "node_cmdlines.csv"), cmd_rows) - edges.to_csv(os.path.join(wdir, "edges.csv"), index=False) ntype = dict(zip(edges["source-id"], edges["source-type"])) ntype.update(zip(edges["destination-id"], edges["destination-type"])) - pd.DataFrame([(n, ntype.get(n, ""), a) for n, a in attrs.items()], - columns=["node", "node_type", "node_attr"]).to_csv( - os.path.join(wdir, "node_attrs.csv"), index=False) - feats.to_csv(os.path.join(wdir, "features_model.csv"), index_label="node_uuid", float_format="%.6f") - nodes.drop(columns=["cmdline", "decoded"]).sort_values("score", ascending=False).to_csv( - os.path.join(wdir, "scores.csv"), index=False) # scores.csv unchanged by D14 - json.dump({"window": wid, "truncated": truncated, "alg1": self.sg, "stats": sg_stats, - "subgraphs": subgraphs}, - open(os.path.join(wdir, "subgraphs.json"), "w"), indent=1) + self.store.write_window(sdir, wid, { + "node_cmdlines.csv": lambda p: cmdlines.write_csv(p, cmd_rows), + "edges.csv": edges, + "node_attrs.csv": pd.DataFrame([(n, ntype.get(n, ""), a) for n, a in attrs.items()], + columns=["node", "node_type", "node_attr"]), + "features_model.csv": (feats, {"index_label": "node_uuid", "float_format": "%.6f"}), + "scores.csv": nodes.drop(columns=["cmdline", "decoded"]).sort_values("score", ascending=False), + "subgraphs.json": {"window": wid, "truncated": truncated, "alg1": self.sg, "stats": sg_stats, + "subgraphs": subgraphs}, + }) # scores.csv unchanged by D14 rec = S["by_id"][wid] fl = nodes[nodes["flagged"]] @@ -471,52 +444,35 @@ def _score(self, sid, wid, w_rows, attrs): max_margin=_f(nodes["margin"].max()), cmdlines_matched=len(cmd_rows)) S["details"][wid] = make_detail(nodes, subgraphs, sg_stats, truncated, self.top_k) if rec["alert"] and self.llm: - self._queue_llm(S, rec, wdir, subgraphs, edges_norm) + self._queue_llm(S, rec, subgraphs, edges_norm) self._write_index(S, rec, info) - write_json_atomic(os.path.join(wdir, "detail.json"), {"window": rec, **S["details"][wid]}) + self.store.save_detail(sdir, wid, {"window": rec, **S["details"][wid]}) self._emit({"type": "window", "window": rec}) # ---------------------------------------------------------------- LLM triage + report (alg2.py) def _budget(self) -> dict: - try: - b = json.load(open(self.budget_path)) - except (OSError, ValueError): - b = {} - day = self.today() - return b if b.get("date") == day else {"date": day, "used": 0} + return self.store.budget(self.today()) def _take_budget(self) -> bool: """Count one investigation against today's budget; False = budget spent (nothing counted).""" - with BUDGET_LOCK: - b = self._budget() - if self.llm_max_per_day and b["used"] >= self.llm_max_per_day: - return False - b["used"] += 1 - os.makedirs(self.sessions_dir, exist_ok=True) - tmp = self.budget_path + ".tmp" - json.dump(b, open(tmp, "w")) - os.replace(tmp, self.budget_path) # atomic: a crash never leaves half a file - return True - - def _queue_llm(self, S, rec, wdir, subgraphs, edges_norm): + return self.store.take_budget(self.llm_max_per_day, self.today()) + + def _queue_llm(self, S, rec, subgraphs, edges_norm): if not self._take_budget(): rec["llm"] = {"status": "skipped", "error": f"daily LLM budget reached ({self.llm_max_per_day} red " f"windows per day, --llm-max-per-day); window stays red"} - with open(os.path.join(S["dir"], "llm_verdicts.csv"), "a", newline="") as fh: - w = csv.writer(fh) - if fh.tell() == 0: - w.writerow(["window", "verdict", "confidence", "tactics", "ms", "model"]) - w.writerow([rec["window"], "skipped", "", "", "", self.llm_cfg["model"]]) + self.store.append_verdict(S["sdir"], [rec["window"], "skipped", "", "", "", self.llm_cfg["model"]]) return rec["llm"] = {"status": "pending"} win = {"window": rec["window"], "start_utc": rec["start_utc"], "end_utc": utc_iso(rec["end_ms"])} - self.llm_jobs.put((S["id"], rec["window"], wdir, [g for g in subgraphs if g["kept"]], edges_norm, win)) + self.llm_jobs.put((S["id"], S["sdir"], rec["window"], [g for g in subgraphs if g["kept"]], edges_norm, win)) def _llm_loop(self): while True: - sid, wid, wdir, kept, edges_norm, win = self.llm_jobs.get() + sid, sdir, wid, kept, edges_norm, win = self.llm_jobs.get() try: try: + wdir = self.store.window_dir(sdir, wid) res = alg2.investigate(kept, edges_norm, win, self.llm, os.path.join(wdir, "llm"), max_subgraphs=self.llm_cfg["max_subgraphs"]) summary = alg2.ui_summary(res) @@ -529,32 +485,25 @@ def _llm_loop(self): with self.lock: # the verdict is kept even if the session rotated meanwhile: it goes to the window's own # folder (sessions//windows/) and to history.jsonl; only the UI memory is per session - sdir = os.path.dirname(os.path.dirname(wdir)) S = self.session - current = S is not None and S["id"] == sid and S["dir"] == sdir + current = S is not None and S["id"] == sid and S["sdir"] == sdir if current: rec = S["by_id"][wid] det = S["details"].setdefault(wid, {}) owner = S else: - row = self.history.get(os.path.basename(sdir), wid) or {"window": wid} - owner = {"dir": sdir, "id": sid, "mode": row.get("mode", "live")} + row = self.history.get(sdir, wid) or {"window": wid} + owner = {"sdir": sdir, "id": sid, "mode": row.get("mode", "live")} rec = {k: v for k, v in row.items() if k not in ("sdir", "session", "mode", "moderate_from")} - try: - det = json.load(open(os.path.join(wdir, "detail.json"))) - except (OSError, ValueError): - det = {} + det = self.store.load_detail(sdir, wid) or {} det.pop("window", None) rec["llm"] = state det["llm"] = summary - with open(os.path.join(sdir, "llm_verdicts.csv"), "a", newline="") as fh: - w = csv.writer(fh) - if fh.tell() == 0: - w.writerow(["window", "verdict", "confidence", "tactics", "ms", "model"]) - w.writerow([wid, state["status"], state.get("confidence"), " ".join(state.get("tactics", [])), - state.get("ms"), self.llm_cfg["model"]]) + self.store.append_verdict(sdir, [wid, state["status"], state.get("confidence"), + " ".join(state.get("tactics", [])), state.get("ms"), + self.llm_cfg["model"]]) self._persist(owner, rec) - write_json_atomic(os.path.join(wdir, "detail.json"), {"window": rec, **det}) + self.store.save_detail(sdir, wid, {"window": rec, **det}) if current: self._emit({"type": "window", "window": rec}) finally: @@ -562,16 +511,16 @@ def _llm_loop(self): def _persist(self, S, rec): """One line in sessions/history.jsonl for this window state (history.py).""" - self.history.append({"sdir": os.path.basename(S["dir"]), "session": S["id"], "mode": S.get("mode", ""), + self.history.append({"sdir": S["sdir"], "session": S["id"], "mode": S.get("mode", ""), "moderate_from": self.sg["moderate_from"], **rec}) def _write_index(self, S, rec, info): self._persist(S, rec) - with open(os.path.join(S["dir"], "windows.csv"), "a", newline="") as fh: - csv.writer(fh).writerow([rec["window"], rec["start_ms"], rec["end_ms"], rec["start_utc"], rec["status"], - rec["edges"], rec["nodes"], rec["flagged"], rec["subgraphs"], - rec["subgraphs_kept"], rec["max_sg_score"], rec["max_level"], rec["alert"], - info.get("edges_dropped_relation", ""), rec.get("llm", {}).get("status", "")]) + self.store.append_index(S["sdir"], [rec["window"], rec["start_ms"], rec["end_ms"], rec["start_utc"], + rec["status"], rec["edges"], rec["nodes"], rec["flagged"], + rec["subgraphs"], rec["subgraphs_kept"], rec["max_sg_score"], + rec["max_level"], rec["alert"], info.get("edges_dropped_relation", ""), + rec.get("llm", {}).get("status", "")]) # ---------------------------------------------------------------- read side def status(self) -> dict: @@ -835,7 +784,7 @@ def gated(system, messages): with eng.lock: S = eng.session rec = S["by_id"][w1] - eng._queue_llm(S, rec, os.path.join(sdir, "windows", w1), [fake], en) + eng._queue_llm(S, rec, [fake], en) assert rec["llm"]["status"] == "pending", rec time.sleep(0.2) assert eng.windows()[1]["llm"]["status"] == "pending", "verdict landed before the LLM answered" @@ -850,7 +799,7 @@ def gated(system, messages): # persistent history (history.py): every closed window is in sessions/history.jsonl, a fresh store (= a # server restart) returns them by range, and the detail on disk matches the in-memory one incl. the verdict - hs = HistoryStore(os.path.join(d, "sessions")) + hs = FileHistoryRepository(os.path.join(d, "sessions")) q = hs.query(base, base + 20 * 60_000, include_replay=True) # the selftest session is a replay assert [w["status"] for w in q["windows"]] == ["partial", "scored", "scored", "scored"], q assert all(w["sdir"] == "selftest" and w["moderate_from"] == alg1.MODERATE_FROM for w in q["windows"]) @@ -861,12 +810,12 @@ def gated(system, messages): # a verdict that lands after the session rotated is still persisted (window folder + history) w2 = wins[2]["window"] eng.ingest({"session": "selftest-b", "mode": "replay", "pid": 999, "batches": []}) - eng.llm_jobs.put(("selftest", w2, os.path.join(sdir, "windows", w2), [fake], en, + eng.llm_jobs.put(("selftest", "selftest", w2, [fake], en, {"window": w2, "start_utc": "", "end_utc": ""})) eng.drain() assert eng.history.get("selftest", w2)["llm"]["status"] == "false_positive" assert eng.history.get("selftest", w2)["status"] == "scored", "rotated-session verdict lost the window" - assert HistoryStore(os.path.join(d, "sessions")).detail("selftest", w2)["llm"]["verdict"] == "false_positive" + assert FileHistoryRepository(os.path.join(d, "sessions")).detail("selftest", w2)["llm"]["verdict"] == "false_positive" # 24/7 restart: a second engine (= the server restarted) on the same run gets a fresh .r2 folder; the # first folder's raw copy is not appended to @@ -895,7 +844,7 @@ def gated(system, messages): S2 = eng2.session for wid in ("w-a", "w-b"): S2["by_id"][wid] = {"window": wid, "start_utc": "", "end_ms": 0} - eng2._queue_llm(S2, S2["by_id"][wid], os.path.join(s2, "windows", wid), [fake], en) + eng2._queue_llm(S2, S2["by_id"][wid], [fake], en) eng2.drain() assert eng2.windows() == [] and S2["by_id"]["w-a"]["llm"]["status"] == "false_positive" assert S2["by_id"]["w-b"]["llm"]["status"] == "skipped", S2["by_id"]["w-b"] diff --git a/src/live/file_store.py b/src/live/file_store.py new file mode 100644 index 0000000..352dbe5 --- /dev/null +++ b/src/live/file_store.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +""" +file_store.py - the file implementations of SessionStore and CrosshostRepository (repository.py): the sessions/ +folder layout the live server has always written. Moved here from engine.py / correlate.py by the repository +refactor; the bytes on disk are unchanged. + + sessions//session.json run parameters, written once (+ restart_of for a .rN restart folder) + sessions//windows.csv one row per closed window + sessions//raw/.json verbatim raw lines (replay / re-judge) + sessions//windows//* edges, attrs, features, scores, subgraphs, detail.json, llm/ + sessions//llm_verdicts.csv one row per LLM verdict + sessions/llm_budget.json {"date", "used"}: red windows investigated today (all engines share it) + sessions/crosshost.jsonl cross-host findings, last line per id wins + +Usage (from the repo root) + uv run python src/live/file_store.py --selftest +""" +from __future__ import annotations + +import csv +import json +import os +import sys +import threading + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from history import write_json_atomic # noqa: E402 +from repository import CrosshostRepository, SessionStore, check_name # noqa: E402 + +# one llm_budget.json, shared by every host's engine and the correlator: a process-wide lock, not per store object +BUDGET_LOCK = threading.Lock() +VERDICT_HEADER = ["window", "verdict", "confidence", "tactics", "ms", "model"] + + +class FileSessionStore(SessionStore): + def __init__(self, sessions_dir: str): + self.root = sessions_dir + self.budget_path = os.path.join(sessions_dir, "llm_budget.json") + os.makedirs(sessions_dir, exist_ok=True) + + def path(self, sdir: str = "") -> str: + if sdir: + check_name(sdir) + return os.path.join(self.root, sdir) if sdir else self.root + + # ---------------------------------------------------------------- session + def create_session(self, name: str, meta: dict, index_header: list[str]) -> str: + check_name(name) + # a restart mid-run re-reads the run from Loki: a fresh folder .r2, .r3, ... instead of appending a + # second copy of the raw lines to the old one (that would corrupt replay / re-judge of the session) + sdir, n = name, 1 + while os.path.exists(os.path.join(self.root, sdir, "session.json")): + n += 1 + sdir = f"{name}.r{n}" + p = self.path(sdir) + os.makedirs(os.path.join(p, "raw"), exist_ok=True) + os.makedirs(os.path.join(p, "windows"), exist_ok=True) + json.dump({**meta, "restart_of": name if sdir != name else None}, + open(os.path.join(p, "session.json"), "w"), indent=2) + with open(os.path.join(p, "windows.csv"), "w", newline="") as fh: + csv.writer(fh).writerow(index_header) + return sdir + + def open_raw(self, sdir: str, stream: str): + check_name(stream) + return open(os.path.join(self.path(sdir), "raw", stream + ".json"), "a", encoding="utf-8") + + # ---------------------------------------------------------------- windows + def window_dir(self, sdir: str, wid: str) -> str: + check_name(wid) + d = os.path.join(self.path(sdir), "windows", wid) + os.makedirs(d, exist_ok=True) + return d + + def write_window(self, sdir: str, wid: str, files: dict) -> None: + import pandas as pd + d = self.window_dir(sdir, wid) + for name, v in files.items(): + check_name(name) + p = os.path.join(d, name) + if callable(v): + v(p) + elif isinstance(v, pd.DataFrame): + v.to_csv(p, index=False) + elif isinstance(v, tuple): # (DataFrame, to_csv kwargs) + v[0].to_csv(p, **v[1]) + else: + json.dump(v, open(p, "w"), indent=1) + + def append_index(self, sdir: str, row: list) -> None: + with open(os.path.join(self.path(sdir), "windows.csv"), "a", newline="") as fh: + csv.writer(fh).writerow(row) + + def append_verdict(self, sdir: str, row: list) -> None: + with open(os.path.join(self.path(sdir), "llm_verdicts.csv"), "a", newline="") as fh: + w = csv.writer(fh) + if fh.tell() == 0: + w.writerow(VERDICT_HEADER) + w.writerow(row) + + def save_detail(self, sdir: str, wid: str, detail: dict) -> None: + write_json_atomic(os.path.join(self.window_dir(sdir, wid), "detail.json"), detail) + + def load_detail(self, sdir: str, wid: str) -> dict | None: + check_name(wid) + try: + return json.load(open(os.path.join(self.path(sdir), "windows", wid, "detail.json"))) + except (OSError, ValueError): + return None + + # ---------------------------------------------------------------- LLM budget + def budget(self, today: str) -> dict: + try: + b = json.load(open(self.budget_path)) + except (OSError, ValueError): + b = {} + return b if b.get("date") == today else {"date": today, "used": 0} + + def take_budget(self, limit: int, today: str) -> bool: + with BUDGET_LOCK: + b = self.budget(today) + if limit and b["used"] >= limit: + return False + b["used"] += 1 + os.makedirs(self.root, exist_ok=True) + tmp = self.budget_path + ".tmp" + json.dump(b, open(tmp, "w")) + os.replace(tmp, self.budget_path) # atomic: a crash never leaves half a file + return True + + +class FileCrosshostRepository(CrosshostRepository): + def __init__(self, sessions_dir: str): + self.path = os.path.join(sessions_dir, "crosshost.jsonl") + os.makedirs(sessions_dir, exist_ok=True) + + def load(self) -> dict[str, dict]: + out = {} + if not os.path.exists(self.path): + return out + with open(self.path, encoding="utf-8") as fh: + for line in fh: + try: + f = json.loads(line) + out[f["id"]] = f + except (ValueError, KeyError): + pass # a line torn by a crash + return out + + def append(self, finding: dict) -> None: + with open(self.path, "a", encoding="utf-8") as fh: + fh.write(json.dumps(finding) + "\n") + + +# --------------------------------------------------------------------------- selftest +def selftest(): + """'It runs': restart folders, file layout, budget per day + limit, crosshost last-wins, name guard.""" + import tempfile + import pandas as pd + with tempfile.TemporaryDirectory() as d: + st = FileSessionStore(d) + hdr = ["window", "status"] + a = st.create_session("live-x", {"session": "live-x"}, hdr) + b = st.create_session("live-x", {"session": "live-x"}, hdr) + assert (a, b) == ("live-x", "live-x.r2"), (a, b) + assert json.load(open(os.path.join(d, b, "session.json")))["restart_of"] == "live-x" + assert json.load(open(os.path.join(d, a, "session.json")))["restart_of"] is None + with st.open_raw(a, "kproc") as fh: + fh.write("line\n") + st.write_window(a, "w1", {"edges.csv": pd.DataFrame({"x": [1]}), + "f.csv": (pd.DataFrame({"y": [0.5]}, index=["n"]), {"index_label": "node_uuid"}), + "sg.json": {"subgraphs": []}, + "c.csv": lambda p: open(p, "w").write("node\n")}) + assert open(os.path.join(d, a, "windows", "w1", "f.csv")).read().startswith("node_uuid,y") + st.append_index(a, ["w1", "scored"]) + assert open(os.path.join(d, a, "windows.csv")).read().splitlines() == ["window,status", "w1,scored"] + st.append_verdict(a, ["w1", "attack", 0.9, "TA0002", 10, "m"]) + st.append_verdict(a, ["w2", "skipped", "", "", "", "m"]) + assert len(open(os.path.join(d, a, "llm_verdicts.csv")).read().splitlines()) == 3 + st.save_detail(a, "w1", {"top": {}}) + assert st.load_detail(a, "w1") == {"top": {}} and st.load_detail(a, "w9") is None + assert st.take_budget(2, "d1") and st.take_budget(2, "d1") and not st.take_budget(2, "d1") + assert st.budget("d1")["used"] == 2 and st.budget("d2")["used"] == 0 and st.take_budget(2, "d2") + assert st.take_budget(0, "d2") and st.budget("d2")["used"] == 2, "limit 0 = no limit" + for bad in ("../x", "a/b"): + try: + st.window_dir(a, bad) + raise AssertionError(f"accepted {bad}") + except ValueError: + pass + cr = FileCrosshostRepository(d) + cr.append({"id": "f1", "level": "pending"}) + cr.append({"id": "f1", "level": "corroborated"}) + with open(cr.path, "a") as fh: + fh.write('{"id": "torn') + assert cr.load() == {"f1": {"id": "f1", "level": "corroborated"}} + print("[file_store] selftest OK (restart folders, window files, index/verdicts, detail, budget, crosshost, names)") + + +if __name__ == "__main__": + if "--selftest" in sys.argv: + selftest() + else: + print(__doc__) diff --git a/src/live/history.py b/src/live/history.py index c097434..dc4670e 100644 --- a/src/live/history.py +++ b/src/live/history.py @@ -30,18 +30,17 @@ import json import math import os -import re import sys -import threading HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(os.path.dirname(HERE), "pipeline")) import alg2 # noqa: E402 (display_attr: NET ints -> ip:port for the UI) +sys.path.insert(0, HERE) +from repository import (META_KEYS, SAFE_NAME, STATUS_RANK, HistoryRepository, check_name, # noqa: E402,F401 + restart_n as _restart_n) + HISTORY_FILE = "history.jsonl" -SAFE_NAME = re.compile(r"^[A-Za-z0-9_-][A-Za-z0-9._-]*$") # session folder / window id: no '/', no leading '.' -STATUS_RANK = {"scored": 4, "error": 3, "empty": 2, "partial": 1} -META_KEYS = ("sdir", "session", "mode", "moderate_from") # --------------------------------------------------------------------------- detail (shared with engine.py) @@ -90,6 +89,26 @@ def write_json_atomic(path: str, obj) -> None: os.replace(tmp, path) # a reader never sees half a file +TRAIN_KEYS = ("layers", "hidden", "lr", "beta", "epochs", "dropout", "contamination", "patience", "tnr_tolerance", + "seed", "val_split") + + +def train_summary(run_dir: str) -> dict: + """The training hyperparameters of a run, from its train_meta.json (train_gnn_models.py writes `args`). + Keys a run does not record are left out (older runs); a missing / unreadable file gives {}.""" + try: + meta = json.load(open(os.path.join(run_dir, "train_meta.json"))) + except (OSError, ValueError): + return {} + args = meta.get("args") or {} + out = {k: args[k] for k in TRAIN_KEYS if k in args} + if "relations" in meta: + out["n_relations"] = len(meta["relations"]) + if "label_source" in meta: + out["label_source"] = meta["label_source"] + return out + + def parse_time_ms(v: str | int | None) -> int | None: """'1793704800000' (epoch ms) or ISO-8601 ('2026-11-03T17:30:00Z', '2026-11-03T17:30+07:00'); naive = UTC.""" if v is None or v == "": @@ -104,18 +123,15 @@ def parse_time_ms(v: str | int | None) -> int | None: return int(d.timestamp() * 1000) -def _restart_n(sdir: str) -> int: - m = re.search(r"\.r(\d+)$", sdir) - return int(m.group(1)) if m else 1 - - # --------------------------------------------------------------------------- store -class HistoryStore: +class FileHistoryRepository(HistoryRepository): + """HistoryRepository on the sessions/ folder: history.jsonl (append-only) + per-window detail.json. + get / query / detail merge come from the base class (repository.py).""" + def __init__(self, sessions_dir: str): + super().__init__() self.dir = sessions_dir self.path = os.path.join(sessions_dir, HISTORY_FILE) - self.lock = threading.Lock() - self.rows: dict[tuple[str, str], dict] = {} # (sdir, window id) -> latest row self.bad_lines = 0 self.backfilled = 0 os.makedirs(sessions_dir, exist_ok=True) @@ -194,56 +210,18 @@ def _backfill(self): print(f"[history] backfilled {len(rows)} windows from {len({r['sdir'] for r in rows})} session folder(s) " f"-> {self.path}") - def get(self, sdir: str, wid: str) -> dict | None: - with self.lock: - r = self.rows.get((sdir, wid)) - return dict(r) if r else None - - def query(self, from_ms: int, to_ms: int, alert_only: bool = False, include_replay: bool = False, - limit: int = 2000, host: str | None = None) -> dict: - """Live sessions (mode 'loki' from Loki, 'live' from the HTTP shipper) by default; replays re-use past - timestamps, so they are left out unless include_replay. host = only that host's windows; rows written - before two-host scoring have no host and match no host filter.""" - with self.lock: - cand = [r for r in self.rows.values() - if isinstance(r.get("start_ms"), int) and r["start_ms"] < to_ms and r.get("end_ms", 0) > from_ms - and (include_replay or r.get("mode") != "replay") - and (host is None or r.get("host") == host)] - best: dict[tuple, tuple] = {} - dups = 0 - for r in cand: - k = (r.get("host") or "", r["start_ms"]) # two hosts share the window grid - rank = (STATUS_RANK.get(r.get("status"), 0), _restart_n(r["sdir"]), r["sdir"]) - if k in best: - dups += 1 - if rank <= best[k][0]: - continue - best[k] = (rank, r) - rows = [r for _, r in sorted(best.values(), key=lambda x: (x[1]["start_ms"], x[1].get("host") or ""))] - if alert_only: - rows = [r for r in rows if r.get("alert")] - return {"from_ms": from_ms, "to_ms": to_ms, "total": len(rows), "duplicates_hidden": dups, - "truncated": len(rows) > limit, "windows": rows[-limit:] if limit else rows} - # ---------------------------------------------------------------- detail def window_dir(self, sdir: str, wid: str) -> str: """Path of one window folder; refuses anything that is not a plain folder name (path traversal).""" - if not (SAFE_NAME.match(sdir) and SAFE_NAME.match(wid)): - raise ValueError("bad session or window name") + check_name(sdir, wid) return os.path.join(self.dir, sdir, "windows", wid) - def detail(self, sdir: str, wid: str) -> dict | None: + def _read_detail(self, sdir: str, wid: str) -> dict | None: wdir = self.window_dir(sdir, wid) - row = self.get(sdir, wid) try: - d = json.load(open(os.path.join(wdir, "detail.json"))) + return json.load(open(os.path.join(wdir, "detail.json"))) except (OSError, ValueError): - d = self._rebuild(wdir) - if d is None and row is None: - return None - d = d or {} - win = {k: v for k, v in (row or d.get("window") or {}).items() if k not in META_KEYS} - return {**d, "window": win, "history": {k: (row or {}).get(k) for k in META_KEYS}} + return self._rebuild(wdir) @staticmethod def _rebuild(wdir: str) -> dict | None: @@ -263,6 +241,9 @@ def _rebuild(wdir: str) -> dict | None: return make_detail(nodes, sg.get("subgraphs", []), sg.get("stats", {}), sg.get("truncated", False)) +HistoryStore = FileHistoryRepository # the name every caller used before the repository refactor + + # --------------------------------------------------------------------------- selftest def selftest(): """'It runs' + invariants: append/reload, last line wins, torn line skipped, range overlap, restart dedup, diff --git a/src/live/live_server.py b/src/live/live_server.py index 1605817..fdc61c5 100644 --- a/src/live/live_server.py +++ b/src/live/live_server.py @@ -14,6 +14,11 @@ --loki-url) a successful Loki poll within 120 s. For monitoring / curl checks. GET / the UI (static/index.html) +Snapshot mode (public demo, deploy/README.md): --snapshot --data-dir serves a recorded, +read-only snapshot (snapshot.py) through the same API: no model, no torch, no Loki, no LLM; POST /ingest is 403. +playback.py replays the recorded windows of --playback-from/--playback-to over SSE, one 5-min window every +--playback-interval-s seconds, in a loop. Every score and LLM verdict shown is the one recorded at the time. + Usage (from the repo root): ./serve.sh [live|local] [flags] wraps uv run python src/live/live_server.py --bind 127.0.0.1 [--loki-url http://127.0.0.1:3100] uv run python src/live/live_server.py --selftest (/healthz + watchdog logic; no model, no Loki) @@ -45,9 +50,11 @@ HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) sys.path.insert(0, os.path.dirname(HERE)) # src/: the `lab` package (current-model pointer) -from engine import Engine # noqa: E402 +sys.path.insert(0, os.path.join(os.path.dirname(HERE), "pipeline")) +# no `engine` import here: it pulls in torch, which snapshot mode must not need (main() imports it for live mode) from history import HistoryStore, parse_time_ms # noqa: E402 -import alg1 # noqa: E402 (engine put src/pipeline on sys.path; default level scale) +from repository import open_repositories # noqa: E402 +import alg1 # noqa: E402 (default level scale) import alg2 # noqa: E402 (provider list + reasoning efforts) @@ -106,11 +113,14 @@ def git(*args): return {"sha": "unknown", "branch": "unknown", "dirty": None} -def create_app(engine: Engine, token: str | None, source=None, members=None, correlator=None, trained=None, - server=None) -> FastAPI: - """members = [{"host", "engine", "source"}], one per scored VM; without it, one member from engine + source. - server = server-wide facts for the UI Parameters panel (code version, start time, flags not per engine).""" - app = FastAPI(title="OCR-APT live") +def create_app(engine, token: str | None, source=None, members=None, correlator=None, trained=None, + server=None, snapshot=None) -> FastAPI: + """engine: an engine.Engine, or playback.SnapshotMember in snapshot mode (same read interface). + members = [{"host", "engine", "source"}], one per scored VM; without it, one member from engine + source. + server = server-wide facts for the UI Parameters panel (code version, start time, flags not per engine). + snapshot = what a recorded snapshot holds (snapshot mode only): the UI shows it, /ingest is refused and the + History default range ends at the snapshot's end instead of now.""" + app = FastAPI(title="OCR-APT live" if snapshot is None else "OCR-APT demo (recorded snapshot)") clients: set[tuple] = set() # (event loop, asyncio.Queue) per open SSE connection members = members or [{"host": None, "engine": engine, "source": source}] @@ -144,10 +154,13 @@ def full_status(host=None): if m["source"] is not None: st["source"] = m["source"].status() return {**st, "selected_host": m["host"], "hosts": [summary(x) for x in members], "trained_for": trained or [], - "correlation": correlator.status() if correlator is not None else None, "server": server or {}} + "correlation": correlator.status() if correlator is not None else None, "server": server or {}, + "snapshot": snapshot} @app.post("/ingest") async def ingest(request: Request): + if snapshot is not None: + raise HTTPException(403, "read-only recorded snapshot: nothing is ingested") if token and request.headers.get("x-lab-token") != token: raise HTTPException(401, "bad token") body = await request.body() @@ -191,7 +204,7 @@ async def history(start: str | None = Query(None, alias="from"), end: str | None host: str | None = None): """Windows overlapping [from, to); from/to = ISO-8601 (naive = UTC) or epoch ms; default the last 24 h.""" try: - to_ms = parse_time_ms(end) or int(time.time() * 1000) + to_ms = parse_time_ms(end) or (snapshot or {}).get("to_ms") or int(time.time() * 1000) from_ms = parse_time_ms(start) or to_ms - 24 * 3600 * 1000 except ValueError as e: raise HTTPException(400, f"bad time: {e}") @@ -320,7 +333,17 @@ def main(): "Count kept in /llm_budget.json, so restarts do not reset it") ap.add_argument("--watchdog-s", type=float, default=300, help="exit (for systemd to restart) when a worker thread died or the Loki poll hangs this long; 0 = off") + g = ap.add_argument_group("snapshot mode (public demo; snapshot.py, playback.py): no model, no Loki, read-only") + g.add_argument("--snapshot", metavar="TAR_GZ", help="serve this recorded snapshot instead of scoring live data") + g.add_argument("--data-dir", metavar="DIR", help="where the snapshot is unpacked (e.g. a k8s emptyDir)") + g.add_argument("--playback-from", metavar="TIME", help="ISO or epoch ms; default: 6 h before the snapshot end") + g.add_argument("--playback-to", metavar="TIME", help="default: the snapshot end") + g.add_argument("--playback-interval-s", type=float, default=3.0, help="seconds per recorded 5-min window") + g.add_argument("--playback-pause-s", type=float, default=30.0, help="pause at the end of a loop") a = ap.parse_args() + if a.snapshot: + return snapshot_main(a) + from engine import Engine from lab import current, live_models, trained_hosts cur = current() explicit = a.run_dir is not None @@ -348,17 +371,18 @@ def main(): print(f"[live] WARNING window {a.window_min} min: the models were trained on 5-min windows " f"(see experiment.json windowing.window_min); features will be off-distribution") import correlate - from history import HistoryStore as Store + # persistence: the sessions/ folder implementations of the repository ports (repository.py) + repos = open_repositories("files", a.sessions_dir) hosts_map = correlate.load_hosts(a.hosts_file or correlate.HOSTS_FILE) names = [p["host"] for p in plans] cor = None if len(plans) > 1: if all(h in hosts_map for h in names): - cor = correlate.Correlator({h: hosts_map[h] for h in names}, a.sessions_dir, int(a.window_min * 60_000)) + cor = correlate.Correlator({h: hosts_map[h] for h in names}, a.sessions_dir, int(a.window_min * 60_000), + repo=repos.crosshost) print(f"[live] correlation on: {cor.ips} (red windows followed to the other VM)") else: print(f"[live] correlation OFF: {names} not all in the hosts file ({hosts_map})") - shared = Store(a.sessions_dir) members = [] for p in plans: engine = Engine(p["run_dir"], p["scaler"], a.sessions_dir, a.window_min, a.stride_min, a.lateness_s, @@ -369,8 +393,8 @@ def main(): llm_provider=a.llm_provider, llm_model=a.llm_model, llm_base_url=a.llm_base_url, llm_api_key=a.llm_api_key, llm_max_subgraphs=a.llm_max_subgraphs, llm_reasoning_effort=a.llm_reasoning_effort, - llm_debug=a.llm_debug, llm_max_per_day=a.llm_max_per_day, host=p["host"], history=shared, - flow_sink=cor.add_line if cor else None) + llm_debug=a.llm_debug, llm_max_per_day=a.llm_max_per_day, host=p["host"], history=repos.history, + flow_sink=cor.add_line if cor else None, store=repos.sessions) print(f"[live] {p['host'] or 'any host'}: model {engine.run_dir} tau={engine.run.tau}") print(f"[live] converter sha256 {engine.conv_sha} ({engine.conv_check})") if cor: @@ -409,6 +433,37 @@ def forward(ev, h=p["host"], e=engine): log_level="warning") +def snapshot_main(a): + """--snapshot: unpack + verify the archive, then serve it read-only with playback (no torch import).""" + import playback + repos = open_repositories("snapshot", a.snapshot, a.data_dir) + man = repos.manifest + try: + play_to = parse_time_ms(a.playback_to) or man["to_ms"] + play_from = parse_time_ms(a.playback_from) or play_to - 6 * 3600 * 1000 + except ValueError as e: + raise SystemExit(f"--playback-from/--playback-to: {e}") + members, player, cor, info = playback.build_members(repos, play_from, play_to, a.playback_interval_s, + a.playback_pause_s) + if not player.slots: + raise SystemExit("no recorded window in the playback range") + print(f"[demo] snapshot {man['counts']} {len(member_hosts := [m.host for m in members])} host(s) {member_hosts}; " + f"playback {len(player.slots)} slots every {a.playback_interval_s:g}s") + player.start() + # the models of the replayed sessions (History can show older ones; each row's session.json names its model) + mh = man.get("model_hosts") or {} + runs = sorted({repos.sessions.session_meta(r["sdir"]).get("run_dir") for _, rows in player.slots for r in rows} - {None}) + trained = trained_text([(run, mh.get(run)) for run in runs]) + # the container has no .git: CI passes the commit as NT2102_CODE_SHA (deploy/docker/Dockerfile) + sha = os.environ.get("NT2102_CODE_SHA") or code_version()["sha"] + server = {"code": {"sha": sha[:12], "branch": "snapshot", "dirty": False}, + "started_ms": int(time.time() * 1000), "snapshot": True} + app = create_app(members[0], None, None, [{"host": m.host, "engine": m, "source": None} for m in members], cor, + trained, server, info) + print(f"[demo] UI: http://{a.bind}:{a.port}/ health: /healthz") + uvicorn.run(app, host=a.bind, port=a.port, log_level="warning") + + def plan_hosts(loki_hosts, default_host, pointer_models, single, assigned) -> list | str: """Which engines to start. -> [{"host", "run", "run_dir", "scaler", "experiment"}], or an error string. @@ -565,11 +620,72 @@ def get(self, fid): assert "repeated" in plan_hosts(["a", "a"], None, None, one, {}) assert "no model" in plan_hosts(["z"], None, ptr, one, {"a": "x"}) tmp.cleanup() + selftest_snapshot() print("[SELFTEST OK] /healthz 200/503, watchdog exits on a dead thread or hung poll, not on Loki being down, " "/api/history range (ISO / ms) + alerts-only + 400/404 + traversal refused, ?host= per VM, trained-for text, cross-host findings, " "which engines start") +def selftest_snapshot(): + """Snapshot mode end to end through HTTP: a recorded two-host snapshot, playback, read-only, no torch.""" + import subprocess + import tempfile + from fastapi.testclient import TestClient + from file_store import FileSessionStore + import playback + import snapshot + base, m5 = 1_794_700_000_000, 300_000 + with tempfile.TemporaryDirectory() as d: + sess = os.path.join(d, "sessions") + h, st = HistoryStore(sess), FileSessionStore(sess) + for host in ("ws-etw-0", "ws-etw-1"): + sdir = f"live-a-{host}" + os.makedirs(os.path.join(sess, sdir)) + json.dump({"run_dir": f"/r/model-{host}", "host": host, "alg1": {"moderate_from": 4.5}}, + open(os.path.join(sess, sdir, "session.json"), "w")) + for k in range(4): + red = host == "ws-etw-1" and k == 2 + row = {"sdir": sdir, "session": "live-a", "mode": "loki", "moderate_from": 4.5, "window": f"w{k}", + "host": host, "start_ms": base + k * m5, "end_ms": base + (k + 1) * m5, "status": "scored", + "alert": red, "max_sg_score": 19.86 if red else 1.0, + **({"llm": {"status": "attack", "confidence": 0.95}} if red else {})} + h.append(row) + st.save_detail(sdir, f"w{k}", {"window": row, "top": {}, + **({"llm": {"verdict": "attack", "subgraphs": []}} if red else {})}) + arc = os.path.join(d, "s.tar.gz") + snapshot.build(sess, base + 4 * m5, arc, log=lambda *_: None) + repos = open_repositories("snapshot", arc, os.path.join(d, "data")) + members, player, cor, info = playback.build_members(repos, base + m5, base + 4 * m5, 0, 0) + player.sleep = lambda s: None + app = create_app(members[0], None, None, [{"host": m.host, "engine": m, "source": None} for m in members], + cor, trained_text([("model-ws-etw-1", ["ws-etw-1"])]), {}, info) + c = TestClient(app) + s = c.get("/api/status").json() + assert s["snapshot"]["to_ms"] == base + 4 * m5 and [x["host"] for x in s["hosts"]] == ["ws-etw-0", "ws-etw-1"] + assert c.post("/ingest", content=b"{}").status_code == 403, "a snapshot must refuse ingest" + assert c.get("/healthz").status_code == 200 + q = c.get("/api/history").json() # default range ends at the snapshot end, not now + assert q["total"] == 8 and q["to_ms"] == base + 4 * m5, q + assert c.get("/api/history", params={"alert": True}).json()["windows"][0]["max_sg_score"] == 19.86 + det = c.get("/api/history/live-a-ws-etw-1/w2").json() + assert det["llm"]["verdict"] == "attack" and det["history"]["sdir"] == "live-a-ws-etw-1", det + assert c.get("/api/history/..%2F..%2Fetc/w2").status_code in (400, 404) + assert c.get("/api/windows", params={"host": "ws-etw-1"}).json() == [], "nothing played yet" + player.run_once() # playback range starts at w1: w1, w2, w3 + ws = c.get("/api/windows", params={"host": "ws-etw-1"}).json() + assert [w["window"] for w in ws] == ["w1", "w2", "w3"] and ws[1]["alert"], ws + assert c.get("/api/windows/w2", params={"host": "ws-etw-1"}).json()["llm"]["verdict"] == "attack" + assert c.get("/api/status", params={"host": "ws-etw-1"}).json()["session"]["played_llm_attack"] == 1 + # snapshot mode must run without torch: importing the snapshot path pulls in none of it + code = ("import sys; sys.path.insert(0, 'src/live'); import live_server, playback, snapshot; " + "assert 'torch' not in sys.modules, 'torch imported'") + repo = os.path.dirname(os.path.dirname(HERE)) + r = subprocess.run([sys.executable, "-c", code], cwd=repo, capture_output=True, text=True) + assert r.returncode == 0, r.stderr + print("[live_server] snapshot mode OK (status + snapshot info, ingest 403, history default = snapshot end, detail " + "with LLM verdict, traversal refused, playback windows over HTTP, no torch import)") + + if __name__ == "__main__": if "--selftest" in sys.argv: selftest() diff --git a/src/live/playback.py b/src/live/playback.py new file mode 100644 index 0000000..52b8dc4 --- /dev/null +++ b/src/live/playback.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +""" +playback.py - snapshot mode of the live server: recorded windows replayed over the same HTTP/SSE API, no model, +no torch. [OURS] demo engineering (deploy/README.md); nothing is scored here. + + SnapshotMember stands in for engine.Engine behind live_server.create_app (same duck-typed interface the + live_server selftest stubs already use: listeners, status, windows, window_detail, health, + history, session). One per recorded host. + Player one thread: walks the recorded windows of a playback range in time order, one 5-min slot every + interval_s seconds, and hands each host its windows (final recorded state: score, level, LLM + verdict). At the end it pauses, then starts a new loop (a new session id, so the UI clears). + SnapshotCorrelator read-only view of the recorded cross-host findings (correlate.Correlator's read side). + +Usage (from the repo root) + uv run python src/live/playback.py --selftest +""" +from __future__ import annotations + +import os +import sys +import threading +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from repository import META_KEYS, Repositories # noqa: E402 + +CORRELATION_LEVELS = ("pending", "one-sided", "corroborated") + + +def _empty_session_counters() -> dict: + """The live-session fields the UI reads; zero / empty, because nothing is ingested in a snapshot.""" + return {"last_seen_s_ago": 0.0, "event_lag_s": None, "clock_skew_s": None, "lines_per_s": 0, "lines_total": {}, + "heap": 0, "late_dropped": 0, "bad_lines": 0, "bad_events": {}, "events": {}, "edges": {}, "excluded": {}, + "unresolved": {}, "unmapped": 0, "exclude_pids": [], "dos_map": {}, "scoring_queue": 0} + + +class SnapshotMember: + read_only = True + + def __init__(self, host: str | None, repos: Repositories, first_sdir: str | None, snapshot_info: dict): + self.host, self.repos, self.history = host, repos, repos.history + self.info = snapshot_info + self.listeners = [] + self.lock = threading.Lock() + self.loop = 0 + self.played: list[dict] = [] # rows played in this loop, in order + self.by_id: dict[str, dict] = {} + self.clock_ms = None + self.next_ms = None + self.sdir = first_sdir # the session whose parameters the status shows + self.session = None + self._new_session() + + # ---------------------------------------------------------------- driven by the Player + def _new_session(self): + self.loop += 1 + # dir "" never equals a history sdir, so /api/history/{sdir}/{wid} always reads the snapshot files + self.session = {"id": f"playback-{self.host or 'host'}-{self.loop}", "dir": "", "mode": "snapshot"} + + def restart(self): + with self.lock: + self.played, self.by_id, self.clock_ms = [], {}, None + self._new_session() + self._emit({"type": "session", "session": self.session["id"]}) + + def play(self, row: dict, next_ms: int | None): + rec = {k: v for k, v in row.items() if k not in META_KEYS} + rec["_sdir"] = row["sdir"] + with self.lock: + self.played.append(rec) + self.by_id[str(rec["window"])] = rec + self.clock_ms = rec["end_ms"] + self.next_ms = next_ms + self.sdir = row["sdir"] + self._emit({"type": "window", "window": self._public(rec)}) + + def tick(self, clock_ms: int, next_ms: int | None): + with self.lock: + self.clock_ms, self.next_ms = clock_ms, next_ms + + # ---------------------------------------------------------------- the engine read interface + @staticmethod + def _public(rec: dict) -> dict: + return {k: v for k, v in rec.items() if k != "_sdir"} + + def windows(self) -> list: + with self.lock: + return [self._public(r) for r in self.played] + + def window_detail(self, wid: str) -> dict | None: + with self.lock: + rec = self.by_id.get(wid) + if rec is None: + return None + d = self.history.detail(rec["_sdir"], wid) + return None if d is None else {**d, "window": self._public(rec)} + + def health(self): + return True, "ok" + + def status(self) -> dict: + with self.lock: + sdir, clock, nxt, n = self.sdir, self.clock_ms, self.next_ms, len(self.played) + red = sum(1 for r in self.played if r.get("alert")) + attack = sum(1 for r in self.played if r.get("alert") and (r.get("llm") or {}).get("status") == "attack") + sid = self.session["id"] + meta = self.repos.sessions.session_meta(sdir) if sdir else {} + run = meta.get("run_dir") or "unknown" + return {"host": self.host, + "model": {"run_dir": run, "tau": meta.get("tau") or {}, "scaler": meta.get("scaler"), + "converter_sha256": meta.get("converter_sha256"), + "converter_check": meta.get("converter_check") or "recorded", + "train": (self.repos.manifest or {}).get("models", {}).get(run, {}), + "score_range": meta.get("score_range") or {}}, + "params": {"window_min": meta.get("window_min", 5), "stride_min": meta.get("stride_min", 5), + "lateness_s": meta.get("lateness_s"), "origin_ms": meta.get("origin_ms", 0), + "alg1": meta.get("alg1") or {}, "llm": {k: v for k, v in (meta.get("llm") or {}).items() + if k in ("provider", "model")}}, + "server_ms": int(time.time() * 1000), + "session": {"id": sid, "mode": "snapshot", "host": self.host or "", "dir": sdir or "", + **_empty_session_counters(), "clock_ms": clock, "watermark_ms": clock, + "max_event_ms": clock, + "open_window": {"start_ms": nxt, "end_ms": nxt + 300_000} if nxt else None, + "windows": n, "played_red": red, "played_llm_attack": attack, "loop": self.loop}, + "snapshot": self.info} + + def ingest(self, payload): + return 403, {"error": "read-only snapshot: nothing is ingested"} + + def _emit(self, ev): + for cb in list(self.listeners): + try: + cb(ev) + except Exception: + pass + + +class Player: + """Walks the recorded windows in [from_ms, to_ms) slot by slot (all hosts of a slot together).""" + + def __init__(self, members: list[SnapshotMember], repos: Repositories, from_ms: int, to_ms: int, + interval_s: float = 3.0, pause_s: float = 30.0, sleep=time.sleep): + self.members = {m.host: m for m in members} + self.interval_s, self.pause_s, self.sleep = interval_s, pause_s, sleep + rows = repos.history.query(from_ms, to_ms, limit=0)["windows"] + rows = [r for r in rows if r.get("host") in self.members or (None in self.members and not r.get("host"))] + self.slots: list[tuple[int, list[dict]]] = [] + for r in rows: + if self.slots and self.slots[-1][0] == r["start_ms"]: + self.slots[-1][1].append(r) + else: + self.slots.append((r["start_ms"], [r])) + self.thread = None + self.stop = threading.Event() + + def run_once(self): + """One loop: every slot, then the pause. The members keep their windows until the next loop's restart.""" + for i, (start, rows) in enumerate(self.slots): + if self.stop.is_set(): + return + nxt = self.slots[i + 1][0] if i + 1 < len(self.slots) else None + for r in rows: + self.members.get(r.get("host") or None, next(iter(self.members.values()))).play(r, nxt) + for m in self.members.values(): # a host with no window in this slot still moves on + if all((r.get("host") or None) != m.host for r in rows): + m.tick(start + 300_000, nxt) + self.sleep(self.interval_s) + self.sleep(self.pause_s) + + def _loop(self): + while not self.stop.is_set(): + self.run_once() + for m in self.members.values(): + m.restart() + + def start(self) -> "Player": + self.thread = threading.Thread(target=self._loop, daemon=True, name="playback") + self.thread.start() + return self + + +class SnapshotCorrelator: + """correlate.Correlator's read side over recorded findings; never opens a new one.""" + + def __init__(self, repo, hosts: list[str]): + self.findings = repo.load() + self.hosts = hosts + self.listeners = [] + + def list(self, limit: int = 100) -> list: + return sorted(self.findings.values(), key=lambda f: f.get("start_ms", 0), reverse=True)[:limit] + + def get(self, fid: str) -> dict | None: + return self.findings.get(fid) + + def status(self) -> dict: + return {"hosts": {h: "" for h in self.hosts}, + "findings": {lv: sum(f.get("level") == lv for f in self.findings.values()) for lv in CORRELATION_LEVELS}} + + +def build_members(repos: Repositories, play_from: int, play_to: int, interval_s: float, pause_s: float, + note: str | None = None): + """-> (members list for create_app, Player (not started), SnapshotCorrelator or None, snapshot info).""" + man = repos.manifest or {} + hosts = man.get("hosts") or [None] + info = {"from_ms": man.get("from_ms"), "to_ms": man.get("to_ms"), "note": note or man.get("note"), + "generated_utc": man.get("generated_utc"), "counts": man.get("counts"), "code": man.get("code"), + "playback": {"from_ms": play_from, "to_ms": play_to, "interval_s": interval_s, "pause_s": pause_s}} + first = {} + for r in repos.history.query(play_from, play_to, limit=0)["windows"]: + first.setdefault(r.get("host"), r["sdir"]) + members = [SnapshotMember(h, repos, first.get(h), info) for h in hosts] + player = Player(members, repos, play_from, play_to, interval_s, pause_s) + cor = SnapshotCorrelator(repos.crosshost, [h for h in hosts if h]) if len(hosts) > 1 else None + return members, player, cor, info + + +# --------------------------------------------------------------------------- selftest +def selftest(): + """'It runs': a two-host snapshot replays slot by slot, details come from the snapshot, the loop restarts.""" + import tempfile + from file_store import FileCrosshostRepository, FileSessionStore + from history import FileHistoryRepository + from repository import open_repositories + import snapshot + base, m5 = 1_794_700_000_000, 300_000 + with tempfile.TemporaryDirectory() as d: + sess = os.path.join(d, "sessions") + h, st = FileHistoryRepository(sess), FileSessionStore(sess) + for host in ("ws-etw-0", "ws-etw-1"): + sdir = f"live-a-{host}" + os.makedirs(os.path.join(sess, sdir)) + import json + json.dump({"run_dir": f"/x/runs/model-{host}", "tau": {"net": -0.1}, "alg1": {"moderate_from": 4.5}, + "llm": {"provider": "deepseek", "model": "m", "max_per_day": 30}}, + open(os.path.join(sess, sdir, "session.json"), "w")) + for k in range(3 if host == "ws-etw-0" else 2): + row = {"sdir": sdir, "session": "live-a", "mode": "loki", "moderate_from": 4.5, "window": f"w{k}", + "host": host, "start_ms": base + k * m5, "end_ms": base + (k + 1) * m5, "status": "scored", + "alert": host == "ws-etw-1" and k == 1, "max_sg_score": 7.2, + "llm": {"status": "attack"} if host == "ws-etw-1" and k == 1 else None} + h.append(row) + st.save_detail(sdir, f"w{k}", {"top": {"net": []}, "window": row}) + FileCrosshostRepository(sess).append({"id": "f1", "start_ms": base, "level": "one-sided"}) + snapshot.build(sess, base + 3 * m5, os.path.join(d, "s.tar.gz"), log=lambda *_: None) + repos = open_repositories("snapshot", os.path.join(d, "s.tar.gz"), os.path.join(d, "data")) + members, player, cor, info = build_members(repos, base, base + 3 * m5, 0, 0) + player.sleep = lambda s: None + seen = [] + for m in members: + m.listeners.append(lambda ev, h=m.host: seen.append((h, ev["type"], ev.get("window", {}).get("window")))) + assert [m.host for m in members] == ["ws-etw-0", "ws-etw-1"] and len(player.slots) == 3 + assert members[1].status()["model"]["run_dir"] == "model-ws-etw-1", "status before the first window" + player.run_once() + assert [w["window"] for w in members[0].windows()] == ["w0", "w1", "w2"] + assert [w["window"] for w in members[1].windows()] == ["w0", "w1"] + s1 = members[1].status() + assert s1["session"]["played_red"] == 1 and s1["session"]["played_llm_attack"] == 1, s1["session"] + assert s1["session"]["clock_ms"] == base + 3 * m5, "a host with no window in a slot still moves on" + assert s1["params"]["llm"] == {"provider": "deepseek", "model": "m"} and s1["snapshot"]["counts"]["windows"] == 5 + det = members[1].window_detail("w1") + assert det["window"]["llm"]["status"] == "attack" and "_sdir" not in det["window"], det + assert members[0].window_detail("nope") is None and members[0].ingest({})[0] == 403 + assert ("ws-etw-1", "window", "w1") in seen + for m in members: + m.restart() + assert members[0].windows() == [] and members[0].session["id"].endswith("-2") + assert ("ws-etw-0", "session", None) in seen + assert cor.list()[0]["id"] == "f1" and cor.status()["findings"]["one-sided"] == 1 + print("[playback] selftest OK (slot order, per-host windows, status from session.json, detail from the snapshot, " + "ingest refused, loop restart, recorded cross-host findings)") + + +if __name__ == "__main__": + if "--selftest" in sys.argv: + selftest() + else: + print(__doc__) diff --git a/src/live/repository.py b/src/live/repository.py new file mode 100644 index 0000000..555ae34 --- /dev/null +++ b/src/live/repository.py @@ -0,0 +1,283 @@ +#!/usr/bin/env python3 +""" +repository.py - the persistence ports of the live server: WHAT is stored, not WHERE. [OURS] engineering (no effect +on how a window is scored). + +The engine, the cross-host correlator and the HTTP layer depend only on these three abstract classes (the Python +counterpart of Spring Data repository interfaces; an ABC = a Java abstract class: @abstractmethod = the contract, +plain methods = shared logic every implementation inherits): + + HistoryRepository every window state change (history.jsonl): append / get / query a time range / detail + CrosshostRepository cross-host follow-ups of red windows (crosshost.jsonl): load all / append one + SessionStore the engine's own files: session.json, raw/.json, windows.csv, windows//*, + llm_verdicts.csv, the daily LLM budget + +Implementations + files history.FileHistoryRepository, file_store.FileSessionStore / FileCrosshostRepository: + the sessions/ folder layout the server has always written (behaviour unchanged by the refactor) + snapshot snapshot.Snapshot*: read-only views of a recorded snapshot archive (deploy/snapshot/*.tar.gz, unpacked + at start); every write raises ReadOnlyRepositoryError. Used by the public demo (deploy/README.md). + +open_repositories() is the one place that picks an implementation. + +Usage (from the repo root) + uv run python src/live/repository.py --selftest +""" +from __future__ import annotations + +import re +import sys +import threading +from abc import ABC, abstractmethod +from dataclasses import dataclass + +SAFE_NAME = re.compile(r"^[A-Za-z0-9_-][A-Za-z0-9._-]*$") # session folder / window id: no '/', no leading '.' +STATUS_RANK = {"scored": 4, "error": 3, "empty": 2, "partial": 1} +META_KEYS = ("sdir", "session", "mode", "moderate_from") # history-row keys that are not window fields + + +class ReadOnlyRepositoryError(RuntimeError): + """A write on a read-only (snapshot) repository.""" + + +def check_name(*names: str) -> None: + """Refuse anything that is not a plain folder name (path traversal: '..', '/x', 'a/b').""" + for n in names: + if not (isinstance(n, str) and SAFE_NAME.match(n)): + raise ValueError("bad session or window name") + + +def restart_n(sdir: str) -> int: + """'live-...-ws-etw-1.r3' -> 3; a first run (no .rN) -> 1.""" + m = re.search(r"\.r(\d+)$", sdir) + return int(m.group(1)) if m else 1 + + +# --------------------------------------------------------------------------- history +class HistoryRepository(ABC): + """Window history. self.rows: (sdir, window id) -> the LATEST row of that window; a row is + {"sdir", "session", "mode", "moderate_from", **window record} (engine.py builds the window record). + Subclasses fill self.rows when they load and implement append + _read_detail.""" + + def __init__(self): + self.lock = threading.Lock() + self.rows: dict[tuple[str, str], dict] = {} + + # ---------------------------------------------------------------- contract + @abstractmethod + def append(self, row: dict) -> None: + """Store one window state; the last row of a (sdir, window) pair wins.""" + + @abstractmethod + def _read_detail(self, sdir: str, wid: str) -> dict | None: + """The stored UI detail of one window (detail.json shape) or None. Names are already checked.""" + + # ---------------------------------------------------------------- shared read logic + def get(self, sdir: str, wid: str) -> dict | None: + with self.lock: + r = self.rows.get((sdir, wid)) + return dict(r) if r else None + + def query(self, from_ms: int, to_ms: int, alert_only: bool = False, include_replay: bool = False, + limit: int = 2000, host: str | None = None) -> dict: + """Windows overlapping [from_ms, to_ms), one row per (host, window start). + + Live sessions (mode 'loki' from Loki, 'live' from the HTTP shipper) by default; replays re-use past + timestamps, so they are left out unless include_replay. host = only that host's windows; rows written + before two-host scoring have no host and match no host filter. A restart re-reads up to 1 h into a new + .rN folder, so the same window can exist twice: scored > error > empty > partial, then the later restart.""" + with self.lock: + cand = [r for r in self.rows.values() + if isinstance(r.get("start_ms"), int) and r["start_ms"] < to_ms and r.get("end_ms", 0) > from_ms + and (include_replay or r.get("mode") != "replay") + and (host is None or r.get("host") == host)] + best: dict[tuple, tuple] = {} + dups = 0 + for r in cand: + k = (r.get("host") or "", r["start_ms"]) # two hosts share the window grid + rank = (STATUS_RANK.get(r.get("status"), 0), restart_n(r["sdir"]), r["sdir"]) + if k in best: + dups += 1 + if rank <= best[k][0]: + continue + best[k] = (rank, r) + rows = [r for _, r in sorted(best.values(), key=lambda x: (x[1]["start_ms"], x[1].get("host") or ""))] + if alert_only: + rows = [r for r in rows if r.get("alert")] + return {"from_ms": from_ms, "to_ms": to_ms, "total": len(rows), "duplicates_hidden": dups, + "truncated": len(rows) > limit, "windows": rows[-limit:] if limit else rows} + + def detail(self, sdir: str, wid: str) -> dict | None: + """UI detail + the history row's window fields + {"history": session meta}; None if neither exists.""" + check_name(sdir, wid) + row = self.get(sdir, wid) + d = self._read_detail(sdir, wid) + if d is None and row is None: + return None + d = d or {} + win = {k: v for k, v in (row or d.get("window") or {}).items() if k not in META_KEYS} + return {**d, "window": win, "history": {k: (row or {}).get(k) for k in META_KEYS}} + + def sessions(self) -> list[str]: + """Every session folder name that has at least one row, sorted.""" + with self.lock: + return sorted({s for s, _ in self.rows}) + + def bounds(self) -> tuple[int, int] | None: + """(first window start, last window end) in epoch ms over every row, or None when empty.""" + with self.lock: + st = [r["start_ms"] for r in self.rows.values() if isinstance(r.get("start_ms"), int)] + en = [r.get("end_ms", 0) for r in self.rows.values() if isinstance(r.get("start_ms"), int)] + return (min(st), max(en)) if st else None + + +# --------------------------------------------------------------------------- cross-host findings +class CrosshostRepository(ABC): + """Cross-host findings (correlate.py). The correlator keeps them in memory; this stores them.""" + + @abstractmethod + def load(self) -> dict[str, dict]: + """Every stored finding: id -> the LAST stored version of it.""" + + @abstractmethod + def append(self, finding: dict) -> None: + """Store one (new or updated) finding; the last one of an id wins on load.""" + + +# --------------------------------------------------------------------------- the engine's own files +class SessionStore(ABC): + """Per-session + per-window files the engine writes while it scores. A session is a folder NAME (sdir, e.g. + 'live-20261115T151036Z-ws-etw-1.r2'); path(sdir) says where it lives (the UI shows it; alg2 / correlate read + and write window folders by path).""" + + @abstractmethod + def path(self, sdir: str = "") -> str: + """Folder of a session ('' = the store root).""" + + @abstractmethod + def create_session(self, name: str, meta: dict, index_header: list[str]) -> str: + """New session folder for run `name` -> its sdir. A folder that already holds a session gets a fresh + .rN (a restart re-reads the run). Writes meta (+ restart_of) as session.json and the index header.""" + + @abstractmethod + def open_raw(self, sdir: str, stream: str): + """Append-mode text handle for the verbatim raw lines of one stream (caller flushes / closes).""" + + @abstractmethod + def window_dir(self, sdir: str, wid: str) -> str: + """Folder of one window (created).""" + + @abstractmethod + def write_window(self, sdir: str, wid: str, files: dict) -> None: + """files: name -> pd.DataFrame | (pd.DataFrame, to_csv kwargs) | dict/list (JSON) | callable(path).""" + + @abstractmethod + def append_index(self, sdir: str, row: list) -> None: + """One row of windows.csv.""" + + @abstractmethod + def append_verdict(self, sdir: str, row: list) -> None: + """One row of llm_verdicts.csv (header written on first use).""" + + @abstractmethod + def save_detail(self, sdir: str, wid: str, detail: dict) -> None: + """detail.json, atomically (a reader never sees half a file).""" + + @abstractmethod + def load_detail(self, sdir: str, wid: str) -> dict | None: + """detail.json or None.""" + + @abstractmethod + def budget(self, today: str) -> dict: + """Today's LLM budget use: {"date", "used"} (another day's count reads as 0).""" + + @abstractmethod + def take_budget(self, limit: int, today: str) -> bool: + """Count one investigation against today's budget; False = spent (nothing counted). limit 0 = no limit.""" + + +# --------------------------------------------------------------------------- factory +@dataclass +class Repositories: + history: HistoryRepository + crosshost: CrosshostRepository + sessions: SessionStore + manifest: dict | None = None # snapshot only: what the archive contains (snapshot.build writes it) + + +def open_repositories(mode: str, path: str, data_dir: str | None = None) -> Repositories: + """mode 'files': path = the sessions folder (read + write). + mode 'snapshot': path = a snapshot .tar.gz, unpacked into data_dir (read-only).""" + if mode == "files": + from file_store import FileCrosshostRepository, FileSessionStore + from history import FileHistoryRepository + return Repositories(FileHistoryRepository(path), FileCrosshostRepository(path), FileSessionStore(path)) + if mode == "snapshot": + import snapshot + return snapshot.open_snapshot(path, data_dir) + raise ValueError(f"unknown repository mode {mode!r} (files | snapshot)") + + +# --------------------------------------------------------------------------- selftest +def selftest(): + """The shared logic of the base classes, on an in-memory subclass. Implementations test themselves + (history.py, file_store.py, snapshot.py).""" + + class Mem(HistoryRepository): + def __init__(self): + super().__init__() + self.details = {} + + def append(self, row): + with self.lock: + self.rows[(row["sdir"], str(row["window"]))] = dict(row) + + def _read_detail(self, sdir, wid): + return self.details.get((sdir, wid)) + + try: + HistoryRepository() # abstract: cannot be built + raise AssertionError("abstract class instantiated") + except TypeError: + pass + h = Mem() + base = 1_794_700_000_000 + w = lambda sdir, k, st="scored", host="a", alert=False: {"sdir": sdir, "session": sdir, "mode": "loki", + "moderate_from": 4.5, "window": f"w{k}", "host": host, + "start_ms": base + k * 300_000, + "end_ms": base + (k + 1) * 300_000, "status": st, + "alert": alert} + h.append(w("s", 0, "partial")) + h.append(w("s.r2", 0, "scored")) # the restart re-scored it: wins + h.append(w("s", 1, alert=True)) + h.append(w("sb", 1, host="b")) + q = h.query(base, base + 3 * 300_000) + assert q["total"] == 3 and q["duplicates_hidden"] == 1, q + assert [r["sdir"] for r in q["windows"]][:1] == ["s.r2"], q + assert h.query(base, base + 3 * 300_000, alert_only=True)["total"] == 1 + assert h.query(base, base + 3 * 300_000, host="b")["total"] == 1 + assert h.bounds() == (base, base + 2 * 300_000) and h.sessions() == ["s", "s.r2", "sb"] + h.details[("s", "w1")] = {"top": {}, "window": {"window": "w1"}} + d = h.detail("s", "w1") + assert d["window"]["alert"] is True and d["history"]["moderate_from"] == 4.5 and "sdir" not in d["window"], d + assert h.detail("s", "nope") is None + for bad in ("..", "../x", "a/b", ".hidden"): + try: + h.detail(bad, "w1") + raise AssertionError(f"accepted {bad!r}") + except ValueError: + pass + assert restart_n("x.r12") == 12 and restart_n("x") == 1 + try: + open_repositories("nope", ".") + raise AssertionError("unknown mode accepted") + except ValueError: + pass + print("[repository] selftest OK (abstract base, query dedup, detail merge, name guard, factory)") + + +if __name__ == "__main__": + if "--selftest" in sys.argv: + selftest() + else: + print(__doc__) diff --git a/src/live/snapshot.py b/src/live/snapshot.py new file mode 100644 index 0000000..7145283 --- /dev/null +++ b/src/live/snapshot.py @@ -0,0 +1,492 @@ +#!/usr/bin/env python3 +""" +snapshot.py - a recorded, read-only copy of the live server's history for the public demo (deploy/README.md). +[OURS] engineering: nothing here scores a window; every score / level / LLM verdict in a snapshot is what the live +server computed at the time, with the model and settings recorded in each session.json. + + build sessions/ (trainer) -> one deterministic .tar.gz: + manifest.json range, counts, models, note, sha256 of every other file + sessions/history.jsonl the WINNING row per (host, window) (restart duplicates and + replay sessions left out), end <= --until + sessions//session.json run parameters (absolute paths cut to names) + sessions//windows//detail.json the UI detail (top nodes, subgraphs, LLM summary + + report), rebuilt from scores.csv where detail.json is missing + sessions/crosshost.jsonl cross-host findings that start before --until + Raw ETW lines, edges, features and LLM prompt logs (calls.jsonl) are NOT copied. Every string goes + through a redaction pass (known secrets + password-looking arguments), then the output is scanned again + and the build fails if a known secret is still in it. + + open SnapshotArchive: unpack the .tar.gz once into a data folder (tarfile filter "data": no path traversal, + no links outside), check every file's sha256 against manifest.json, then serve it through the read-only + Snapshot* repositories (repository.py). Any write raises ReadOnlyRepositoryError. + +Usage (from the repo root) + lab snapshot build --until 2026-11-15T20:15Z --out deploy/snapshot/nt2102-snapshot.tar.gz + uv run python src/live/snapshot.py --selftest +""" +from __future__ import annotations + +import gzip +import hashlib +import io +import json +import os +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from repository import (CrosshostRepository, HistoryRepository, ReadOnlyRepositoryError, # noqa: E402 + Repositories, SessionStore, check_name) + +FORMAT = 1 +MANIFEST = "manifest.json" +REDACTED = "[REDACTED]" +# password-looking arguments in command lines (Sysmon EID 1, D14) and LLM reports quoting them: +# -Password x | /p:x | password=x | --password x | -p 'x' after a user flag is too ambiguous and is not touched +SECRET_PATTERNS = [re.compile(r"(?i)(-{1,2}password[\s:=]+)(['\"]?)([^\s'\"]+)"), + re.compile(r"(?i)((? str: + for sec in secrets: + if sec: + s = s.replace(sec, REDACTED) + for pat in SECRET_PATTERNS: + s = pat.sub(lambda m: m.group(1) + m.group(2) + REDACTED, s) + return s + + +def redact(obj, secrets: list[str]): + """Every string inside a JSON-like object (dict keys too); numbers / bools untouched.""" + if isinstance(obj, str): + return redact_str(obj, secrets) + if isinstance(obj, dict): + return {redact(k, secrets): redact(v, secrets) for k, v in obj.items()} + if isinstance(obj, list): + return [redact(v, secrets) for v in obj] + return obj + + +def secrets_from_ini(path: str, keys=("win_password", "grafana_admin_password")) -> list[str]: + """Values of key=value lines in an Ansible inventory (proxmox.ini); missing file -> [].""" + out = [] + try: + for line in open(path, encoding="utf-8"): + k, sep, v = line.strip().partition("=") + if sep and k.strip() in keys and v.strip(): + out.append(v.strip().strip("'\"")) + except OSError: + pass + return out + + +# --------------------------------------------------------------------------- build +def _sha256(path: str) -> str: + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def _dump(path: str, obj, secrets: list[str]) -> None: + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + json.dump(redact(obj, secrets), fh, separators=(",", ":"), default=str) + + +def _git_sha(repo: str) -> str: + try: + return subprocess.run(["git", "-C", repo, "rev-parse", "--short", "HEAD"], capture_output=True, text=True, + timeout=5, check=True).stdout.strip() + except (OSError, subprocess.SubprocessError): + return "unknown" + + +def _tar_deterministic(src_dir: str, out_path: str) -> None: + """Same input files -> same bytes: sorted names, mtime 0, uid/gid 0, fixed modes, gzip header mtime 0.""" + names = [] + for root, dirs, files in os.walk(src_dir): + dirs.sort() + for f in sorted(files): + names.append(os.path.relpath(os.path.join(root, f), src_dir)) + names.sort(key=lambda n: (n != MANIFEST, n)) # manifest first: readable without unpacking all + os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True) + tmp = out_path + ".tmp" + with open(tmp, "wb") as raw, gzip.GzipFile(fileobj=raw, mode="wb", mtime=0, compresslevel=9) as gz, \ + tarfile.open(fileobj=gz, mode="w", format=tarfile.PAX_FORMAT) as tar: + for n in names: + ti = tarfile.TarInfo(n) + data = open(os.path.join(src_dir, n), "rb").read() + ti.size, ti.mtime, ti.mode, ti.uid, ti.gid, ti.uname, ti.gname = len(data), 0, 0o644, 0, 0, "", "" + tar.addfile(ti, io.BytesIO(data)) + os.replace(tmp, out_path) + + +def build(sessions_dir: str, until_ms: int, out_path: str, from_ms: int | None = None, secrets: list[str] = (), + runs_dir: str | None = None, note: str = DEFAULT_NOTE, repo: str | None = None, log=print) -> dict: + """sessions_dir (a live server's, read only) -> out_path .tar.gz. Returns the manifest.""" + from file_store import FileCrosshostRepository + from history import FileHistoryRepository, train_summary + if not os.path.exists(os.path.join(sessions_dir, "history.jsonl")): + raise SystemExit(f"{sessions_dir}/history.jsonl not found: not a live server's sessions folder") + secrets = [s for s in secrets if s] + src = FileHistoryRepository(sessions_dir) + first = src.bounds() + if first is None: + raise SystemExit("history.jsonl is empty") + lo = from_ms if from_ms is not None else first[0] + # the winning row per (host, window start), live sessions only; then only windows that END by `until` + rows = [r for r in src.query(lo, until_ms, limit=0)["windows"] if r.get("end_ms", 0) <= until_ms] + if not rows: + raise SystemExit("no window in that range") + + stage = tempfile.mkdtemp(prefix="nt2102-snapshot-") + try: + sroot = os.path.join(stage, "sessions") + details = 0 + for r in rows: + d = src._read_detail(r["sdir"], str(r["window"])) + if d is not None: + _dump(os.path.join(sroot, r["sdir"], "windows", str(r["window"]), "detail.json"), d, secrets) + details += 1 + os.makedirs(sroot, exist_ok=True) + with open(os.path.join(sroot, "history.jsonl"), "w", encoding="utf-8") as fh: + for r in rows: + fh.write(json.dumps(redact(r, secrets), default=str) + "\n") + models, model_hosts = {}, {} + sdirs = sorted({r["sdir"] for r in rows}) + for sdir in sdirs: + try: + meta = json.load(open(os.path.join(sessions_dir, sdir, "session.json"))) + except (OSError, ValueError): + continue + run = os.path.basename(os.path.normpath(meta.get("run_dir") or "")) or None + if run: + meta["run_dir"] = run # a name, not the trainer's home path + if run not in models: + models[run] = train_summary(os.path.join(runs_dir, run)) if runs_dir else {} + if meta.get("host"): + model_hosts.setdefault(run, set()).add(meta["host"]) + if meta.get("scaler"): + meta["scaler"] = os.path.basename(meta["scaler"]) + _dump(os.path.join(sroot, sdir, "session.json"), meta, secrets) + found = [f for f in FileCrosshostRepository(sessions_dir).load().values() + if isinstance(f.get("start_ms"), int) and f["start_ms"] < until_ms and f["start_ms"] >= lo] + with open(os.path.join(sroot, "crosshost.jsonl"), "w", encoding="utf-8") as fh: + for f in sorted(found, key=lambda f: f["start_ms"]): + f = {k: v for k, v in f.items() if k not in ("dirty", "fresh")} + fh.write(json.dumps(redact(f, secrets), default=str) + "\n") + + # scan: no known secret may survive (the redaction is the guard, this is the check) + files = {} + for root, _, fs in os.walk(stage): + for f in fs: + p = os.path.join(root, f) + text = open(p, encoding="utf-8").read() + for sec in secrets: + if sec in text: + raise SystemExit(f"redaction failed: a known secret is still in {os.path.relpath(p, stage)}") + files[os.path.relpath(p, stage).replace(os.sep, "/")] = _sha256(p) + hosts = sorted({r.get("host") for r in rows if r.get("host")}) + red = [r for r in rows if r.get("alert")] + manifest = { + "format": FORMAT, "from_ms": rows[0]["start_ms"], "to_ms": max(r["end_ms"] for r in rows), + "until_ms": until_ms, "generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "code": _git_sha(repo or os.path.dirname(os.path.dirname(HERE))), "hosts": hosts, + "counts": {"windows": len(rows), "details": details, "sessions": len(sdirs), "red": len(red), + "llm_attack": sum(1 for r in red if (r.get("llm") or {}).get("status") == "attack"), + "crosshost": len(found)}, + "models": models, "model_hosts": {k: sorted(v) for k, v in sorted(model_hosts.items())}, "note": note, "files": dict(sorted(files.items())), + } + json.dump(manifest, open(os.path.join(stage, MANIFEST), "w"), indent=1) + _tar_deterministic(stage, out_path) + finally: + shutil.rmtree(stage, ignore_errors=True) + log(f"[snapshot] {manifest['counts']} -> {out_path} ({os.path.getsize(out_path) / 1e6:.1f} MB)") + return manifest + + +# --------------------------------------------------------------------------- open (unpack + verify) +class SnapshotError(RuntimeError): + pass + + +class SnapshotArchive: + """Unpacks a snapshot .tar.gz into data_dir// once (a restart with the same archive and a + kept data_dir skips it), verifies every file against manifest.json, and exposes root + manifest.""" + + def __init__(self, root: str, manifest: dict, sha256: str): + self.root, self.manifest, self.sha256 = root, manifest, sha256 + + @classmethod + def open(cls, tar_path: str, data_dir: str, log=print) -> "SnapshotArchive": + t0 = time.time() + sha = _sha256(tar_path) + root = os.path.join(data_dir, sha[:16]) + ok_mark = os.path.join(root, ".verified") + if not os.path.exists(ok_mark): + if os.path.exists(root): + shutil.rmtree(root) # a half-done unpack from a killed start + tmp = root + ".part" + shutil.rmtree(tmp, ignore_errors=True) + os.makedirs(tmp) + with tarfile.open(tar_path, "r:gz") as tar: + tar.extractall(tmp, filter="data") # refuses absolute paths, '..', links out of tmp + cls._verify(tmp) + open(os.path.join(tmp, ".verified"), "w").write(sha + "\n") + os.replace(tmp, root) + log(f"[snapshot] unpacked + verified {tar_path} -> {root} in {time.time() - t0:.1f}s") + else: + log(f"[snapshot] reusing {root} (already verified)") + manifest = json.load(open(os.path.join(root, MANIFEST))) + return cls(root, manifest, sha) + + @staticmethod + def _verify(root: str) -> None: + try: + manifest = json.load(open(os.path.join(root, MANIFEST))) + except (OSError, ValueError) as e: + raise SnapshotError(f"no readable {MANIFEST}: {e}") + if manifest.get("format") != FORMAT: + raise SnapshotError(f"snapshot format {manifest.get('format')} != {FORMAT}") + for rel, want in manifest.get("files", {}).items(): + p = os.path.join(root, *rel.split("/")) + if not os.path.isfile(p) or _sha256(p) != want: + raise SnapshotError(f"{rel}: missing or sha256 mismatch") + + +# --------------------------------------------------------------------------- read-only repositories +def _read_only(*_a, **_k): + raise ReadOnlyRepositoryError("this is a recorded snapshot: read-only") + + +class SnapshotHistoryRepository(HistoryRepository): + def __init__(self, root: str): + super().__init__() + self.dir = os.path.join(root, "sessions") + with open(os.path.join(self.dir, "history.jsonl"), encoding="utf-8") as fh: + for line in fh: + r = json.loads(line) + self.rows[(r["sdir"], str(r["window"]))] = r + + append = _read_only + + def _read_detail(self, sdir: str, wid: str) -> dict | None: + try: + return json.load(open(os.path.join(self.dir, sdir, "windows", wid, "detail.json"), encoding="utf-8")) + except (OSError, ValueError): + return None + + +class SnapshotCrosshostRepository(CrosshostRepository): + def __init__(self, root: str): + self.path = os.path.join(root, "sessions", "crosshost.jsonl") + + def load(self) -> dict[str, dict]: + out = {} + try: + with open(self.path, encoding="utf-8") as fh: + for line in fh: + f = json.loads(line) + out[f["id"]] = f + except OSError: + pass + return out + + append = _read_only + + +class SnapshotSessionStore(SessionStore): + def __init__(self, root: str): + self.root = os.path.join(root, "sessions") + + def path(self, sdir: str = "") -> str: + if sdir: + check_name(sdir) + return os.path.join(self.root, sdir) if sdir else self.root + + def window_dir(self, sdir: str, wid: str) -> str: + check_name(wid) + return os.path.join(self.path(sdir), "windows", wid) + + def load_detail(self, sdir: str, wid: str) -> dict | None: + try: + return json.load(open(os.path.join(self.window_dir(sdir, wid), "detail.json"), encoding="utf-8")) + except (OSError, ValueError): + return None + + def session_meta(self, sdir: str) -> dict: + try: + return json.load(open(os.path.join(self.path(sdir), "session.json"), encoding="utf-8")) + except (OSError, ValueError): + return {} + + def budget(self, today: str) -> dict: + return {"date": today, "used": 0} + + create_session = open_raw = write_window = append_index = append_verdict = save_detail = take_budget = _read_only + + +def open_snapshot(tar_path: str, data_dir: str | None) -> Repositories: + if not data_dir: + raise SnapshotError("a snapshot needs a data dir to unpack into (--data-dir)") + arc = SnapshotArchive.open(tar_path, data_dir) + return Repositories(SnapshotHistoryRepository(arc.root), SnapshotCrosshostRepository(arc.root), + SnapshotSessionStore(arc.root), {**arc.manifest, "archive_sha256": arc.sha256}) + + +# --------------------------------------------------------------------------- selftest +def selftest(): + """'It runs': build from a synthetic sessions folder, cut-off, dedup, redaction + scan, determinism, unpack + + verify + tamper detection, traversal refused, read-only repositories. Says nothing about detection quality.""" + from file_store import FileCrosshostRepository, FileSessionStore + from history import FileHistoryRepository + from repository import open_repositories + base = 1_794_700_000_000 + m5 = 300_000 + secret = "Hunter2!lab" + with tempfile.TemporaryDirectory() as d: + sess = os.path.join(d, "sessions") + h, st = FileHistoryRepository(sess), FileSessionStore(sess) + for sdir in ("live-a-ws-etw-1", "live-a-ws-etw-1.r2", "replay-x"): + os.makedirs(os.path.join(sess, sdir), exist_ok=True) + json.dump({"session": sdir, "run_dir": "/home/it2102/NT2102/src/artifacts/runs/exp15-ws1", + "scaler": "/home/it2102/x/feature_scaler.json", "alg1": {"moderate_from": 4.5}}, + open(os.path.join(sess, sdir, "session.json"), "w")) + for k in range(6): + s = base + k * m5 + mode = "loki" + row = {"session": "live-a", "mode": mode, "moderate_from": 4.5, "window": f"w{k}", "host": "ws-etw-1", + "start_ms": s, "end_ms": s + m5, "status": "scored", "alert": k == 2, "max_sg_score": 7.0} + h.append({"sdir": "live-a-ws-etw-1", **row, "status": "partial" if k < 2 else "scored"}) + if k < 2: # the restart re-scored w0, w1: those rows win + h.append({"sdir": "live-a-ws-etw-1.r2", **row}) + st.save_detail("live-a-ws-etw-1.r2", f"w{k}", {"top": {}, "window": row}) + elif k != 3: + st.save_detail("live-a-ws-etw-1", f"w{k}", { + "top": {"process": [{"id": "p1", "cmdline": f"net use \\\\dc /user:x /p:{secret}"}]}, + "llm": {"verdict": "attack", "subgraphs": [{"report": f"used -Password {secret} then {secret}"}]}, + "window": row}) + h.append({"sdir": "replay-x", **row, "mode": "replay"}) + FileCrosshostRepository(sess).append({"id": "f1", "start_ms": base + 2 * m5, "level": "one-sided", "dirty": True}) + FileCrosshostRepository(sess).append({"id": "f9", "start_ms": base + 9 * m5, "level": "one-sided"}) + + until = base + 5 * m5 # w0..w4 end by then; w5 does not + out = os.path.join(d, "snap.tar.gz") + man = build(sess, until, out, secrets=[secret], log=lambda *_: None) + assert man["counts"]["windows"] == 5 and man["counts"]["red"] == 1 and man["counts"]["crosshost"] == 1, man + assert man["counts"]["details"] == 4, "w3 had no detail and is still listed" + raw = gzip.open(out).read() + assert secret.encode() not in raw and b"/home/it2102" not in raw, "secret or home path in the archive" + out2 = os.path.join(d, "snap2.tar.gz") + man2 = build(sess, until, out2, secrets=[secret], log=lambda *_: None) + assert man2["files"] == man["files"], "same input must give the same files" + try: + build(sess, until, os.path.join(d, "x.tar.gz"), secrets=["1"], log=lambda *_: None) # in a timestamp + raise AssertionError("scan missed a secret") + except SystemExit as e: + assert "redaction" in str(e) or "secret" in str(e), e + + repos = open_repositories("snapshot", out, os.path.join(d, "data")) + q = repos.history.query(0, 10 ** 15)["windows"] + assert [r["window"] for r in q] == ["w0", "w1", "w2", "w3", "w4"], q + assert q[0]["sdir"] == "live-a-ws-etw-1.r2" and repos.history.query(0, 10 ** 15, include_replay=True)[ + "duplicates_hidden"] == 0, "replays and duplicates must not be in the snapshot" + det = repos.history.detail("live-a-ws-etw-1", "w2") + assert det["llm"]["verdict"] == "attack" and REDACTED in det["llm"]["subgraphs"][0]["report"], det + assert REDACTED in det["top"]["process"][0]["cmdline"], det + assert repos.history.detail("live-a-ws-etw-1", "w3")["window"]["window"] == "w3" + assert repos.sessions.session_meta("live-a-ws-etw-1")["run_dir"] == "exp15-ws1" + assert list(repos.crosshost.load()) == ["f1"] and "dirty" not in repos.crosshost.load()["f1"] + assert repos.manifest["hosts"] == ["ws-etw-1"] + for write in (lambda: repos.history.append({}), lambda: repos.crosshost.append({}), + lambda: repos.sessions.save_detail("a", "b", {}), lambda: repos.sessions.take_budget(1, "d")): + try: + write() + raise AssertionError("write accepted") + except ReadOnlyRepositoryError: + pass + # second open: reuse; a tampered unpack (no .verified mark) is redone and a tampered archive is refused + root = SnapshotArchive.open(out, os.path.join(d, "data"), log=lambda *_: None).root + os.remove(os.path.join(root, ".verified")) + open(os.path.join(root, "sessions", "history.jsonl"), "a").write("tampered\n") + SnapshotArchive.open(out, os.path.join(d, "data"), log=lambda *_: None) # re-unpacked from the archive + assert len(open(os.path.join(root, "sessions", "history.jsonl")).read().splitlines()) == 5 + bad = os.path.join(d, "bad.tar.gz") + with tarfile.open(out, "r:gz") as src, tarfile.open(bad, "w:gz") as dst: + for m in src.getmembers(): + data = src.extractfile(m).read() + if m.name.endswith("history.jsonl"): + data += b"{}\n" + m.size = len(data) + dst.addfile(m, io.BytesIO(data)) + try: + SnapshotArchive.open(bad, os.path.join(d, "data2"), log=lambda *_: None) + raise AssertionError("tampered archive accepted") + except SnapshotError: + pass + evil = os.path.join(d, "evil.tar.gz") + with tarfile.open(evil, "w:gz") as tar: + ti = tarfile.TarInfo("../escape.txt") + ti.size = 1 + tar.addfile(ti, io.BytesIO(b"x")) + try: + SnapshotArchive.open(evil, os.path.join(d, "data3"), log=lambda *_: None) + raise AssertionError("path traversal accepted") + except (tarfile.TarError, SnapshotError): + pass + assert not os.path.exists(os.path.join(d, "escape.txt")) + assert redact_str("x -Password 'abc' y", []) == f"x -Password '{REDACTED}' y" + assert redact_str("password=abc&x", []) == f"password={REDACTED}&x" + print("[snapshot] selftest OK (cut-off, dedup, replays out, redaction + scan, deterministic files, unpack + " + "verify, tamper + traversal refused, read-only repositories)") + + +def main(argv=None): + import argparse + from history import parse_time_ms + ap = argparse.ArgumentParser(prog="snapshot.py", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--selftest", action="store_true") + sub = ap.add_subparsers(dest="cmd") + b = sub.add_parser("build", help="sessions/ -> snapshot .tar.gz") + repo = os.path.dirname(os.path.dirname(HERE)) + b.add_argument("--sessions-dir", default=os.path.join(HERE, "sessions")) + b.add_argument("--until", required=True, metavar="TIME", + help="keep windows that END by this time (ISO-8601, naive = UTC, or epoch ms)") + b.add_argument("--from", dest="start", metavar="TIME", help="first window start (default: the first in history)") + b.add_argument("--out", required=True, metavar="TAR_GZ") + b.add_argument("--runs-dir", default=os.path.join(repo, "src", "artifacts", "runs"), + help="model folders, for the training hyperparameters shown in the UI") + b.add_argument("--secrets-ini", default=os.path.join(repo, "src", "ansible", "proxmox.ini"), + help="redact the passwords set in this Ansible inventory") + b.add_argument("--secret", action="append", default=[], help="another literal to redact (repeatable)") + b.add_argument("--note", default=DEFAULT_NOTE, help="the text the demo UI shows about the data") + a = ap.parse_args(argv) + if a.selftest: + selftest() + return 0 + if a.cmd != "build": + ap.print_help() + return 1 + secrets = secrets_from_ini(a.secrets_ini) + a.secret + [os.environ.get("LAB_TOKEN", "")] + build(a.sessions_dir, parse_time_ms(a.until), a.out, parse_time_ms(a.start), secrets, a.runs_dir, a.note, repo) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/live/static/index.html b/src/live/static/index.html index 589428d..6f3f7b8 100644 --- a/src/live/static/index.html +++ b/src/live/static/index.html @@ -125,6 +125,10 @@ .trained span{border:1px solid var(--win);color:var(--win);background:var(--win-soft);border-radius:6px;padding:3px 10px;font-weight:600} .trained span.unknown{border-color:var(--warn);color:var(--warn);background:none} .hosttabs{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px} +/* snapshot mode (public demo): recorded data, read-only */ +.snapbanner{border:1px solid var(--win);background:var(--win-soft);border-radius:10px;padding:10px 14px;margin-bottom:12px} +.snapbanner b{color:var(--win)} +.snapbanner .muted{display:block;margin-top:4px} .hosttabs button{font:600 .85rem var(--sans);color:var(--ink);background:var(--paper);border:1px solid var(--line); border-radius:6px;padding:5px 12px;cursor:pointer} .hosttabs button.on{border-color:var(--win);color:var(--win);background:var(--win-soft)} @@ -207,6 +211,7 @@

OCR-APT live

+
@@ -252,7 +257,7 @@

History (every window kept on disk, across restarts and - +
@@ -309,10 +314,25 @@

Top nodes per type (margin = sco let status = null, selected = null, pinned = false, cy = null, detail = null, sgIdx = 0; let histSel = null; // {sdir, wid} when the detail panel shows a window picked from History + // snapshot mode (live_server.py --snapshot): "now" is the end of the recorded data, not the wall clock + const snap = () => status?.snapshot || null; + const nowMs = () => snap()?.to_ms ?? Date.now(); + function renderSnapshot() { + const sn = snap(); + $("snapBanner").hidden = !sn; $("hAll").hidden = !sn; + if (!sn) return; + const pb = sn.playback || {}, c = sn.counts || {}; + $("snapBanner").innerHTML = `Recorded snapshot · read-only demo. ${esc(dhm(sn.from_ms))} → ${esc(dhm(sn.to_ms))} (lab time), + ${esc(c.windows)} windows, ${esc(c.red)} red, ${esc(c.llm_attack)} with an LLM attack verdict. + The live panels replay ${esc(dhm(pb.from_ms))} → ${esc(hm(pb.to_ms))} at one 5-min window every ${esc(pb.interval_s)} s, in a loop; + History holds the whole range.${esc(sn.note || "")}`; + } + // ------------------------------------------------------------- status tiles function renderStatus() { const s = status?.session; renderHosts(); + renderSnapshot(); $("modelTxt").textContent = status ? "model " + base(status.model.run_dir) + " · converter " + status.model.converter_check : ""; const p = status?.params; if (p) $("winParams").textContent = `w = ${p.window_min} min, s = ${p.stride_min} min, lateness ${p.lateness_s} s`; @@ -323,6 +343,21 @@

Top nodes per type (margin = sco if (status) $("tauTxt").textContent = "τ per type: " + Object.entries(status.model.tau).map(([k,v]) => `${k} ${num(v,5)}`).join(" · "); if (!s) { $("tiles").innerHTML = '
waiting for data (shipper or Loki)…
'; return; } $("sessionTxt").textContent = `session ${s.id} (${s.mode}${s.host ? ", " + s.host : ""})`; + if (snap()) { // playback: no shipper, no Loki; show what is being replayed + $("conn").className = "dot on"; + $("connTxt").textContent = "playback of recorded data"; + const played = [...curWins().values()]; + $("tiles").innerHTML = [ + ["recorded clock (lab time)", s.clock_ms ? dhm(s.clock_ms) : "–"], + ["windows played (this loop)", s.windows], + ["red windows (this loop)", s.played_red ?? played.filter(w => w.alert).length, (s.played_red ?? 0) ? "bad" : ""], + ["LLM attack verdicts (this loop)", s.played_llm_attack ?? 0], + ["loop", s.loop ?? 1], + ["snapshot built (lab time)", snap().generated_utc ? dhm(Date.parse(snap().generated_utc)) : "–"], + ].map(([k,v,c]) => `
${esc(k)}
${esc(v)}
`).join(""); + renderTimeline(); + return; + } const ago = s.last_seen_s_ago; $("conn").className = "dot " + (ago == null ? "" : ago < 5 ? "on" : ago < 30 ? "stale" : "off"); const src = status.source; @@ -586,13 +621,15 @@

Top nodes per type (margin = sco }); $("hGo").addEventListener("click", queryHistory); document.querySelectorAll("[data-h]").forEach(b => b.addEventListener("click", () => { - const now = Date.now(); - $("hTo").value = toInput(now); $("hFrom").value = toInput(now - Number(b.dataset.h) * 3600e3); + const now = nowMs(); + $("hTo").value = toInput(now); + $("hFrom").value = toInput(b.dataset.h === "all" ? (snap()?.from_ms ?? now - 168 * 3600e3) : now - Number(b.dataset.h) * 3600e3); queryHistory(); })); - function initHistory() { + async function initHistory() { const h = new URLSearchParams(location.hash.slice(1)); - const now = Date.now(); + if (!status) { try { status = await (await fetch("api/status")).json(); renderSnapshot(); } catch (e) {} } + const now = nowMs(); const parse = v => { const t = Date.parse(v); return Number.isNaN(t) ? null : t; }; $("hTo").value = toInput(parse(h.get("to")) ?? now); $("hFrom").value = toInput(parse(h.get("from")) ?? now - 6 * 3600e3);