diff --git a/.claude/tasks/contracts/2026-11-04-extract-guard-2214.md b/.claude/tasks/contracts/2026-11-04-extract-guard-2214.md new file mode 100644 index 0000000..8e0bf33 --- /dev/null +++ b/.claude/tasks/contracts/2026-11-04-extract-guard-2214.md @@ -0,0 +1,31 @@ +# CONTRACT — extract-guard +- date: 2026-11-04 | flow: feat | branch: feature/extract-guard (off develop 06d2576) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +on a eu un cas la ou on a extrait un paquet debian et ca a ecrase des binaires etc. voici le raport claude + +[pasted incident report, verbatim essentials:] « Une règle dans ~/.claude/CLAUDE.md, sous « Destructive tools & data loss », à côté de la règle lftp. Texte proposé : Installer un paquet ou une archive sur une machine ou une VM : jamais d'extraction (dpkg -x, tar x, unzip, cp -r) vers /, /usr, /etc ou un autre répertoire système. Les distributions usr-merge ont /lib, /bin, /sbin et /lib64 en liens symboliques, et une archive qui contient ces chemins les remplace par de vrais dossiers. D'abord lister le contenu (dpkg -c, tar tf), puis extraire dans un dossier de travail et passer par PATH ou PYTHONPATH. Sans gestionnaire de paquets sur la cible, on le dit à l'utilisateur au lieu de bricoler. 2. Un hook PreToolUse sur Bash qui bloque ces commandes avant exécution. C'est le seul vrai garde-fou, puisqu'une règle écrite peut être oubliée ou mal appliquée. Il refuserait toute commande, y compris dans un ssh ou vaas-cli ssh, qui contient : dpkg -x ou dpkg-deb -x avec une destination / ou absente ; tar avec -C / ; unzip -d /. Cela passerait par la skill update-config. » + +fais en sorte d'eviter ca a l'avenir en ajoutant au harnais + +## CLARIFICATIONS +Pass A: request complete (outcome: such commands are refused before they run and the doctrine names the rule; scope: the harness = this repo's hooks, settings.json, CLAUDE.global.md). +Context: BLK-022 (open) — the general `hooks/guard-bash.sh` was withheld by the safety classifier; its spec `lib/tests/guard-bash.test.sh` (214 cases) SKIPs while the hook is absent. This guard is a separate, narrow hook so that spec stays untouched. + +Pass B `[gated 2026-11-04]` (user: recommended options): deny, not ask (the user runs a real install with `! `); watched commands = dpkg -x / dpkg-deb -x (long forms), tar extraction, unzip, cpio -i, plus recursive `cp` (-r/-R/-a); system roots = /, /usr, /etc, /bin, /sbin, /lib, /lib32, /lib64, /libx32, /boot, /opt, /var, /srv, /root, /sys, /proc, /dev (subdirectories included; /tmp, /home, /mnt, /media and relative paths pass); an unresolvable destination ($VAR, $(…), backtick) is refused. + +Design gate `[gated 2026-11-04]` (after the plan challenge: r1 FATAL ×3, r2 FATAL(9)/FATAL(7)/CONCERNS(2); user: "Hook simple + soft_deny", vaas-cli "les deux formes"): one POSIX-awk scanner that re-tokenizes every quoted, `$(…)`, backtick and heredoc text (no carrier list) and runs a detector from every watched tool word; remote commands follow the local rules (relative or absent destination passes); plus an `autoMode.soft_deny` line in settings.json for the forms no static parser sees; `vaas-cli ssh -- ` and `vaas-cli ssh ''` both covered; accepted false positive: a text containing a complete extraction command into a system dir. Ruling: matcher `Bash|Monitor` (push-guard precedent, BDR-112), FILE SCOPE gains templates/settings/SETTINGS.md and CHANGELOG.md (doc-sync). + +## ACCEPTANCE CRITERIA +1. A PreToolUse Bash hook refuses, before it runs, a command that extracts a package or archive into `/` or a system directory: `dpkg -x` / `dpkg-deb -x` (and their long forms) with such a destination; `tar` extracting with `-C` / `--directory` to one, or after a `cd` to one in the same command; `unzip -d` to one; including when the command sits inside `ssh … ''`, `vaas-cli ssh … ''` or `bash -c ''`. The refusal names the rule and the safe path (list first, extract into a work dir, or let the user run it). +2. The same tools with a non-system destination (a relative path, `/tmp/x`, a `mktemp -d` path, the project dir) and listing forms (`dpkg -c`, `tar tf`, `unzip -l`) pass untouched; any other command passes silently. +3. The hook fails safe on its own errors per the push-guard precedent (missing jq: warn on stderr and allow), never prints on an allowed command, and is wired in settings.json `hooks.PreToolUse` (matcher `Bash`) committed through the git index without the uncommitted UI writes (LRN-253). +4. CLAUDE.global.md § "Destructive tools & data loss" holds the doctrine bullet (list first, work dir + PATH/PYTHONPATH, usr-merge reason, no package manager → tell the user), and the doctrine-citers census stays green. +5. A test suite drives the hook with deny and allow cases (each criterion-1 form, each criterion-2 form) and `make test` is green; shellcheck clean. + +## FILE SCOPE +- hooks/extract-guard.sh (new), lib/tests/extract-guard.test.sh (new) +- settings.json (one PreToolUse entry + one autoMode.soft_deny line, through the index) +- CLAUDE.global.md (one bullet) +- README.md / USAGE.md / templates/settings/SETTINGS.md / CHANGELOG.md (doc-sync), .claude/tasks/plans/ (plan), this contract diff --git a/.claude/tasks/plans/2026-11-04-extract-guard-2214.md b/.claude/tasks/plans/2026-11-04-extract-guard-2214.md new file mode 100644 index 0000000..ad5010b --- /dev/null +++ b/.claude/tasks/plans/2026-11-04-extract-guard-2214.md @@ -0,0 +1,66 @@ +# PLAN r3 — extract-guard (feat, contract .claude/tasks/contracts/2026-11-04-extract-guard-2214.md) + +Branch `feature/extract-guard` off develop. Pass B and design gate `[gated 2026-11-04]`: deny; watched = extraction tools + recursive `cp`; wide system roots; unresolvable destination refused; design = "simple hook + soft_deny" (user, after r1 FATAL ×3 and r2 FATAL(9)/FATAL(7)/CONCERNS(2)); `vaas-cli ssh` in both forms (`vaas-cli ssh -- ` and `vaas-cli ssh ''`); remote commands follow the local rules (a relative or absent destination passes); accepted false positive: a text that itself contains a complete extraction command into a system dir (write it `dpkg -x ` in prose). + +Why simple: a static shell parser cannot be complete (r1/r2 found 30+ forms); `ssh`, `sudo`, `su`, `eval`, `… | bash` are already denied statically in settings.json; the auto-mode classifier reads intent, so a `soft_deny` line covers what the hook cannot see. The hook targets the incident shapes and their common variants, and states its MISSES. + +PLAN: + [ ] hooks/extract-guard.sh — bash wrapper (≤ 60 lines, bash 3.2 safe: no arrays under `set -u`, no `mapfile`, no `declare -A`, no `${a[-1]}`) + one POSIX awk program (no gawk-only functions: no `gensub`, `asort`, `length(array)`, `\y`) that does all parsing and prints either nothing (allow) or one reason line (deny) + [ ] lib/tests/extract-guard.test.sh — deny/allow suite, timed flood cases, quiet corpus, plumbing, wiring assertion (run last) + [ ] settings.json — PreToolUse entry `{"matcher":"Bash|Monitor","hooks":[{"type":"command","command":"bash ~/.claude/hooks/extract-guard.sh","timeout":10}]}` after the push-guard group, AND one `autoMode.soft_deny` line (text below); index route (§ Wiring) + [ ] CLAUDE.global.md — doctrine bullet after the lftp bullet (text below) + [ ] (doc-sync) templates/settings/SETTINGS.md guardrail table row, CHANGELOG `[Unreleased]` + +## Hook flow (bash wrapper) +1. jq or awk missing → one stderr line `extract-guard: missing, guard inactive`, exit 0. +2. `cmd=$(jq -r '.tool_input.command // empty')`; empty or unparseable → exit 0. +3. Prefilter: `printf '%s' "$cmd" | grep -qE '(^|[^[:alnum:]_.-])(dpkg|dpkg-deb|tar|bsdtar|gtar|unzip|cpio|cp)([^[:alnum:]_-]|$)' || exit 0`. +4. `reason=$(printf '%s' "$cmd" | awk -f <(the program) )` — the program text is a shell variable passed with `awk "$PROG"`; rc ≠ 0 → reason `extract-guard: refused: the checker failed on a command that names ; run it yourself if it is safe: ! ` (fail closed only past the prefilter). +5. Non-empty reason → print the deny JSON with `jq -n --arg r "$reason" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:$r}}'`, exit 0; else exit 0 silently. Exactly one JSON object (test: two violations in one command → `jq -s length` is 1). + +## The awk program +- `scan(text, depth)`: tokenizes `text` into records and words; `depth > 3` with a watched word → deny `nesting too deep`. +- Tokenizer (adapted from hooks/push-guard.sh `simple_cmds` at fe7d5cd, the adaptations named in a comment): quotes removed with their content kept in the word, INCLUDING newlines (a newline inside quotes never ends a record); `\`+newline folded; records end at unquoted `;`, `&&`, `||`, `|`, `&` (not part of `>&`, `&>`, `2>&1`), newline, `(`, `)`; `<<<` is a redirection operator (no heredoc); `<<`/`<<-` reads a delimiter and the heredoc BODY text is passed to `scan(body, depth+1)` whatever command owns it; `$(…)` (balanced) and backticks: the inner text goes to `scan(inner, depth+1)` and the outer word keeps a literal `$` marker so a destination built from it is unresolvable; `#` at a word start (unquoted) starts a comment to end of line. +- Re-scan rule: every word that contains a blank or a newline (it came from quotes) is also passed to `scan(word, depth+1)` — no carrier list (covers `ssh … '…'`, `vaas-cli ssh … '…'`, `bash -c '…'`, `sudo sh -c "…"`, `timeout 9 ssh …`, `find -exec sh -c '…'`, multi-line scripts). +- Flood: more than 5000 records or 300 re-scans in total → deny `command too large to check`. +- Per record: drop redirection words (`>`, `>>`, `<`, `2>`, `&>`, `>&2`, `2>&1`, `>file`, `2>/dev/null`) and the word after a bare operator; drop find terminators `;`, `+`, `\;` and `{}`; track `cd`/`pushd` (options `-P -L --` skipped) → `DIR` (relative target joined to the previous `DIR`; empty `DIR` + relative → stays empty; `~`/`$HOME` targets → home; `cd -`, bare `cd`, `popd` → empty). `DIR` is per scan level (a nested scan starts with the caller's `DIR` and does not change it). +- For every word position k whose basename is a watched tool, run its detector on the words after k (this one rule covers wrappers `sudo`, `nice -n 10`, `stdbuf -oL`, `busybox`, `xargs`, `find -exec`, and argv-form remotes `vaas-cli ssh vm -- …`, `ssh vm sudo …`). +- Bundle = a word matching `^-[A-Za-z]+$`. +- Detectors (collect every destination; refuse if any is system or unresolvable): + - tar/bsdtar/gtar: extract when a bundle contains `x`, or the first word after the tool matches `^[A-Za-z]+$` and contains `x` (old style), or a word is `--extract` / `--get`; never when a bundle or the old-style word contains `t` or a word is `--list`. Destinations: `-C `, `-C`, a bundle ending in `C` takes the next word, `--directory `, `--directory=`. + - dpkg / dpkg-deb: a word `-x`, `-X`, `--extract`, `--vextract` (dpkg-deb also `-R`, `--raw-extract`); destination = the second non-option word after it; absent → refused. + - unzip: listing when a bundle contains `l`, `v`, `t`, `Z` or `z` → no verdict; destination `-d `, `-d`, a bundle ending in `d` takes the next word. + - cpio: extract when a bundle contains `i` and no `t`, or `--extract`; destination `-D `, `-D`, `--directory `, `--directory=`, a bundle ending in `D` takes the next word. + - cp: recursive when a bundle contains `r`, `R` or `a`, or `--recursive` / `--archive`; destination `-t `, `-t`, a bundle ending in `t` takes the next word, `--target-directory `, `--target-directory=`, else the last non-option word of the record. + - An extraction with no destination option → the destination is `DIR` when set, else no verdict (local and remote alike). +- `is_system(p)`: `~` / `~/…` / `$HOME` / `${HOME}` prefixes → replaced by `/HOME`; any other `$` or backtick → unresolvable; relative → joined to `DIR` when set, else not system; normalize (collapse `//`, drop `/.`, resolve `..`, trailing `/` stripped while length > 1); `/HOME` and below, `/var/tmp`, `/var/folders` and below → not system; system when `/` or under `/usr /etc /bin /sbin /lib /lib32 /lib64 /libx32 /boot /opt /var /srv /root /sys /proc /dev`. +- Reason text: `extract-guard: refused: writes into system directory (CLAUDE.md "Destructive tools & data loss"). List it first (dpkg -c, tar tf, unzip -l), run mktemp -d alone and extract into the literal path it prints, then use PATH or PYTHONPATH; a real system install is the user's: ! `; unresolvable: `… destination cannot be checked; write the literal path`. + +## soft_deny line (settings.json autoMode.soft_deny, appended) +`Extracting, unpacking or recursively copying a package or an archive into / or a system directory (/usr, /etc, /bin, /sbin, /lib*, /boot, /opt, /var, /srv, /root), on this machine or on a remote machine or VM (ssh, vaas-cli ssh, a script it runs): refuse; list the archive, extract into a work dir and use PATH or PYTHONPATH, or tell the user there is no package manager.` + +## Doctrine bullet (CLAUDE.global.md, after the lftp bullet) +``` +- Installing a package or an archive on a machine or a VM never extracts it + (`dpkg -x`, `tar x`, `unzip`, `cpio -i`, `cp -r`) into `/`, `/usr`, `/etc` + or another system directory: on usr-merge distributions `/bin`, `/sbin`, + `/lib`, `/lib64` are symlinks that an archive carrying those paths + replaces with real directories. List it first (`dpkg -c`, `tar tf`), + extract into a literal `mktemp -d` path and use PATH or PYTHONPATH; no + package manager on the target → say so to the user, never improvise. + `hooks/extract-guard.sh` refuses these commands. +``` + +## Wiring (LRN-253) +After the suite is green except its wiring assertion: `git show HEAD:settings.json > T`; `jq '' T > T2`; `jq -e` checks both are present in T2; `h=$(git hash-object -w T2)`; `git update-index --cacheinfo 100644,$h,settings.json`; commit. The working copy (UI writes kept) gets the same jq into a temp file, `jq -e` checked, `cp` over `settings.json` — only after the verifier and security gates pass (the hook goes live machine-wide through the `~/.claude` symlinks). Rollback: the same route with both removed. Then the wiring assertion runs green. + +## Tests (lib/tests/extract-guard.test.sh), literal commands +Deny: `dpkg -x p.deb /`; `dpkg-deb --extract p.deb /usr`; `dpkg -x p.deb`; `dpkg -x p.deb \⏎/`; `tar -xzf a.tgz -C /usr`; `tar -xf a.tar -C "/usr"`; `tar -C /usr -xzf a.tgz`; `tar -z -xvf a.tgz -C /`; `tar xzf a.tgz -C/`; `tar -xvC / -f a.tar`; `tar -xf a.tar --directory=/etc`; `tar -C /tmp/w -C / -xf a.tar`; `tar -xzf a.tgz \⏎ -C /usr`; `cd / && tar xf a.tar`; `cd / && cd usr && tar xf a.tar`; `pushd /usr && unzip a.zip`; `unzip a.zip -d '/opt'`; `unzip -od /usr a.zip`; `cpio -idm -D /usr < a.cpio`; `cd / && cpio -vidm < a.cpio`; `cp -r build /opt/app`; `cp -r build /opt/app 2>/dev/null`; `cp -rt /usr/lib src`; `cp -a src "/usr/local/x"`; `find dist -exec cp -r {} /var/www/html \;`; `ssh vm 'dpkg -x p.deb /'`; `ssh -i k -p 2222 root@vm 'tar -xf /tmp/a.tar -C /'`; `vaas-cli ssh vm -- tar -xzf a.tgz -C /usr`; `vaas-cli ssh vm 'dpkg -x /tmp/p.deb /'`; `vaas-cli ssh vm "⏎set -e⏎cd /⏎tar xf /tmp/a.tar⏎"` (multi-line); `bash -c "cd /usr/lib && unzip a.zip"`; `sudo sh -c 'cd / && tar xzf /tmp/a.tgz'`; `timeout 600 vaas-cli ssh vm 'dpkg -x p.deb /'`; `ssh vm bash -s <<'EOF' 2>&1 | tail -5⏎tar -xf a.tar -C /⏎EOF`; `grep -q ok <<< "$x"⏎tar -xf a.tar -C /`; `tar -xf $(ls *.tar) -C /`; ``tar -xf `ls *.tar` -C /usr``; `out="$(vaas-cli ssh vm 'dpkg -x /tmp/p.deb /')"`; `tar -xf a.tar -C "$DEST"`; `tar -xf a.tar -C ~/../../usr`; `stdbuf -oL tar -xf a.tar -C /`; `busybox tar -xf a.tar -C /`; `for f in *.deb; do dpkg -x $f /; done`; two violations in one command (one JSON object); a 5001-record flood with one `tar` word (deny under 2 s). +Allow: `tar -C /tmp/x -xf a.tar`; `tar -cf /tmp/a.tar /usr`; `tar tf a.tar`; `tar -tvf a.tar -C /`; `tar -xf a.tar`; `tar -xf a.tar -C ~/x`; `tar -xf a.tar -C "$HOME/x"`; `tar -xf a.tar -C /var/folders/ab/T/tmp.X`; `tar -xf a.tar -C /var/tmp/w`; `dpkg -c p.deb`; `dpkg -R -i debs/`; `unzip -l a.zip`; `unzip -Z1 a.zip`; `cpio -itv < a.cpio`; `unzip a.zip -d build`; `cp a.txt /etc/hosts`; `cp -r src dist`; `cp --parents a /tmp/x`; `cp -r a b > /dev/null`; `grep -rn "dpkg -x" docs`; `echo "tar xf a"`; `vaas-cli ssh vm 'tar -xf a.tar -C /tmp/w'`; `vaas-cli ssh vm 'unzip a.zip -d build'`; `vaas-cli ssh vm 'command -v unzip || sudo apt-get install -y unzip'`; `sudo apt install tar xz-utils`; `git commit -m "doc: list an archive with tar tf before extracting"`; `bash ~/.claude/lib/memory.sh add learning --title "dpkg -x into a system dir breaks usr-merge" --body-file /tmp/b`; a quiet corpus of 20 ordinary commands (jq filters, awk scripts, a heredoc commit, `echo "a" "b"`, `ls /usr/lib | grep tar`) → silent rc 0; a 5000-line text without watched words → allow under 1 s; 299 `bash -c 'cp -r a b'` records → allow under 3 s. +Plumbing: jq missing (PATH shim) → rc 0 + one stderr line; deny output parses with `permissionDecision == "deny"`; allowed commands print nothing; the suite also runs the hook under `/bin/sh`-free paths only (the hook is invoked with `bash`); wiring assertion (last): committed settings.json holds the `Bash|Monitor` entry and the soft_deny line. + +## MISSES (header comment) +A destination built at runtime outside the text (script file, Makefile, alias, variable set in an earlier call); option values swallowed by the "watched word anywhere" rule; old-style tar `C` letter (`tar xfC a.tar /usr`), getopt_long abbreviations (`--dir=`), `--one-top-level=`; archive members escaping a safe `-C` (`../../usr`, `-P`) — the doctrine's "list first" covers them; an extraction with no destination run from a remote shell whose cwd is a system dir. The soft_deny line is the net for these. + +## Disposition +Honors BDR-095 (layer C static refusal), BDR-090 (soft_deny for what static rules miss; deny over inert ask), BDR-111/112 (deny shape, `Bash|Monitor` matcher, a ruling: push-guard precedent, the contract's "matcher Bash" read as the floor), BLK-022 (narrow hook; guard-bash spec untouched), BLK-026 (bash 3.2: logic in POSIX awk), LRN-253 + BDR-131 (index route, UI writes kept), LRN-196 (timeout 10), LRN-199 (quoted prose of ordinary commands only denied when it holds a complete extraction into a system dir: accepted FP), LRN-201 (timed flood tests), BDR-100 (bullet adds no heading). EVAL-057: the adapted tokenizer names push-guard fe7d5cd.