From 3b687a218eb67a31e0cfb05362a8aab73328bdd7 Mon Sep 17 00:00:00 2001 From: bchanot Date: Tue, 10 Nov 2026 22:33:49 +0100 Subject: [PATCH] feat(supabase): db:trial accounts, grants, equine drawings, app account: confirmed account through GoTrue's admin API, hidden password typed twice. grant: owner/admin by the operator path (factors counted in SQL and again in the transaction, names sanitised); catalogue rights mirror grant_catalog_right (admin first for sheet_editor), audit row, no implicit admin. Every grant typed at a terminal. assets: R5.5 tool through the gateway. app: Vite stopped and waited on exit. 323 stub-only harness cases. --- .../tasks/plans/2026-11-09-db-trial-stack.md | 18 + scripts/db-trial-check.sh | 378 +++++++++++++++++- scripts/db-trial.sh | 260 +++++++++++- 3 files changed, 649 insertions(+), 7 deletions(-) diff --git a/.claude/tasks/plans/2026-11-09-db-trial-stack.md b/.claude/tasks/plans/2026-11-09-db-trial-stack.md index 9ba17f74..3da20857 100644 --- a/.claude/tasks/plans/2026-11-09-db-trial-stack.md +++ b/.claude/tasks/plans/2026-11-09-db-trial-stack.md @@ -3363,6 +3363,24 @@ fresh_log; trial stop; fresh_log; trial app check "app: refused while the stack is stopped" refused "is not running" ``` +#### Lot B3 review fixes (2026-11-10) + +Already made by the B3 executor, kept: the lock is taken first (`require_state; take_lock` before `require_running`); `account` refuses a piped stdin; `app_stop` prints its message once; `grant` and `assets` die with a message when the factor read or the upload tool fails. + +1. Factor gate: `factor_count` (SQL `count(*)` of verified TOTP factors, never output lines) and `factor_list`, whose names are sanitised in SQL (`left(regexp_replace(..., '[^[:alnum:] ._-]', '?', 'g'), 40)`): no newline, CR or escape reaches the terminal. +2. `grant_platform_role`: the grant transaction counts the factors again (`select assign_platform_role(...) where (count) >= :need \gset`, `need` 2 for owner, 1 for admin): fewer rows nothing, `\gset` fails under ON_ERROR_STOP, the unfinished transaction rolls back, the operator reads "nothing was granted". +3. Catalogue rights mirror `public.grant_catalog_right` in operator SQL (the RPC needs an owner JWT at aal2): `catalog_grant_status` answers no_account, inactive, no_totp, not_admin, already or ok (confirmed active account; verified TOTP except catalog_reader; admin for sheet_editor and sheet_publisher; no active row), each refused with its own message and nothing written. The practitioner procedure is admin first (`pnpm db:trial grant admin`), then sheet_editor; the "granted but inactive under O1" note is gone. The write (insert, then `private.log_event(null, 'catalog_grant.operator_bootstrap', ...)`) is one `begin; ... commit;` that re-checks the rules; `granted_by` is the account's own id (NOT NULL column, the operator has no profile). An already active right stays exit 0, nothing written. +4. Every grant, catalogue included, asks the exact typed phrase `grant ` after the checks and the factor list, before any write. +5. Grant SQL (role and catalogue): explicit `begin;` ... `commit;` instead of `--single-transaction` (which commits a truncated script), ON_ERROR_STOP kept. +6. `read_new_password`: `IFS= read -rsp`, blanks kept and counted in the 12-character minimum. +7. `cmd_account` and `cmd_grant` lowercase the address (`${1,,}`, GoTrue stores it lowercased) before any use. +8. `read_new_password`: locals renamed `_rnp_typed` and `_rnp_again`, so a caller's variable cannot collide with the nameref. +9. `app_stop` finds Vite through `jobs -p` (no window between `&` and the pid assignment leaves an orphan) and `wait`s for it, so port 5194 is free on return; `cmd_app` ends with `wait $!`. +10. `require_terminal` in `check_arguments` for account, grant, restore, destroy: a non-terminal stdin is refused before any Docker call ("needs a terminal ... nothing was changed"). Moved assertions: B2 "restore/destroy with the phrase piped" now `refused_early` (no docker call); "restore refuses an incomplete backup" and the B3 lock case for `grant` now run at a terminal (`trial_tty`). +11. Known limit, no code: `app` takes no lock, so a `rotate-keys` can pass `refuse_while_app_runs` just before Vite binds; the app then keeps the previous anon key until its expiry. Holding the lock for the whole app session would block backup and migrate with a misleading message. Noted as a `shortcut:` comment in `cmd_app`. +12. Harness: one case per fix (stub hooks `answers/grant-factor-count`, `answers/txn-factors`, `vite-hold` with `vite-hold-sig`, `int-trial.sh`); the changed assertions are those of fix 10, the O1 cases (now the not_admin refusal), the grant cases that now run at a terminal, and the `-v need=` argument of the role grant. +13. Re-review (2026-11-10): the `shortcut:` above `cmd_app` now states the whole unlocked window and its upgrade path; harness comment on SIGINT corrected; the two-line factor name case now runs `factor_list` (indented lines, nothing written before the confirmation) with the SQL sanitisation kept as a named text check; the failing grant session case is named for the script's handling; the `granted_by` case asserts the bash comment; new case `fail/grant-catalog-write` (catalogue write failing after a passing check). + --- ### Lot C: documentation, comments, TODO diff --git a/scripts/db-trial-check.sh b/scripts/db-trial-check.sh index 5ec923b3..8912e6a8 100755 --- a/scripts/db-trial-check.sh +++ b/scripts/db-trial-check.sh @@ -70,6 +70,9 @@ done sleep 0.5 STUB +# The same with SIGINT (Ctrl+C reaches the script, not only its children). +sed 's/kill -TERM/kill -INT/' "$WORK/term-trial.sh" > "$WORK/int-trial.sh" + cat > "$WORK/bin/docker" <<'STUB' #!/usr/bin/env bash # docker stand-in: one log line per call (newlines shown as \n), one file per pretend resource. @@ -213,6 +216,14 @@ case "$sub" in printf '%s\n' "${ROT_DIGEST:-}" > "$st/answers/rotation-marker"; echo "stub: stream lost" >&2; exit 3 fi if [ -n "$tag" ] && [ -f "$st/fail/$tag" ]; then echo "stub: $tag refused" >&2; exit 3; fi + # txn-factors: what the grant transaction finds when it counts the factors again. Like psql with + # ON_ERROR_STOP, the session fails (\gset finds no row) when the SQL holds that count and the + # number is below the :need it was given; an SQL without the count goes through. + if [ "$tag" = grant-role ] && [ -f "$st/answers/txn-factors" ] && grep -q mfa_factors <<<"$query"; then + need='' prev='' + for a in "$@"; do case "$prev:$a" in -v:need=*) need="${a#need=}" ;; esac; prev="$a"; done + if [ "$(cat "$st/answers/txn-factors")" -lt "$need" ]; then echo "stub: no rows returned for \\gset" >&2; exit 3; fi + fi if [ -n "$tag" ] && [ -s "$st/answers/$tag.seq" ]; then head -n 1 "$st/answers/$tag.seq"; sed -i 1d "$st/answers/$tag.seq" elif [ -n "$tag" ] && [ -f "$st/answers/$tag" ]; then cat "$st/answers/$tag"; fi @@ -223,7 +234,8 @@ STUB cat > "$WORK/bin/curl" <<'STUB' #!/usr/bin/env bash # curl stand-in. The trial gateway's identity endpoint answers faunosteo_trial, or -# answers/identity, or fails (fail/identity, curl -f's exit 22). +# answers/identity, or fails (fail/identity, curl -f's exit 22). fail/admin-users: GoTrue's admin +# API refuses the account (exit 22). { printf 'curl'; for a in "$@"; do printf ' %s' "$a"; done; printf '\n'; } >> "$STUB_LOG" for a in "$@"; do case "$a" in @@ -232,6 +244,7 @@ for a in "$@"; do @/dev/fd/*) sha256sum < "${a#@}" | cut -c1-16 > "$STUB_STATE/curl-header-sha" ;; esac done +case "$*" in */admin/users*) [ ! -f "$STUB_STATE/fail/admin-users" ] || exit 22 ;; esac case "${*: -1}" in */__faunosteo_stack) [ ! -f "$STUB_STATE/fail/identity" ] || exit 22 @@ -275,6 +288,23 @@ cat > "$WORK/repo/apps/app/node_modules/.bin/vite" <<'STUB' "$(printf '%s' "${VITE_SUPABASE_ANON_KEY:-}" | sha256sum | cut -c1-16)" "${PGPASSWORD:+set}" \ "${NODE_OPTIONS:-}" "${FAUNOSTEO_TRIAL_GATEWAY:-}" "${FAUNOSTEO_TRIAL_HOST:-}" "${VITE_SUPABASE_URL:-}" \ "${http_proxy:-}${HTTP_PROXY:-}${https_proxy:-}${HTTPS_PROXY:-}${all_proxy:-}${ALL_PROXY:-}${NODE_USE_ENV_PROXY:-}"; } >> "$STUB_LOG" +# term-in-vite: the app is running when the script gets a SIGTERM. +if [ -f "$STUB_STATE/term-in-vite" ]; then bash "$STUB_TERM"; fi +# vite-hold: a long-running server on 5194 that writes its pid and takes a second to die on SIGTERM +# (the launcher resets SIGINT to default: that is about the harness's own backgrounded shell, the real +# Vite dies on a terminal Ctrl+C as node resets dispositions at startup). vite-hold-sig: the signaller script to +# run once it listens (term-trial.sh or int-trial.sh), the pid file written before. +if [ -f "$STUB_STATE/vite-hold" ]; then + exec python3 -c 'import os, signal, socket, sys, time +s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +s.bind(("127.0.0.1", 5194)); s.listen(1) +open(sys.argv[1], "w").write(str(os.getpid())) +def term(*_): + time.sleep(1); sys.exit(0) +signal.signal(signal.SIGTERM, term) +if os.path.exists(sys.argv[2]): os.system("bash " + open(sys.argv[2]).read().strip()) +time.sleep(30)' "$STUB_STATE/vite.pid" "$STUB_STATE/vite-hold-sig" +fi STUB cat > "$WORK/repo/scripts/upload-sheet-assets.sh" <<'STUB' #!/usr/bin/env bash @@ -358,7 +388,8 @@ new_case() { # name printf '%s\n' "$ASSET_LINE" > "$CASE/stub/answers/asset-rows" echo 1 > "$CASE/stub/answers/assets-uploaded" echo 0 > "$CASE/stub/answers/rotation-active" - echo 'granted false' > "$CASE/stub/answers/grant-catalog" + echo ok > "$CASE/stub/answers/grant-catalog" + echo 0 > "$CASE/stub/answers/grant-factor-count" EXTRA=() CASE_PATH="$WORK/bin:$BASE_PATH" # The no-daemon barrier: a unix socket that does not exist (so the script's local-daemon guard @@ -388,6 +419,43 @@ sys.stdout.flush() _, status = os.waitpid(pid, 0) sys.exit(os.waitstatus_to_exitcode(status)) ' +# The same for a hidden prompt: each line is typed once the previous prompt (text ending in ": ") has +# been printed and the script had time to switch the terminal echo off, so a password is never echoed +# into the captured output. +PTY_PROMPT_DRIVER=' +import os, pty, sys, time +pid, fd = pty.fork() +if pid == 0: + os.execvp(sys.argv[1], sys.argv[1:]) +lines = sys.stdin.buffer.read().split(b"\n") +if lines and lines[-1] == b"": + lines.pop() +def pump(stop_at_prompt): + seen = b"" + while True: + try: + chunk = os.read(fd, 4096) + except OSError: + return False + if not chunk: + return False + sys.stdout.buffer.write(chunk) + seen += chunk + if stop_at_prompt and seen.endswith(b": "): + return True +alive = True +for line in lines: + alive = pump(True) + if not alive: + break + time.sleep(0.3) + os.write(fd, line + b"\n") +if alive: + pump(False) +sys.stdout.flush() +_, status = os.waitpid(pid, 0) +sys.exit(os.waitstatus_to_exitcode(status)) +' LAUNCH=() run_script() { # script args... → RC, output in $CASE/out; stdin as the caller set it local script="$1" entry @@ -412,6 +480,13 @@ trial_tty() { # input args...: the input typed at the script's terminal run_script db-trial.sh "$@" <<<"$input" LAUNCH=() } +trial_typed() { # lines args...: lines typed one per prompt at the script's terminal, never echoed + local input="$1" + shift + LAUNCH=(python3 -c "$PTY_PROMPT_DRIVER") + run_script db-trial.sh "$@" <<<"$input" + LAUNCH=() +} sandbox() { LAUNCH=(); run_script db-sandbox.sh "$@" < /dev/null; } fresh_log() { : > "$CASE/log"; } @@ -672,7 +747,7 @@ rm -f "$CASE/stub/short-archive"; fresh_log; trial start mkdir -m 700 "$STATE_DIR/backups/20000101T000000Z-partial" fresh_log; trial status check "status marks a folder without SHA256SUMS incomplete" bash -c 'grep -F "20000101T000000Z-partial" "$1" | grep -qF incomplete' _ "$CASE/out" -fresh_log; trial restore 20000101T000000Z-partial +fresh_log; trial_tty x restore 20000101T000000Z-partial check "restore refuses an incomplete backup before any change" refused "is incomplete" rmdir "$STATE_DIR/backups/20000101T000000Z-partial" @@ -770,7 +845,7 @@ rm -f "$CASE/stub/fail/image" fresh_log; trial_tty nope restore "$NAME" check "restore: a wrong phrase changes nothing" refused "not confirmed" fresh_log; trial_input restore "$NAME" <<<"restore $NAME" -check "restore: the phrase piped without a terminal is refused" refused "needs a terminal" +check "restore: the phrase piped without a terminal is refused before any call (B2, moved by fix 10)" refused_early "needs a terminal" fresh_log; trial_tty "restore $NAME" restore "$NAME" check "restore: succeeds" [ "$RC" -eq 0 ] check "restore: says the backup brings back older secrets" out_has "holds other secrets than the current ones" @@ -784,7 +859,7 @@ echo "-- destroy" fresh_log; trial_tty '' destroy check "destroy with an empty answer: nothing changed" refused "not confirmed" fresh_log; trial_input destroy <<<"faunosteo_trial" -check "destroy with the phrase piped without a terminal: refused, nothing changed" refused "needs a terminal" +check "destroy with the phrase piped without a terminal: refused before any call (B2, moved by fix 10)" refused_early "needs a terminal" fresh_log; trial_tty faunosteo_trial destroy check "destroy: succeeds" [ "$RC" -eq 0 ] check "destroy: a backup before any removal" before 'faunosteo_trial_db:/volume:ro --entrypoint tar' 'docker rm faunosteo_trial_db' @@ -1040,6 +1115,299 @@ new_case term-rotation; trial create echo '^tag:rotate$' > "$CASE/stub/term-on"; fresh_log; trial rotate-secrets check "rotate-secrets terminated by SIGTERM: one message, the uncommitted branch" bash -c '[ "$(grep -c "rotate-secrets stopped" "$1")" -eq 1 ] && grep -qF "stopped before secrets.env took the new secrets" "$1"' _ "$CASE/out" +echo "-- accounts, grants, drawings, app" +PW=correct-horse-battery +fresh_stdin() { find "$CASE/stub/stdin" -type f -delete; } +no_role_assigned() { stdin_lacks assign_platform_role; } +# A catalogue grant never writes a platform role: neither the function nor the table appears in any SQL it sent. +catalog_grant_only() { stdin_lacks assign_platform_role && stdin_lacks profile_roles && stdin_has anatomical_catalog_grants; } +no_catalog_write() { stdin_lacks 'db-trial:grant-catalog-write'; } # the audit row is part of that SQL +set_factors() { # n: n verified factors, as the count and as the list the stub answers + echo "$1" > "$CASE/stub/answers/grant-factor-count" + printf '%s\n' 'Phone | 2026-11-09 10:00 UTC' 'Tablet | 2026-11-09 10:05 UTC' | head -n "$1" > "$CASE/stub/answers/grant-factors" +} +# shellcheck disable=SC2046 +stdin_of() { grep -l -- "-- db-trial:$1\$" /dev/null $(stdin_files) | head -n 1; } # the SQL a tag sent +new_case people; trial create +check "people: create" [ "$RC" -eq 0 ] +fresh_log; trial account 'not-an-email' +check "account: a malformed address is refused before any call" refused_early "e-mail address" +fresh_log; trial_input account owner@trial.test <<<"$PW"$'\n'"$PW" +check "account: a password is never read from a pipe, nothing sent" bash -c '[ "$1" -ne 0 ] && grep -qF "needs a terminal" "$2" && ! grep -q "^curl .*admin/users" "$3" && ! grep -qF "$4" "$2" "$3"' _ "$RC" "$CASE/out" "$CASE/log" "$PW" +fresh_log; trial_typed $'short\nshort' account owner@trial.test +check "account: a short password is refused, nothing sent" bash -c '[ "$1" -ne 0 ] && ! grep -q "^curl .*admin/users" "$2" && grep -qF "12 characters" "$3" && ! grep -qF short "$2"' _ "$RC" "$CASE/log" "$CASE/out" +fresh_log; trial_typed "$PW"$'\nother-horse-battery' account owner@trial.test +check "account: two different passwords are refused, nothing sent" bash -c '[ "$1" -ne 0 ] && grep -qF "differ" "$2" && ! grep -q "^curl .*admin/users" "$3"' _ "$RC" "$CASE/out" "$CASE/log" +: > "$CASE/stub/fail/admin-users" +fresh_log; trial_typed "$PW"$'\n'"$PW" account owner@trial.test +check "account: GoTrue refusing the account is told, no password in calls or output" bash -c '[ "$1" -ne 0 ] && grep -qF "account not created" "$2" && ! grep -qF "$3" "$2" "$4"' _ "$RC" "$CASE/out" "$PW" "$CASE/log" +rm -f "$CASE/stub/fail/admin-users" +fresh_log; trial_typed "$PW"$'\n'"$PW" account owner@trial.test +check "account: created and confirmed" bash -c '[ "$1" -eq 0 ] && grep -qF "account owner@trial.test created and confirmed" "$2"' _ "$RC" "$CASE/out" +check "account: GoTrue admin API on loopback, header through a pipe fd, body on stdin" bash -c 'grep -qE "^curl -q --noproxy \* -fsS -o /dev/null -X POST http://127.0.0.1:58999/admin/users -H @/dev/fd/[0-9]+ -H Content-Type: application/json --data-binary @-$" "$1"' _ "$CASE/log" +check "account: the header sent carries exactly the checked service key, no header file exists" bash -c '[ "$(cat "$1")" = "$(printf "Authorization: Bearer %s\n" "$(sed -n "s/^TR_SERVICE_KEY=//p" "$2")" | sha256sum | cut -c1-16)" ] && [ ! -e "$3/service-header" ]' _ "$CASE/stub/curl-header-sha" "$STATE_DIR/secrets.env" "$STATE_DIR" +check "account: the password never appears in calls or output" bash -c '! grep -qF "$1" "$2" "$3"' _ "$PW" "$CASE/log" "$CASE/out" +check "account: no secret in calls or output" secrets_absent "$STATE_DIR/secrets.env" +check "account: the body is a confirmed account" stdin_has '"email_confirm":true' +check "account: the state folder holds no file that is not 600" bash -c '[ -z "$(find "$1" -type f ! -perm 600)" ]' _ "$STATE_DIR" +fresh_log; trial grant owner@trial.test root +check "grant: an unknown right is refused before any call" refused_early "right:" +set_factors 1 +fresh_stdin; fresh_log; trial_tty 'grant owner' grant owner@trial.test owner +check "grant owner with one factor: refused (two needed), nothing assigned" bash -c '[ "$1" -ne 0 ] && grep -qF "owner needs 2" "$2" && grep -qF "nothing was granted" "$2"' _ "$RC" "$CASE/out" +check "grant owner with one factor: no role SQL ran" no_role_assigned +set_factors 2 +fresh_log; trial_tty no grant owner@trial.test owner +check "grant owner, wrong phrase: nothing assigned" bash -c '[ "$1" -ne 0 ] && grep -qF "not confirmed" "$2"' _ "$RC" "$CASE/out" +check "grant owner, wrong phrase: no role SQL ran" no_role_assigned +fresh_log; trial_input grant owner@trial.test owner <<<'grant owner' +check "grant owner, phrase piped without a terminal: refused before any call" refused_early "needs a terminal" +check "grant owner, phrase piped: no role SQL ran" no_role_assigned +: > "$CASE/stub/fail/grant-factors" +fresh_log; trial_tty 'grant owner' grant owner@trial.test owner +check "grant: factors that cannot be read refuse, nothing granted" bash -c '[ "$1" -ne 0 ] && grep -qF "nothing was granted" "$2"' _ "$RC" "$CASE/out" +rm -f "$CASE/stub/fail/grant-factors" +: > "$CASE/stub/fail/grant-role" +fresh_log; trial_tty 'grant owner' grant owner@trial.test owner +check "grant owner: the role SQL failing is told" bash -c '[ "$1" -ne 0 ] && grep -qF "owner not granted to owner@trial.test" "$2"' _ "$RC" "$CASE/out" +rm -f "$CASE/stub/fail/grant-role"; fresh_stdin +fresh_log; trial_tty 'grant owner' grant owner@trial.test owner +check "grant owner: factors shown, operator path, audit row" bash -c '[ "$1" -eq 0 ] && grep -qF "Tablet | 2026-11-09 10:05 UTC" "$2" && grep -rlF "private.assign_platform_role(null, :'"'"'uid'"'"'::uuid" "$3" | grep -q . && grep -rlF "platform_role.operator_bootstrap" "$3" | grep -q .' _ "$RC" "$CASE/out" "$CASE/stub/stdin" +check "grant owner: email, role and operator as psql variables" log_has "-v email=owner@trial.test -v role=owner -v need=2 -v operator=" +check "grant owner: no secret in calls or output" secrets_absent "$STATE_DIR/secrets.env" +set_factors 1 +fresh_log; trial_tty 'grant admin' grant practitioner@trial.test admin +check "grant admin with one factor: granted, one factor suffices" bash -c '[ "$1" -eq 0 ] && grep -qF "admin granted to practitioner@trial.test" "$2"' _ "$RC" "$CASE/out" +check "grant admin: role passed as a psql variable" log_has "-v email=practitioner@trial.test -v role=admin -v need=1 -v operator=" +set_factors 0 +fresh_log; trial_tty 'grant admin' grant practitioner@trial.test admin +check "grant admin with no factor: refused" bash -c '[ "$1" -ne 0 ] && grep -qF "admin needs 1" "$2"' _ "$RC" "$CASE/out" +fresh_stdin; fresh_log; trial_tty 'grant sheet_editor' grant practitioner@trial.test sheet_editor +check "grant sheet_editor (admin already): inserted, no O1 note" bash -c '[ "$1" -eq 0 ] && grep -qF "sheet_editor granted" "$2" && ! grep -qF "rule O1" "$2"' _ "$RC" "$CASE/out" +check "grant sheet_editor: a catalogue right never assigns a platform role (no implicit admin)" catalog_grant_only +echo already > "$CASE/stub/answers/grant-catalog" +fresh_stdin; fresh_log; trial_tty 'x' grant practitioner@trial.test sheet_editor +check "grant sheet_editor again: nothing changed, nothing written" bash -c '[ "$1" -eq 0 ] && grep -qF "already active" "$2"' _ "$RC" "$CASE/out" +check "grant sheet_editor again: no write SQL sent" no_catalog_write +echo ok > "$CASE/stub/answers/grant-catalog" +fresh_log; trial_tty 'grant catalog_reader' grant practitioner@trial.test catalog_reader +check "grant catalog_reader: granted" bash -c '[ "$1" -eq 0 ] && grep -qF "catalog_reader granted" "$2"' _ "$RC" "$CASE/out" +echo 'oops' > "$CASE/stub/answers/grant-catalog" +fresh_log; trial_tty 'grant sheet_reviewer' grant practitioner@trial.test sheet_reviewer +check "grant: an unexpected database answer is refused" bash -c '[ "$1" -ne 0 ] && grep -qF "unexpected answer" "$2"' _ "$RC" "$CASE/out" +echo ok > "$CASE/stub/answers/grant-catalog" +: > "$CASE/stub/fail/grant-catalog-write" +fresh_stdin; fresh_log; trial_tty 'grant sheet_reviewer' grant practitioner@trial.test sheet_reviewer +check "grant: the catalogue write failing after a passing check: refused, nothing granted" bash -c '[ "$1" -ne 0 ] && grep -qF "sheet_reviewer not granted" "$2" && grep -qF "nothing was granted" "$2" && ! grep -qF "sheet_reviewer granted to" "$2"' _ "$RC" "$CASE/out" +rm -f "$CASE/stub/fail/grant-catalog-write" + +echo "-- B3 review fixes" +# 3: every refusal reason, distinct, with no write SQL and no audit row. +for pair in 'no_account|no account practitioner@trial.test|sheet_reviewer' 'inactive|inactive or its e-mail is not confirmed|sheet_reviewer' \ + 'no_totp|holds no verified TOTP factor|sheet_reviewer' 'not_admin|grant practitioner@trial.test admin|sheet_editor' 'not_admin|grant practitioner@trial.test admin|sheet_publisher'; do + IFS='|' read -r status text kind <<<"$pair" + echo "$status" > "$CASE/stub/answers/grant-catalog" + fresh_stdin; fresh_log; trial_tty "grant $kind" grant practitioner@trial.test "$kind" + check "grant $kind, $status: refused with its own reason, nothing written" bash -c '[ "$1" -ne 0 ] && grep -qF -- "$2" "$3" && grep -qF "nothing was granted" "$3"' _ "$RC" "$text" "$CASE/out" + check "grant $kind, $status: no insert, no audit row" no_catalog_write +done +echo ok > "$CASE/stub/answers/grant-catalog" +# 3: the check SQL carries the rules of public.grant_catalog_right. +fresh_stdin; fresh_log; trial_tty 'grant sheet_editor' grant practitioner@trial.test sheet_editor +check "grant catalogue: the eligibility rules are in the check and again in the write" bash -c 'for f in "$@"; do grep -q is_confirmed_active_account "$f" && grep -q has_verified_totp "$f" && grep -q is_platform_admin "$f" || exit 1; done' _ "$(stdin_of grant-catalog)" "$(stdin_of grant-catalog-write)" +file_has_all() { local f="$1" t; shift; for t in "$@"; do grep -qF -- "$t" "$f" || return 1; done; } +ACTIVE_ROW="g.revoked_at is null and (g.expires_at is null or g.expires_at > now())" +check "grant catalogue: the check SQL carries every reason and rule of public.grant_catalog_right" file_has_all "$(stdin_of grant-catalog)" \ + "when u.id is null then 'no_account'" "when not private.is_confirmed_active_account(u.id) then 'inactive'" \ + "when :'kind' <> 'catalog_reader' and not private.has_verified_totp(u.id) then 'no_totp'" \ + "when :'kind' in ('sheet_editor', 'sheet_publisher') and not private.is_platform_admin(u.id) then 'not_admin'" \ + "$ACTIVE_ROW) then 'already'" +check "grant catalogue: the write SQL re-checks the same rules and the active-row rule" file_has_all "$(stdin_of grant-catalog-write)" \ + "private.is_confirmed_active_account(:'uid'::uuid)" "(:'kind' = 'catalog_reader' or private.has_verified_totp(:'uid'::uuid))" \ + "(:'kind' not in ('sheet_editor', 'sheet_publisher') or private.is_platform_admin(:'uid'::uuid))" "$ACTIVE_ROW" +check "grant catalogue: insert and audit row in one explicit transaction" bash -c 'f="$1"; [ "$(sed -n 2p "$f")" = "begin;" ] && grep -q "^insert into public.anatomical_catalog_grants" "$f" && grep -q "catalog_grant.operator_bootstrap" "$f" && [ "$(tail -n 1 "$f")" = "commit;" ]' _ "$(stdin_of grant-catalog-write)" +check "grant catalogue: the audit row names kind, operator and reason" bash -c 'grep -q "jsonb_build_object(.kind., :.kind., .operator., :.operator." "$1"' _ "$(stdin_of grant-catalog-write)" +check "grant catalogue: the script comments granted_by as the account's own id, and no platform role is written" bash -c 'grep -qF "# granted_by is the account'"'"'s own id" "$1" && ! grep -qE "profile_roles|assign_platform_role" "$2" "$3"' _ "$REPO/scripts/db-trial.sh" "$(stdin_of grant-catalog-write)" "$(stdin_of grant-catalog)" +check "grant: no --single-transaction in any psql call" bash -c '! grep -q -- "--single-transaction" "$1"' _ "$CASE/log" +fresh_stdin; fresh_log; trial_tty 'grant catalog_reader' grant practitioner@trial.test catalog_reader +check "grant catalog_reader: needs no TOTP and no admin (the check SQL scopes both to other kinds)" bash -c '[ "$1" -eq 0 ] && grep -qF "<> '"'"'catalog_reader'"'"' and not private.has_verified_totp" "$2" && grep -qF "catalog_reader granted" "$3"' _ "$RC" "$(stdin_of grant-catalog)" "$CASE/out" +# 4: exact typed phrase for a catalogue grant; piped or wrong refuses with nothing written. +fresh_stdin; fresh_log; trial_tty 'grant sheet_reviewe' grant practitioner@trial.test sheet_reviewer +check "grant catalogue, wrong phrase: not confirmed, nothing written" bash -c '[ "$1" -ne 0 ] && grep -qF "not confirmed" "$2"' _ "$RC" "$CASE/out" +check "grant catalogue, wrong phrase: no insert, no audit" no_catalog_write +fresh_log; trial_input grant practitioner@trial.test sheet_reviewer <<<'grant sheet_reviewer' +check "grant catalogue, phrase piped: refused before any call" refused_early "needs a terminal" +# 10: terminal-only commands refuse a piped stdin before any call. +fresh_log; trial_input account owner@trial.test <<<"$PW" +check "account, piped stdin: refused before any call" refused_early "needs a terminal" +fresh_log; trial_input restore 20261101T101010Z-manual <<<'restore' +check "restore, piped stdin: refused before any call" refused_early "needs a terminal" +fresh_log; trial_input destroy <<<'destroy' +check "destroy, piped stdin: refused before any call" refused_early "needs a terminal" +# 1: the count comes from SQL; a name with a newline cannot add a line. +set_factors 1 +printf '%s\n' 'Phone | 2026-11-09 10:00 UTC' 'Injected | 2026-11-09 10:01 UTC' > "$CASE/stub/answers/grant-factors" +fresh_stdin; fresh_log; trial_tty 'x' grant owner@trial.test admin +check "grant: factor_list output is shown one indented line per factor line, nothing written before the confirmation" bash -c '[ "$1" -ne 0 ] && grep -qE "^ Phone \| 2026-11-09 10:00 UTC[[:cntrl:]]*$" "$2" && grep -qE "^ Injected \| 2026-11-09 10:01 UTC[[:cntrl:]]*$" "$2"' _ "$RC" "$CASE/out" +check "grant: no role SQL sent before the confirmation" stdin_lacks db-trial:grant-role +check "grant: the factor count is a count(*) in SQL" bash -c 'grep -qE "select count\(\*\)" "$1" && grep -q "factor_type = .totp. and f.status = .verified." "$1"' _ "$(stdin_of grant-factor-count)" +set_factors 2; fresh_stdin; fresh_log; trial_tty 'grant owner' grant owner@trial.test owner +SANITISED="left(regexp_replace(coalesce(nullif(f.friendly_name, ''), '(no name)'), '[^[:alnum:] ._-]', '?', 'g'), 40)" +check "grant: SQL text check, the displayed name is sanitised in SQL (no newline, CR or ESC reaches the terminal)" bash -c 'grep -qF -- "$2" "$1"' _ "$(stdin_of grant-factors)" "$SANITISED" +# 2: the transaction counts again. +echo 1 > "$CASE/stub/answers/txn-factors"; fresh_stdin +fresh_log; trial_tty 'grant owner' grant owner@trial.test owner +check "grant owner: script handling of a failing grant session (stub emulates \\gset with zero rows, count 2 then 1): nothing granted" bash -c '[ "$1" -ne 0 ] && grep -qF "nothing was granted" "$2" && ! grep -qF "owner granted to owner@trial.test" "$2"' _ "$RC" "$CASE/out" +check "grant owner: the transaction SQL counts the factors against :need" bash -c 'grep -q "mfa_factors" "$1" && grep -q ">= :need" "$1"' _ "$(stdin_of grant-role)" +check "grant role: explicit begin and commit, never --single-transaction" bash -c 'f="$1"; [ "$(sed -n 2p "$f")" = "begin;" ] && [ "$(tail -n 1 "$f")" = "commit;" ] && ! grep -q -- "--single-transaction" "$2"' _ "$(stdin_of grant-role)" "$CASE/log" +echo 2 > "$CASE/stub/answers/txn-factors"; fresh_stdin; fresh_log; trial_tty 'grant owner' grant owner@trial.test owner +check "grant owner: two factors still there in the transaction: granted" bash -c '[ "$1" -eq 0 ] && grep -qF "owner granted to owner@trial.test" "$2"' _ "$RC" "$CASE/out" +rm -f "$CASE/stub/answers/txn-factors" +# 7: the e-mail is lowercased before any use. +fresh_stdin; fresh_log; trial_tty 'grant sheet_reviewer' grant Foo@Example.com sheet_reviewer +check "grant Foo@Example.com: the lowercased address is used everywhere" bash -c '[ "$1" -eq 0 ] && grep -qF -- "-v email=foo@example.com" "$2" && ! grep -qF "Foo@" "$2" "$3"' _ "$RC" "$CASE/log" "$CASE/out" +fresh_stdin; fresh_log; trial_typed "$PW"$'\n'"$PW" account Foo@Example.com +check "account Foo@Example.com: the body carries the lowercased address" bash -c '[ "$1" -eq 0 ] && grep -qF "\"email\":\"foo@example.com\"" $(find "$2" -type f) && ! grep -qF "Foo@" "$3"' _ "$RC" "$CASE/stub/stdin" "$CASE/out" +# 6: passwords count their blanks. +fresh_log; trial_typed '12345678901'$'\n''12345678901' account long@trial.test +check "account: an 11-character password is refused" bash -c '[ "$1" -ne 0 ] && grep -qF "12 characters" "$2" && ! grep -q "^curl .*admin/users" "$3"' _ "$RC" "$CASE/out" "$CASE/log" +fresh_stdin; fresh_log; trial_typed '123456789012'$'\n''123456789012' account long@trial.test +check "account: a 12-character password is accepted" [ "$RC" -eq 0 ] +SPACED=' leading-and-trailing ' +fresh_stdin; fresh_log; trial_typed "$SPACED"$'\n'"$SPACED" account spaced@trial.test +check "account: a password with leading and trailing blanks reaches the body unchanged" bash -c '[ "$1" -eq 0 ] && [ "$(node -e "const b = JSON.parse(require(\"fs\").readFileSync(process.argv[1], \"utf8\")); console.log(b.password === process.argv[2] ? 1 : 0)" "$(find "$2" -type f | head -n 1)" "$3")" = 1 ]' _ "$RC" "$CASE/stub/stdin" "$SPACED" +check "account: the spaced password is in no call or output" bash -c '! grep -qF "leading-and-trailing" "$1" "$2"' _ "$CASE/log" "$CASE/out" +# 8: read_new_password cannot collide with a caller's variable name. +check "read_new_password: callers named typed or again still get their password" bash -c ' + die() { echo "$*" >&2; exit 1; } + source <(sed -n "/^read_new_password()/,/^}/p" "$1") + for v in typed again; do + read_new_password "$v" <<<"correct-horse-battery"$'"'"'\n'"'"'"correct-horse-battery" 2>/dev/null || exit 1 + [ "${!v}" = correct-horse-battery ] || exit 1 + done' _ "$WORK/repo/scripts/db-trial.sh" +SERVICE_SHA="$(sed -n 's/^TR_SERVICE_KEY=//p' "$STATE_DIR/secrets.env" | tr -d '\n' | sha256sum | cut -c1-16)" +ANON_SHA="$(sed -n 's/^TR_ANON_KEY=//p' "$STATE_DIR/secrets.env" | tr -d '\n' | sha256sum | cut -c1-16)" +fresh_log; EXTRA=(INIT_CWD=/elsewhere FAUNOSTEO_DEV_HOST=127.0.0.1); trial assets; EXTRA=() +check "assets: upload then check, through the trial gateway" bash -c '[ "$1" -eq 0 ] && grep -qx "upload supabase/seed/anatomical-sheets/equine/draft" "$2" && grep -qx "upload --check supabase/seed/anatomical-sheets/equine/draft" "$2" && [ "$(grep -c "^upload-env url=http://127.0.0.1:58801 " "$2")" -eq 2 ]' _ "$RC" "$CASE/log" +check "assets: the service key by environment, LAN host and INIT_CWD dropped" bash -c '[ "$(grep -c "^upload-env .*key-sha=$1 dev-host= init-cwd=$" "$2")" -eq 2 ]' _ "$SERVICE_SHA" "$CASE/log" +check "assets: every drawing confirmed" out_has "1/1 uploaded" +check "assets: no secret in calls or output" secrets_absent "$STATE_DIR/secrets.env" +echo 0 > "$CASE/stub/answers/assets-uploaded"; fresh_log; trial assets +check "assets: a drawing not confirmed in the database fails" bash -c '[ "$1" -ne 0 ] && grep -qF "not every drawing row" "$2"' _ "$RC" "$CASE/out" +echo 1 > "$CASE/stub/answers/assets-uploaded" +EXTRA=(http_proxy=http://127.0.0.1:9 HTTPS_PROXY=http://127.0.0.1:9 ALL_PROXY=socks5://127.0.0.1:9 NODE_USE_ENV_PROXY=1) +fresh_log; trial app; EXTRA=() +check "app: Vite on the trial host and 5194, strict port" log_has 'vite --config vite/trial.config.ts --host 127.0.0.1 --port 5194 --strictPort' +check "app: anon key by environment, no PGPASSWORD, heap capped, trial gateway" bash -c 'grep -qx "vite-env anon-sha=$1 pgpassword= node-options=--max-old-space-size=768 gateway=http://127.0.0.1:58801 host=127.0.0.1 url=http://127.0.0.1:5194 proxies=" "$2"' _ "$ANON_SHA" "$CASE/log" +check "app: every curl pinned (-q, --noproxy), Vite started with no proxy variable" curls_pinned +check "app: no secret in calls or output" secrets_absent "$STATE_DIR/secrets.env" +if hold_port 5194; then fresh_log; trial app; check "app: port 5194 in use, nothing started" refused "5194 is in use"; release_port +else fail "could not hold 127.0.0.1:5194 for the app case"; fi +: > "$CASE/stub/term-in-vite"; fresh_log; trial app; rm -f "$CASE/stub/term-in-vite" +check "app terminated by SIGTERM: exit 130, one message, the stack untouched" bash -c '[ "$1" -eq 130 ] && [ "$(grep -c "trial app stopped" "$2")" -eq 1 ] && ! grep -qE "^docker (stop|rm)" "$3"' _ "$RC" "$CASE/out" "$CASE/log" + +# 9: the stop waits for Vite and leaves no orphan, whichever signal ends the script. +vite_gone_and_port_free() { # script exit code, the expected code + [ "$RC" -eq "$1" ] && [ -s "$CASE/stub/vite.pid" ] && ! kill -0 "$(cat "$CASE/stub/vite.pid")" 2>/dev/null \ + && [ -z "$(ss -Hltn 'sport = :5194')" ] && [ "$(grep -c 'trial app stopped' "$CASE/out")" -eq 1 ] && ! grep -qE '^docker (stop|rm)' "$CASE/log" +} +for sig in term int; do + rm -f "$CASE/stub/vite.pid"; : > "$CASE/stub/vite-hold"; echo "$WORK/$sig-trial.sh" > "$CASE/stub/vite-hold-sig" + # A harness started in the background has SIGINT ignored, and a script cannot trap what it inherits ignored. + LAUNCH=(python3 -c 'import os, signal, sys; signal.signal(signal.SIGINT, signal.SIG_DFL); os.execvp(sys.argv[1], sys.argv[1:])') + fresh_log; run_script db-trial.sh app < /dev/null; LAUNCH=() + check "app ended by SIG${sig^^}: exit 130, Vite gone and port 5194 free on return, the stack untouched" vite_gone_and_port_free 130 + rm -f "$CASE/stub/vite-hold" "$CASE/stub/vite-hold-sig" +done +# Each run of the app uses the host of its own FAUNOSTEO_TRIAL_HOST (the address is decided at each use). +PRIVATE_HOST="$(ip -4 -o addr | sed -n 's/^.* inet \(10\.[0-9.]*\|192\.168\.[0-9.]*\|172\.\(1[6-9]\|2[0-9]\|3[01]\)\.[0-9.]*\)\/.*$/\1/p' | head -n 1)" +for host in 127.0.0.1 $PRIVATE_HOST; do + fresh_log; EXTRA=(FAUNOSTEO_TRIAL_HOST="$host"); trial app; EXTRA=() + check "app: FAUNOSTEO_TRIAL_HOST=$host: Vite, URL and proxy host follow it" bash -c '[ "$1" -eq 0 ] && grep -qF -- "--host $2 --port 5194" "$3" && grep -qF "host=$2 url=http://$2:5194" "$3" && grep -qF "trial app: http://$2:5194" "$4"' _ "$RC" "$host" "$CASE/log" "$CASE/out" +done +[ -n "$PRIVATE_HOST" ] || echo "SKIP app with a private FAUNOSTEO_TRIAL_HOST: this machine has no private IPv4 address (untested)" + +echo "-- the lock comes first for account, grant, assets" +new_case people-lock; trial create +rm -f "$CASE/stub/volumes/faunosteo_trial_db" +flock "$STATE_DIR/.lock" sleep 6 & LOCK_HOLDER=$! +sleep 0.5 +fresh_log; trial assets +check "assets: the lock is taken before the stack is checked" bash -c '[ "$1" -ne 0 ] && grep -qF "another pnpm db:trial command is running" "$2"' _ "$RC" "$CASE/out" +fresh_log; trial_tty x grant owner@trial.test sheet_editor +check "grant: the lock is taken before the stack is checked" bash -c '[ "$1" -ne 0 ] && grep -qF "another pnpm db:trial command is running" "$2"' _ "$RC" "$CASE/out" +fresh_log; trial_typed "$PW"$'\n'"$PW" account owner@trial.test +check "account: the lock is taken before the prompt" bash -c '[ "$1" -ne 0 ] && grep -qF "another pnpm db:trial command is running" "$2" && ! grep -qF "Password" "$2"' _ "$RC" "$CASE/out" +wait "$LOCK_HOLDER" + +echo "-- identity of the target (R13)" +new_case people-r13; trial create +echo other_service > "$CASE/stub/answers/identity" +for action in app assets; do + fresh_log; trial "$action" + check "$action: a gateway port answering another identity is refused" refused "does not answer as the faunosteo_trial gateway" +done +rm -f "$CASE/stub/answers/identity"; : > "$CASE/stub/fail/identity" +fresh_log; trial app +check "app: no identity answer at all is refused" refused "does not answer as the faunosteo_trial gateway" +rm -f "$CASE/stub/fail/identity" +cp -p "$CASE/stub/ports/faunosteo_trial_gateway" "$CASE/gateway.port" +echo '8000/tcp -> 127.0.0.1:58802' > "$CASE/stub/ports/faunosteo_trial_gateway" +for action in app assets; do + fresh_log; trial "$action" + check "$action: the gateway container published elsewhere is refused" refused "faunosteo_trial_gateway is not published on 127.0.0.1:58801 only" +done +cp -p "$CASE/gateway.port" "$CASE/stub/ports/faunosteo_trial_gateway" +cp -p "$CASE/stub/ports/faunosteo_trial_auth" "$CASE/auth.port" +echo '9999/tcp -> 0.0.0.0:58999' > "$CASE/stub/ports/faunosteo_trial_auth" +fresh_log; trial_typed "$PW"$'\n'"$PW" account second@trial.test +check "account: GoTrue published elsewhere is refused before the prompt" bash -c '[ "$1" -ne 0 ] && grep -qF "faunosteo_trial_auth is not published on 127.0.0.1:58999 only" "$2" && ! grep -qF "Password" "$2" && ! grep -q "^curl .*admin/users" "$3"' _ "$RC" "$CASE/out" "$CASE/log" +cp -p "$CASE/auth.port" "$CASE/stub/ports/faunosteo_trial_auth" +# Keys that look right but are not this stack's: the sandbox issuer signed with the trial secret, +# and the trial claims signed with another secret. +cp -p "$STATE_DIR/secrets.env" "$CASE/secrets.good" +forge TR_ANON_KEY db-sandbox own anon; fresh_log; trial app +check "app: an anon key of the sandbox issuer is refused" refused "anon key in secrets.env is not this stack's" +cp -p "$CASE/secrets.good" "$STATE_DIR/secrets.env" +forge TR_ANON_KEY faunosteo-trial other anon; fresh_log; trial app +check "app: an anon key signed with another secret is refused" refused "anon key in secrets.env is not this stack's" +cp -p "$CASE/secrets.good" "$STATE_DIR/secrets.env" +forge TR_SERVICE_KEY faunosteo-trial other service_role +fresh_log; trial assets +check "assets: a service key signed with another secret is refused" refused "service_role key in secrets.env is not this stack's" +fresh_log; trial_typed "$PW"$'\n'"$PW" account third@trial.test +check "account: the same forged service key is refused before the prompt" bash -c '[ "$1" -ne 0 ] && grep -qF "service_role key in secrets.env is not this stack" "$2" && ! grep -qF "Password" "$2" && ! grep -q "^curl .*admin/users" "$3"' _ "$RC" "$CASE/out" "$CASE/log" +DB_ENV_BEFORE="$(env_file_state "$STATE_DIR/db.env")"; STORAGE_ENV_BEFORE="$(env_file_state "$STATE_DIR/storage.env")" +rm -f "$CASE/stub/containers/faunosteo_trial_rest" "$CASE/stub/ports/faunosteo_trial_rest" +sleep 1; fresh_log; trial start +check "start: a forged service key and a missing container: refused, no env file rewritten (content, mtime)" bash -c '[ "$1" -ne 0 ] && grep -qF "service_role key in secrets.env is not this stack" "$2" && [ -z "$3" ] && [ "$4" = "$5" ] && [ "$6" = "$7" ]' _ "$RC" "$CASE/out" "$(changes)" "$DB_ENV_BEFORE" "$(env_file_state "$STATE_DIR/db.env")" "$STORAGE_ENV_BEFORE" "$(env_file_state "$STATE_DIR/storage.env")" +cp -p "$CASE/secrets.good" "$STATE_DIR/secrets.env" +fresh_log; trial start +check "start: with this stack's keys the missing container is recreated" bash -c '[ "$1" -eq 0 ] && grep -q "^docker run -d --name faunosteo_trial_rest " "$2"' _ "$RC" "$CASE/log" + +echo "-- expired keys (F1)" +forge TR_ANON_KEY faunosteo-trial own anon -60; forge TR_SERVICE_KEY faunosteo-trial own service_role -60 +fresh_log; trial app +check "app: an expired anon key is refused, naming rotate-keys" refused "expired: pnpm db:trial rotate-keys" +fresh_log; trial assets +check "assets: an expired service key is refused, naming rotate-keys" refused "expired: pnpm db:trial rotate-keys" +fresh_log; trial_typed "$PW"$'\n'"$PW" account fourth@trial.test +check "account: an expired service key is refused before the prompt" bash -c '[ "$1" -ne 0 ] && grep -qF "expired: pnpm db:trial rotate-keys" "$2" && ! grep -qF "Password" "$2" && ! grep -q "^curl .*admin/users" "$3"' _ "$RC" "$CASE/out" "$CASE/log" +fresh_log; trial status +check "status reports expired keys" out_has "EXPIRED" +rm -f "$CASE/stub/containers/faunosteo_trial_rest" "$CASE/stub/ports/faunosteo_trial_rest" +fresh_log; trial start +check "start: expired keys never block the recreation of a missing container" bash -c '[ "$1" -eq 0 ] && grep -q "^docker run -d --name faunosteo_trial_rest " "$2"' _ "$RC" "$CASE/log" +fresh_log; trial stop; fresh_log; trial rotate-keys +check "rotate-keys on a stopped stack with expired keys: renewed, Storage removed for start to recreate" bash -c '[ "$1" -eq 0 ] && grep -qx "docker rm faunosteo_trial_storage" "$2" && ! grep -q "^docker run -d --name faunosteo_trial_storage " "$2" && grep -qF "pnpm db:trial start recreates Storage" "$3"' _ "$RC" "$CASE/log" "$CASE/out" +fresh_log; trial start +check "start after it recreates Storage with the new keys; app accepts them" bash -c '[ "$1" -eq 0 ] && grep -q "^docker run -d --name faunosteo_trial_storage " "$2"' _ "$RC" "$CASE/log" +fresh_log; trial app +check "app: the renewed anon key passes" [ "$RC" -eq 0 ] + +fresh_log; trial stop; fresh_log; trial app +check "app: refused while the stack is stopped" refused "is not running" + echo "-- db:sandbox state guard" new_case sandbox-guard; mkdir -p "$CASE/trialstate"; : > "$CASE/trialstate/.faunosteo-trial-state" EXTRA=(FAUNOSTEO_SANDBOX_DIR="$CASE/trialstate"); sandbox down diff --git a/scripts/db-trial.sh b/scripts/db-trial.sh index 26c14b24..5d9c21a4 100755 --- a/scripts/db-trial.sh +++ b/scripts/db-trial.sh @@ -1548,6 +1548,248 @@ cmd_rotate_secrets() { say "secrets renewed: sessions signed with the old secret are refused (sign in again); account passwords and TOTP factors unchanged; backup before it: $(basename "$LAST_BACKUP")" } +# ---- accounts, grants, drawings, app + +trial_email() { # one fixed shape, nothing else reaches curl or psql + [[ "${1:-}" =~ ^[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,120}\.[A-Za-z]{2,24}$ ]] || die "an e-mail address is expected" +} + +# Typed twice at a hidden prompt into the caller's variable; it lives in this process only. The +# locals carry a prefix so that no caller's variable name can collide with them (nameref). +# IFS is emptied: leading and trailing blanks are part of the password and count in the minimum. +read_new_password() { # variable name + local -n _rnp_typed=$1 + local _rnp_again + IFS= read -rsp "Password (12 characters min.): " _rnp_typed || die "no password read: no account created" + echo >&2 + IFS= read -rsp "Again: " _rnp_again || die "no password read: no account created" + echo >&2 + [ "$_rnp_typed" = "$_rnp_again" ] || die "the two passwords differ: no account created" + [ "${#_rnp_typed}" -ge 12 ] || die "12 characters min.: no account created" +} + +# GoTrue's admin API on its loopback port; the body (JSON built by node from the environment) goes +# through stdin, the service key header through a process substitution (builtin printf, from the +# very key client_key checked): never argv, never a file that could differ from it. +create_account() { # email password + TRIAL_EMAIL="$1" TRIAL_PW="$2" node -e ' + process.stdout.write(JSON.stringify({ email: process.env.TRIAL_EMAIL, + password: process.env.TRIAL_PW, email_confirm: true }));' \ + | curl -q --noproxy '*' -fsS -o /dev/null -X POST "http://127.0.0.1:$PORT_AUTH/admin/users" \ + -H @<(printf 'Authorization: Bearer %s\n' "$TR_SERVICE_KEY") -H 'Content-Type: application/json' --data-binary @- \ + || die "account not created (already existing, or password refused): nothing was changed" +} +# Terminal-only commands (a typed answer is read) refuse before any Docker call. +require_terminal() { # action + [ -t 0 ] || die "$1 needs a terminal (a typed answer is read, stdin is not one): nothing was changed" +} +cmd_account() { + local password email + [ $# -eq 1 ] || die "account " + trial_email "$1" + email="${1,,}" # GoTrue stores addresses lowercased + require_terminal account + require_state + take_lock + require_running + published_exactly "$AUTH" + client_key "$TR_SERVICE_KEY" service_role + read_new_password password + create_account "$email" "$password" + say "account $email created and confirmed" + echo "Next: pnpm db:trial app, sign in, enrol TOTP in Mon compte > Sécurité (two factors for the owner account), then pnpm db:trial grant" +} + +# Platform roles follow V1-2_ANATOMICAL_SHEETS.md §5.7.1: the account enrols its factors first, the +# operator reads them (name, creation time) and confirms, then the role is assigned last through +# the operator path (null actor, JWT-less session) and an audit row records the reason and the +# operator. Owner needs two verified TOTP factors, admin one. The database counts them, here and +# again inside the grant transaction; a factor name is sanitised in SQL before it reaches the terminal. +factor_count() { # email: verified TOTP factors of the account + sb_psql -t -A -v email="$1" <<'SQL' +-- db-trial:grant-factor-count +select count(*) +from auth.mfa_factors f join auth.users u on u.id = f.user_id +where u.email = :'email' and f.factor_type = 'totp' and f.status = 'verified'; +SQL +} +factor_list() { # email: name | creation time, one line per verified TOTP factor + sb_psql -t -A -F ' | ' -v email="$1" <<'SQL' +-- db-trial:grant-factors +select left(regexp_replace(coalesce(nullif(f.friendly_name, ''), '(no name)'), '[^[:alnum:] ._-]', '?', 'g'), 40), + to_char(f.created_at at time zone 'UTC', 'YYYY-MM-DD HH24:MI "UTC"') +from auth.mfa_factors f join auth.users u on u.id = f.user_id +where u.email = :'email' and f.factor_type = 'totp' and f.status = 'verified' +order by f.created_at; +SQL +} +grant_platform_role() { # email role + local need=1 factors count + [ "$2" != owner ] || need=2 + count="$(factor_count "$1")" || die "the verified TOTP factors of $1 cannot be counted: nothing was granted" + [[ "$count" =~ ^[0-9]+$ ]] || die "the verified TOTP factors of $1 cannot be counted: nothing was granted" + [ "$count" -ge "$need" ] \ + || die "$1 holds $count verified TOTP factor(s), $2 needs $need: the account enrols them in Mon compte > Sécurité first (nothing was granted)" + factors="$(factor_list "$1")" || die "the verified TOTP factors of $1 cannot be read: nothing was granted" + echo "Verified TOTP factors of $1 (check they are the ones its holder enrolled):" + printf '%s\n' "$factors" | sed 's/^/ /' + confirm "grant $2" + sb_psql -v email="$1" -v role="$2" -v need="$need" -v operator="$(id -un)" >/dev/null <<'SQL' \ + || die "$2 not granted to $1 (fewer factors than needed now, already active, or account inactive): nothing was granted" +-- db-trial:grant-role +begin; +select id::text as uid from auth.users where email = :'email' \gset +-- The factors are counted again here: when one went away since the check, no row comes back, +-- \gset fails, ON_ERROR_STOP ends the session and the transaction rolls back unfinished. +select private.assign_platform_role(null, :'uid'::uuid, :'role'::public.platform_role)::text as role_id +where (select count(*) from auth.mfa_factors f + where f.user_id = :'uid'::uuid and f.factor_type = 'totp' and f.status = 'verified') >= :need \gset +select private.log_event(null, 'platform_role.operator_bootstrap', 'profile_role', :'role_id'::uuid, + :'uid'::uuid, null, jsonb_build_object('role', :'role', 'operator', :'operator', + 'reason', 'db:trial operator bootstrap (V1-2 contract 5.7.1)')); +commit; +SQL + say "$2 granted to $1: the account signs in again and passes the step-up (aal2)" +} + +# Catalogue rights mirror public.grant_catalog_right (it needs an owner JWT at aal2, so the operator +# path cannot call it): confirmed active account; a verified TOTP factor for every kind but +# catalog_reader; admin for sheet_editor and sheet_publisher; no active row of that kind. Nothing +# grants a platform role here: the practitioner is made admin first, on purpose. +catalog_grant_status() { # email kind: ok | already | no_account | inactive | no_totp | not_admin + sb_psql -t -A -v email="$1" -v kind="$2" <<'SQL' +-- db-trial:grant-catalog +select case + when u.id is null then 'no_account' + when not private.is_confirmed_active_account(u.id) then 'inactive' + when :'kind' <> 'catalog_reader' and not private.has_verified_totp(u.id) then 'no_totp' + when :'kind' in ('sheet_editor', 'sheet_publisher') and not private.is_platform_admin(u.id) then 'not_admin' + when exists (select 1 from public.anatomical_catalog_grants g + where g.user_id = u.id and g.grant_kind = :'kind'::public.catalog_grant_kind + and g.revoked_at is null and (g.expires_at is null or g.expires_at > now())) then 'already' + else 'ok' end +from (select 1) one left join auth.users u on u.email = :'email'; +SQL +} +grant_catalog_right() { # email kind + local status + status="$(catalog_grant_status "$1" "$2")" || die "the state of $1 cannot be read: nothing was granted" + case "$status" in + ok) ;; + already) say "$2 already active for $1: nothing changed"; return 0 ;; + no_account) die "no account $1 (pnpm db:trial account $1 first): nothing was granted" ;; + inactive) die "the account $1 is inactive or its e-mail is not confirmed: nothing was granted" ;; + no_totp) die "$1 holds no verified TOTP factor: the account enrols one in Mon compte > Sécurité first (nothing was granted)" ;; + not_admin) die "$2 needs $1 to hold admin first: pnpm db:trial grant $1 admin, then this again (nothing was granted)" ;; + *) die "unexpected answer from the database: nothing is known about $2 for $1" ;; + esac + confirm "grant $2" + # granted_by is the account's own id: the column is NOT NULL and the operator has no profile. + sb_psql -v email="$1" -v kind="$2" -v operator="$(id -un)" >/dev/null <<'SQL' \ + || die "$2 not granted to $1 (the account changed since the check?): nothing was granted" +-- db-trial:grant-catalog-write +begin; +select id::text as uid from auth.users where email = :'email' \gset +select 1 as locked from public.profiles where id = :'uid'::uuid for no key update \gset +insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by) +select :'uid'::uuid, :'kind'::public.catalog_grant_kind, 'db:trial operator bootstrap', + case when :'kind' = 'catalog_reader' then null else 'db:trial operator bootstrap' end, :'uid'::uuid +where private.is_confirmed_active_account(:'uid'::uuid) + and (:'kind' = 'catalog_reader' or private.has_verified_totp(:'uid'::uuid)) + and (:'kind' not in ('sheet_editor', 'sheet_publisher') or private.is_platform_admin(:'uid'::uuid)) + and not exists (select 1 from public.anatomical_catalog_grants g + where g.user_id = :'uid'::uuid and g.grant_kind = :'kind'::public.catalog_grant_kind + and g.revoked_at is null and (g.expires_at is null or g.expires_at > now())) +returning id::text as grant_id \gset +select private.log_event(null, 'catalog_grant.operator_bootstrap', 'catalog_grant', :'grant_id'::uuid, + :'uid'::uuid, null, jsonb_build_object('kind', :'kind', 'operator', :'operator', + 'reason', 'db:trial operator bootstrap')); +commit; +SQL + say "$2 granted to $1" +} +cmd_grant() { + local email + [ $# -eq 2 ] || die "grant " + trial_email "$1" + email="${1,,}" # GoTrue stores addresses lowercased + [[ "$2" =~ ^(owner|admin|catalog_reader|sheet_editor|sheet_reviewer|sheet_publisher)$ ]] \ + || die "right: owner | admin | catalog_reader | sheet_editor | sheet_reviewer | sheet_publisher" + require_terminal grant + require_state + take_lock + require_running + case "$2" in + owner | admin) grant_platform_role "$email" "$2" ;; + *) grant_catalog_right "$email" "$2" ;; + esac +} + +# The existing R5.5 tool (no overwrite, verify after upload, rerun = nothing to do) through the +# trial gateway; the service key in its environment only; the LAN address and pnpm's INIT_CWD +# dropped so the tool accepts loopback only and resolves the seed folder from the repository. +upload_assets() { # [--check] + ( unset FAUNOSTEO_DEV_HOST INIT_CWD + SUPABASE_URL="http://127.0.0.1:$PORT_GATEWAY" SUPABASE_SERVICE_ROLE_KEY="$TR_SERVICE_KEY" \ + bash scripts/upload-sheet-assets.sh "$@" "$SEED" ) +} +cmd_assets() { + [ $# -eq 0 ] || die "assets takes no argument" + local out expected + require_state + take_lock + require_running + gateway_identity + client_key "$TR_SERVICE_KEY" service_role + upload_assets || die "the upload tool failed: some drawings may be uploaded already, pnpm db:trial assets again does nothing for those" + out="$(upload_assets --check)" || die "the upload tool's check failed: pnpm db:trial assets again" + printf '%s\n' "$out" + expected="$(expected_assets | grep -c .)" + [ "$(grep -c 'nothing to do' <<<"$out")" -eq "$expected" ] || die "the tool does not report every drawing verified" + [ "$(uploaded_count)" -eq "$expected" ] || die "not every drawing row is confirmed with its object in the bucket" + say "equine drawings: $expected/$expected uploaded, verified and confirmed" +} + +# No proxy variable reaches Vite (Node 24 honours NODE_USE_ENV_PROXY): its identity fetch and its +# proxy to the gateway go straight to 127.0.0.1. +# The app origin is the Vite server itself (/auth/v1, /rest/v1, /storage/v1 proxied to the trial +# gateway by apps/app/vite/trial.config.ts): same origin, no CORS. The anon key reaches Vite +# through its environment, never argv. +# The traps find Vite through the job table, so no signal window between the launch and the +# assignment of its pid leaves it running; the stop waits for it, so the port is free on return. +app_stop() { + local pid + for pid in $(jobs -p); do kill "$pid" 2>/dev/null || true; done + wait 2>/dev/null || true + say "trial app stopped; the stack runs until pnpm db:trial stop" +} +# shortcut: app takes no lock and checks the gateway identity only at its start. refuse_while_app_runs +# (stop, destroy, restore, rotate-keys, rotate-secrets) sees the app only once Vite listens on 5194, +# so one of them run in another terminal in the second before Vite binds goes ahead: after rotate-keys +# the app keeps the previous anon key until its expiry; after rotate-secrets its requests are refused +# (401) until app is restarted; after stop or destroy it proxies to whatever later listens on +# 127.0.0.1:58801. Holding the lock all session would block backup and migrate with a misleading +# message. Upgrade: a dedicated app lock, shared by app and exclusive for those commands. +cmd_app() { + [ $# -eq 0 ] || die "app takes no argument" + local host + require_running + gateway_identity + client_key "$TR_ANON_KEY" anon + host="$(trial_host)" + if port_listening "$PORT_APP"; then die "port $PORT_APP is in use: nothing was started"; fi + trap app_stop EXIT + trap 'exit 130' INT TERM + say "trial app: http://$host:$PORT_APP (Ctrl+C stops the app; the stack runs until pnpm db:trial stop)" + ( cd apps/app && FAUNOSTEO_TRIAL_GATEWAY="http://127.0.0.1:$PORT_GATEWAY" FAUNOSTEO_TRIAL_HOST="$host" \ + VITE_SUPABASE_URL="http://$host:$PORT_APP" VITE_SUPABASE_ANON_KEY="$TR_ANON_KEY" \ + NODE_OPTIONS=--max-old-space-size=768 \ + exec env -u http_proxy -u HTTP_PROXY -u https_proxy -u HTTPS_PROXY -u all_proxy -u ALL_PROXY \ + -u no_proxy -u NO_PROXY -u NODE_USE_ENV_PROXY \ + node_modules/.bin/vite --config vite/trial.config.ts --host "$host" --port "$PORT_APP" --strictPort ) & + wait $! +} + # Every command's arguments are checked before any Docker call (a refusal here logs nothing). # The commands keep their own checks too, so each stays safe if called on its own. check_arguments() { # action args... @@ -1556,11 +1798,21 @@ check_arguments() { # action args... case "$action" in plan | create | start | stop | status) [ $# -eq 0 ] || die "$action takes no argument" ;; - migrate | backup | rotate-keys | rotate-secrets | destroy) + migrate | backup | rotate-keys | rotate-secrets) [ $# -eq 0 ] || die "$action takes no argument" ;; + destroy) [ $# -eq 0 ] || die "$action takes no argument"; require_terminal destroy ;; + app | assets) [ $# -eq 0 ] || die "$action takes no argument" ;; + account) [ $# -eq 1 ] || die "account "; trial_email "$1"; require_terminal account ;; + grant) + [ $# -eq 2 ] || die "grant " + trial_email "$1" + [[ "$2" =~ ^(owner|admin|catalog_reader|sheet_editor|sheet_reviewer|sheet_publisher)$ ]] \ + || die "right: owner | admin | catalog_reader | sheet_editor | sheet_reviewer | sheet_publisher" + require_terminal grant ;; restore) [ $# -eq 1 ] && [[ "$1" =~ ^[0-9]{8}T[0-9]{6}Z-[a-z0-9-]+$ ]] \ - || die "restore : the name of a folder in $BACKUPS (pnpm db:trial status lists them)" ;; + || die "restore : the name of a folder in $BACKUPS (pnpm db:trial status lists them)" + require_terminal restore ;; *) usage; exit 1 ;; esac } @@ -1591,5 +1843,9 @@ case "$action" in rotate-keys) cmd_rotate_keys "$@" ;; rotate-secrets) cmd_rotate_secrets "$@" ;; destroy) cmd_destroy "$@" ;; + app) cmd_app "$@" ;; + account) cmd_account "$@" ;; + grant) cmd_grant "$@" ;; + assets) cmd_assets "$@" ;; *) usage; exit 1 ;; esac