Skip to content

feat(server): opt-in sign-in before anything can be changed - #534

Merged
LeMyst merged 4 commits into
cooklang:mainfrom
LeMyst:feat/server-auth
Sep 28, 2026
Merged

LeMyst merged 4 commits into
cooklang:mainfrom
LeMyst:feat/server-auth

Conversation

@LeMyst

@LeMyst LeMyst commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #312.

What this does

cook server can now require sign-in before anything changes, while staying open to readers. It is opt-in: with no users configured, the server behaves exactly as it does today.

cook server user add alice   # asks for alice's password, twice
cook server --host

Once a users file exists:

Guest Signed in
Browse, search, view recipes, menus, shopping list, pantry ✅ ✅
Create, edit, delete recipes ❌ 401 / sent to sign in ✅
Change the shopping list or the pantry ❌ 401 ✅
Editor language server (/api/ws/lsp), CookCloud sync controls ❌ 401 ✅

Guests get a Sign in link in the nav, and the controls that change things are hidden: New Recipe, Edit, Add to shopping list, Clear/Remove, the shopping-list ticks, pantry add/edit/delete, the sync section, and the matching keyboard shortcuts. Opening /edit/… or /new sends a guest to /login and back afterwards.

Activity log

Every change made through the server prints a line on stdout (so it shows up in docker logs), saying when, who, and what:

2026-09-27 08:41:56 alice signed in
2026-09-27 08:42:03 alice created recipe "Soups/Pea soup.cook"
2026-09-27 08:43:12 alice added "Soups/Pea soup.cook" ×2 to the shopping list
2026-09-27 08:44:05 alice removed "milk" from the "dairy" section of the pantry
2026-09-27 08:45:51 alice deleted menu "Week.menu"
2026-09-27 09:12:44 guest failed to sign in
  • Coverage: recipes and menus (created vs updated, deleted, title picture set or removed, the /new form), the shopping list (add, add menu, remove, clear, check, uncheck, compact), the pantry (add, update, remove), linking to cook.md, and signing in and out.
  • Who: the actor is the signed-in user, or guest without sign-in and for a failed sign-in. A failed sign-in never shows the name that was typed, since that is sometimes the password.
  • Why stdout: it uses println! next to the startup lines, rather than tracing. Tracing writes to stderr and shows only warnings unless -v is given, so the earlier signed in info lines were invisible by default.
  • Safe to read: names and paths come from requests and are Debug-quoted, so a newline in one cannot forge a line.
  • One pattern: every write handler takes Extension<Viewer>, which the middleware inserts on every route, and records once the change has succeeded. CLAUDE.md notes the rule for new write routes.

Users are managed on the server only

There is no sign-up and no password change in the browser. Users live in users.toml in the configuration directory (or wherever --users-file / COOK_USERS_FILE points), managed with:

cook server user add <name>
cook server user passwd <name>
cook server user remove <name>
cook server user list
cook server hash-password        # for editing the file by hand
  • Passwords are stored as argon2id PHC strings.
  • The commands edit the file with toml_edit, so an admin's comments survive, and write it atomically.
  • A running server watches the file and reloads it. A new user can sign in right away, and removing a user or changing their password signs them out everywhere. Only the first user needs a restart, because sign-in turns on when the server starts with a users file.
  • A broken edit is ignored: the server logs an error and keeps the last good list.
  • An empty [users] table keeps sign-in on with nobody able to sign in, i.e. a read-only site.

