Skip to content

Server auth: API tokens for non-browser clients (Home Assistant, scripts) #763

Open

Description

@dubadub

Problem

Once a users file exists, every write needs a signed-in session — and the only way to get one is the browser login form (HttpOnly session cookie). Non-browser clients have no way to authenticate, so on a server with sign-in enabled they're read-only:

  • homeassistant-cookcli — add_recipe_to_shopping_list, clear_shopping_list, removing recipes, and ticking ingredients off (/api/shopping_list/add|remove|clear|check|uncheck) all get 401. Reads and POST /api/shopping_list still work since they're open.
  • curl / cron / shell scripts against the API.

Users who self-host behind a NAS or reverse proxy are exactly the ones who turn sign-in on and want home automation.

Proposal

Bearer tokens tied to a user, so they inherit that user's role (Reader / Shopper / Editor / Admin) and the existing middleware capability checks apply unchanged:

cook server token add <user> [--name home-assistant]   # prints the token once
cook server token list
cook server token revoke <name>
  • Request: Authorization: Bearer <token>; the middleware resolves it to a Viewer the same way it does a session cookie.
  • Store only a hash next to the users file; picked up by the existing watcher, revocation applies on the next request (like role changes and revoked.rs).
  • A token never sets a cookie, so it doesn't widen the browser's CSRF surface.
  • Typical setup: cook server user add ha --role shopper + a token for it — least privilege for automations.
  • Document in /api-docs.

Then

homeassistant-cookcli adds an optional token field to its config flow and sends the header.

Activity

  1. LeMyst commented on Oct 17, 2026

    @LeMyst
    Collaborator

    Agreed on the need. I checked this against main (5822cf8): all five shopping-list writes HA makes (add, remove, clear, check, uncheck) need EditLists and get a 401 without a session, so a shopper account is enough. The design also fits: Auth::viewer(headers) is the single place a request becomes a Viewer, so a bearer check there leaves required_capability, the 401/403 answers and the templates untouched. Under --recipes-only only guests are limited (Viewer::limited_to_recipes), so a token would also restore the reads HA polls there (/api/stats, /api/menus, /api/shopping_list/items).

    A few things worth settling before implementation:

    1. Service accounts must not be able to sign in

    cook server user add ha --role shopper currently requires a password (read_new_password, and validate_hash insists on an argon2 hash), so the "least privilege" automation account could also be used to sign in through the browser. A service account should be token-only: no password, never accepted by /login, and so never able to get a session cookie. For example cook server user add ha --role shopper --service (or a token-only / service = true marker in its entry), with check_password always refusing it. Its only credential is then the token, which also makes it obvious in user list which accounts are machines.

    2. host_guard blocks the target setups before auth runs

    cors::host_guard refuses every request (reads included) sent to a hostname that is not localhost, an IP, or the host of a --cors-origin. HA pointed at http://nas.local:9080, a Docker service name like http://cookcli:9080, or a reverse-proxy name gets a 403 with or without a token, unless the server also runs with --cors-origin or --no-csrf-check. The HA default URL is localhost:9080, which hides this.

    I'd suggest a request carrying a valid bearer token skips host_guard and write_guard: a DNS-rebinding page cannot attach a token it does not have. The comments on allows_write and the a_request_without_an_origin_is_not_a_browser test ("the API has no authentication for them to bypass") would need updating either way.

    3. Don't verify tokens with argon2

    Password checks are capped at 2 concurrent (CONCURRENT_VERIFICATIONS) at ~19 MiB each; doing that per API request would throttle HA's polling. Tokens are high-entropy, so 256 random bits + SHA-256 + constant-time compare is enough. A format like cook_<id>_<secret> lets the server look up the hash by id instead of trying them all.

    4. Removing the tokens file must revoke, not keep

    watcher::reload deliberately keeps the current users when the file disappears (so a half-done edit can't lock everyone out). Applied to tokens, deleting the file would leave every token valid until restart. For tokens, a missing file should mean no tokens. The watcher also only reacts to the users file today (touches_users_file).

    5. Where to store them

    Inside users.toml would make older servers refuse the whole file: UsersFile and EntryTable are deny_unknown_fields. A separate file beside it, written 0600 like auth-secret, avoids that.

    6. Password changes and user removal

    Session cookies are MAC'd with the user's current password hash, so a password change signs everyone out. Tokens should say explicitly what they do: with token-only service accounts (point 1) there is no password to change, but for a token on a regular user I'd keep it alive across password changes and drop it when the user is removed (resolve the role through users.role(token.user) on every request, as sessions do).

    Smaller points

    • Name scope: token revoke <name> implies server-wide unique names; either enforce that or take <user> <name>.
    • Invalid tokens: an invalid or revoked token should get 401 with WWW-Authenticate: Bearer, not silently fall back to guest, so HA can trigger re-auth.
    • API only? Consider accepting bearer only under /api, keeping /edit, /new and /api/ws/lsp to browser sessions.
    • Lower roles: an optional --role on token add, capped at the user's own role, would be cheap.
    • Activity log: activity::record should name the token, e.g. ha (token home-assistant).
    • Docs: regenerate docs/api.md (UPDATE_API_DOCS=1 cargo test --test api_docs_md_test) alongside /api-docs.

    🤖 Analysis and recommendations made by Claude (Anthropic's AI assistant), posted on behalf of @LeMyst.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions