# Authentication: the login, the cookie, and how to recover from it **Scope.** How the operator sets and rotates the password, turns the second factor on, reads what a session is, and recovers from the two ways this can lock someone out (a forgotten password, a clock that disagrees with the phone). It does not cover the master key beyond how it interacts with sessions — `docs/runbooks/secrets.md` and ADR-0040 own that — and it does not cover the bearer token's use by scripts beyond the actor it records. **The decision.** ADR-0047. One operator, a scrypt password hash in the environment, an optional RFC 6238 second factor, and a stateless signed cookie. Reads are closed too: the book was sensitive before the buttons were. **Current state (read this before relying on it).** `src/tapebook/app/auth.py` is the core and it is merged and tested. The middleware in `entrypoints/api.py` is **not** — a second lane owns that file — so on a running server today every page is still anonymous (GAP-138). Until GAP-138 closes, this runbook describes the intended behaviour and the pieces that already exist; it is not yet a statement about a live `tape serve`. --- ## 1. What is protected, and what must stay open | Open without a session | Why | |---|---| | `/health` | a supervisor's liveness probe; returns no desk data | | `/login`, `/logout` | the form that creates a session and the POST that ends it | | `/static/*` | CSS, JS, icons; the login page cannot render without them | | `/manifest.webmanifest`, `/sw.js`, `/offline` | the PWA shell; the offline page must render when the network is gone | Everything else — `/`, `/sleeve/…`, `/moves`, `/chat`, every `/api/*` route — needs a session. `app.auth.is_open_path` is the single source of that list; the middleware calls it, so the runbook and the code cannot drift by editing a route. ## 2. Set the password Generate the hash on the machine where the desk runs. The command prompts (the password is not echoed, not passed as an argument, and does not enter shell history) and prints one line: ```bash uv run python -c "import getpass; from tapebook.app.auth import hash_password; print(hash_password(getpass.getpass('password: ')))" # scrypt:n=16384,r=8,p=1:: ``` Put that whole line in `.env` (mode `0600`) as `TAPEBOOK_PASSWORD_HASH=…`, or in the secret file and set `TAPEBOOK_PASSWORD_HASH_FILE` to its path. Restart `serve` (or `docker compose up -d serve`). The hash is also what the CLI's tests use to build an `AuthConfig`; nothing else reads it. What the value is, in one line: scrypt with `n=2**14, r=8, p=1` over a 16-byte per-hash salt, 32-byte output. The parameters travel inside the string, so a future cost change verifies old hashes and hashes new ones at the new cost. The format uses `:` rather than `$` because Docker Compose interpolates `$` inside `.env` values; a `$scrypt$…` string would arrive corrupted and the symptom would be "the right password does not work". **Wrong or missing values are refused at boot, not at the login.** The refusal names `TAPEBOOK_PASSWORD_HASH` and says how to generate one; it never prints what it read. If you see that refusal, nothing is listening: fix the variable and restart. ## 3. Turn on the second factor 1. In an authenticator, add an entry manually and type a base32 key of your choosing (any password-manager-generated base32 secret works; the desk does not need a QR). 2. Set `TAPEBOOK_TOTP_SECRET=` — or `TAPEBOOK_TOTP_SECRET_FILE` pointing at a `0600` file. 3. Restart. The login form now asks for the six-digit code as well as the password. Setting the variable is the switch; there is no separate "require TOTP" flag that could disagree with it. A malformed base32 value refuses at boot naming the variable. A code is accepted for the current 30-second step and one step either side, so a phone a few seconds off still works; a phone off by several minutes does not — fix the phone's clock rather than the desk. ## 4. What a login gives you - **A cookie, `tapebook_session`**, holding `v1..`: issued-at, expiry and a random nonce, signed with HMAC-SHA256 under a key derived from `TAPEBOOK_MASTER_KEY`. `HttpOnly`, `SameSite=Strict`, `Path=/`, `Secure` when the page is served over https. - **Twelve hours**, renewed while you use it: after an hour, the next page load reissues the cookie (new nonce, new expiry), at most once an hour. An open tab therefore does not expire mid-day; an unused session expires on schedule. - **No session table.** Nothing is written to Postgres, nothing needs cleaning up. The cost is §6. - **What the audit log records.** A session approval records the actor `operator`. A script's approval records the bearer token's label. That is the whole distinction, and it is why the token stays. There is no "remember this device", no device list and no "sign out everywhere" button. The emergency kill switch is rotating `TAPEBOOK_MASTER_KEY` (§5). ## 5. Rotation and recovery **Change the password.** Generate a new hash and replace the value; restart. Existing sessions stay valid until they expire — a password change does not by itself invalidate a cookie that was already issued. If you are changing the password *because someone has the old one*, also rotate the master key (below). **Rotate `TAPEBOOK_MASTER_KEY`.** Put the old key in `TAPEBOOK_MASTER_KEY_PREVIOUS`, generate a new current key, restart, and re-seal tokens with `tape token reencrypt` (ADR-0040, `docs/runbooks/credential-rotation.md`). Sessions are signed with the **current** key only, so this signs every browser out immediately. That is the intended behaviour: one root secret, one kill switch. **Forgot the password.** There is no reset flow and no email. Generate a new hash with the command in §2, replace `TAPEBOOK_PASSWORD_HASH`, restart. Any browser holding a session keeps it until it expires; clear the cookie or rotate the master key if that matters. **Locked out by the throttle.** Five failures in fifteen minutes locks that address for fifteen minutes. Wait it out: the lockout does not extend on further attempts, and a reboot of `serve` clears every counter because the throttle is in memory (§6). ## 6. Knowing the limits - **No per-session revocation.** A copied cookie works until it expires; logging out deletes only the copy in that browser. Rotating the master key is the only way to invalidate one session, and it invalidates all of them. GAP-139. - **The throttle is per process.** Five attempts per address per `serve` process. On the `single` profile that is exact. Under `scaled`/`ha` it multiplies by the replica count and a restart refills it. GAP-140. - **The throttle keys on the socket peer.** `_client_address` deliberately ignores `X-Forwarded-For` (attacker text). With a reverse proxy in front, every browser arrives as the proxy's address, so the five-failure budget is shared by everyone and one attacker can lock the operator out for fifteen minutes at a time. The default deployment has no proxy; if one is added, decide how the client address is trusted **before** relying on the throttle. - **No CSRF token on the login form.** `SameSite=Strict` plus the existing origin police refuse a cross-site POST, and a login form has no session for a token to protect. ## 7. Troubleshooting | Symptom | Meaning | |---|---| | Boot refuses, naming `TAPEBOOK_PASSWORD_HASH` | missing or malformed; regenerate with §2 | | Boot refuses, naming `TAPEBOOK_TOTP_SECRET` | not base32; use the key an authenticator shows | | Boot refuses, naming `TAPEBOOK_MASTER_KEY` | the session key is derived from it; ADR-0040 applies | | Login says the code is wrong, password is right | the phone's clock; the desk accepts ±30 s | | A correct password is rejected five times and then everything is locked | the throttle, §5; check nothing is posting on your behalf | | 401 on `/api/*` but the pages work | the script is using a stale token, not a session | | Every page redirects to `/login` after a restart | expected if the master key changed (rotation) | An error message in this path never contains the password, the hash, the TOTP secret or the master key. If one does, that is a leak to report and fix, not to paste into an issue. ## 8. Managed instances: one runtime, one tenant A managed desk is not a multi-tenant server. The control plane provisions **one isolated runtime per tenant**, so authentication is unchanged in shape — one operator password, an optional second factor, a signed cookie — and the isolation is the runtime boundary, not a tenant column in every query. This section is what differs. **Identity.** Four variables describe the instance: `TAPEBOOK_TENANT_ID`, `TAPEBOOK_INSTANCE_SLUG`, `TAPEBOOK_PLAN`, `TAPEBOOK_DESK_URL`, plus `TAPEBOOK_MANAGED=1`. At first start `app/tenancy.ensure_identity` writes one `instance_identity` row and never rewrites it. The row's `tenant_id` is the owner of this database; the environment's value is what the process was told. They must agree. - `TAPEBOOK_MANAGED=1` with no `TAPEBOOK_TENANT_ID` is a **startup refusal naming both**. Such an instance could not be billed, backed up or deleted as anybody's; it must not start as an anonymous self-hoster. - `TAPEBOOK_MANAGED=1` with no `TAPEBOOK_PLAN` is a refusal too: the absent value would otherwise decode to the unlimited self-hosted ceiling. - An unknown `TAPEBOOK_PLAN` is refused naming `self_hosted, basic`. There is one managed plan; `solo` and `pro` were retired names and are refused like any typo (migration 0032 rewrote the stored rows into `basic`). **What the plan refuses, and where.** Three actions, and only these: starting a desk whose runner config *adds* a sleeve or a market-data venue over the ceiling (`app.config.plan_guard`, called by `Desk.prepare` before anything is registered), and a *new paid* model call once the month's spend has reached the ceiling (`app.chat.ChatBudget.check_call`, checked only after the provider cache misses). Everything else is unblockable on purpose: reading, closing a position, selling, halting, clearing a halt, withdrawing, restoring and exporting, plus any verb this build does not know. A downgrade from `self_hosted` to `basic` does not stop a desk that is already trading — it warns, keeps every running sleeve, and refuses only the next added one. An over-spend desk still answers a chat question from its own records, without a model, and says so. **A managed start needs its identity written.** The gate reads `TAPEBOOK_PLAN`, so a desk is refused before it trades when the plan name is wrong; that is a startup refusal in the same shape as a missing `TAPEBOOK_MASTER_KEY`. Two gaps are recorded rather than papered over: nothing calls `ensure_identity` at boot yet, so the ownership row is not written by `serve`/`runner`, and no page shows the tenant, slug, plan or an overage warning (GAP-179). **The cookie does not cross runtimes.** Sessions are signed with this instance's `TAPEBOOK_MASTER_KEY`. Tenant A's browser holding a valid cookie against A's runtime is an ordinary authenticated request; the same cookie presented to tenant B's runtime is invalid, because B has a different key. Do not share `TAPEBOOK_MASTER_KEY` between tenants, and do not put two tenants behind one `serve` process — either one breaks the isolation this section relies on and is a deployment bug, not a supported mode. **A restored backup cannot change owner.** A backup carries the `instance_identity` row. Restoring tenant A's desk into tenant B's runtime restores A's `tenant_id`; `ensure_identity` compares it with `TAPEBOOK_TENANT_ID` and refuses to start, naming both. The migration's trigger refuses any `UPDATE` that would change `tenant_id`, and the app role has no `UPDATE` grant on the table either. The recovery is not to edit the row (you cannot, deliberately): restore the artefact under the tenant that owns it, or into an empty database started as that tenant. **What to do when startup says the tenant does not match.** Stop. Do not delete the row, do not `TRUNCATE instance_identity`, and do not "fix" it by setting `TAPEBOOK_TENANT_ID` to the value in the database unless that is genuinely the tenant you mean to run — the row is evidence of whose book this is, and adopting it silently is the incident. Take the artefact to the owning tenant's runtime, or open a new empty runtime for the tenant named in the environment and restore there only if the artefact belongs to them. **Export always works.** `tape backup ` is available on every plan and at any overage; `app/tenancy.export_manifest(connection)` lists the tables and command. A tenant leaving is not blocked by a quota, a halt or a locked session cookie. **Deletion is not a button in this app.** Ending a tenant destroys the runtime and its volume — the database included. There is no in-app delete that removes one tenant's rows, because that would destroy the ledger's evidence. Take an export first; the control plane owns the destruction step. See `docs/cloud/plans.md` for the plan ceilings and the two actions a plan may refuse.