Design notes

  • One enforcement point. A single middleware (src/server/auth/middleware.rs), layered inside the --url-prefix nest, decides which requests need a user:
    • every non-GET/HEAD/OPTIONS request is refused by default, except an exact-match allowlist: POST /api/shopping_list (it only computes a list), /api/reload (a no-op), /login and /logout;
    • a short list of GETs is also protected: /new, /edit/…, /api/ws/lsp, /api/sync/….
      So a write route added later is protected without anyone remembering to list it. api() is untouched, so the router-scan tests in api_docs.rs still pass.
  • Signed sessions, with sign-outs revoked on the server.
    • The cookie is cook_session=<user>:<expiry>:<id>:<HMAC-SHA256>, where <id> is 128 random bits unique to the sign-in. It is set with HttpOnly; SameSite=Lax; Path=<prefix or />; Max-Age=30d, plus Secure behind X-Forwarded-Proto: https.
    • The MAC covers the user's current password hash, so changing a password or removing a user invalidates their cookies without a session store.
    • The key is kept in auth-secret in the configuration directory (0600 on Unix), so sessions survive restarts, and deleting it signs everyone out.
    • Signing out revokes that session on the server, not just in the browser, so a copied cookie (from a shared computer or a proxy log) stops working, while the user's other sign-ins stay valid. The session id is recorded in revoked-sessions beside auth-secret (0600, written atomically), and an entry is dropped once the cookie would have expired anyway. Only verified, unexpired cookies are recorded, so the list stays as short as the last 30 days of sign-outs. A list the server cannot read stops it from starting, rather than bringing the signed-out sessions back.
  • Fails closed. The server refuses to start rather than silently run open when:
    • a named users file is missing;
    • the file has a malformed entry or a hash that is not argon2;
    • the users file or the key would sit inside the recipe directory. /api/static serves that directory, dotfiles included, so the hashes would be public and the key would let anyone forge a session.
  • Sign-in hardening.
    • Unknown usernames are verified against a stand-in hash, so timing does not reveal who has an account.
    • Argon2 runs on the blocking pool behind a 2-permit semaphore.
    • Passwords are capped at 1 KiB.
    • A failed sign-in is logged without the username, since people sometimes type their password into that field.
  • CSRF. /login and /logout are POSTs, so the existing write_guard covers them like every other write.
  • Dependencies. New crates in the lockfile: argon2, password-hash, blake2, hmac. sha2 0.10, console, toml_edit, subtle and rand_core were already there. All are optional, behind the server feature. argon2 and blake2 get opt-level = 3 in the dev profile, because unoptimized argon2 takes seconds per sign-in.

Relation to #334

@le-yams's plan in #334 was a useful map of the routes and the pitfalls, thank you. This implementation differs in a few deliberate ways:

  • several users instead of one;
  • the users file's presence turns sign-in on, with no separate --enable-auth flag;
  • argon2 instead of bcrypt, with no plaintext option;
  • cook server user … instead of hand-editing hashes;
  • a signed cookie plus a short list of signed-out sessions, instead of a persisted session store;
  • live reload of the users file.

Other open PRs

Docs

  • docs/server.md gets new "Signing in to make changes" and "Activity log" sections.
  • README.md gets cook server user examples, a Sign-in in a container section, and COOK_USERS_FILE under Configuration. The container section covers COOK_CONFIG_DIR on a volume, mkdir config first, and adding users with docker compose exec without a restart.
  • docker-compose.yml gets the same lines, commented out.
  • docs/api.md (regenerated) describes the cookie flow for scripts and the 401 status.
  • CLAUDE.md gets notes on the middleware rule and on recording each change in the activity log.

Tests

  • Unit tests: activity-line formatting and quoting, users-file parsing and validation, comment-preserving edits, cookie sign/verify (tampering, expiry, password change, removed user, unique session ids), the signed-out-session list (reload, expiry pruning, malformed file), the requires_user table, next sanitising, key-file handling, the inside-the-recipe-directory check, and clap parsing of cook server <dir> against cook server user ….

  • tests/server_auth_test.rs, 17 end-to-end tests against a real cook server:

    • open by default, with changes logged as guest;
    • the activity log, line for line: create/update/delete, shopping list, pantry, sign-in and sign-out. The test also checks that a failed sign-in does not log the typed name, and that a newline sent in a request stays quoted;
    • guest 401s and redirects, and nothing changes on disk;
    • sign-in, sign-out and forged cookies. After sign-out, a copy of the cookie is refused while the user's other session is not, and that holds across a restart;
    • --url-prefix (cookie Path=/cook);
    • COOK_USERS_FILE;
    • each startup refusal;
    • the read-only empty list;
    • the user commands and hash-password;
    • live reload: remove a user and their session ends, add one and they can sign in, break the file and nothing changes.
  • Checks run:

    • cargo fmt --all -- --check
    • cargo clippy --workspace --all-targets --all-features -- -D warnings
    • cargo clippy --no-default-features --features server,lsp --all-targets -- -D warnings
    • cargo test --workspace
    • cargo test --no-default-features
  • Manual, in a browser: guest and signed-in views, live reload, and a session surviving a restart.

  • Container: the README steps, run with Podman on an image built from this branch:

    • the first user added from a one-off container, then the server started with COOK_CONFIG_DIR=/config on a volume;
    • a guest gets 401, and a signed-in user can save;
    • exec … user add bob lets bob sign in with no restart;
    • exec … user remove bob ends his session;
    • alice's session survives a container restart.

    Not covered:

    • The interactive no-echo prompt (console::Term::read_secure_line); every test pipes the password in.
    • The UID 1000 / mkdir config advice: Podman on Windows does not enforce ownership on bind mounts.
  • Playwright (shopping list, pantry, editor, navigation, recipe display) against a server without users: 44 passed. The 2 failures are the known Windows-only step-image tests, which build image URLs with \; that is fixed on a separate branch and has nothing to do with this change. CI runs Linux.

