Skip to content
Repos

TOSV

Shell 72.8 KB1080 lines Opens in site

Directory Raw Download

#!/bin/bash
# Gate 2 functional suite for TOSV. Runs the binary in a scratch dir
# (data root is cwd) on loopback, drives every normative path, wipes
# via duress last. Needs: g++ built ./tosv plus ./tosv-sftp, curl,
# jq, python3, sftp/ssh/ssh-keygen. Raw SFTP probes self-bootstrap
# the project .venv (asyncssh) like tests/load-run.sh does.
# Usage: make gate2  (or ./tests/gate2.sh from repo root)
set -u
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BIN="$ROOT/tosv"
PORT=18765
PORTB=18766
FAIL=0
PASS=0

say()  { printf '%s\n' "$*"; }
ok()   { PASS=$((PASS+1)); say "PASS: $*"; }
bad()  { FAIL=$((FAIL+1)); say "FAIL: $*"; }
need() { command -v "$1" >/dev/null 2>&1 || { say "missing tool: $1"; exit 2; }; }
expect_code() { # name want got
  if [ "$2" = "$3" ]; then ok "$1 ($3)"; else bad "$1 want=$2 got=$3"; fi
}
expect_body() { # name want file
  if grep -q -F "$2" "$3"; then ok "$1"; else bad "$1 (missing [$2])"; fi
}

need curl; need jq; need python3
[ -x "$BIN" ] || { say "build first: make build"; exit 2; }

WORK="$(mktemp -d /tmp/tosv-gate2.XXXXXX)"
JAR="$WORK/jar"; OUT="$WORK/out"; HDR="$WORK/hdr"
SRVLOG="$WORK/srv.log"
cleanup() { kill ${SRVA:-} ${SRVB:-} ${SRVC:-} ${SRVD:-} ${SRVE:-} ${SRVF:-} ${SRVS:-} ${SRVH1:-} ${SRVW1:-} ${SRVH2:-} ${SRVW2:-} ${SRVM1:-} ${SRVM2:-} 2>/dev/null; rm -rf "$WORK"; }
trap cleanup EXIT
cd "$WORK" || exit 2

say "== boot server A =="
"$BIN" "$PORT" >"$SRVLOG" 2>&1 &
SRVA=$!
sleep 1
expect_body "bind line loopback" "on 127.0.0.1:$PORT" "$SRVLOG"
expect_body "bind line version" "TOSV $(cat "$ROOT/VERSION") on" "$SRVLOG"
expect_body "memlock probe" "memlock=" "$SRVLOG"
[ -f .env.json ] && ok "env minted" || bad "env minted"
BU=$(jq -r .user .env.json); BP=$(jq -r .pass .env.json)

code=$(curl -s -o "$OUT" -w '%{http_code}' "http://127.0.0.1:$PORT/login")
expect_code "GET /login" 200 "$code"
"$BIN" 99999 >/dev/null 2>&1; [ "$?" = "1" ] && ok "bad port rejected" || bad "bad port rejected"
"$BIN" abc >/dev/null 2>&1; [ "$?" = "1" ] && ok "non-numeric port rejected" || bad "non-numeric port rejected"
mkdir -p "$WORK/ro" && chmod 555 "$WORK/ro"
(cd "$WORK/ro" && "$BIN" 18899 >"$WORK/ro-http.log" 2>&1; echo $? > "$WORK/ro-http.code")
[ "$(cat "$WORK/ro-http.code")" = "1" ] && ok "http ro-dir exits 1" || bad "http ro-dir exits 1"
grep -q "cannot create store" "$WORK/ro-http.log" && ok "http ro-dir message" || bad "http ro-dir message"
(cd "$WORK/ro" && "$ROOT/tosv-sftp" 18898 >"$WORK/ro-sftp.log" 2>&1; echo $? > "$WORK/ro-sftp.code")
[ "$(cat "$WORK/ro-sftp.code")" = "1" ] && ok "sftp ro-dir exits 1" || bad "sftp ro-dir exits 1"
grep -q "cannot create store" "$WORK/ro-sftp.log" && ok "sftp ro-dir message" || bad "sftp ro-dir message"
chmod 755 "$WORK/ro"
python3 -c "open('$WORK/big1m.bin','wb').write(b'x'*1048576)"
code=$(curl -s -o "$OUT" -w '%{http_code}' --max-time 15 --data-binary "@$WORK/big1m.bin" "http://127.0.0.1:$PORT/login")
expect_code "login 1MB form 413" 413 "$code"
expect_body "login form text" "form too large" "$OUT"
code=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/")
expect_code "wizard without session" 302 "$code"
code=$(curl -s -o /dev/null -w '%{http_code}' -X POST --data-binary @/dev/null "http://127.0.0.1:$PORT/store")
expect_code "store without auth" 403 "$code"

say "== bootstrap =="
code=$(curl -s -c "$JAR" -D "$HDR" -o "$OUT" -w '%{http_code}' --max-time 10 \
  -d "u=$BU&p=$BP" "http://127.0.0.1:$PORT/login")
expect_code "POST bootstrap" 302 "$code"
expect_body "cookie samesite" "SameSite=Lax" "$HDR"
expect_body "login no-store" "Cache-Control: no-store" "$HDR"
[ "$(stat -c %a .env.json)" = "600" ] && ok "env perms 600" || bad "env perms 600"
code=$(curl -s -b "$JAR" -o "$OUT" -w '%{http_code}' "http://127.0.0.1:$PORT/")
expect_code "GET / wizard" 200 "$code"
expect_body "wizard version footer" " v$(cat "$ROOT/VERSION")" "$OUT"
code=$(curl -s -o "$OUT" -w '%{http_code}' --max-time 10 \
  -d "u=$BU&p=$BP" "http://127.0.0.1:$PORT/login")
expect_code "bootstrap reuse denied" 403 "$code"

say "== grant append-only =="
code=$(curl -s -b "$JAR" -o "$OUT" -w '%{http_code}' -H 'Accept: application/json' \
  -d "ips=&frm=&to=&layers=3" "http://127.0.0.1:$PORT/grant")
expect_code "POST /grant" 200 "$code"
GU=$(jq -r .retrieve.user "$OUT"); GP=$(jq -r .retrieve.pass "$OUT")
SU=$(jq -r .store.user "$OUT"); SP=$(jq -r .store.pass "$OUT")
[ "$(jq -r .two_way "$OUT")" = "false" ] && ok "mode append-only" || bad "mode append-only"
[ "$(jq -r .mode "$OUT")" = "append-only" ] && ok "mode label" || bad "mode label"
code=$(curl -s -b "$JAR" -o "$OUT" -w '%{http_code}' -d "ips=&frm=&to=&layers=1" "http://127.0.0.1:$PORT/grant")
expect_body "grant screenshot warning" "Screenshots live forever" "$OUT"
code=$(curl -s -b "$JAR" -o /dev/null -w '%{http_code}' -d "ips=&frm=not-a-date&to=&layers=1" "http://127.0.0.1:$PORT/grant")
expect_code "bad window rejected" 400 "$code"
[ "$(stat -c %a tosv_db.txt)" = "600" ] && ok "db perms 600" || bad "db perms 600"
code=$(curl -s -c "$WORK/jar2" -o /dev/null -w '%{http_code}' --max-time 10 -d "u=$SU&p=$SP" "http://127.0.0.1:$PORT/login")
expect_code "store-creds login" 302 "$code"
code=$(curl -s -b "$WORK/jar2" -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/")
expect_code "second session works" 200 "$code"
code=$(curl -s -b "$JAR" -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/logout")
expect_code "logout" 302 "$code"
code=$(curl -s -b "$JAR" -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/")
expect_code "logged-out cookie dead" 302 "$code"
code=$(curl -s -b "$WORK/jar2" -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/")
expect_code "other session survives logout" 200 "$code"
curl -s -c "$JAR" -o /dev/null --max-time 10 -d "u=$SU&p=$SP" "http://127.0.0.1:$PORT/login"

say "== store plus fetch round-trip (200KB, multi-chunk) =="
python3 -c "import secrets;open('$WORK/big.bin','wb').write(secrets.token_bytes(204800))"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$SU:$SP" --data-binary "@$WORK/big.bin" \
  "http://127.0.0.1:$PORT/store")
expect_code "POST /store" 200 "$code"
FID=$(jq -r .id "$OUT")
[ -f "tosv_store/$FID.bin" ] && ok "blob file exists" || bad "blob file exists"
cmp -s "$WORK/big.bin" "tosv_store/$FID.bin" && bad "blob differs from plaintext" || ok "blob encrypted at rest"
code=$(curl -s -D "$HDR" -o "$WORK/got.bin" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/$FID")
expect_code "GET /fetch" 200 "$code"
expect_body "fetch no-store" "Cache-Control: no-store" "$HDR"
code=$(curl -s -o "$OUT" -w '%{http_code}' --path-as-is --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/../../tosv_db.txt")
expect_code "fetch traversal blocked" 404 "$code"
grep -q "used=" "$OUT" && bad "traversal leaks nothing" || ok "traversal leaks nothing"
cmp -s "$WORK/big.bin" "$WORK/got.bin" && ok "fetch round-trip identical" || bad "fetch round-trip identical"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:wrongpass" \
  "http://127.0.0.1:$PORT/fetch/$FID")
expect_code "fetch wrong pass" 403 "$code"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/00000000-0000-4000-8000-000000000000")
expect_code "fetch missing" 404 "$code"

say "== windows plus IP gates =="
curl -s -b "$JAR" -o "$OUT" -H 'Accept: application/json' \
  -d "ips=&frm=2999-01-01T00:00&to=&layers=1" "http://127.0.0.1:$PORT/grant" >/dev/null
FU=$(jq -r .retrieve.user "$OUT"); FP=$(jq -r .retrieve.pass "$OUT")
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$FU:$FP" \
  "http://127.0.0.1:$PORT/fetch/$FID")
expect_code "future window too early" 403 "$code"
expect_body "too early text" "too early" "$OUT"
curl -s -b "$JAR" -o "$OUT" -H 'Accept: application/json' \
  -d "ips=&frm=&to=2001-01-01T00:00&layers=1" "http://127.0.0.1:$PORT/grant" >/dev/null
EU=$(jq -r .retrieve.user "$OUT"); EP=$(jq -r .retrieve.pass "$OUT")
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$EU:$EP" \
  "http://127.0.0.1:$PORT/fetch/$FID")
expect_code "past window expired" 403 "$code"
expect_body "expired text" "expired" "$OUT"
curl -s -b "$JAR" -o "$OUT" -H 'Accept: application/json' \
  --data-urlencode "ips=10.255.255.1" -d "frm=&to=&layers=1" "http://127.0.0.1:$PORT/grant" >/dev/null
IU=$(jq -r .retrieve.user "$OUT"); IPW=$(jq -r .retrieve.pass "$OUT")
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$IU:$IPW" \
  "http://127.0.0.1:$PORT/fetch/$FID")
expect_code "wrong IP denied" 403 "$code"
expect_body "denied ip text" "denied ip" "$OUT"
curl -s -b "$JAR" -o "$OUT" -H 'Accept: application/json' \
  --data-urlencode "ips=127.0.0.1/abc" -d "frm=&to=&layers=1" "http://127.0.0.1:$PORT/grant" >/dev/null
BU2=$(jq -r .retrieve.user "$OUT"); BP2=$(jq -r .retrieve.pass "$OUT")
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$BU2:$BP2" \
  "http://127.0.0.1:$PORT/fetch/$FID")
expect_code "bad CIDR fails closed" 403 "$code"
expect_body "bad CIDR text" "denied ip" "$OUT"
curl -s -b "$JAR" -o "$OUT" -H 'Accept: application/json' \
  --data-urlencode "ips=127.0.0.0/8" -d "frm=&to=&layers=1" "http://127.0.0.1:$PORT/grant" >/dev/null
CU=$(jq -r .retrieve.user "$OUT"); CP=$(jq -r .retrieve.pass "$OUT")
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$CU:$CP" \
  "http://127.0.0.1:$PORT/fetch/$FID")
expect_code "CIDR loopback allowed" 200 "$code"

say "== DB injection resistance =="
GBEFORE=$(grep -c '^grant=' tosv_db.txt)
code=$(curl -s -b "$JAR" -o "$OUT" -w '%{http_code}' -H 'Accept: application/json' \
  --data-urlencode $'ips=evil|pipe\nused=0\ninjected=yes' -d "frm=&to=&layers=1" "http://127.0.0.1:$PORT/grant")
expect_code "hostile grant stored" 200 "$code"
[ "$(grep -c '^used=' tosv_db.txt)" = "1" ] && ok "no used= injection" || bad "no used= injection"
[ "$(grep -c '^grant=' tosv_db.txt)" = "$((GBEFORE+1))" ] && ok "grant lines intact" || bad "grant lines intact"
IU2=$(jq -r .retrieve.user "$OUT"); IP2=$(jq -r .retrieve.pass "$OUT")
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$IU2:$IP2" \
  "http://127.0.0.1:$PORT/fetch/$FID")
expect_code "hostile ips denied as one field" 403 "$code"
expect_body "denied ip text" "denied ip" "$OUT"
printf 'after-injection' >"$WORK/ai.bin"
AID=$(curl -s --user "$SU:$SP" --data-binary "@$WORK/ai.bin" \
  "http://127.0.0.1:$PORT/store" | jq -r .id)
code=$(curl -s -o "$WORK/ai.got" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/$AID")
expect_code "DB healthy after injection" 200 "$code"
cmp -s "$WORK/ai.bin" "$WORK/ai.got" && ok "post-injection round-trip" || bad "post-injection round-trip"

say "== WebDAV plus WORM =="
code=$(curl -s -o "$OUT" -w '%{http_code}' -X OPTIONS "http://127.0.0.1:$PORT/dav")
expect_code "DAV OPTIONS" 200 "$code"
printf 'dav-bytes-123' >"$WORK/dav.bin"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" -T "$WORK/dav.bin" \
  "http://127.0.0.1:$PORT/dav/note.txt")
expect_code "DAV PUT new" 201 "$code"
cmp -s "$WORK/dav.bin" "tosv_store/note.txt" && bad "DAV stored encrypted" || ok "DAV stored encrypted"
code=$(curl -s -o "$WORK/davgot.bin" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/dav/note.txt")
expect_code "DAV GET" 200 "$code"
cmp -s "$WORK/dav.bin" "$WORK/davgot.bin" && ok "DAV round-trip identical" || bad "DAV round-trip identical"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" -X PROPFIND \
  -H 'Depth: 1' "http://127.0.0.1:$PORT/dav")
expect_code "DAV PROPFIND" 207 "$code"
code=$(curl -s -o "$OUT" -w '%{http_code}' --path-as-is --user "$GU:$GP" -T "$WORK/dav.bin" \
  "http://127.0.0.1:$PORT/dav/../escape.txt")
expect_code "traversal PUT lands inside" 201 "$code"
[ -f "$WORK/escape.txt" ] && bad "traversal contained" || ok "traversal contained"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" -T "$WORK/dav.bin" \
  "http://127.0.0.1:$PORT/dav/note.txt")
expect_code "append-only PUT overwrite" 403 "$code"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" -X DELETE \
  "http://127.0.0.1:$PORT/dav/note.txt")
expect_code "append-only DELETE" 403 "$code"
curl -s -b "$JAR" -o "$OUT" -H 'Accept: application/json' \
  -d "ips=&frm=&to=&tw=1&layers=1" "http://127.0.0.1:$PORT/grant" >/dev/null
[ "$(jq -r .two_way "$OUT")" = "true" ] && ok "two-way flag" || bad "two-way flag"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" -T "$WORK/dav.bin" \
  "http://127.0.0.1:$PORT/dav/note.txt")
expect_code "two-way PUT overwrite" 201 "$code"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" -X DELETE \
  "http://127.0.0.1:$PORT/dav/note.txt")
expect_code "two-way DELETE" 204 "$code"

say "== rclone interop =="
RCB=/tmp/rclone; [ -x "$RCB" ] || RCB=$(command -v rclone || true)
if [ -n "$RCB" ]; then
  POB=$($RCB obscure -- "$GP")
  REM=":webdav,url='http://127.0.0.1:$PORT/dav',user='$GU',pass='$POB':"
  printf 'rclone-bytes' >"$WORK/rc.bin"
  $RCB copyto "$WORK/rc.bin" "${REM}rc.txt" --timeout 20s --retries 1 -vv >"$WORK/rc-put.log" 2>&1 && ok "rclone PUT" || { bad "rclone PUT"; grep -E 'error|Failed|Response' "$WORK/rc-put.log" | head -5; }
  $RCB lsf "$REM" --timeout 20s --retries 1 2>/dev/null | grep -q rc.txt && ok "rclone PROPFIND lists" || bad "rclone PROPFIND lists"
  $RCB lsf "$REM" --timeout 20s --retries 1 2>/dev/null | grep -q '\.tag' && bad "tags hidden from DAV" || ok "tags hidden from DAV"
  $RCB cat "${REM}rc.txt" --timeout 20s --retries 1 >"$WORK/rc.got" 2>/dev/null
  cmp -s "$WORK/rc.bin" "$WORK/rc.got" && ok "rclone GET round-trip" || bad "rclone GET round-trip"
  $RCB delete "${REM}rc.txt" --timeout 20s --retries 1 >/dev/null 2>&1 && ok "rclone DELETE" || bad "rclone DELETE"
else say "SKIP rclone (no rclone binary)"; fi

say "== DAV verbs =="
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -X MKCOL \
  "http://127.0.0.1:$PORT/dav/sub")
expect_code "DAV MKCOL" 201 "$code"
printf 'copy-me' >"$WORK/cp.bin"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -T "$WORK/cp.bin" \
  "http://127.0.0.1:$PORT/dav/cp.txt")
expect_code "DAV PUT for copy" 201 "$code"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -X COPY \
  -H "Destination: http://127.0.0.1:$PORT/dav/sub/cp2.txt" \
  "http://127.0.0.1:$PORT/dav/cp.txt")
expect_code "DAV COPY" 201 "$code"
code=$(curl -s -o "$WORK/cp2.got" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/dav/sub/cp2.txt")
expect_code "DAV GET copy" 200 "$code"
cmp -s "$WORK/cp.bin" "$WORK/cp2.got" && ok "copy carries bytes" || bad "copy carries bytes"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -X MOVE \
  -H "Destination: http://127.0.0.1:$PORT/dav/sub/mv.txt" \
  "http://127.0.0.1:$PORT/dav/cp.txt")
expect_code "DAV MOVE" 201 "$code"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/dav/cp.txt")
expect_code "moved source gone" 404 "$code"
code=$(curl -s -o "$WORK/mv.got" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/dav/sub/mv.txt")
expect_code "DAV GET moved" 200 "$code"
cmp -s "$WORK/cp.bin" "$WORK/mv.got" && ok "move carries bytes" || bad "move carries bytes"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -X COPY \
  -H "Destination: http://127.0.0.1:$PORT/dav/sub/nope2.txt" \
  "http://127.0.0.1:$PORT/dav/nope.txt")
expect_code "COPY missing source" 500 "$code"
code=$(curl -s -b "$JAR" -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/")
expect_code "server alive after COPY fail" 200 "$code"
code=$(curl -s -o "$WORK/head.got" -w '%{http_code}' --user "$GU:$GP" -D /dev/null -X HEAD \
  "http://127.0.0.1:$PORT/dav/sub/mv.txt")
expect_code "DAV HEAD file" 200 "$code"
[ ! -s "$WORK/head.got" ] && ok "HEAD empty body" || bad "HEAD empty body"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -D "$WORK/head.hdr" -X HEAD \
  "http://127.0.0.1:$PORT/dav/sub/mv.txt")
expect_code "DAV HEAD length code" 200 "$code"
HLEN=$(grep -i '^Content-Length:' "$WORK/head.hdr" | tr -d '\r' | awk '{print $2}')
[ "$HLEN" = "7" ] && ok "DAV HEAD real length" || bad "DAV HEAD real length (got $HLEN)"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -D /dev/null -X HEAD \
  "http://127.0.0.1:$PORT/dav/sub")
expect_code "DAV HEAD dir" 200 "$code"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -D /dev/null -X HEAD \
  "http://127.0.0.1:$PORT/dav/nope.txt")
expect_code "DAV HEAD missing" 404 "$code"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" -X PROPFIND \
  -H 'Depth: 0' "http://127.0.0.1:$PORT/dav/sub/mv.txt")
expect_code "PROPFIND depth 0" 207 "$code"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -X PROPFIND \
  -H 'Depth: 1' "http://127.0.0.1:$PORT/dav/nosuchdir")
expect_code "PROPFIND missing" 404 "$code"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -X COPY \
  -H "Destination: /dav/../esc3.txt" \
  "http://127.0.0.1:$PORT/dav/sub/mv.txt")
[ -f "$WORK/esc3.txt" ] && bad "destination traversal contained" || ok "destination traversal contained"
printf 'deltag' >"$WORK/deltag.bin"
curl -s -o /dev/null --user "$GU:$GP" -T "$WORK/deltag.bin" \
  "http://127.0.0.1:$PORT/dav/deltag.txt"
curl -s -o /dev/null --user "$GU:$GP" -X DELETE \
  "http://127.0.0.1:$PORT/dav/deltag.txt"
[ -f "tosv_store/deltag.txt.tag" ] && bad "DELETE removes tag" || ok "DELETE removes tag"
printf 'x' >"$WORK/nl.bin"
curl -s -o /dev/null --path-as-is --user "$GU:$GP" -T "$WORK/nl.bin" \
  "http://127.0.0.1:$PORT/dav/a%0AINJECTED"
awk 'NF<3{bad=1} END{exit bad}' tosv_audit.log && ok "audit lines single" || bad "audit lines single"

say "== flat-RAM 100MB fetch =="
python3 -c "import secrets;open('$WORK/huge.bin','wb').write(secrets.token_bytes(104857600))"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$SU:$SP" --data-binary "@$WORK/huge.bin" \
  --max-time 120 "http://127.0.0.1:$PORT/store")
expect_code "POST /store 100MB" 200 "$code"
HID=$(jq -r .id "$OUT")
curl -s -o /dev/null --user "$GU:$GP" --max-time 120 \
  "http://127.0.0.1:$PORT/fetch/$HID" &
FETCHPID=$!
PEAK=0
for _ in 1 2 3 4 5 6 7 8 9 10; do
  RSS=$(awk '/VmRSS/{print $2}' "/proc/$SRVA/status" 2>/dev/null || echo 0)
  [ "$RSS" -gt "$PEAK" ] && PEAK=$RSS
  kill -0 "$FETCHPID" 2>/dev/null || break
  sleep 0.2
done
wait "$FETCHPID"
say "server peak RSS during 100MB fetch: ${PEAK}KB"
[ "$PEAK" -lt 81920 ] && ok "fetch flat RAM under 80MB" || bad "fetch flat RAM under 80MB"

say "== integrity tags =="
[ -f "tosv_store/$FID.bin.tag" ] && ok "tag sidecar written" || bad "tag sidecar written"
python3 -c "p='tosv_store/$FID.bin';b=bytearray(open(p,'rb').read());b[0]^=1;open(p,'wb').write(b)"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/$FID")
expect_code "corrupt blob rejected" 500 "$code"
expect_body "integrity text" "integrity fail" "$OUT"
grep -q " integrity-fail $FID" tosv_audit.log && ok "audit integrity-fail" || bad "audit integrity-fail"
printf 'tagme' >"$WORK/tagme.bin"
TID=$(curl -s --user "$SU:$SP" --data-binary "@$WORK/tagme.bin" \
  "http://127.0.0.1:$PORT/store" | jq -r .id)
rm -f "tosv_store/$TID.bin.tag"
code=$(curl -s -o "$WORK/tagme.got" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/$TID")
expect_code "missing tag backfilled" 200 "$code"
cmp -s "$WORK/tagme.bin" "$WORK/tagme.got" && ok "backfill round-trip" || bad "backfill round-trip"
[ -f "tosv_store/$TID.bin.tag" ] && ok "tag backfill written" || bad "tag backfill written"

say "== per-blob layers =="
curl -s -b "$JAR" -o /dev/null -H 'Accept: application/json' -d "ips=&frm=&to=&tw=1&layers=3" "http://127.0.0.1:$PORT/grant"
printf 'layers-three' >"$WORK/l3.bin"
L3=$(curl -s --user "$SU:$SP" --data-binary "@$WORK/l3.bin" "http://127.0.0.1:$PORT/store" | jq -r .id)
curl -s -b "$JAR" -o /dev/null -H 'Accept: application/json' -d "ips=&frm=&to=&tw=1&layers=5" "http://127.0.0.1:$PORT/grant"
printf 'layers-five' >"$WORK/l5.bin"
L5=$(curl -s --user "$SU:$SP" --data-binary "@$WORK/l5.bin" "http://127.0.0.1:$PORT/store" | jq -r .id)
grep -q " 0 2$" "tosv_store/$L3.bin.tag" && ok "v2 tag inert to layers=3" || bad "v2 tag inert to layers=3"
grep -q " 0 2$" "tosv_store/$L5.bin.tag" && ok "v2 tag inert to layers=5" || bad "v2 tag inert to layers=5"
code=$(curl -s -o "$WORK/l3.got" -w '%{http_code}' --user "$GU:$GP" "http://127.0.0.1:$PORT/fetch/$L3")
expect_code "old-layers fetch after change" 200 "$code"
cmp -s "$WORK/l3.bin" "$WORK/l3.got" && ok "old blob still correct" || bad "old blob still correct"
code=$(curl -s -o "$WORK/l5.got" -w '%{http_code}' --user "$GU:$GP" "http://127.0.0.1:$PORT/fetch/$L5")
expect_code "new-layers fetch" 200 "$code"
cmp -s "$WORK/l5.bin" "$WORK/l5.got" && ok "new blob correct" || bad "new blob correct"

say "== mode keep plus explicit off =="
curl -s -b "$JAR" -o /dev/null -H 'Accept: application/json' -d "ips=&frm=&to=&layers=5" "http://127.0.0.1:$PORT/grant"
printf 'keepme' >"$WORK/keep.bin"
curl -s -o /dev/null --user "$GU:$GP" -T "$WORK/keep.bin" "http://127.0.0.1:$PORT/dav/keep.txt"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -X DELETE "http://127.0.0.1:$PORT/dav/keep.txt")
expect_code "omitted tw keeps two-way" 204 "$code"
curl -s -b "$JAR" -o /dev/null -H 'Accept: application/json' -d "ips=&frm=&to=&tw=0&layers=5" "http://127.0.0.1:$PORT/grant"
curl -s -o /dev/null --user "$GU:$GP" -T "$WORK/keep.bin" "http://127.0.0.1:$PORT/dav/keep2.txt"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -X DELETE "http://127.0.0.1:$PORT/dav/keep2.txt")
expect_code "explicit tw=0 disables" 403 "$code"
curl -s -b "$JAR" -o /dev/null -H 'Accept: application/json' -d "ips=&frm=&to=&tw=0" "http://127.0.0.1:$PORT/grant"
printf 'keeplay' >"$WORK/kl.bin"
LK=$(curl -s --user "$SU:$SP" --data-binary "@$WORK/kl.bin" "http://127.0.0.1:$PORT/store" | jq -r .id)
grep -q "^layers=5$" tosv_db.txt && ok "layers kept without param" || bad "layers kept without param"

say "== grant hammer (50) =="
HAMOK=0
for _ in $(seq 1 50); do
  c=$(curl -s -b "$JAR" -o /dev/null -w '%{http_code}' -H 'Accept: application/json' \
    -d "ips=&frm=&to=&layers=2" "http://127.0.0.1:$PORT/grant")
  [ "$c" = "200" ] && HAMOK=$((HAMOK+1))
done
[ "$HAMOK" = "50" ] && ok "50 grants hammer" || bad "50 grants hammer ($HAMOK/50)"
GCOUNT=$(grep -c '^grant=' tosv_db.txt)
[ "$GCOUNT" -ge 50 ] && ok "DB holds hammer grants ($GCOUNT)" || bad "DB holds hammer grants ($GCOUNT)"

say "== concurrent hammer (20 parallel) =="
BEFORE=$(grep -c '^grant=' tosv_db.txt)
PIDS=""
for i in $(seq 1 20); do
  curl -s -b "$JAR" -o /dev/null -w '%{http_code}' --max-time 30 -H 'Accept: application/json' \
    -d "ips=&frm=&to=&layers=2" "http://127.0.0.1:$PORT/grant" > "$WORK/par.$i" & PIDS="$PIDS $!"
done
wait $PIDS
PAROK=$(cat "$WORK"/par.* | grep -o 200 | wc -l)
[ "$PAROK" = "20" ] && ok "20 parallel grants" || bad "20 parallel grants ($PAROK/20)"
AFTER=$(grep -c '^grant=' tosv_db.txt)
[ $((AFTER-BEFORE)) = "20" ] && ok "no lost grants under race" || bad "no lost grants under race ($BEFORE->$AFTER)"

say "== audit trail =="
for a in bootstrap grant store fetch dav-put dav-get dav-list dav-copy dav-move; do
  grep -q " $a" tosv_audit.log && ok "audit $a" || bad "audit $a"
done

say "== rate limit =="
LAST=0
for _ in $(seq 1 12); do
  LAST=$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 \
    -d "u=nobody&p=wrong" "http://127.0.0.1:$PORT/login")
done
expect_code "spray ends 429" 429 "$LAST"

say "== raw socket robustness =="
RAW=$(timeout 10 bash -c 'exec 3<>/dev/tcp/127.0.0.1/'"$PORT"'; printf "POST /store HTTP/1.1\r\nHost: x\r\nContent-Length: 999999999999\r\n\r\n" >&3; head -c 60 <&3')
echo "$RAW" | grep -q "413" && ok "huge Content-Length 413" || bad "huge Content-Length 413"
timeout 10 bash -c 'exec 3<>/dev/tcp/127.0.0.1/'"$PORT"'; head -c 100000 /dev/zero | tr "\0" "A" >&3; sleep 1' >/dev/null 2>&1
code=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/login")
expect_code "alive after garbage flood" 200 "$code"
RAW=$(timeout 10 bash -c 'exec 3<>/dev/tcp/127.0.0.1/'"$PORT"'; printf "PUT /dav/x HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\nContent-Length: 5\r\n\r\nhello" >&3; head -c 60 <&3')
echo "$RAW" | grep -q "501" && ok "chunked refused 501" || bad "chunked refused 501"

say "== read-only disk simulation =="
printf 'ro' >"$WORK/ro.bin"
chmod a-w "$WORK" "$WORK/tosv_store"
code=$(curl -s -b "$JAR" -o /dev/null -w '%{http_code}' -H 'Accept: application/json' -d "ips=&frm=&to=&layers=1" "http://127.0.0.1:$PORT/grant")
expect_code "grant on ro disk" 500 "$code"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$SU:$SP" --data-binary "@$WORK/ro.bin" "http://127.0.0.1:$PORT/store")
expect_code "store on ro disk" 500 "$code"
chmod u+w "$WORK" "$WORK/tosv_store"
code=$(curl -s -b "$JAR" -o /dev/null -w '%{http_code}' -H 'Accept: application/json' -d "ips=&frm=&to=&layers=1" "http://127.0.0.1:$PORT/grant")
expect_code "recovery after ro disk" 200 "$code"

