API v1: foundation and read endpoints #122

Closed
opened 2026-12-03 04:31:06 +00:00 by jfro · 1 comment
Owner

Part of the Ink Lantern rename & API project. Follows the design in the API design issue.

  • /api/v1 scope in the router on the :api pipeline, with a Bearer-auth plug that uses RmAnalyzer.ApiKeys.authorize/1 and builds the same Scope as MCP (item limits apply).
  • Consistent JSON errors (401 without a valid key, 403 when the key lacks the permission, 404 for items outside the key's library), pagination.
  • Read endpoints: documents, folders, pages (text and image), search, stats, changes, suggestions, key info (/me).
  • Permission checks share one path with the MCP tool checks, so a key limited to some tools is limited the same way here.
  • Tests for auth, item limits and each endpoint; mix precommit passes.
Part of the Ink Lantern rename & API project. Follows the design in the API design issue. - `/api/v1` scope in the router on the `:api` pipeline, with a Bearer-auth plug that uses `RmAnalyzer.ApiKeys.authorize/1` and builds the same `Scope` as MCP (item limits apply). - Consistent JSON errors (401 without a valid key, 403 when the key lacks the permission, 404 for items outside the key's library), pagination. - Read endpoints: documents, folders, pages (text and image), search, stats, changes, suggestions, key info (`/me`). - Permission checks share one path with the MCP tool checks, so a key limited to some tools is limited the same way here. - Tests for auth, item limits and each endpoint; `mix precommit` passes.
Author
Owner

Posted by Haystack for Nye (attack checklist for the #122 review; Nye's token cannot comment).

#122 read endpoints: attack checklist (Nye, from main @68d5022 + docs/api.md draft)

Keys to make in tests (all via RmAnalyzer.ApiKeys):

  • FULL: tools nil, item_ids nil, can_write false
  • LIMITED: item_ids = [one folder "Work"] (a document outside it = "outside"; inside = "inside")
  • TRIMMED: tools = ["search_notes", "read_pages"] (no list_documents, view_page, get_stats, list_changes, list_suggestions)
  • REVOKED: a key made then ApiKeys.delete/2'd (there is no revoked flag: delete = row gone)
  • NONE: no Authorization header; also "Bearer junk", "Bearer rma_unknown", Basic auth, and a chat answer token (NotesAccess.scope token, Choice G)
  • GONE USER: key whose user was deleted (ApiKeys.authorize returns nil)

Expected for every endpoint: NONE/REVOKED/GONE USER/chat token -> 401 + WWW-Authenticate: Bearer realm="rm-analyzer", error.code "unauthorized", no body data.

Endpoint FULL LIMITED TRIMMED
GET /me 200 200, limited: true, no item list of other folders 200, tools == ["search_notes","read_pages"]
GET /documents 200 200, only inside docs; folder_id= -> 404 (not empty 200); folder_id="" -> only reached My files items (likely none) 403 permission list_documents
GET /documents/:id 200 inside 200; outside 404; unknown id 404 (same body as outside) 403 list_documents
GET /folders 200 only Work and its subfolders; parent path names outside it not leaked in path 403 list_documents
GET /tags 200 counts only over reached docs; tags only on outside docs absent 403 list_documents
GET /documents/:id/pages 200 inside 200; outside 404 200
GET /documents/:id/pages/:n (and ?page_id=) 200 outside 404; page_id of an outside doc under an inside doc id -> 404 200
GET /documents/:id/pages/:n/image 200 png outside 404 403 view_page
GET /search?q= 200 hits only from inside; document_id= -> 404 200
GET /stats 200 counts only reached (WritingStats already filters, writing_stats.ex:209-220); folder/doc filter outside -> 404 or refused 403 get_stats
GET /suggestions 200 filtered as AgentTools.suggestions (agent_tools.ex:622-666): no moves unless Quick sheets reached AND target reached; tags only for reached docs 403 list_suggestions
GET /changes?since= 200 only changes Changes.reaches? lets through (changes.ex:151) 403 list_changes
GET /sync 200 200 (account-wide status, no item names in last_error) 200
GET /openapi.json public 200, no key needed, no user data

Also:

  • 404 bodies for "outside" and "doesn't exist" must be byte-identical (no existence oracle). Same for ETag/304: If-None-Match on an outside doc -> 404, not 304.
  • Pagination cursor made by FULL key replayed by LIMITED key -> still filtered (cursor must not carry scope); tampered cursor -> 400 invalid_cursor, not 500.
  • limit=0, limit=201, limit=-1, limit=abc -> 400 invalid_params (or clamped, as documented), never 500.
  • Page n=0, n=999, n=abc -> 400/404, never 500.
  • No CORS headers on any response; OPTIONS preflight gets no Access-Control-Allow-*.
  • A write method on a read path (POST /documents/:id) with a can_write=false key -> 404/405, never a write.
  • Only the :api pipeline: no session cookie set, no CSRF needed, :browser plugs not run.
  • Changing a key's access (update_access) takes effect on the very next request (no cached scope).

MCP checks that live outside the shared Scope (REST would miss these)

  1. Tool permission: name in allowed in the transport, lib/rm_analyzer_web/notes_mcp.ex:249 (allowed = ApiKeys.tools/1 at :93). Scope carries no tools. -> #122 adds ApiKeys.allowed?/2 and both call it (Rule 2).
  2. tools/list filtering by allowed, notes_mcp.ex:118-121 (definitions/1); /me must return the same list.
  3. BUG F1: resources/list, resources/read, resources/subscribe of rm-analyzer://changes (notes_mcp.ex:265-320) and the GET event stream (:69, :125) never check list_changes. A TRIMMED key reads the change feed today. Proof: test/rm_analyzer_web/notes_mcp_tool_limit_nye_test.exs on local branch review/122-attack (fails on main). REST /changes and /events must require list_changes, and MCP's resource paths should use the same allowed?/2.
  4. Chat answer tokens vs API keys are told apart in the transport (notes_mcp.ex:86-93): NotesAccess.scope first. The API's auth plug must call only ApiKeys.authorize/1 (Choice G).
  5. 401 + WWW-Authenticate realm is set in the transport (notes_mcp.ex:51-54); the API plug must set it itself.
  6. Side effect in transport: SyncServer.sync_if_stale on resources/read/subscribe (:287, :314). If REST /changes copies it, a TRIMMED/LIMITED key can still trigger syncs; fine (own cloud) but should follow the permission check, not precede it.
  7. Library limits: Scope.library honoured in Chat.Notes, AgentTools, Changes, WritingStats; NOT in Sorting, Tagging, Todos, QuickNotes. Read side: /suggestions must go through AgentTools.suggestions/1, not Sorting.list_suggestions/2 directly.
F1 proof: test/rm_analyzer_web/notes_mcp_tool_limit_nye_test.exs (fails on main)
defmodule RmAnalyzerWeb.NotesMCPToolLimitNyeTest do
  # A key whose tools list leaves out list_changes must not read the change
  # feed some other way: the rm-analyzer://changes resource is list_changes.
  use RmAnalyzerWeb.ConnCase, async: false

  import RmAnalyzer.AccountsFixtures, only: [user_scope_fixture: 0]
  import RmAnalyzer.ChatFixtures, only: [library_fixture: 1]

  alias RmAnalyzer.ApiKeys

  setup %{conn: conn} do
    scope = user_scope_fixture()
    library_fixture(scope)
    {:ok, key, token} = ApiKeys.create(scope, %{"name" => "Reader"})
    {:ok, _key} = ApiKeys.update_access(scope, key, %{"tools" => ["search_notes", "read_pages"]})
    %{conn: put_req_header(conn, "authorization", "Bearer #{token}")}
  end

  defp call(conn, method, params) do
    conn
    |> put_req_header("content-type", "application/json")
    |> post(~p"/mcp", Jason.encode!(%{jsonrpc: "2.0", id: 1, method: method, params: params}))
    |> json_response(200)
  end

  test "a key without list_changes can't read rm-analyzer://changes", %{conn: conn} do
    response = call(conn, "resources/read", %{uri: "rm-analyzer://changes"})
    refute Map.has_key?(response, "result"), "read the change feed: #{inspect(response)}"
  end

  test "a key without list_changes isn't offered rm-analyzer://changes", %{conn: conn} do
    response = call(conn, "resources/list", %{})
    assert get_in(response, ["result", "resources"]) in [nil, []], inspect(response)
  end
end

_Posted by Haystack for Nye (attack checklist for the #122 review; Nye's token cannot comment)._ # #122 read endpoints: attack checklist (Nye, from main @68d5022 + docs/api.md draft) Keys to make in tests (all via RmAnalyzer.ApiKeys): - FULL: tools nil, item_ids nil, can_write false - LIMITED: item_ids = [one folder "Work"] (a document outside it = "outside"; inside = "inside") - TRIMMED: tools = ["search_notes", "read_pages"] (no list_documents, view_page, get_stats, list_changes, list_suggestions) - REVOKED: a key made then ApiKeys.delete/2'd (there is no revoked flag: delete = row gone) - NONE: no Authorization header; also "Bearer junk", "Bearer rma_unknown", Basic auth, and a chat answer token (NotesAccess.scope token, Choice G) - GONE USER: key whose user was deleted (ApiKeys.authorize returns nil) Expected for every endpoint: NONE/REVOKED/GONE USER/chat token -> 401 + WWW-Authenticate: Bearer realm="rm-analyzer", error.code "unauthorized", no body data. | Endpoint | FULL | LIMITED | TRIMMED | |---|---|---|---| | GET /me | 200 | 200, limited: true, no item list of other folders | 200, tools == ["search_notes","read_pages"] | | GET /documents | 200 | 200, only inside docs; folder_id=<outside folder> -> 404 (not empty 200); folder_id="" -> only reached My files items (likely none) | 403 permission list_documents | | GET /documents/:id | 200 | inside 200; outside 404; unknown id 404 (same body as outside) | 403 list_documents | | GET /folders | 200 | only Work and its subfolders; parent path names outside it not leaked in `path` | 403 list_documents | | GET /tags | 200 | counts only over reached docs; tags only on outside docs absent | 403 list_documents | | GET /documents/:id/pages | 200 | inside 200; outside 404 | 200 | | GET /documents/:id/pages/:n (and ?page_id=) | 200 | outside 404; page_id of an outside doc under an inside doc id -> 404 | 200 | | GET /documents/:id/pages/:n/image | 200 png | outside 404 | 403 view_page | | GET /search?q= | 200 | hits only from inside; document_id=<outside> -> 404 | 200 | | GET /stats | 200 | counts only reached (WritingStats already filters, writing_stats.ex:209-220); folder/doc filter outside -> 404 or refused | 403 get_stats | | GET /suggestions | 200 | filtered as AgentTools.suggestions (agent_tools.ex:622-666): no moves unless Quick sheets reached AND target reached; tags only for reached docs | 403 list_suggestions | | GET /changes?since= | 200 | only changes Changes.reaches? lets through (changes.ex:151) | 403 list_changes | | GET /sync | 200 | 200 (account-wide status, no item names in last_error) | 200 | | GET /openapi.json | public 200, no key needed, no user data | | | Also: - 404 bodies for "outside" and "doesn't exist" must be byte-identical (no existence oracle). Same for ETag/304: If-None-Match on an outside doc -> 404, not 304. - Pagination cursor made by FULL key replayed by LIMITED key -> still filtered (cursor must not carry scope); tampered cursor -> 400 invalid_cursor, not 500. - limit=0, limit=201, limit=-1, limit=abc -> 400 invalid_params (or clamped, as documented), never 500. - Page n=0, n=999, n=abc -> 400/404, never 500. - No CORS headers on any response; OPTIONS preflight gets no Access-Control-Allow-*. - A write method on a read path (POST /documents/:id) with a can_write=false key -> 404/405, never a write. - Only the :api pipeline: no session cookie set, no CSRF needed, :browser plugs not run. - Changing a key's access (update_access) takes effect on the very next request (no cached scope). ## MCP checks that live outside the shared Scope (REST would miss these) 1. Tool permission: `name in allowed` in the transport, lib/rm_analyzer_web/notes_mcp.ex:249 (allowed = ApiKeys.tools/1 at :93). Scope carries no tools. -> #122 adds ApiKeys.allowed?/2 and both call it (Rule 2). 2. tools/list filtering by allowed, notes_mcp.ex:118-121 (definitions/1); /me must return the same list. 3. BUG F1: resources/list, resources/read, resources/subscribe of rm-analyzer://changes (notes_mcp.ex:265-320) and the GET event stream (:69, :125) never check list_changes. A TRIMMED key reads the change feed today. Proof: test/rm_analyzer_web/notes_mcp_tool_limit_nye_test.exs on local branch review/122-attack (fails on main). REST /changes and /events must require list_changes, and MCP's resource paths should use the same allowed?/2. 4. Chat answer tokens vs API keys are told apart in the transport (notes_mcp.ex:86-93): NotesAccess.scope first. The API's auth plug must call only ApiKeys.authorize/1 (Choice G). 5. 401 + WWW-Authenticate realm is set in the transport (notes_mcp.ex:51-54); the API plug must set it itself. 6. Side effect in transport: SyncServer.sync_if_stale on resources/read/subscribe (:287, :314). If REST /changes copies it, a TRIMMED/LIMITED key can still trigger syncs; fine (own cloud) but should follow the permission check, not precede it. 7. Library limits: Scope.library honoured in Chat.Notes, AgentTools, Changes, WritingStats; NOT in Sorting, Tagging, Todos, QuickNotes. Read side: /suggestions must go through AgentTools.suggestions/1, not Sorting.list_suggestions/2 directly. <details><summary>F1 proof: test/rm_analyzer_web/notes_mcp_tool_limit_nye_test.exs (fails on main)</summary> ```elixir defmodule RmAnalyzerWeb.NotesMCPToolLimitNyeTest do # A key whose tools list leaves out list_changes must not read the change # feed some other way: the rm-analyzer://changes resource is list_changes. use RmAnalyzerWeb.ConnCase, async: false import RmAnalyzer.AccountsFixtures, only: [user_scope_fixture: 0] import RmAnalyzer.ChatFixtures, only: [library_fixture: 1] alias RmAnalyzer.ApiKeys setup %{conn: conn} do scope = user_scope_fixture() library_fixture(scope) {:ok, key, token} = ApiKeys.create(scope, %{"name" => "Reader"}) {:ok, _key} = ApiKeys.update_access(scope, key, %{"tools" => ["search_notes", "read_pages"]}) %{conn: put_req_header(conn, "authorization", "Bearer #{token}")} end defp call(conn, method, params) do conn |> put_req_header("content-type", "application/json") |> post(~p"/mcp", Jason.encode!(%{jsonrpc: "2.0", id: 1, method: method, params: params})) |> json_response(200) end test "a key without list_changes can't read rm-analyzer://changes", %{conn: conn} do response = call(conn, "resources/read", %{uri: "rm-analyzer://changes"}) refute Map.has_key?(response, "result"), "read the change feed: #{inspect(response)}" end test "a key without list_changes isn't offered rm-analyzer://changes", %{conn: conn} do response = call(conn, "resources/list", %{}) assert get_in(response, ["result", "resources"]) in [nil, []], inspect(response) end end ``` </details>
jfro closed this issue 2026-12-03 05:29:22 +00:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
jfro/rm-analyzer#122
No description provided.