🤖 Generated with Claude Code

LeMyst and others added 4 commits September 27, 2026 18:08
Without a users file the server stays open to anyone who can reach it,
exactly as before. Once one exists, guests can still browse, but every
request that changes something needs a signed-in user: recipes, the
pantry, the shopping list, the editor's language server and the cook.md
sync controls. Guests get a Sign in link, and the controls that change
things are hidden from them.

Users are managed on the server only, with `cook server user
add|passwd|remove|list` (and `cook server hash-password` for hand
edits). They live in users.toml in the configuration directory, or in
--users-file / COOK_USERS_FILE, as argon2 hashes. A running server
reloads the file when it changes, so adding a user, changing a password
or removing a user takes effect without a restart.

One middleware decides which requests need a user: every non-GET
request except an exact allowlist, plus /new, /edit, /api/ws/lsp and
/api/sync. Sessions are a stateless HMAC-signed cookie whose MAC covers
the user's password hash, keyed by auth-secret in the configuration
directory, so they survive restarts and a password change or removal
signs that user out everywhere. The server refuses to start rather than
run open when a named users file is missing or invalid, or when the
users file or key would sit inside the recipe directory it publishes.

Closes cooklang#312

Co-Authored-By: Claude Opus 5.5 <[email protected]>
German, Spanish, Basque, Dutch and Swedish, alongside the English and
French that came with the sign-in page. Each follows its file's existing
register and wording for adding, editing and deleting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…iled sign-in logs

Session cookies are stateless, so signing out only cleared the cookie in
that browser: a copy of it (a shared computer, a proxy log) stayed valid
for the rest of its 30 days.

Each sign-in now carries a random 128-bit session id, covered by the MAC
(cookie format `<user>:<expiry>:<id>:<mac>`, context bumped to v2).
Signing out records that id in `revoked-sessions`, beside `auth-secret`,
and the server refuses the session from then on, across restarts. Only
verified, unexpired cookies are recorded and each entry is dropped once
its cookie would have expired, so the list stays as short as the last 30
days of sign-outs. The user's other sign-ins are unaffected. A list the
server cannot read stops it from starting rather than bringing revoked
sessions back; with a temporary key the list lives in memory only.

A failed sign-in is now logged without the username: people type their
password into that field by mistake.

The users file writer becomes the shared `auth::write_private_file`
(atomic, 0600) so both files are written the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BUvontmCsKnp5q9r5NPcm8
Every change made through the server now prints one line on standard
output: when, who, and what.

    2026-09-27 08:42:03 alice created recipe "Soups/Pea soup.cook"
    2026-09-27 08:43:12 alice added "Soups/Pea soup.cook" ×2 to the shopping list
    2026-09-27 08:44:05 alice removed "milk" from the "dairy" section of the pantry
    2026-09-27 09:12:44 guest failed to sign in

It covers recipes and menus (created vs updated, deleted, title picture
set or removed, the /new form), the shopping list (add, add menu,
remove, clear, check, uncheck, compact), the pantry (add, update,
remove), linking to cook.md, and signing in and out. The actor is the
signed-in user, or `guest` without sign-in and for a failed sign-in,
which never shows the name typed.

It goes to stdout with println!, next to the startup lines, rather than
through tracing: tracing writes to stderr and shows only warnings unless
-v is given, so the existing "signed in" / "signed out" info lines were
invisible by default; they move here. Names and paths come from
requests and are Debug-quoted, so a newline in one cannot forge a line.

Each write handler takes Extension<Viewer>, which the auth middleware
inserts on every route, and records after the change succeeded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BUvontmCsKnp5q9r5NPcm8

@dubadub dubadub left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for taking it, it's a highly requested feature. I procrastinated and never felt I'm ready to implement that. Probably I overthink it.

It seems to me after reviewing other projects and open issues, people need more flexibility on that. And I was thinking to implement proper RBAC to allow different users access different paths and maybe limited write also. For example I'd allow my wife to write into the shopping list, but my friends will have read only access of my pubic recipes.

I think it's a good foundation we can build on top adding roles and fine control to define these roles.

@LeMyst

LeMyst commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator Author

Would this be a good base for finer-grained access (roles, private recipes, folder access)?