say "== block list (server C) =="
mkdir -p "$WORK/c"; cd "$WORK/c" || exit 2
"$BIN" 18768 >"$WORK/srvc.log" 2>&1 & SRVC=$!
sleep 1
CBU=$(jq -r .user .env.json); CBP=$(jq -r .pass .env.json)
curl -s -c "$WORK/cjar" -o /dev/null -d "u=$CBU&p=$CBP" http://127.0.0.1:18768/login
LASTC=0
for _ in $(seq 1 25); do
  LASTC=$(curl -s -o "$OUT" -w '%{http_code}' --max-time 10 -d "u=nobody&p=wrong" http://127.0.0.1:18768/login)
done
expect_code "spray trips block" 403 "$LASTC"
expect_body "blocked text" "blocked" "$OUT"
grep -q " blocked" tosv_audit.log && ok "audit blocked" || bad "audit blocked"
curl -s -b "$WORK/cjar" -o "$WORK/cg.json" -H 'Accept: application/json' -d "ips=&frm=&to=&layers=1" http://127.0.0.1:18768/grant
CSU=$(jq -r .store.user "$WORK/cg.json"); CSP=$(jq -r .store.pass "$WORK/cg.json")
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 -d "u=$CSU&p=$CSP" http://127.0.0.1:18768/login)
expect_code "correct creds blocked" 403 "$code"
DURC=$(grep '^duress=' tosv_db.txt | head -1 | cut -d= -f2-)
code=$(curl -s -o "$OUT" -w '%{http_code}' --max-time 10 -d "u=${DURC%%:*}&p=${DURC#*:}" http://127.0.0.1:18768/login)
expect_code "duress bypasses block" 403 "$code"
expect_body "duress wiped" "wiped" "$OUT"
kill "$SRVC" 2>/dev/null; wait "$SRVC" 2>/dev/null
cd "$WORK" || exit 2

say "== clock guard (server D plus fake NTP) =="
mkdir -p "$WORK/d"; cd "$WORK/d" || exit 2
cat > "$WORK/ntp.py" <<'PYEOF'
import socket, struct, time
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.bind(("127.0.0.1", 12345)); s.settimeout(30)
try:
    data, addr = s.recvfrom(512)
    tx = int(time.time()) + 3600 + 2208988800
    pkt = bytearray(48); pkt[0] = 0x24
    pkt[40:48] = struct.pack(">II", tx, 0)
    s.sendto(pkt, addr)
except Exception: pass
PYEOF
python3 "$WORK/ntp.py" & NTPPID=$!
TOSV_NTP=127.0.0.1:12345 "$BIN" 18769 >"$WORK/srvd.log" 2>&1 & SRVD=$!
sleep 9
grep -q " clock-skew " tosv_audit.log && ok "audit clock-skew" || bad "audit clock-skew"
grep -q "clock-skew 36" tosv_audit.log && ok "skew magnitude about 3600s" || bad "skew magnitude about 3600s"
kill "$SRVD" "$NTPPID" 2>/dev/null; wait "$SRVD" "$NTPPID" 2>/dev/null
cd "$WORK" || exit 2
[ "$(grep -c " clock-skew " tosv_audit.log)" = "0" ] && ok "no skew lines without NTP" || bad "no skew lines without NTP"

say "== prebootstrap guards (server E) =="
mkdir -p "$WORK/e"; cd "$WORK/e" || exit 2
"$BIN" 18770 >"$WORK/srve.log" 2>&1 & SRVE=$!
sleep 1
code=$(curl -s -o /dev/null -w '%{http_code}' --user ":" --data-binary @/dev/null "http://127.0.0.1:18770/store")
expect_code "colon store prebootstrap" 403 "$code"
code=$(curl -s -o /dev/null -w '%{http_code}' --user ":" "http://127.0.0.1:18770/dav")
expect_code "colon DAV prebootstrap" 401 "$code"
printf 'not-json{{{' > .env.json
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 -d "u=&p=" "http://127.0.0.1:18770/login")
expect_code "empty bootstrap on corrupt env" 403 "$code"
kill "$SRVE" 2>/dev/null; wait "$SRVE" 2>/dev/null
cd "$WORK" || exit 2

say "== unreachable NTP stays alive (server F) =="
mkdir -p "$WORK/f"; cd "$WORK/f" || exit 2
TOSV_NTP=127.0.0.1:1 "$BIN" 18771 >"$WORK/srvf.log" 2>&1 & SRVF=$!
sleep 8
code=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:18771/login")
expect_code "alive with dead NTP" 200 "$code"
kill "$SRVF" 2>/dev/null; wait "$SRVF" 2>/dev/null
cd "$WORK" || exit 2

say "== v2 AEAD plus v1 migration =="
python3 -c "import secrets;open('$WORK/v2.bin','wb').write(secrets.token_bytes(100000))"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$SU:$SP" --data-binary "@$WORK/v2.bin" \
  "http://127.0.0.1:$PORT/store")
expect_code "v2 store" 200 "$code"
FID2=$(jq -r .id "$OUT")
[ "$(head -c1 "tosv_store/$FID2.bin" | od -An -tu1 | tr -d ' ')" = "2" ] && ok "v2 version byte" || bad "v2 version byte"
grep -q " 0 2$" "tosv_store/$FID2.bin.tag" && ok "v2 tag version" || bad "v2 tag version"
[ "$(stat -c%s "tosv_store/$FID2.bin")" = "100075" ] && ok "v2 size math" || bad "v2 size math ($(stat -c%s "tosv_store/$FID2.bin"))"
code=$(curl -s -o "$WORK/v2got.bin" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/$FID2")
expect_code "v2 fetch" 200 "$code"
cmp -s "$WORK/v2.bin" "$WORK/v2got.bin" && ok "v2 round-trip identical" || bad "v2 round-trip identical"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$SU:$SP" --data-binary @/dev/null \
  "http://127.0.0.1:$PORT/store")
expect_code "v2 empty store" 200 "$code"
FIDE=$(jq -r .id "$OUT")
[ "$(stat -c%s "tosv_store/$FIDE.bin")" = "58" ] && ok "v2 empty size" || bad "v2 empty size"
code=$(curl -s -o "$WORK/empty.bin" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/$FIDE")
expect_code "v2 empty fetch" 200 "$code"
[ ! -s "$WORK/empty.bin" ] && ok "v2 empty body" || bad "v2 empty body"
python3 -c "import secrets;open('$WORK/exact.bin','wb').write(secrets.token_bytes(131072))"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$SU:$SP" --data-binary "@$WORK/exact.bin" \
  "http://127.0.0.1:$PORT/store")
expect_code "v2 exact-multiple store" 200 "$code"
FIDX=$(jq -r .id "$OUT")
[ "$(stat -c%s "tosv_store/$FIDX.bin")" = "131147" ] && ok "v2 exact size" || bad "v2 exact size"
code=$(curl -s -o "$WORK/exactgot.bin" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/$FIDX")
expect_code "v2 exact fetch" 200 "$code"
cmp -s "$WORK/exact.bin" "$WORK/exactgot.bin" && ok "v2 exact identical" || bad "v2 exact identical"
python3 -c "import secrets;open('$WORK/tamp.bin','wb').write(secrets.token_bytes(100))"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$SU:$SP" --data-binary "@$WORK/tamp.bin" \
  "http://127.0.0.1:$PORT/store")
expect_code "v2 tamper-blob store" 200 "$code"
FIDT=$(jq -r .id "$OUT")
python3 -c "p='tosv_store/$FIDT.bin';b=bytearray(open(p,'rb').read());b[50]^=1;open(p,'wb').write(b)"
H=$(sha256sum "tosv_store/$FIDT.bin" | cut -d' ' -f1); echo "$H 0 2" > "tosv_store/$FIDT.bin.tag"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/$FIDT")
expect_code "v2 tamper detected" 500 "$code"
expect_body "v2 tamper text" "integrity fail" "$OUT"
grep -q "aead-fail $FIDT" tosv_audit.log && ok "v2 crypto layer fired" || bad "v2 crypto layer fired"
python3 -c "import secrets;open('$WORK/trunc.bin','wb').write(secrets.token_bytes(131072))"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$SU:$SP" --data-binary "@$WORK/trunc.bin" \
  "http://127.0.0.1:$PORT/store")
expect_code "v2 trunc-blob store" 200 "$code"
FIDR=$(jq -r .id "$OUT")
python3 -c "p='tosv_store/$FIDR.bin';b=open(p,'rb').read()[:-65553];open(p,'wb').write(b)"
H=$(sha256sum "tosv_store/$FIDR.bin" | cut -d' ' -f1); echo "$H 0 2" > "tosv_store/$FIDR.bin.tag"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/$FIDR")
expect_code "v2 truncation detected" 500 "$code"
grep -q "aead-fail $FIDR" tosv_audit.log && ok "v2 trunc crypto fired" || bad "v2 trunc crypto fired"
python3 -c "p='tosv_store/$FIDE.bin';b=bytearray(open(p,'rb').read());b[50]^=1;open(p,'wb').write(b)"
H=$(sha256sum "tosv_store/$FIDE.bin" | cut -d' ' -f1); echo "$H 0 2" > "tosv_store/$FIDE.bin.tag"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/$FIDE")
expect_code "v2 empty-tamper detected" 500 "$code"
grep -q "aead-fail $FIDE" tosv_audit.log && ok "v2 empty crypto fired" || bad "v2 empty crypto fired"
python3 -c "import secrets;open('$WORK/hd.bin','wb').write(secrets.token_bytes(1000))"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$SU:$SP" --data-binary "@$WORK/hd.bin" \
  "http://127.0.0.1:$PORT/store")
expect_code "v2 hdr-blob store" 200 "$code"
FIDH=$(jq -r .id "$OUT")
python3 -c "p='tosv_store/$FIDH.bin';b=bytearray(open(p,'rb').read());b[5]^=1;open(p,'wb').write(b)"
H=$(sha256sum "tosv_store/$FIDH.bin" | cut -d' ' -f1); echo "$H 0 2" > "tosv_store/$FIDH.bin.tag"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/$FIDH")
expect_code "v2 salt-tamper detected" 500 "$code"
grep -q "aead-fail $FIDH" tosv_audit.log && ok "v2 salt crypto fired" || bad "v2 salt crypto fired"
curl -s -b "$JAR" -o /dev/null -H 'Accept: application/json' -d "ips=&frm=&to=&tw=1&layers=3" "http://127.0.0.1:$PORT/grant"
printf 'cache-one' >"$WORK/c1.bin"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -T "$WORK/c1.bin" "http://127.0.0.1:$PORT/dav/cache.txt")
expect_code "cache DAV PUT one" 201 "$code"
code=$(curl -s -o "$WORK/c1.got" -w '%{http_code}' --user "$GU:$GP" "http://127.0.0.1:$PORT/dav/cache.txt")
expect_code "cache DAV GET one" 200 "$code"
cmp -s "$WORK/c1.bin" "$WORK/c1.got" && ok "cache first read identical" || bad "cache first read identical"
printf 'cache-two-longer' >"$WORK/c2.bin"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -T "$WORK/c2.bin" "http://127.0.0.1:$PORT/dav/cache.txt")
expect_code "cache DAV PUT two" 201 "$code"
code=$(curl -s -o "$WORK/c2.got" -w '%{http_code}' --user "$GU:$GP" "http://127.0.0.1:$PORT/dav/cache.txt")
expect_code "cache DAV GET two" 200 "$code"
cmp -s "$WORK/c2.bin" "$WORK/c2.got" && ok "cache overwrite identical" || bad "cache overwrite identical"
CF=0
for i in $(seq 1 130); do printf "k$i" >"$WORK/k.bin"; c1=$(curl -s -o /dev/null -w '%{http_code}' --user "$GU:$GP" -T "$WORK/k.bin" "http://127.0.0.1:$PORT/dav/churn-$i.bin"); c2=$(curl -s -o "$WORK/k.got" -w '%{http_code}' --user "$GU:$GP" "http://127.0.0.1:$PORT/dav/churn-$i.bin"); [ "$c1" = "201" ] && [ "$c2" = "200" ] || CF=1; done
[ "$CF" = "0" ] && ok "churn 130 clean" || bad "churn 130 clean"
code=$(curl -s -o "$WORK/k1.got" -w '%{http_code}' --user "$GU:$GP" "http://127.0.0.1:$PORT/dav/churn-1.bin")
expect_code "churn first refetch" 200 "$code"
printf 'k1' | cmp -s - "$WORK/k1.got" && ok "churn first identical" || bad "churn first identical"
code=$(curl -s -o "$WORK/k130.got" -w '%{http_code}' --user "$GU:$GP" "http://127.0.0.1:$PORT/dav/churn-130.bin")
expect_code "churn last refetch" 200 "$code"
printf 'k130' | cmp -s - "$WORK/k130.got" && ok "churn last identical" || bad "churn last identical"
python3 -c "import secrets;open('$WORK/tcache.bin','wb').write(secrets.token_bytes(1048576))"
FIDC=$(curl -s --user "$SU:$SP" --data-binary "@$WORK/tcache.bin" "http://127.0.0.1:$PORT/store" | jq -r .id)
curl -s -o "$WORK/tcache.warm" --user "$GU:$GP" "http://127.0.0.1:$PORT/fetch/$FIDC"
cmp -s "$WORK/tcache.bin" "$WORK/tcache.warm" && ok "cache warm identical" || bad "cache warm identical"
S=$(date +%s%N)
for i in $(seq 1 30); do curl -s -o "$WORK/tcache.got" --user "$GU:$GP" "http://127.0.0.1:$PORT/fetch/$FIDC"; done
E=$(date +%s%N); MS=$(( (E-S)/1000000 )); say "cache-hit sample: ${MS}ms per 30x1MB fetch"
cmp -s "$WORK/tcache.bin" "$WORK/tcache.got" && ok "cache hits identical" || bad "cache hits identical"
[ "$MS" -lt 2000 ] && ok "cache-hit tripwire" || bad "cache-hit tripwire (${MS}ms)"
HT=$(cut -d' ' -f1 "tosv_store/$FID2.bin.tag"); echo "$HT 0 9" > "tosv_store/$FID2.bin.tag"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/$FID2")
expect_code "v2 unknown version rejected" 500 "$code"
expect_body "v2 unknown version text" "unsupported version" "$OUT"
echo "$HT 0 2" > "tosv_store/$FID2.bin.tag"
python3 -c "import secrets;open('$WORK/nfr.bin','wb').write(secrets.token_bytes(1048576))"
S=$(date +%s%N)
curl -s -o /dev/null --user "$SU:$SP" --data-binary "@$WORK/nfr.bin" "http://127.0.0.1:$PORT/store"
E=$(date +%s%N); MS=$(( (E-S)/1000000 )); say "store latency sample: ${MS}ms per 1MB store"
[ "$MS" -lt 2000 ] && ok "store latency tripwire" || bad "store latency tripwire (${MS}ms)"
python3 -c "import secrets;open('$WORK/nfr10.bin','wb').write(secrets.token_bytes(10485760))"
FIDN=$(curl -s --user "$SU:$SP" --data-binary "@$WORK/nfr10.bin" "http://127.0.0.1:$PORT/store" | jq -r .id)
S=$(date +%s%N)
curl -s -o "$WORK/nfr10.got" --user "$GU:$GP" "http://127.0.0.1:$PORT/fetch/$FIDN"
E=$(date +%s%N); MS=$(( (E-S)/1000000 )); say "NFR-04 sample: ${MS}ms per 10MB fetch"
cmp -s "$WORK/nfr10.bin" "$WORK/nfr10.got" && ok "NFR-04 blob correct" || bad "NFR-04 blob correct"
[ "$MS" -lt 2000 ] && ok "NFR-04 tripwire" || bad "NFR-04 tripwire (${MS}ms)"
FX="$ROOT/tests/fixtures/v1"
cp "$FX/blob.bin" tosv_store/migr8.bin; cp "$FX/blob.tag" tosv_store/migr8.bin.tag
. "$FX/meta.env"
sed -i "s/^su=.*/su=$STORE_USER/; s/^sp=.*/sp=$STORE_PASS/" tosv_db.txt
code=$(curl -s -o "$WORK/mig.bin" -w '%{http_code}' --user "$GU:$GP" \
  "http://127.0.0.1:$PORT/fetch/migr8")
expect_code "v1 fixture fetch" 200 "$code"
cmp -s "$FX/plain.bin" "$WORK/mig.bin" && ok "v1 migration identical" || bad "v1 migration identical"

say "== SFTP subsystem (server S, shared DB) =="
SFTPBIN="$ROOT/tosv-sftp"
[ -x "$SFTPBIN" ] || { say "build first: make build"; exit 2; }
need sftp; need ssh; need ssh-keygen
SFTPP=18767
VPY="$ROOT/.venv/bin/python"
if ! "$VPY" -c "import asyncssh" >/dev/null 2>&1; then
  say "creating project env for sftp probes..."
  python3 -m venv "$ROOT/.venv" && "$ROOT/.venv/bin/pip" -q install -r "$ROOT/tests/sftp/requirements.txt" || { say "venv setup failed"; exit 2; }
fi
SU=$(grep '^su=' tosv_db.txt | cut -d= -f2-); SP=$(grep '^sp=' tosv_db.txt | cut -d= -f2-)
code=$(curl -s -b "$JAR" -o "$OUT" -w '%{http_code}' -H 'Accept: application/json' \
  -d "tw=1&ips=&frm=&to=&layers=3" "http://127.0.0.1:$PORT/grant")
expect_code "sftp grant1 tw=1" 200 "$code"
SGU1=$(jq -r .retrieve.user "$OUT"); SGP1=$(jq -r .retrieve.pass "$OUT"); SGID1=$(jq -r .retrieve.id "$OUT")
curl -s -b "$JAR" -o "$OUT" -H 'Accept: application/json' \
  -d "tw=1&ips=&frm=&to=&layers=3" "http://127.0.0.1:$PORT/grant" >/dev/null
SGID2=$(jq -r .retrieve.id "$OUT")
curl -s -b "$JAR" -o "$OUT" -H 'Accept: application/json' \
  -d "tw=1&ips=&frm=&to=&layers=3" "http://127.0.0.1:$PORT/grant" >/dev/null
SGID3=$(jq -r .retrieve.id "$OUT")
ssh-keygen -t ed25519 -f "$WORK/sftpkey" -N '' -q
ssh-keygen -t ed25519 -f "$WORK/badkey" -N '' -q
PUB=$(cut -d' ' -f2 "$WORK/sftpkey.pub")
echo "ssh-ed25519 $PUB sftptest gids=$SGID1,$SGID2" > sftp_gateway_keys
chmod 600 sftp_gateway_keys
[ "$(stat -c %a sftp_gateway_keys)" = "600" ] && ok "gateway keys 600" || bad "gateway keys 600"
TOSV_SFTP_ALLOW_CLASSICAL=1 "$SFTPBIN" "$SFTPP" >"$WORK/sftpsrv.log" 2>&1 &
SRVS=$!
sleep 1
expect_body "sftp bind line" "TOSV-SFTP $(cat "$ROOT/VERSION") on 127.0.0.1:$SFTPP" "$WORK/sftpsrv.log"
expect_body "sftp memlock" "memlock=" "$WORK/sftpsrv.log"
[ -f sftp_host_ed25519 ] && ok "host key minted" || bad "host key minted"
[ "$(stat -c %a sftp_host_ed25519)" = "600" ] && ok "host key 600" || bad "host key 600"
SFTPC="sftp -P $SFTPP -i $WORK/sftpkey -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10"
SFTPD="u@127.0.0.1"
: > "$WORK/empty.bin"
printf 'pwd\nquit\n' > "$WORK/b0"
$SFTPC -b "$WORK/b0" $SFTPD >"$WORK/s0" 2>&1; [ "$?" = "0" ] && ok "sftp batch exit 0" || bad "sftp batch exit 0"
expect_body "sftp pwd root" "Remote working directory: /" "$WORK/s0"
printf 'ls /\nquit\n' > "$WORK/b1"
$SFTPC -b "$WORK/b1" $SFTPD >"$WORK/s1" 2>&1
expect_body "sftp root lists gid1" "$SGID1" "$WORK/s1"
expect_body "sftp root lists gid2" "$SGID2" "$WORK/s1"
grep -q -F "$SGID3" "$WORK/s1" && bad "sftp root hides unbound" || ok "sftp root hides unbound"
chmod 666 sftp_gateway_keys
$SFTPC -b "$WORK/b0" $SFTPD >"$WORK/s666" 2>&1; [ "$?" != "0" ] && ok "gateway 666 refused" || bad "gateway 666 refused"
chmod 600 sftp_gateway_keys
$SFTPC -b "$WORK/b0" $SFTPD >"$WORK/s600" 2>&1; [ "$?" = "0" ] && ok "gateway 600 works again" || bad "gateway 600 works again"
printf 'cd /%s/%s\npwd\nquit\n' "$SGID1" "$SGP1" > "$WORK/b2"
$SFTPC -b "$WORK/b2" $SFTPD >"$WORK/s2" 2>&1; [ "$?" = "0" ] && ok "sftp cd grant" || bad "sftp cd grant"
expect_body "sftp pwd redacted" "/$SGID1/*" "$WORK/s2"
printf 'cd /%s/AAAAAAAAAAAAAAAAAAAAAA\nquit\n' "$SGID1" > "$WORK/bw"
$SFTPC -b "$WORK/bw" $SFTPD >"$WORK/sw" 2>&1; [ "$?" != "0" ] && ok "sftp wrong gp refused" || bad "sftp wrong gp refused"
printf 'cd /%s/AAAAAAAAAAAAAAAAAAAAAA\nquit\n' "$SGID3" > "$WORK/bm"
$SFTPC -b "$WORK/bm" $SFTPD >"$WORK/sm" 2>&1
grep -i 'canoni' "$WORK/sw" > "$WORK/swl"; grep -i 'canoni' "$WORK/sm" > "$WORK/sml"
cmp -s "$WORK/swl" "$WORK/sml" && ok "sftp wrong-gp equals missing" || bad "sftp wrong-gp equals missing"
printf 'cd /%s/%s\nput %s s-big.bin\nls -l\nget s-big.bin %s\nquit\n' "$SGID1" "$SGP1" "$WORK/big.bin" "$WORK/s-big.got" > "$WORK/b3"
$SFTPC -b "$WORK/b3" $SFTPD >"$WORK/s3" 2>&1; [ "$?" = "0" ] && ok "sftp put-get batch" || bad "sftp put-get batch"
cmp -s "$WORK/big.bin" "$WORK/s-big.got" && ok "sftp 200KB identical" || bad "sftp 200KB identical"
grep -E -q "^-rw------- 1 0 0 204800 [A-Z][a-z]{2} +[0-9]+ [0-9]{2}:[0-9]{2} s-big.bin$" "$WORK/s3" && ok "sftp ls-l parses" || bad "sftp ls-l parses"
printf 'cd /%s/%s\nput %s s-empty.bin\nget s-empty.bin %s\nquit\n' "$SGID1" "$SGP1" "$WORK/empty.bin" "$WORK/s-empty.got" > "$WORK/b4"
$SFTPC -b "$WORK/b4" $SFTPD >/dev/null 2>&1; [ "$?" = "0" ] && ok "sftp empty batch" || bad "sftp empty batch"
[ ! -s "$WORK/s-empty.got" ] && ok "sftp empty identical" || bad "sftp empty identical"
printf 'cd /%s/%s\nmkdir sdir\nls\nrmdir sdir\nquit\n' "$SGID1" "$SGP1" > "$WORK/b5"
$SFTPC -b "$WORK/b5" $SFTPD >"$WORK/s5" 2>&1; [ "$?" = "0" ] && ok "sftp mkdir-rmdir" || bad "sftp mkdir-rmdir"
expect_body "sftp ls shows dir" "sdir" "$WORK/s5"
printf 'cd /%s/%s\nput %s s-rn1.bin\nrename s-rn1.bin s-rn2.bin\nls\nquit\n' "$SGID1" "$SGP1" "$WORK/empty.bin" > "$WORK/b6"
$SFTPC -b "$WORK/b6" $SFTPD >"$WORK/s6" 2>&1; [ "$?" = "0" ] && ok "sftp rename" || bad "sftp rename"
expect_body "sftp ls shows renamed" "s-rn2.bin" "$WORK/s6"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$SGU1:$SGP1" "http://127.0.0.1:$PORT/fetch/s-rn2")
expect_code "sftp rename tag follows" 200 "$code"
printf 'cd /%s/%s\nput %s s-del.bin\nrm s-del.bin\nquit\n' "$SGID1" "$SGP1" "$WORK/empty.bin" > "$WORK/b7"
$SFTPC -b "$WORK/b7" $SFTPD >/dev/null 2>&1; [ "$?" = "0" ] && ok "sftp rm" || bad "sftp rm"
printf 'cd /%s/%s\nchmod 777 s-big.bin\nget s-big.bin %s\nquit\n' "$SGID1" "$SGP1" "$WORK/s-big2.got" > "$WORK/b8"
$SFTPC -b "$WORK/b8" $SFTPD >/dev/null 2>&1; [ "$?" = "0" ] && ok "sftp chmod ignored-ok" || bad "sftp chmod ignored-ok"
cmp -s "$WORK/big.bin" "$WORK/s-big2.got" && ok "sftp post-chmod identical" || bad "sftp post-chmod identical"
printf 'cd /%s/%s\nsymlink s-big.bin s-lnk\nquit\n' "$SGID1" "$SGP1" > "$WORK/b9"
$SFTPC -b "$WORK/b9" $SFTPD >"$WORK/s9" 2>&1; [ "$?" != "0" ] && ok "sftp symlink refused" || bad "sftp symlink refused"
grep -q '\.tag' "$WORK/s3" && bad "sftp hides tags" || ok "sftp hides tags"
printf 'cd /%s/%s\nget s-big.bin.tag /dev/null\nquit\n' "$SGID1" "$SGP1" > "$WORK/b10"
$SFTPC -b "$WORK/b10" $SFTPD >/dev/null 2>&1; [ "$?" != "0" ] && ok "sftp tag direct missing" || bad "sftp tag direct missing"
touch tosv_store/orphan.bin.part.999
printf 'cd /%s/%s\nls\nquit\n' "$SGID1" "$SGP1" > "$WORK/b11a"
$SFTPC -b "$WORK/b11a" $SFTPD >"$WORK/s11a" 2>&1
grep -q 'orphan' "$WORK/s11a" && bad "sftp hides part files" || ok "sftp hides part files"
printf 'cd /%s/%s\nget orphan.bin.part.999 %s\nquit\n' "$SGID1" "$SGP1" "$WORK/nil.bin" > "$WORK/b11b"
$SFTPC -b "$WORK/b11b" $SFTPD >/dev/null 2>&1; [ "$?" != "0" ] && ok "sftp part missing" || bad "sftp part missing"
rm -f tosv_store/orphan.bin.part.999
printf 'cd /%s/%s/../../x\nquit\n' "$SGID1" "$SGP1" > "$WORK/b12"
$SFTPC -b "$WORK/b12" $SFTPD >/dev/null 2>&1; [ "$?" != "0" ] && ok "sftp escape missing" || bad "sftp escape missing"
grep -q "sftp-escape" tosv_audit.log && ok "sftp escape audited" || bad "sftp escape audited"
grep -q -F "$SGP1" tosv_audit.log && bad "sftp gp never in audit" || ok "sftp gp never in audit"
grep -q "sftp-open $SGID1/s-big.bin" tosv_audit.log && ok "sftp open audit shape" || bad "sftp open audit shape"
for i in $(seq 1 10005); do touch "tosv_store/cap-$i.bin"; done
printf 'cd /%s/%s\nls -l\nquit\n' "$SGID1" "$SGP1" > "$WORK/b13"
$SFTPC -b "$WORK/b13" $SFTPD >"$WORK/s13" 2>&1
N13=$(grep -c '^[-d]' "$WORK/s13"); [ "$N13" = "10000" ] && ok "sftp readdir 10k cap" || bad "sftp readdir 10k cap ($N13)"
rm -f tosv_store/cap-*.bin
printf 'cd /%s/%s\nget migr8.bin %s\nquit\n' "$SGID1" "$SGP1" "$WORK/mig-sftp.bin" > "$WORK/b14"
$SFTPC -b "$WORK/b14" $SFTPD >/dev/null 2>&1; [ "$?" = "0" ] && ok "sftp v1 get" || bad "sftp v1 get"
cmp -s "$ROOT/tests/fixtures/v1/plain.bin" "$WORK/mig-sftp.bin" && ok "sftp v1 identical" || bad "sftp v1 identical"
python3 -c "import secrets;open('$WORK/stamp.bin','wb').write(secrets.token_bytes(100))"
FIDST=$(curl -s --user "$SU:$SP" --data-binary "@$WORK/stamp.bin" "http://127.0.0.1:$PORT/store" | jq -r .id)
python3 -c "p='tosv_store/$FIDST.bin';b=bytearray(open(p,'rb').read());b[50]^=1;open(p,'wb').write(b)"
H=$(sha256sum "tosv_store/$FIDST.bin" | cut -d' ' -f1); echo "$H 0 2" > "tosv_store/$FIDST.bin.tag"
printf 'cd /%s/%s\nget %s.bin /dev/null\nquit\n' "$SGID1" "$SGP1" "$FIDST" > "$WORK/b15"
$SFTPC -b "$WORK/b15" $SFTPD >/dev/null 2>&1; [ "$?" != "0" ] && ok "sftp tamper refused" || bad "sftp tamper refused"
grep -q "aead-fail $SGID1/$FIDST.bin" tosv_audit.log && ok "sftp tamper aead audit" || bad "sftp tamper aead audit"
python3 -c "p='tosv_store/$FIDST.bin';b=open(p,'rb').read()[:50];open(p,'wb').write(b)"
printf 'cd /%s/%s\nget %s.bin /dev/null\nquit\n' "$SGID1" "$SGP1" "$FIDST" > "$WORK/b16"
$SFTPC -b "$WORK/b16" $SFTPD >/dev/null 2>&1; [ "$?" != "0" ] && ok "sftp trunc refused" || bad "sftp trunc refused"
grep -q "integrity-fail $SGID1/$FIDST.bin" tosv_audit.log && ok "sftp trunc audit" || bad "sftp trunc audit"
echo "x 0 9" > "tosv_store/$FIDST.bin.tag"
$SFTPC -b "$WORK/b16" $SFTPD >/dev/null 2>&1; [ "$?" != "0" ] && ok "sftp badver refused" || bad "sftp badver refused"
# store rate cap (20 per 300s per IP) is per process and the main server has spent it by now: use a fresh instance on the same data root
("$BIN" 18784 >"$WORK/xsrv.log" 2>&1 & echo $! > "$WORK/xsrv.pid"); XSRV=$(cat "$WORK/xsrv.pid"); sleep 1
for SZ in 0 1 65536 65537 5242880; do
  python3 -c "import secrets;open('$WORK/x-$SZ.bin','wb').write(secrets.token_bytes($SZ))"
  printf 'cd /%s/%s\nput %s x1-%s.bin\nquit\n' "$SGID1" "$SGP1" "$WORK/x-$SZ.bin" "$SZ" > "$WORK/bx"
  $SFTPC -b "$WORK/bx" $SFTPD >/dev/null 2>&1
  code=$(curl -s -o "$WORK/x1-$SZ.got" -w '%{http_code}' --user "$SGU1:$SGP1" "http://127.0.0.1:$PORT/fetch/x1-$SZ")
  [ "$code" = "200" ] && cmp -s "$WORK/x-$SZ.bin" "$WORK/x1-$SZ.got" && ok "x-surface sftp-put/http-fetch $SZ" || bad "x-surface sftp-put/http-fetch $SZ"
  FIDX2=$(curl -s --user "$SU:$SP" --data-binary "@$WORK/x-$SZ.bin" "http://127.0.0.1:18784/store" | jq -r .id)
  { [ -n "$FIDX2" ] && [ "$FIDX2" != "null" ]; } && ok "x-surface http-store id $SZ" || bad "x-surface http-store id $SZ"
  printf 'cd /%s/%s\nget %s.bin %s\nquit\n' "$SGID1" "$SGP1" "$FIDX2" "$WORK/x2-$SZ.got" > "$WORK/bx"
  $SFTPC -b "$WORK/bx" $SFTPD >/dev/null 2>&1
  cmp -s "$WORK/x-$SZ.bin" "$WORK/x2-$SZ.got" && ok "x-surface http-store/sftp-get $SZ" || bad "x-surface http-store/sftp-get $SZ"
  code=$(curl -s -o /dev/null -w '%{http_code}' -X PUT --user "$SGU1:$SGP1" --data-binary "@$WORK/x-$SZ.bin" "http://127.0.0.1:$PORT/dav/x3-$SZ.bin")
  [ "$code" = "201" ] && ok "x-surface dav-put $SZ" || bad "x-surface dav-put $SZ ($code)"
  printf 'cd /%s/%s\nget x3-%s.bin %s\nquit\n' "$SGID1" "$SGP1" "$SZ" "$WORK/x3-$SZ.got" > "$WORK/bx"
  $SFTPC -b "$WORK/bx" $SFTPD >/dev/null 2>&1
  cmp -s "$WORK/x-$SZ.bin" "$WORK/x3-$SZ.got" && ok "x-surface dav-put/sftp-get $SZ" || bad "x-surface dav-put/sftp-get $SZ"
  printf 'cd /%s/%s\nput %s x4-%s.bin\nquit\n' "$SGID1" "$SGP1" "$WORK/x-$SZ.bin" "$SZ" > "$WORK/bx"
  $SFTPC -b "$WORK/bx" $SFTPD >/dev/null 2>&1
  code=$(curl -s -o "$WORK/x4-$SZ.got" -w '%{http_code}' --user "$SGU1:$SGP1" "http://127.0.0.1:$PORT/dav/x4-$SZ.bin")
  [ "$code" = "200" ] && cmp -s "$WORK/x-$SZ.bin" "$WORK/x4-$SZ.got" && ok "x-surface sftp-put/dav-get $SZ" || bad "x-surface sftp-put/dav-get $SZ"
done
kill "$XSRV" 2>/dev/null; wait "$XSRV" 2>/dev/null
"$VPY" "$ROOT/tests/sftp/raw_probe.py" "$SFTPP" "$SGID1" "$SGP1" "$WORK/sftpkey" "sftp_host_ed25519.pub" >"$WORK/raw.out" 2>&1
RRC=$?
while IFS= read -r RL; do case "$RL" in PASS:*) ok "${RL#PASS: }";; FAIL:*) bad "${RL#FAIL: }";; SKIP:*) say "SKIP: ${RL#SKIP: }";; esac; done < "$WORK/raw.out"
[ "$RRC" = "0" ] && ok "raw probe exit" || bad "raw probe exit"
curl -s -b "$JAR" -o /dev/null -H 'Accept: application/json' \
  -d "tw=0&ips=&frm=&to=&layers=3" "http://127.0.0.1:$PORT/grant" >/dev/null
printf 'cd /%s/%s\nput %s s-big.bin\nquit\n' "$SGID1" "$SGP1" "$WORK/empty.bin" > "$WORK/b17"
$SFTPC -b "$WORK/b17" $SFTPD >"$WORK/s17" 2>&1; [ "$?" != "0" ] && ok "sftp append-only overwrite refused" || bad "sftp append-only overwrite refused"
grep -q 'ermission denied' "$WORK/s17" && ok "sftp append-only text" || bad "sftp append-only text"
printf 'cd /%s/%s\nrm s-big.bin\nquit\n' "$SGID1" "$SGP1" > "$WORK/b18"
$SFTPC -b "$WORK/b18" $SFTPD >/dev/null 2>&1; [ "$?" != "0" ] && ok "sftp append-only rm refused" || bad "sftp append-only rm refused"
printf 'cd /%s/%s\nrename s-big.bin s-big3.bin\nquit\n' "$SGID1" "$SGP1" > "$WORK/b19"
$SFTPC -b "$WORK/b19" $SFTPD >/dev/null 2>&1; [ "$?" != "0" ] && ok "sftp append-only rename refused" || bad "sftp append-only rename refused"
printf 'cd /%s/%s\nput %s s-new0.bin\nmkdir s-mk0\nquit\n' "$SGID1" "$SGP1" "$WORK/empty.bin" > "$WORK/b20"
$SFTPC -b "$WORK/b20" $SFTPD >/dev/null 2>&1; [ "$?" = "0" ] && ok "sftp append-only create+mkdir" || bad "sftp append-only create+mkdir"
curl -s -b "$JAR" -o "$OUT" -H 'Accept: application/json' \
  -d "tw=0&ips=&frm=&to=2001-01-01T00:00&layers=3" "http://127.0.0.1:$PORT/grant" >/dev/null
