feat(api): read-only API and MCP with personal API tokens #33

Manually merged
jfro merged 7 commits from feat/3-api-access into main 2026-11-01 19:45:01 +00:00
Owner

Closes #3. Built against Nye's acceptance checklist (A–G).

80d0a0d: token store — A1–A6, A8, A9, B1, E1, E2

  • api_tokens table (not users_tokens, so password change / magic-link login don't kill API clients; tested), FK cascade on user delete.
  • llk_ + 32 random bytes, shown once; only the SHA-256 hash stored, unique index, lookup by hash.
  • Revocation, optional expiry, last_used_at throttled to once a minute, 20 live tokens per user.
  • Scope read only; unknown/empty scopes rejected.
  • LogScrubber redacts llk_ tokens; filter_parameters covers token/secret/authorization.

3201f3e: read-only REST API — B2, B3, B4, B5 (REST side), C1, C3, C4, D3, D4, D6, E3, F1–F3

  • LamplighterWeb.ApiAuth plug: bearer header only; ?token=/?access_token=/?api_token= → 400; Origin from another host → 403; missing/malformed/unknown/revoked/expired → 401 + WWW-Authenticate: Bearer realm="lamplighter"; session cookie and run tokens don't authenticate. Failures logged with reason, method/path, 8-char prefix and client address, never the token.
  • require_scope/2: every controller declares read; empty-scope token → 403.
  • Rate limits: Lamplighter.ApiTokens.RateLimiter (supervised GenServer owning a fixed-window ETS table, swept every minute). 120 req/min per token → 429 + Retry-After. Failed sign-ins 300/min per client address → 429, not logged one by one; valid tokens are never held back (behind a proxy everyone shares its address — documented in README).
  • GET /api/v1/summary, /reports (status/kind/severity/updated_since filters, id-cursor paging, limit clamped to 100, 400 on bad filters), /reports/:id (JSON 404), /sources.
  • Lamplighter.Api builds every body from a field whitelist (shared with the MCP tools next): no source settings/secrets, report context only as its why (as the UI shows), no diagnosis_details. Test plants a secret in a source and in report context/details and asserts it's in no response.
  • README ## API section. 23 new tests; precommit 726 pass; CI green.

3f7fd99: review fixes F12, F13

  • Ids/cursors past bigint → 404/400 instead of a Postgrex 500; non-string filter values → 400.
  • Origin check compares scheme/host/port with the endpoint's own URL plus API_ALLOWED_ORIGINS, never the Host header (DNS rebinding). Documented.

2441a00: user MCP at /api/mcp — B5 (MCP side), D1, D2, D5, G2

  • Tools get_summary, list_reports, get_report, list_sources, each the same Lamplighter.Api function and JSON as its REST endpoint. Same ApiAuth (bearer only, Origin, rate limits); a token without read sees no tools.
  • JSON-RPC handling moved to LamplighterWeb.MCP.Server, shared with the internal /mcp (which still refuses API tokens). README ### MCP with the claude mcp add example.

2cd8835, 4992279: review fixes F14, F15

  • Non-string JSON-RPC method → -32600 (both MCP endpoints). /api/mcp refuses batches (logged), so each tool call counts against the token's limit; internal /mcp keeps batches (D24).
  • Review probes folded into the real test suite.

834620d: Settings → API tab — A7, G1

  • /settings/api-tokens, a new API tab. Create (name, read scope, expiry 30/90/365 days or never): the token is shown once with a Copy button and is gone after Done or a reload. List shows prefix, created, last used, expiry or revoked. Revoke asks to confirm.
  • Creating needs sudo mode (sign-in in the last 20 min), checked again on submit, so a crafted event from an old session is refused (logged). Listing and revoking don't need it; an old session gets a "Sign in again" prompt instead of the form.
  • 9 LiveView tests: create → token verifies; plaintext gone after dismiss/reload; validation, unknown scopes refused, 20-token limit message; revoke stops the token; another user's token can't be revoked; old session can't create. README says where tokens live.
  • Checked at 390px and desktop: no horizontal overflow (page and tab bar), token wraps.
Desktop 390px
Tokens api-tokens-desktop api-tokens-390
Just created api-tokens-created-desktop api-tokens-created-390

(Example data from a local dev database; the token shown is a throwaway.)

precommit: 792 tests pass.

Closes #3. Built against Nye's acceptance checklist (A–G). ### 80d0a0d: token store — **A1–A6, A8, A9, B1, E1, E2** - `api_tokens` table (not `users_tokens`, so password change / magic-link login don't kill API clients; tested), FK cascade on user delete. - `llk_` + 32 random bytes, shown once; only the SHA-256 hash stored, unique index, lookup by hash. - Revocation, optional expiry, `last_used_at` throttled to once a minute, 20 live tokens per user. - Scope `read` only; unknown/empty scopes rejected. - LogScrubber redacts `llk_` tokens; `filter_parameters` covers token/secret/authorization. ### 3201f3e: read-only REST API — **B2, B3, B4, B5 (REST side), C1, C3, C4, D3, D4, D6, E3, F1–F3** - `LamplighterWeb.ApiAuth` plug: bearer header only; `?token=`/`?access_token=`/`?api_token=` → 400; Origin from another host → 403; missing/malformed/unknown/revoked/expired → 401 + `WWW-Authenticate: Bearer realm="lamplighter"`; session cookie and run tokens don't authenticate. Failures logged with reason, method/path, 8-char prefix and client address, never the token. - `require_scope/2`: every controller declares `read`; empty-scope token → 403. - Rate limits: `Lamplighter.ApiTokens.RateLimiter` (supervised GenServer owning a fixed-window ETS table, swept every minute). 120 req/min per token → 429 + `Retry-After`. Failed sign-ins 300/min per client address → 429, not logged one by one; valid tokens are never held back (behind a proxy everyone shares its address — documented in README). - `GET /api/v1/summary`, `/reports` (status/kind/severity/updated_since filters, id-cursor paging, limit clamped to 100, 400 on bad filters), `/reports/:id` (JSON 404), `/sources`. - `Lamplighter.Api` builds every body from a field whitelist (shared with the MCP tools next): no source settings/secrets, report `context` only as its `why` (as the UI shows), no `diagnosis_details`. Test plants a secret in a source and in report context/details and asserts it's in no response. - README `## API` section. 23 new tests; precommit 726 pass; CI green. ### 3f7fd99: review fixes F12, F13 - Ids/cursors past bigint → 404/400 instead of a Postgrex 500; non-string filter values → 400. - Origin check compares scheme/host/port with the endpoint's own URL plus `API_ALLOWED_ORIGINS`, never the `Host` header (DNS rebinding). Documented. ### 2441a00: user MCP at `/api/mcp` — **B5 (MCP side), D1, D2, D5, G2** - Tools `get_summary`, `list_reports`, `get_report`, `list_sources`, each the same `Lamplighter.Api` function and JSON as its REST endpoint. Same `ApiAuth` (bearer only, Origin, rate limits); a token without `read` sees no tools. - JSON-RPC handling moved to `LamplighterWeb.MCP.Server`, shared with the internal `/mcp` (which still refuses API tokens). README `### MCP` with the `claude mcp add` example. ### 2cd8835, 4992279: review fixes F14, F15 - Non-string JSON-RPC `method` → -32600 (both MCP endpoints). `/api/mcp` refuses batches (logged), so each tool call counts against the token's limit; internal `/mcp` keeps batches (D24). - Review probes folded into the real test suite. ### 834620d: Settings → API tab — **A7, G1** - `/settings/api-tokens`, a new **API** tab. Create (name, `read` scope, expiry 30/90/365 days or never): the token is shown once with a Copy button and is gone after Done or a reload. List shows prefix, created, last used, expiry or revoked. Revoke asks to confirm. - Creating needs sudo mode (sign-in in the last 20 min), checked again on submit, so a crafted event from an old session is refused (logged). Listing and revoking don't need it; an old session gets a "Sign in again" prompt instead of the form. - 9 LiveView tests: create → token verifies; plaintext gone after dismiss/reload; validation, unknown scopes refused, 20-token limit message; revoke stops the token; another user's token can't be revoked; old session can't create. README says where tokens live. - Checked at 390px and desktop: no horizontal overflow (page and tab bar), token wraps. | | Desktop | 390px | | --- | --- | --- | | Tokens | ![api-tokens-desktop](https://git.knope.dev/attachments/735ee1a9-d661-468e-a7df-534fa03d0309) | ![api-tokens-390](https://git.knope.dev/attachments/c10435dc-6c3b-4b68-b5f1-1730711b72fe) | | Just created | ![api-tokens-created-desktop](https://git.knope.dev/attachments/bc433f27-eb57-4050-ac28-aeba2e606933) | ![api-tokens-created-390](https://git.knope.dev/attachments/77389595-f84d-482f-b816-6e06dff11e85) | (Example data from a local dev database; the token shown is a throwaway.) precommit: 792 tests pass.
feat(api): personal API tokens, stored hashed apart from session tokens
All checks were successful
CI / test (pull_request) Successful in 30s
80d0a0d1f0
Tokens are llk_ plus 32 random bytes, shown once; only a SHA-256 hash is
kept, looked up by hash. read is the only scope. Revocation, optional
expiry, throttled last-use, 20 live tokens per user. Password changes and
magic-link logins leave them alone. LogScrubber redacts them and
filter_parameters now covers tokens, secrets and authorization.

Refs #3
feat(api): read-only REST API at /api/v1 with bearer API tokens
All checks were successful
CI / test (pull_request) Successful in 27s
3201f3ee66
Adds LamplighterWeb.ApiAuth (bearer llk_ tokens only: no session, no
query-string tokens, cross-origin browser requests refused, 401 with
WWW-Authenticate), per-token and failed-sign-in rate limits in a supervised
ETS table, and GET endpoints for summary, reports (filters, cursor paging,
max 100) and sources. Lamplighter.Api builds every response from a field
whitelist, so source settings and secrets, report context, and diagnosis
details never leave.
F12: ids and cursors past bigint are treated as bad ids (404/400) instead of
raising in Postgrex, and non-string filter values get a 400.
F13: the Origin check no longer trusts the Host header (DNS rebinding);
it compares scheme, host and port to the endpoint URL plus
API_ALLOWED_ORIGINS.
Author
Owner

Nye's early review of #33 at 3201f3e (REST side)

Checked the items the PR claims from the #3 checklist: B2-B5, C1, C3, C4, D3, D4, D6, E3, F1-F3. mix precommit passes (726 tests). Two low findings; everything else claimed holds.

F12 (low): bad input gives 500, not 4xx (D4/C4)

  • GET /api/v1/reports/99999999999999999999 and ?cursor=99999999999999999999: parse_id/1 accepts any positive integer, Postgrex raises DBConnection.EncodeError (out of int8 range) -> 500.
  • ?updated_since[a]=b: to_string(map) in filter/3 raises Protocol.UndefinedError -> 500.
  • Fix: cap parse_id/1 at 9_223_372_036_854_775_807 (too big -> nil, so 404 / 400); in the updated_since clause match when is_binary(since) and let other shapes hit an error clause. While there, the catch-all filter(_query, key, _value) message says "must be open, resolved, or all" for any key; it's only reached for bad status today, but kind/severity non-binaries should say their own thing.
  • Proof: test/nye/api_review_test.exs (attached), lines 18-40.

F13 (low, security): Origin check doesn't stop DNS rebinding (D3)

  • same_origin?/2 accepts an Origin whose host equals conn.host. In a rebinding attack the page is on evil.example, resolved to the homelab IP, so the browser sends Origin: http://evil.example and Host: evil.example: they match and the request goes through (test gets 200). Low today because the API needs a bearer token the page doesn't have, but the moduledoc says it's there for the MCP rule, and /api/mcp will rely on it.
  • Fix: compare only to the configured LamplighterWeb.Endpoint.config(:url)[:host] (and, if you want, an env-settable allow-list), never to the request's Host. Compare scheme+host+port if you can.
  • Proof: same file, line 46.

Checked and fine

  • B4: :api_token pipeline has no session/fetch_session; cookie doesn't authenticate.
  • C1: sources serializer is a field whitelist; secret test covers body.
  • C3: id-desc pages with limit+1 probe, clamp at 100, cursor stable.
  • D4: missing / malformed / wrong-prefix -> 401 with WWW-Authenticate; lowercase bearer is a 401, not a 500 (RFC 9110 says the scheme is case-insensitive; optional to accept it).
  • D6: token/access_token/api_token query params -> 400.
  • E3: failures log reason + 8-char prefix + IP, never the token; success logs id at debug.
  • F1-F3: per-token 120/min -> 429 + Retry-After; failed-auth keyed per IP, valid tokens never held back; ETS owned by a supervised GenServer with a minute sweep.

Not reviewed yet (not in this commit): D1/D2/D5 MCP, A7/G1 settings tab.


Posted by Upper Wolfjaw. F12 and F13 fixed in 3f7fd99: ids/cursors capped at bigint, non-string filters are 400s, and Origin is checked against the endpoint URL (scheme+host+port) plus API_ALLOWED_ORIGINS, never the Host header.

## Nye's early review of #33 at 3201f3e (REST side) Checked the items the PR claims from the #3 checklist: B2-B5, C1, C3, C4, D3, D4, D6, E3, F1-F3. `mix precommit` passes (726 tests). Two low findings; everything else claimed holds. **F12 (low): bad input gives 500, not 4xx (D4/C4)** - `GET /api/v1/reports/99999999999999999999` and `?cursor=99999999999999999999`: `parse_id/1` accepts any positive integer, Postgrex raises `DBConnection.EncodeError` (out of int8 range) -> 500. - `?updated_since[a]=b`: `to_string(map)` in `filter/3` raises `Protocol.UndefinedError` -> 500. - Fix: cap `parse_id/1` at `9_223_372_036_854_775_807` (too big -> nil, so 404 / 400); in the `updated_since` clause match `when is_binary(since)` and let other shapes hit an error clause. While there, the catch-all `filter(_query, key, _value)` message says "must be open, resolved, or all" for any key; it's only reached for bad `status` today, but `kind`/`severity` non-binaries should say their own thing. - Proof: `test/nye/api_review_test.exs` (attached), lines 18-40. **F13 (low, security): Origin check doesn't stop DNS rebinding (D3)** - `same_origin?/2` accepts an Origin whose host equals `conn.host`. In a rebinding attack the page is on evil.example, resolved to the homelab IP, so the browser sends `Origin: http://evil.example` and `Host: evil.example`: they match and the request goes through (test gets 200). Low today because the API needs a bearer token the page doesn't have, but the moduledoc says it's there for the MCP rule, and `/api/mcp` will rely on it. - Fix: compare only to the configured `LamplighterWeb.Endpoint.config(:url)[:host]` (and, if you want, an env-settable allow-list), never to the request's Host. Compare scheme+host+port if you can. - Proof: same file, line 46. **Checked and fine** - B4: `:api_token` pipeline has no session/fetch_session; cookie doesn't authenticate. - C1: sources serializer is a field whitelist; secret test covers body. - C3: id-desc pages with limit+1 probe, clamp at 100, cursor stable. - D4: missing / malformed / wrong-prefix -> 401 with `WWW-Authenticate`; lowercase `bearer` is a 401, not a 500 (RFC 9110 says the scheme is case-insensitive; optional to accept it). - D6: `token`/`access_token`/`api_token` query params -> 400. - E3: failures log reason + 8-char prefix + IP, never the token; success logs id at debug. - F1-F3: per-token 120/min -> 429 + Retry-After; failed-auth keyed per IP, valid tokens never held back; ETS owned by a supervised GenServer with a minute sweep. Not reviewed yet (not in this commit): D1/D2/D5 MCP, A7/G1 settings tab. --- _Posted by Upper Wolfjaw. F12 and F13 fixed in 3f7fd99: ids/cursors capped at bigint, non-string filters are 400s, and Origin is checked against the endpoint URL (scheme+host+port) plus `API_ALLOWED_ORIGINS`, never the Host header._
feat(api): user-facing MCP server at /api/mcp with API tokens
All checks were successful
CI / test (pull_request) Successful in 26s
2441a0070a
The REST reads as MCP tools (get_summary, list_reports, get_report,
list_sources) answering with the REST JSON, authorized by ApiAuth and
filtered by token scope. The JSON-RPC handling moves to MCP.Server, shared
with the internal run-tools /mcp, which still refuses API tokens.

Nye's review probes (test/nye) are folded into auth_test.exs and dropped.
jfro force-pushed feat/3-api-access from 2441a0070a
All checks were successful
CI / test (pull_request) Successful in 26s
to 460007797b
All checks were successful
CI / test (pull_request) Successful in 27s
2026-11-01 19:22:25 +00:00
Compare
A JSON-RPC batch ran every call on one rate-limit hit, so one request could
run hundreds of tool calls; /api/mcp now refuses batches (MCP 2025-06-18
dropped them) and the internal /mcp keeps them. A method that isn't a string
crashed the Method not found message with a 500; it's now -32600.
test: fold Nye's notification review probes into the real tests
All checks were successful
CI / test (pull_request) Successful in 27s
499227943e
Moves the paged-recovery, severity-flap, and secrets-in-logs checks into
triggers_notifications_test and notifications_test, and drops test/nye and
test/review, which landed in main with #32.
feat(settings): API tokens tab to create, copy once, list, and revoke tokens
All checks were successful
CI / test (pull_request) Successful in 26s
834620d471
jfro changed title from WIP: feat(api): read-only API and MCP with personal API tokens to feat(api): read-only API and MCP with personal API tokens 2026-11-01 19:35:54 +00:00
jfro manually merged commit ded6ca5590 into main 2026-11-01 19:45:01 +00:00
Sign in to join this conversation.
No description provided.