Short answer: yes for authentication and coarse roles, only partly for per-folder or per-recipe access. No change is needed in this PR to keep either option open, but per-path access would be a separate, larger refactor, not an extension of the middleware.

What carries over as-is

  • Identity. users.toml, argon2, the signed cookie, sign-out revocation and live reload don't depend on any role model. The user list is read on every request (Auth::viewer), so a role or permission change would apply immediately, just as removing a user does today.
  • Viewer on every route. Every handler already receives Extension<Viewer>. That is the right place to carry a role or a permission set, and the templates already ask it what to show (can_edit()).
  • Deny-by-default writes. One middleware, where any non-GET is refused unless allowlisted. A read-only user role is almost free here: can_edit() becomes a role check, and nothing else in the enforcement model changes. The same goes for splitting write rights by area (for example, "may tick the shopping list but not edit recipes", or "only admins see the sync controls"). That is a mapping from path prefix to capability in requires_user.
  • Activity log. It gives the audit trail that roles usually need.
  • File format. users.toml can grow without breaking anything: a value could later be either a hash string (today) or a table { hash = "…", role = "reader" }, via an untagged enum. Because of deny_unknown_fields, an older server refuses a newer file instead of ignoring rules it doesn't understand.

What doesn't carry over: private recipes and folder access

The middleware decides from method + URL. Per-recipe access needs a decision per file, and in this server a recipe is reached through far more than its own URL:

Where a recipe can leak Why a URL rule can't cover it
/api/static/… (ServeDir over the whole recipe dir) Serves the raw .cook text and images of every file
Recipe list, /directory/…, search, stats, random recipe These return sets; a private recipe has to be filtered out, not blocked
Menus, and recipe references (@./Private/Sauce{}) A public file pulls in a private one
POST /api/shopping_list, shopping_list/add The recipe names are in the body
Shopping list and pantry One store for the whole server (ShoppingListStore::new(base_path)), not per user; a private recipe added there is visible to everyone
/api/ws/lsp The language server's workspace is the whole base_path
cook.md sync Syncs the whole directory to one account

So private recipes need enforcement at the data-access layer, not at the router edge: one accessor (roughly RecipeStore::for_viewer(&viewer)) through which every handler lists, reads, resolves references and writes. It would replace the many direct base_path / cooklang_find uses in ui.rs, handlers/* and lsp_bridge.rs. That refactor is the real cost, and it's independent of how sign-in works.

A few design points I'd settle before starting:

  1. Where the rules live. I'd use path-based rules in a server-side file (e.g. an [access] table: "Family/**" = { alice = "write", bob = "read" }, "alice/**" = { alice = "write" }, with folders inheriting), not frontmatter such as visibility: private. Frontmatter can be edited by anyone who can write the file, has to be parsed before you can decide whether to show the file, and a rename or sync client never checks it.
  2. Guests become a principal with rules, since reads are open today.
  3. Shared state. Either accept a shared shopping list and pantry (and document that they reveal recipe names and ingredients), or make them per user.
  4. Out-of-band access. This only protects the web UI. Anyone with shell access, cook on the directory, or the linked cook.md account still sees everything, so the docs should say that.
  5. Scoped users and the editor. The LSP and sync should probably be admin-only once scoped users exist.

Suggested path

  • This PR: keep the scope as it is. Nothing here would have to be undone.
  • Follow-up 1 (small): roles such as reader / editor / admin in users.toml, cook server user add --role, Viewer::role(), and per-area capabilities in the middleware.
  • Follow-up 2 (large): path ACLs through a single viewer-scoped recipe accessor; restrict /api/static to images whose recipe is readable; filter lists, search, menus and references; add an e2e test for each row of the table above.

@LeMyst
LeMyst merged commit 0e8dacf into cooklang:main Sep 28, 2026
7 checks passed
LeMyst added a commit that referenced this pull request Oct 11, 2026
Since sign-in landed (0e8dacf, #534), a page left open after its
visitor's sign-in ended keeps the controls of a signed-in user. What they
do with them was refused without a word: a shopping list tick unticked
itself, and other writes showed the middleware's English error with no
way to sign in again.

The middleware now marks its API 401 and 403 with
`X-Cook-Refused: sign-in|role` and writes their `error` in the visitor's
language (unchanged in English). static/js/sign-in-notice.js watches
every write a page sends and, on a marked refusal, shows one notice: for
a 401, that the change was not made, with a Sign in link back to the
page; for a 403, the translated role-forbidden text. Pages only get the
notice when a users file is in use.

Closes #675

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Read-only server by default with authenticated write access

2 participants