EGID=$(jq -r .retrieve.id "$OUT"); EGP=$(jq -r .retrieve.pass "$OUT")
curl -s -b "$JAR" -o "$OUT" -H 'Accept: application/json' \
  -d "tw=0&ips=&frm=2999-01-01T00:00&to=&layers=3" "http://127.0.0.1:$PORT/grant" >/dev/null
FGID=$(jq -r .retrieve.id "$OUT"); FGP=$(jq -r .retrieve.pass "$OUT")
curl -s -b "$JAR" -o "$OUT" -H 'Accept: application/json' \
  -d "tw=0&ips=10.9.9.9/32&frm=&to=&layers=3" "http://127.0.0.1:$PORT/grant" >/dev/null
IGID=$(jq -r .retrieve.id "$OUT"); IGP=$(jq -r .retrieve.pass "$OUT")
echo "ssh-ed25519 $PUB sftptest gids=$SGID1,$SGID2,$EGID,$FGID,$IGID" > sftp_gateway_keys
chmod 600 sftp_gateway_keys
printf 'cd /%s/%s\nquit\n' "$EGID" "$EGP" > "$WORK/be"
$SFTPC -b "$WORK/be" $SFTPD >"$WORK/se" 2>&1; [ "$?" != "0" ] && ok "sftp expired refused" || bad "sftp expired refused"
grep -q ': denied' "$WORK/se" && ok "sftp expired text" || bad "sftp expired text"
printf 'cd /%s/%s\nquit\n' "$FGID" "$FGP" > "$WORK/bf"
$SFTPC -b "$WORK/bf" $SFTPD >/dev/null 2>&1; [ "$?" != "0" ] && ok "sftp future refused" || bad "sftp future refused"
printf 'cd /%s/%s\nquit\n' "$IGID" "$IGP" > "$WORK/bi"
$SFTPC -b "$WORK/bi" $SFTPD >/dev/null 2>&1; [ "$?" != "0" ] && ok "sftp wrong-ip refused" || bad "sftp wrong-ip refused"
ssh -p "$SFTPP" -i "$WORK/sftpkey" -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10 u@127.0.0.1 true >/dev/null 2>&1
[ "$?" != "0" ] && ok "ssh exec refused" || bad "ssh exec refused"
ssh -t -p "$SFTPP" -i "$WORK/sftpkey" -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10 u@127.0.0.1 true >/dev/null 2>&1
[ "$?" != "0" ] && ok "ssh pty refused" || bad "ssh pty refused"
ssh -p "$SFTPP" -oCiphers=aes128-ctr -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10 u@127.0.0.1 true >"$WORK/saes" 2>&1
[ "$?" != "0" ] && ok "ssh aes-only refused" || bad "ssh aes-only refused"
grep -q 'no matching cipher' "$WORK/saes" && ok "ssh aes-only text" || bad "ssh aes-only text"
sftp -P "$SFTPP" -i "$WORK/sftpkey" -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10 -oKexAlgorithms=curve25519-sha256 -oCiphers=chacha20-poly1305@openssh.com -oHostKeyAlgorithms=ssh-ed25519 -oPubkeyAcceptedAlgorithms=+ssh-ed25519 -b "$WORK/b0" u@127.0.0.1 >/dev/null 2>&1
[ "$?" = "0" ] && ok "sftp constrained profile ok" || bad "sftp constrained profile ok"
grep -q "sftp-kex curve25519" tosv_audit.log && ok "sftp classic kex audited" || bad "sftp classic kex audited"
sftp -P "$SFTPP" -i "$WORK/sftpkey" -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10 -oKexAlgorithms=mlkem768x25519-sha256 -oCiphers=chacha20-poly1305@openssh.com -oHostKeyAlgorithms=ssh-ed25519 -oPubkeyAcceptedAlgorithms=+ssh-ed25519 -b "$WORK/b0" u@127.0.0.1 >/dev/null 2>&1
[ "$?" = "0" ] && ok "sftp pq-only kex ok" || bad "sftp pq-only kex ok"
grep -q "sftp-kex mlkem768x25519" tosv_audit.log && ok "sftp pq kex audited" || bad "sftp pq kex audited"
GB=$(grep -c '^grant=' tosv_db.txt)
PIDS=""
for i in $(seq 1 50); do curl -s -b "$JAR" -o /dev/null -d "tw=0&ips=&frm=&to=&layers=1" "http://127.0.0.1:$PORT/grant" & PIDS="$PIDS $!"; done
printf 'ls /\nquit\n' > "$WORK/bh"
for i in $(seq 1 50); do $SFTPC -b "$WORK/bh" $SFTPD >/dev/null 2>&1 & PIDS="$PIDS $!"; done
wait $PIDS
GA=$(grep -c '^grant=' tosv_db.txt)
[ "$GA" = "$((GB+50))" ] && ok "hammer 50 grants" || bad "hammer 50 grants ($GB->$GA)"
awk '/^grant=/{n=split($0,a,"|"); if(n!=6) bad=1} END{exit bad}' tosv_db.txt && ok "hammer db well-formed" || bad "hammer db well-formed"
for i in $(seq 1 25); do sftp -P "$SFTPP" -i "$WORK/badkey" -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10 -b "$WORK/b0" u@127.0.0.1 >/dev/null 2>&1; done
grep -q "blocked 127.0.0.1" tosv_audit.log && ok "sftp block fires" || bad "sftp block fires"

say "== sftp wipe INT-03 both directions =="
W1="$WORK/w1"; mkdir -p "$W1"
(cd "$W1" && exec "$BIN" 18773 >http.log 2>&1 & echo $! > "$WORK/w1h.pid")
(cd "$W1" && exec "$SFTPBIN" 18774 >sftp.log 2>&1 & echo $! > "$WORK/w1s.pid")
SRVH1=$(cat "$WORK/w1h.pid"); SRVW1=$(cat "$WORK/w1s.pid")
sleep 1
W1U=$(jq -r .user "$W1/.env.json"); W1P=$(jq -r .pass "$W1/.env.json")
curl -s -c "$WORK/w1jar" -o /dev/null --max-time 10 -d "u=$W1U&p=$W1P" "http://127.0.0.1:18773/login"
WG1=$(curl -s -b "$WORK/w1jar" -H 'Accept: application/json' -d "tw=1&ips=&frm=&to=&layers=1" "http://127.0.0.1:18773/grant" | jq -r .retrieve.id)
echo "ssh-ed25519 $PUB w1 gids=$WG1" > "$W1/sftp_gateway_keys"; chmod 600 "$W1/sftp_gateway_keys"
DUR1=$(grep '^duress=' "$W1/tosv_db.txt" | head -1 | cut -d= -f2-)
code=$(curl -s -o "$OUT" -w '%{http_code}' --max-time 10 -d "u=${DUR1%%:*}&p=${DUR1#*:}" "http://127.0.0.1:18773/login")
expect_code "wipe-http duress" 403 "$code"
sftp -P 18774 -i "$WORK/sftpkey" -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10 -b "$WORK/b0" u@127.0.0.1 >/dev/null 2>&1
[ "$?" != "0" ] && ok "wipe-http-to-sftp refused" || bad "wipe-http-to-sftp refused"
[ -f "$W1/.wiped" ] && ok "wipe sentinel http-side" || bad "wipe sentinel http-side"
code=$(curl -s -o "$OUT" -w '%{http_code}' "http://127.0.0.1:18773/login")
expect_code "wipe-http login dead" 403 "$code"
kill "$SRVH1" "$SRVW1" 2>/dev/null; wait "$SRVH1" "$SRVW1" 2>/dev/null
W2="$WORK/w2"; mkdir -p "$W2"
(cd "$W2" && exec "$BIN" 18775 >http.log 2>&1 & echo $! > "$WORK/w2h.pid")
(cd "$W2" && exec "$SFTPBIN" 18776 >sftp.log 2>&1 & echo $! > "$WORK/w2s.pid")
SRVH2=$(cat "$WORK/w2h.pid"); SRVW2=$(cat "$WORK/w2s.pid")
sleep 1
W2U=$(jq -r .user "$W2/.env.json"); W2P=$(jq -r .pass "$W2/.env.json")
curl -s -c "$WORK/w2jar" -o /dev/null --max-time 10 -d "u=$W2U&p=$W2P" "http://127.0.0.1:18775/login"
WG2=$(curl -s -b "$WORK/w2jar" -H 'Accept: application/json' -d "tw=1&ips=&frm=&to=&layers=1" "http://127.0.0.1:18775/grant" | jq -r .retrieve.id)
echo "ssh-ed25519 $PUB w2 gids=$WG2" > "$W2/sftp_gateway_keys"; chmod 600 "$W2/sftp_gateway_keys"
printf 'cd /!duress/00000000\nquit\n' > "$WORK/bd0"
sftp -P 18776 -i "$WORK/sftpkey" -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10 -b "$WORK/bd0" u@127.0.0.1 >/dev/null 2>&1
[ "$?" != "0" ] && ok "sftp wrong duress missing" || bad "sftp wrong duress missing"
[ -f "$W2/tosv_db.txt" ] && ok "sftp wrong duress harmless" || bad "sftp wrong duress harmless"
DUR2=$(grep '^duress=' "$W2/tosv_db.txt" | head -1 | cut -d= -f2-); SUF2="${DUR2#*:}"
printf 'cd /!duress/%s\nquit\n' "$SUF2" > "$WORK/bd1"
sftp -P 18776 -i "$WORK/sftpkey" -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10 -b "$WORK/bd1" u@127.0.0.1 >/dev/null 2>&1
[ "$?" != "0" ] && ok "sftp duress disconnects" || bad "sftp duress disconnects"
[ -f "$W2/.wiped" ] && ok "wipe sentinel sftp-side" || bad "wipe sentinel sftp-side"
grep -q " duress" "$W2/tosv_audit.log" && ok "wipe sftp duress audit" || bad "wipe sftp duress audit"
code=$(curl -s -o "$OUT" -w '%{http_code}' "http://127.0.0.1:18775/login")
expect_code "wipe-sftp-to-http dead" 403 "$code"
expect_body "wipe-sftp-to-http text" "wiped" "$OUT"
sftp -P 18776 -i "$WORK/sftpkey" -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10 -b "$WORK/b0" u@127.0.0.1 >/dev/null 2>&1
[ "$?" != "0" ] && ok "wipe-sftp-to-sftp refused" || bad "wipe-sftp-to-sftp refused"
kill "$SRVH2" "$SRVW2" 2>/dev/null; wait "$SRVH2" "$SRVW2" 2>/dev/null

say "== measurement: kill -9 recovery =="
M1="$WORK/m1"; mkdir -p "$M1"
(cd "$M1" && exec "$BIN" 18777 >http.log 2>&1 & echo $! > "$WORK/m1.pid")
SRVM1=$(cat "$WORK/m1.pid")
sleep 1
M1U=$(jq -r .user "$M1/.env.json"); M1P=$(jq -r .pass "$M1/.env.json")
curl -s -c "$WORK/m1jar" -o /dev/null --max-time 10 -d "u=$M1U&p=$M1P" "http://127.0.0.1:18777/login"
MG1=$(curl -s -b "$WORK/m1jar" -H 'Accept: application/json' -d "tw=1&ips=&frm=&to=&layers=1" "http://127.0.0.1:18777/grant")
MGU=$(echo "$MG1" | jq -r .retrieve.user); MGP=$(echo "$MG1" | jq -r .retrieve.pass)
MSU=$(echo "$MG1" | jq -r .store.user); MSP=$(echo "$MG1" | jq -r .store.pass)
head -c 2000000 /dev/urandom > "$WORK/k9.bin"
K9ID=$(curl -s --user "$MSU:$MSP" --data-binary @"$WORK/k9.bin" "http://127.0.0.1:18777/store" | jq -r .id)
[ -n "$K9ID" ] && [ "$K9ID" != "null" ] && ok "kill-9 baseline stored" || bad "kill-9 baseline stored"
cp "$M1/tosv_store/$K9ID.bin" "$WORK/k9full.bin"
head -c 100000 "$WORK/k9full.bin" > "$M1/tosv_store/$K9ID.bin"
rm -f "$M1/tosv_store/$K9ID.bin.tag"
kill -9 "$SRVM1" 2>/dev/null; wait "$SRVM1" 2>/dev/null
(cd "$M1" && exec "$BIN" 18777 >http2.log 2>&1 & echo $! > "$WORK/m1.pid")
SRVM1=$(cat "$WORK/m1.pid")
sleep 1
curl -s -c "$WORK/m1jar" -o /dev/null --max-time 10 -d "u=$MSU&p=$MSP" "http://127.0.0.1:18777/login"
code=$(curl -s -o "$OUT" -w '%{http_code}' --user "$MGU:$MGP" "http://127.0.0.1:18777/fetch/$K9ID")
expect_code "kill-9 partial fails closed" 500 "$code"
grep -q -E "aead-fail|integrity-fail" "$M1/tosv_audit.log" && ok "kill-9 audit marker" || bad "kill-9 audit marker"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$MGU:$MGP" -X PROPFIND -H 'Depth: 1' "http://127.0.0.1:18777/dav")
expect_code "kill-9 server serves after restart" 207 "$code"

say "== measurement: 512MB boundary =="
head -c 536870912 /dev/urandom > "$WORK/big.bin"
BIGSHA=$(sha256sum "$WORK/big.bin" | awk '{print $1}')
code=$(curl -s -o "$WORK/big.id" -w '%{http_code}' --user "$MSU:$MSP" --max-time 300 --data-binary @"$WORK/big.bin" "http://127.0.0.1:18777/store")
expect_code "512MB store" 200 "$code"
BIGID=$(jq -r .id "$WORK/big.id")
rm -f "$WORK/big.bin"
curl -s -o "$WORK/big.got" --user "$MGU:$MGP" --max-time 300 "http://127.0.0.1:18777/fetch/$BIGID"
GOTSHA=$(sha256sum "$WORK/big.got" | awk '{print $1}')
[ "$BIGSHA" = "$GOTSHA" ] && ok "512MB round-trip identical" || bad "512MB round-trip identical"
rm -f "$WORK/big.got"
head -c 536870913 /dev/urandom > "$WORK/big1.bin"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$MSU:$MSP" --max-time 300 --data-binary @"$WORK/big1.bin" "http://127.0.0.1:18777/store")
expect_code "512MB+1 refused" 413 "$code"
rm -f "$WORK/big1.bin"

say "== measurement: PROPFIND 10k cap =="
printf 'cap-base' > "$WORK/capbase.bin"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$MGU:$MGP" -T "$WORK/capbase.bin" "http://127.0.0.1:18777/dav/cap/base.txt")
expect_code "cap base PUT" 201 "$code"
seq 1 10001 | xargs -P 8 -I{} curl -s -o /dev/null --user "$MGU:$MGP" -X COPY -H "Destination: http://127.0.0.1:18777/dav/cap/f{}.txt" "http://127.0.0.1:18777/dav/cap/base.txt"
code=$(curl -s -o "$WORK/cap.xml" -w '%{http_code}' --user "$MGU:$MGP" -X PROPFIND -H 'Depth: 1' "http://127.0.0.1:18777/dav/cap")
expect_code "PROPFIND 10k" 207 "$code"
NRESP=$(grep -o '<d:response>' "$WORK/cap.xml" | wc -l | tr -d ' ')
[ "$NRESP" = "10001" ] && ok "PROPFIND caps at self+10000" || bad "PROPFIND caps ($NRESP)"
curl -s -o /dev/null --user "$MGU:$MGP" -X MKCOL "http://127.0.0.1:18777/dav/inf" >/dev/null
curl -s -o /dev/null --user "$MGU:$MGP" -X PUT --data-binary @/dev/null "http://127.0.0.1:18777/dav/inf/l1.txt" >/dev/null
curl -s -o /dev/null --user "$MGU:$MGP" -X MKCOL "http://127.0.0.1:18777/dav/inf/sub" >/dev/null
curl -s -o /dev/null --user "$MGU:$MGP" -X PUT --data-binary @/dev/null "http://127.0.0.1:18777/dav/inf/sub/deep.txt" >/dev/null
code=$(curl -s -o "$WORK/inf.xml" -w '%{http_code}' --user "$MGU:$MGP" -X PROPFIND -H 'Depth: infinity' "http://127.0.0.1:18777/dav/inf")
expect_code "PROPFIND infinity" 207 "$code"
NINF=$(grep -o '<d:response>' "$WORK/inf.xml" | wc -l | tr -d ' ')
[ "$NINF" = "4" ] && ok "PROPFIND infinity recurses" || bad "PROPFIND infinity ($NINF)"
curl -s -o /dev/null --user "$MGU:$MGP" -X PUT --data-binary @/dev/null "http://127.0.0.1:18777/dav/blocker" >/dev/null
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$MGU:$MGP" -X MKCOL "http://127.0.0.1:18777/dav/blocker/sub")
expect_code "MKCOL through file 500" 500 "$code"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$MGU:$MGP" -X COPY -H "Destination: http://other-host/x" "http://127.0.0.1:18777/dav/cap/base.txt")
expect_code "COPY off-dav dest 400" 400 "$code"
code=$(curl -s -o "$WORK/cap.got" -w '%{http_code}' --user "$MGU:$MGP" "http://127.0.0.1:18777/dav/cap/f10001.txt")
expect_code "beyond-cap file still GETs" 200 "$code"
cmp -s "$WORK/capbase.bin" "$WORK/cap.got" && ok "beyond-cap bytes intact" || bad "beyond-cap bytes intact"

say "== measurement: ipv6 family mismatch =="
V6G=$(curl -s -b "$WORK/m1jar" -H 'Accept: application/json' -d "ips=::1/128&frm=&to=&layers=1" "http://127.0.0.1:18777/grant")
V6U=$(echo "$V6G" | jq -r .retrieve.user); V6P=$(echo "$V6G" | jq -r .retrieve.pass)
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$V6U:$V6P" "http://127.0.0.1:18777/fetch/$BIGID")
expect_code "v6-only grant from v4 peer" 403 "$code"

say "== measurement: live caps (10k grants, 100k blobs) =="
M2="$WORK/m2"; mkdir -p "$M2"
(cd "$M2" && exec "$BIN" 18779 >http.log 2>&1 & echo $! > "$WORK/m2.pid")
SRVM2=$(cat "$WORK/m2.pid")
sleep 1
M2U=$(jq -r .user "$M2/.env.json"); M2P=$(jq -r .pass "$M2/.env.json")
curl -s -c "$WORK/m2jar" -o /dev/null --max-time 10 -d "u=$M2U&p=$M2P" "http://127.0.0.1:18779/login"
M2G1=$(curl -s -b "$WORK/m2jar" -H 'Accept: application/json' -d "tw=1&ips=&frm=&to=&layers=1" "http://127.0.0.1:18779/grant")
M2SU=$(echo "$M2G1" | jq -r .store.user); M2SP=$(echo "$M2G1" | jq -r .store.pass)
GOK=$(python3 - "$WORK/m2jar" <<'PYEOF'
import http.client, sys
cookie = None
for ln in open(sys.argv[1]):
    if ln.startswith('#HttpOnly_'):
        ln = ln[len('#HttpOnly_'):]
    if ln.startswith('#') or not ln.strip():
        continue
    parts = ln.rstrip('\n').split('\t')
    if len(parts) >= 7 and parts[5] == 'tosv':
        cookie = parts[6]
assert cookie, 'no session cookie in jar'
made = 0
for _i in range(9999):
    c = http.client.HTTPConnection('127.0.0.1', 18779, timeout=30)
    body = 'ips=&frm=&to=&layers=1'
    c.request('POST', '/grant', body, {'Cookie': 'tosv=' + cookie, 'Content-Length': str(len(body))})
    r = c.getresponse()
    r.read()
    if r.status == 200:
        made += 1
    c.close()
print(made + 1)
PYEOF
)
[ "$GOK" = "10000" ] && ok "10k grants created" || bad "10k grants created ($GOK)"
code=$(curl -s -b "$WORK/m2jar" -o /dev/null -w '%{http_code}' -d "ips=&frm=&to=&layers=1" "http://127.0.0.1:18779/grant")
expect_code "grant 10001 refused" 507 "$code"
for _i in $(seq 1 100000); do : > "$M2/tosv_store/v$_i.bin"; done
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$M2SU:$M2SP" --data-binary @/dev/null "http://127.0.0.1:18779/store")
expect_code "store at 100000 allowed" 200 "$code"
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$M2SU:$M2SP" --data-binary @/dev/null "http://127.0.0.1:18779/store")
expect_code "store at 100001 refused" 507 "$code"
find "$M2/tosv_store" -maxdepth 1 -name 'v*.bin' -delete
code=$(curl -s -o /dev/null -w '%{http_code}' --user "$M2SU:$M2SP" --data-binary @/dev/null "http://127.0.0.1:18779/store")
expect_code "store after volume clear" 200 "$code"
python3 -c "open('$M2/tosv_db.txt','ab').write(b'x=1\n'*5000000)"
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 --user "$M2SU:$M2SP" --data-binary @/dev/null "http://127.0.0.1:18779/store")
expect_code "20MB db still serves head" 200 "$code"
kill "$SRVM1" "$SRVM2" 2>/dev/null; wait "$SRVM1" "$SRVM2" 2>/dev/null

say "== duress on fresh process =="
DUR=$(grep '^duress=' tosv_db.txt | head -1 | cut -d= -f2-)
DU="${DUR%%:*}"; DPW="${DUR#*:}"
kill "$SRVA" 2>/dev/null; wait "$SRVA" 2>/dev/null
"$BIN" "$PORTB" >"$WORK/srvb.log" 2>&1 &
SRVB=$!
sleep 1
code=$(curl -s -o "$OUT" -w '%{http_code}' --max-time 10 \
  -d "u=$DU&p=$DPW" "http://127.0.0.1:$PORTB/login")
expect_code "duress reply" 403 "$code"
expect_body "wiped text" "wiped" "$OUT"
grep -q " duress" tosv_audit.log && ok "audit duress" || bad "audit duress"
[ -f tosv_db.txt ] && bad "DB removed by wipe" || ok "DB removed by wipe"
LEFT=$(find tosv_store -type f | wc -l)
[ "$LEFT" = "0" ] && ok "store emptied by wipe" || bad "store emptied by wipe ($LEFT left)"

say "== R-17 sftp is PQ-only by default (SF-62) plus R-20 restore-v2 (FR-17) =="
WP="$WORK/wp"; mkdir -p "$WP"
(cd "$WP" && exec "$BIN" 18777 >http.log 2>&1 & echo $! > "$WORK/wph.pid")
(cd "$WP" && exec "$SFTPBIN" 18778 >sftp.log 2>&1 & echo $! > "$WORK/wps.pid")
SRVHP=$(cat "$WORK/wph.pid"); SRVWP=$(cat "$WORK/wps.pid")
sleep 1
WPU=$(jq -r .user "$WP/.env.json"); WPP=$(jq -r .pass "$WP/.env.json")
curl -s -c "$WORK/wpjar" -o /dev/null --max-time 10 -d "u=$WPU&p=$WPP" "http://127.0.0.1:18777/login"
WPG=$(curl -s -b "$WORK/wpjar" -H 'Accept: application/json' -d "tw=1&ips=&frm=&to=&layers=1" "http://127.0.0.1:18777/grant" | jq -r .retrieve.id)
echo "ssh-ed25519 $PUB pq gids=$WPG" > "$WP/sftp_gateway_keys"; chmod 600 "$WP/sftp_gateway_keys"
sftp -P 18778 -i "$WORK/sftpkey" -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10 -oKexAlgorithms=curve25519-sha256 -b "$WORK/b0" u@127.0.0.1 >/dev/null 2>&1
[ "$?" != "0" ] && ok "pq-only refuses curve25519" || bad "pq-only refuses curve25519"
sftp -P 18778 -i "$WORK/sftpkey" -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout=10 -oKexAlgorithms=mlkem768x25519-sha256 -b "$WORK/b0" u@127.0.0.1 >/dev/null 2>&1
[ "$?" = "0" ] && ok "pq-only accepts mlkem" || bad "pq-only accepts mlkem"
grep -q "sftp-kex mlkem768x25519" "$WP/tosv_audit.log" && ok "pq-only audited pq" || bad "pq-only audited pq"
grep -q "sftp-kex curve25519" "$WP/tosv_audit.log" && bad "pq-only no classic kex audited" || ok "pq-only no classic kex audited"
kill "$SRVHP" "$SRVWP" 2>/dev/null; wait "$SRVHP" "$SRVWP" 2>/dev/null
WR="$WORK/wr"; mkdir -p "$WR/tosv_store"
cp "$FX/blob.bin" "$WR/tosv_store/migr8.bin"; cp "$FX/blob.tag" "$WR/tosv_store/migr8.bin.tag"
printf 'su=%s\nsp=%s\nlayers=%s\ngrant=%s|%s|migr8|||\n' "$STORE_USER" "$STORE_PASS" "$LAYERS" "$GRANT_USER" "$GRANT_PASS" > "$WR/tosv_db.txt"
(cd "$WR" && "$BIN" --restore-v2 >"$WR/dry.out" 2>&1)
grep -q "v1=1 converted=0" "$WR/dry.out" && ok "restore-v2 dry-run counts" || bad "restore-v2 dry-run counts"
cmp -s "$FX/blob.bin" "$WR/tosv_store/migr8.bin" && ok "restore-v2 dry-run leaves v1" || bad "restore-v2 dry-run leaves v1"
(cd "$WR" && "$BIN" --restore-v2 --apply >"$WR/app.out" 2>&1); RC=$?
[ "$RC" = "0" ] && ok "restore-v2 apply rc 0" || bad "restore-v2 apply rc ($RC)"
[ "$(head -c1 "$WR/tosv_store/migr8.bin" | xxd -p)" = "02" ] && ok "restore-v2 blob now v2" || bad "restore-v2 blob now v2"
cmp -s "$FX/blob.bin" "$WR/tosv_v1_bak/migr8.bin" && ok "restore-v2 original backed up" || bad "restore-v2 original backed up"
(cd "$WR" && "$BIN" --restore-v2 2>&1 | grep -q "v1=0") && ok "restore-v2 idempotent" || bad "restore-v2 idempotent"
(cd "$WR" && exec "$BIN" 18779 >http.log 2>&1 & echo $! > "$WORK/wrh.pid")
SRVHR=$(cat "$WORK/wrh.pid"); sleep 1
curl -s -o "$WR/got.bin" --user "$GRANT_USER:$GRANT_PASS" "http://127.0.0.1:18779/fetch/migr8"
cmp -s "$FX/plain.bin" "$WR/got.bin" && ok "restore-v2 plaintext identical" || bad "restore-v2 plaintext identical"
kill "$SRVHR" 2>/dev/null; wait "$SRVHR" 2>/dev/null

say "== R-16 in-tree TLS 1.3 (SEC-11, ADR 0011): hybrid PQ by default, no external library =="
WT="$WORK/wt"; mkdir -p "$WT"
(cd "$WT" && TOSV_BIND=0.0.0.0 timeout 5 "$BIN" 18781 >bind2.out 2>&1); RC=$?
[ "$RC" != "0" ] && grep -q "requires TLS" "$WT/bind2.out" && ok "non-loopback bind refused without TLS" || bad "non-loopback bind refused without TLS"
"$BIN" --tls-selfsign 127.0.0.1 "$WT/c.pem" "$WT/k.pem" >/dev/null && ok "tls-selfsign writes cert and key" || bad "tls-selfsign writes cert and key"
"$BIN" --tls-selfsign 127.0.0.1 "$WT/c.pem" "$WT/k.pem" >/dev/null 2>&1; [ "$?" != "0" ] && ok "tls-selfsign refuses overwrite" || bad "tls-selfsign refuses overwrite"
[ "$(stat -c %a "$WT/k.pem")" = "600" ] && ok "tls key file mode 600" || bad "tls key file mode 600"
(cd "$WT" && TOSV_TLS_CERT=c.pem TOSV_TLS_KEY=/dev/null timeout 5 "$BIN" 18782 >tls0.out 2>&1); [ "$?" != "0" ] && ok "tls bad key refused loudly" || bad "tls bad key refused loudly"
(cd "$WT" && TOSV_TLS_CERT=c.pem TOSV_TLS_KEY=k.pem exec "$BIN" 18783 >srv.log 2>&1 & echo $! > "$WORK/wt.pid"); SRVT=$(cat "$WORK/wt.pid"); sleep 1
grep -q "groups=X25519MLKEM768$" "$WT/srv.log" && ok "tls banner pq-only groups by default" || bad "tls banner pq-only groups by default"
curl -s -m 10 --cacert "$WT/c.pem" --curves X25519MLKEM768 -o "$OUT" -w '%{http_code}' https://127.0.0.1:18783/login >"$WORK/tc"; expect_code "tls pq client login page" 200 "$(cat "$WORK/tc")"
curl -sv -m 10 --cacert "$WT/c.pem" --curves X25519MLKEM768 -o /dev/null https://127.0.0.1:18783/login 2>&1 | grep -q "TLSv1.3.*X25519MLKEM768" && ok "tls negotiated TLS1.3 X25519MLKEM768" || bad "tls negotiated TLS1.3 X25519MLKEM768"
curl -s -m 10 --cacert "$WT/c.pem" --curves X25519 -o /dev/null https://127.0.0.1:18783/login; [ "$?" != "0" ] && ok "tls refuses x25519-only client by default" || bad "tls refuses x25519-only client by default"
curl -s -m 5 -o /dev/null http://127.0.0.1:18783/login; [ "$?" != "0" ] && ok "tls port refuses plain http" || bad "tls port refuses plain http"
printf '\x16\x03\x01\x02\x00abc' | timeout 3 nc 127.0.0.1 18783 >/dev/null 2>&1; head -c 2000 /dev/urandom | timeout 3 nc 127.0.0.1 18783 >/dev/null 2>&1
curl -s -m 10 --cacert "$WT/c.pem" -o /dev/null -w '%{http_code}' https://127.0.0.1:18783/login >"$WORK/tc"; expect_code "tls survives garbage and truncated hello" 200 "$(cat "$WORK/tc")"
echo | openssl s_client -connect 127.0.0.1:18783 -CAfile "$WT/c.pem" -groups X25519:X25519MLKEM768 -tls1_3 2>&1 | grep -q "Negotiated TLS1.3 group: X25519MLKEM768" && ok "tls HelloRetryRequest steers to hybrid group" || bad "tls HelloRetryRequest steers to hybrid group"
(printf 'KU\n'; sleep 1; printf 'GET /login HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n'; sleep 1) | timeout 8 openssl s_client -connect 127.0.0.1:18783 -CAfile "$WT/c.pem" -groups X25519MLKEM768 -tls1_3 -ign_eof 2>&1 | grep -q "HTTP/1.1" && ok "tls traffic continues after KeyUpdate" || bad "tls traffic continues after KeyUpdate"
WTU=$(jq -r .user "$WT/.env.json"); WTP=$(jq -r .pass "$WT/.env.json")
curl -s --cacert "$WT/c.pem" -c "$WORK/wtjar" -o /dev/null -d "u=$WTU&p=$WTP" https://127.0.0.1:18783/login
python3 -c "import secrets;open('$WT/big.bin','wb').write(secrets.token_bytes(8000000))"
WTSU=$(grep '^su=' "$WT/tosv_db.txt" | cut -d= -f2-); WTSP=$(grep '^sp=' "$WT/tosv_db.txt" | cut -d= -f2-)
WTF=$(curl -s --cacert "$WT/c.pem" --user "$WTSU:$WTSP" --data-binary "@$WT/big.bin" https://127.0.0.1:18783/store | jq -r .id)
WTG=$(curl -s --cacert "$WT/c.pem" -b "$WORK/wtjar" -H 'Accept: application/json' -d 'tw=0&ips=&frm=&to=&layers=1' https://127.0.0.1:18783/grant)
curl -s --cacert "$WT/c.pem" --user "$(echo "$WTG" | jq -r .retrieve.user):$(echo "$WTG" | jq -r .retrieve.pass)" -o "$WT/got.bin" "https://127.0.0.1:18783/fetch/$WTF"
cmp -s "$WT/big.bin" "$WT/got.bin" && ok "tls 8MB store+fetch identical" || bad "tls 8MB store+fetch identical"
kill "$SRVT" 2>/dev/null; wait "$SRVT" 2>/dev/null
(cd "$WT" && TOSV_TLS_ALLOW_CLASSICAL=1 TOSV_TLS_CERT=c.pem TOSV_TLS_KEY=k.pem exec "$BIN" 18784 >srv2.log 2>&1 & echo $! > "$WORK/wt2.pid"); SRVT2=$(cat "$WORK/wt2.pid"); sleep 1
curl -s -m 10 --cacert "$WT/c.pem" --curves X25519 -o /dev/null -w '%{http_code}' https://127.0.0.1:18784/login >"$WORK/tc"; expect_code "tls classical client accepted only with ALLOW_CLASSICAL" 200 "$(cat "$WORK/tc")"
kill "$SRVT2" 2>/dev/null; wait "$SRVT2" 2>/dev/null

say "== result: $PASS passed, $FAIL failed =="
[ "$FAIL" = "0" ]
49.3ms