From f1d4c10a4507c5f82ffc5d7ede5d9d23e587e4d6 Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Mon, 23 Nov 2026 22:24:38 +0000 Subject: [PATCH] :books: Separate token and resource permission guidance Document token authentication separately from resource and invitation permissions, and replace the former mixed-domain memory. AI-assisted-by: gpt-6.1-terra --- .../auth-permissions-product-domains.md | 46 ------------------- .serena/memories/backend/auth-sso.md | 4 +- .serena/memories/backend/auth-tokens.md | 6 +++ .serena/memories/backend/core.md | 2 +- .serena/memories/backend/http-rpc.md | 2 +- .serena/memories/backend/permissions.md | 7 +++ .../backend/websocket-subscriptions.md | 2 +- 7 files changed, 18 insertions(+), 51 deletions(-) delete mode 100644 .serena/memories/backend/auth-permissions-product-domains.md create mode 100644 .serena/memories/backend/auth-tokens.md create mode 100644 .serena/memories/backend/permissions.md diff --git a/.serena/memories/backend/auth-permissions-product-domains.md b/.serena/memories/backend/auth-permissions-product-domains.md deleted file mode 100644 index 56ca732a67..0000000000 --- a/.serena/memories/backend/auth-permissions-product-domains.md +++ /dev/null @@ -1,46 +0,0 @@ -# Backend Auth, Permissions, and Product Domain Subtleties - -## Auth and sessions - -- LDAP identity, SSO redirects and invitation-based registration: `mem:backend/auth-sso`. -- Public auth endpoints must explicitly set `::rpc/auth false`; RPC auth defaults to enabled. Session cookie creation/deletion is usually attached as an RPC response transform. -- Account lockout (flag `:account-lockout`, `app.auth.login-lockout`) is Redis-backed and keyed per profile id. Password and LDAP flows check/increment on the profile derived from the typed email and clear on the profile that actually logs in. -- Lockout and RPC rate limits share the `app.http.errors/handle-error :rate-limit` HTTP path: status 429, body `{:type :rate-limit :code ... :hint ... :ttl ...}`, and any supplied `::http/headers` preserved. Account lockout raises `:code :account-locked` and, when it carries a non-nil `:ttl` (seconds), the handler adds `retry-after`. The RPC limiter (`app.rpc.rlimit`) raises `:code :request-blocked` and sets `retry-after` itself in `::http/headers` (seconds until the longest rejecting limit resets), alongside `x-rate-limit-remaining`/`x-rate-limit-reset`. CORS (`app.http.middleware/with-cors-headers`) exposes `content-type`, `retry-after`, and both `x-rate-limit-*` headers. External flags: `enable-account-lockout`, `enable-rpc-rlimit`. -- Access tokens (`app.http.access-token`): personal tokens have JWT issuer `access-token` and DB type other than `mcp`; MCP tokens have issuer `urn:penpot:mcp-token` (`actoken/mcp-token-issuer`) and DB type `mcp`. Authentication requires issuer and type to agree, and the claim `uid` to match the row's profile; other issuers and undecryptable tokens are treated as anonymous. -- Management RPC (`/api/management/methods/:name`) is shared-key only. The middleware authenticates ` `; the RPC wrapper `wrap-shared-key-authorization` authorizes the key id against the method's `::rpc/allowed-shared-keys` set. Absent metadata accepts any configured key; all current methods declare one (`exporter`/`media-processor` for `upload-tempfile`, `nexus` for file analysis, `exporter` for jobs, `admin-console` for Nitrate). A valid key outside the set answers 403 `:shared-key-not-allowed`; denied calls do not reach the audit wrapper. -- Personal tokens need flag `:access-tokens`. MCP tokens need `:mcp` or `:access-tokens`, and only on routes whose `actoken/authz` gets `::actoken/allow-mcp true` (the RPC routes); elsewhere (e.g. assets) they are anonymous. -- On RPC, an MCP token reaches only commands with `::rpc/token-type "mcp"` (`wrap-authentication` in `app.rpc`); every other command answers 403 `:token-auth-required`. A command with that metadata also rejects sessions and personal tokens. Currently only `send-mcp-feedback`. Blocking a profile invalidates sessions, not tokens, so such commands check `:is-blocked`/`:is-active` themselves. -- HTTP/session parsing details such as cookie/header precedence, JWT session token versions, and SameSite behavior are in `mem:backend/http-rpc`. - -## Permission model - -- `app.rpc.permissions` provides predicate/check factories. Failed permission checks intentionally raise `:not-found` / `:object-not-found`, not an authorization-specific error, to avoid leaking object existence. -- Team role flags are normalized as owner > admin > editor > viewer. Owner/admin imply edit; any membership row implies read. -- File/project role rows only count with a live team membership: the file/project permission queries require a matching `team_profile_rel` row, and leaving or removing a member deletes their team-scoped `file`/`project`/`team-project-profile-rel` rows (GHSA-v9r9-h77c-55m2). -- The organization-owner fallback (`get-organization-owner-permissions` via Nitrate over HTTP) grants read-only access for a non-member organization owner. It resolves the owning team through `resolve-team-id`, which refuses soft-deleted file/project/team: the file and project lookups filter `deleted_at`, and a final `db/get*` check covers the team row itself — `nil` means no access. `db/get*` only filters soft-deleted rows when `deleted_at` is in the projection. The re-checks of open websocket subscriptions rely on this (`mem:backend/websocket-subscriptions`). -- File/project/comment checks are implemented in the owning command namespaces, often via helpers imported from `files`, `teams`, or `projects`; do not bypass those helpers with direct DB lookups unless preserving their not-found semantics. -- Comment permission includes both logged-in state and the file/team comment policy. Shared viewer paths may pass `share-id`; preserve that path when changing comment queries. RPCs that accept `share-id` enforce the link's page scope before mutating (`share-link-pages` + `check-page-scope`): a thread or page outside the link raises `:not-found`, and that check runs before the ownership checks. `get-profiles-for-file-comments` filters its query by the same pages. `mark-all-threads-as-read` does not take `share-id`. -- Share-link view-only bundles are page-scoped for components too: `get-view-only-bundle` filters `pages`/`pages-index` to the link, trims the primary file's `:components` to live components referenced transitively from the allowed pages (deleted components never travel), and emits them inline; membership bundles keep the full primary components map. Linked libraries are trimmed to the components the emitted data references, and that walk reads the emitted data itself (scoped pages plus the trimmed components map) rather than the full realized file, so neither excluded pages nor deleted primary components — whose stored `:objects` may instance library components — retain a library component; library pages never travel either. `get-file-fragment` (`check-fragment-scope`) authorizes only fragments of the link's pages for share links (`:not-found` otherwise): no root-level pointer, components included, is ever authorized. - -## Teams, projects, and invitations - -- Team/project commands mix DB changes, email, message bus notifications, media/storage cleanup, feature flags, quotas, and audit metadata. Keep mutations transactional when the existing command does so. -- Invitation flows validate muted/bounced emails before sending and use tokenized invitation state. Accepting an invitation is tied to the invited member identity, not just possession of a token. -- The whole invitation family is team-admin only: creating, updating and deleting invitations, minting the invitation token (`get-team-invitation-token`) and listing the pending ones (`get-team-invitations`, which carries the invited email and the offered role). The token of an invitation that grants the `owner` role is restricted to the team owner, because an admin cannot create nor promote an owner invitation (`cant-promote-to-owner`). This family is the exception to the rule above: it answers `:validation` / `:insufficient-permissions` instead of `:not-found`, so the five commands speak one language. -- With the `:admin-console` flag, the organization `send-invitations` policy (role value plus Nitrate `restrictions-met`, through `cto/allowed?`) gates every invitation command that hands out or manages access: create (and resend, which reuses it), `update-team-invitation-role`, `delete-team-invitation` and `get-team-invitation-token`. Only `get-team-invitations` stays on team admin alone, so a blocked admin still sees the list. The shared helper `check-send-invitations-policy` in `teams_invitations.clj` does a strict Nitrate lookup (fails closed; 404 means no organization) and runs outside a DB transaction, which is why the role and delete commands carry no `::db/transaction`. -- Logical deletion is used for many product objects; prefer existing logical-deletion helpers over hard deletes unless the command already performs permanent cleanup. -- Bounced/spam-complaint emails can mute/block a profile for login/registration and email sending. Devenv Mailpit is the normal local path for registration/email-flow testing. - -## Comments, webhooks, and audit - -- Comment thread queries join file/project/profile state and exclude deleted files/projects. Unread comment counts depend on `comment_thread_status.modified-at` and profile notification preferences. -- Webhook edits are allowed for team editors/admins or the webhook creator. Webhook validation performs a synchronous HEAD request with a short timeout; validation errors are mapped through `app.loggers.webhooks`. -- Audit events are prepared from RPC metadata, result metadata, params, request context, and selected auth identifiers. Webhook event batching can be controlled through audit/webhook metadata on commands or results. -- Webhook and audit logging are cross-cutting side effects of product commands; when adding a command, check nearby command metadata and result metadata patterns before inventing a new event shape. - -## Local testing notes - -- Enable LDAP login locally with frontend flag `enable-login-with-ldap`; the devenv includes a configured test LDAP service. -- OIDC testing requires external provider app credentials plus matching backend/frontend config. -- Backend domain tests usually live under `backend/test/backend_tests/rpc/commands/*_test.clj` or nearby backend test namespaces. Use focused `clojure -M:dev:test --focus ...` from `backend/` when possible. -- For auth/session or HTTP behavior, combine backend tests with the HTTP/session notes in `mem:backend/http-rpc` because RPC-level tests may not exercise cookie/header transforms. diff --git a/.serena/memories/backend/auth-sso.md b/.serena/memories/backend/auth-sso.md index 37b5ed3fba..5c6754b947 100644 --- a/.serena/memories/backend/auth-sso.md +++ b/.serena/memories/backend/auth-sso.md @@ -1,7 +1,7 @@ # Backend SSO and registration -- Start at `app.auth.oidc`, `app.rpc.commands.auth` and `app.rpc.commands.ldap`. For HTTP session and token boundaries see `mem:backend/http-rpc` and `mem:backend/auth-permissions-product-domains`. -- LDAP binds the session to the directory-returned email, not the typed login: aliases and multi-valued attributes can resolve to a different profile. Lockout checks use the typed identity, but successful login clears the counter for the profile actually logged in. +- Start at `app.auth.oidc`, `app.rpc.commands.auth` and `app.rpc.commands.ldap`. For HTTP session and token boundaries see `mem:backend/http-rpc` and `mem:backend/auth-tokens`. +- LDAP binds the session to the directory-returned email, not the typed login: aliases and multi-valued attributes can resolve to a different profile. Redis-backed account lockout checks use the typed identity, but successful login clears the counter for the profile actually logged in. Lockout and RPC rate limits use the `app.http.errors` 429 path; keep `retry-after` and rate-limit headers available through CORS. - `check-nitrate-sso` receives the client route as a query string, not an absolute URL. `build-dest-url` validates parameter keys and builds the destination under `public-uri`; invalid input falls back there. Accept root routes without `screen`, and keep callback revalidation for older state tokens. The state token binds the SSO grant to the profile that initiated it: a different session must not receive that grant. - A client-supplied organization ID requires `app.nitrate/organization-access?` before SSO; callers without organization access get the no-access short circuit, not an SSO challenge. - When public registration is disabled, a matching invitation can allow registration. Password registration rechecks the non-expired invitation row under lock. OIDC registration requires `:registration`, `:oidc-registration` or an invitation whose member email matches the provider email after `clean-email`; the callback verifies it and registration revalidates it under lock when the flags are off. Only recognized OIDC provider types take the SSO registration path. Keep invitation identity checks on authenticated login too. diff --git a/.serena/memories/backend/auth-tokens.md b/.serena/memories/backend/auth-tokens.md new file mode 100644 index 0000000000..0b3eae3865 --- /dev/null +++ b/.serena/memories/backend/auth-tokens.md @@ -0,0 +1,6 @@ +# Backend access tokens + +- Start at `app.http.access-token` for token authentication and `app.rpc/wrap-authentication` for command restrictions. For session and management shared-key handling see `mem:backend/http-rpc`; MCP OAuth provisioning is `mem:mcp/oauth`. +- Personal and MCP tokens have distinct issuers and database types. Authentication requires issuer and row type to agree and the token's `uid` to match the row's profile; expired, undecryptable or unknown-issuer tokens do not authenticate. +- Personal tokens require `:access-tokens`. MCP tokens require `:mcp` or `:access-tokens` and a route that opts into `::actoken/allow-mcp`; assets do not. An MCP token can call only RPCs declaring `::rpc/token-type "mcp"`, which also reject sessions and personal tokens. +- Blocking a profile invalidates sessions, not access tokens. A token-only command that requires an active profile must check that itself; see `send-mcp-feedback`. Authentication does not replace resource authorization: `mem:backend/permissions`. diff --git a/.serena/memories/backend/core.md b/.serena/memories/backend/core.md index 36422e9ef7..97fd538ec2 100644 --- a/.serena/memories/backend/core.md +++ b/.serena/memories/backend/core.md @@ -18,7 +18,7 @@ JVM Clojure backend. Start in `app.main` for Integrant wiring, `app.rpc.commands - File-data blob references, offload and partition-aware lookups: `mem:backend/file-data-storage`. - Graph projection parity, debug sessions, access and native resource ownership: `mem:backend/graph-experiment`. - Session lifetime, token `:exp` and session GC: `mem:backend/session-expiration`. -- Auth, product permissions, teams, projects, invitations, comments and webhooks: `mem:backend/auth-permissions-product-domains`. +- Personal and MCP token authentication: `mem:backend/auth-tokens`. Resource, share-link and invitation permissions: `mem:backend/permissions`. - LDAP identity, SSO redirects and invitation-based registration: `mem:backend/auth-sso`. - WebSocket connection ownership and revocation: `mem:backend/websocket-subscriptions`. - Audit event attribution, fan-out and privacy: `mem:audit-log`; cursor ordering, archival and retention: `mem:backend/audit-consumers`. diff --git a/.serena/memories/backend/http-rpc.md b/.serena/memories/backend/http-rpc.md index 0c042b74f0..2d7997ff4e 100644 --- a/.serena/memories/backend/http-rpc.md +++ b/.serena/memories/backend/http-rpc.md @@ -5,4 +5,4 @@ - A malformed body is a client error classified at the parse boundary, not by exception class. Preserve 400 `:malformed-json` for malformed input and 413 for oversized bodies. See `app.http.middleware` for parsing and `Accept`/`_fmt` response negotiation, and `mem:backend/metrics` for pre-dispatch counters. - Upload schemas validate shape, not path ownership. Declare file params in `::rpc/multipart-only-params` so the wrapper requires server-confirmed multipart input, and run `media.v/check-upload-path` before reading the file. The binfile job creation RPC instead takes a chunked upload ID; see `mem:backend/binfile`. - Session auth selects the cookie before the `Authorization` header. Only current `kid=1`/`ver=1` tokens enter the session decoder. Plain HTTP on a host other than `localhost` changes the secure-cookie default via `app.config/parse-flags`; SameSite is `None` for CORS and otherwise follows the strict-cookie flag. See `mem:backend/session-expiration` for renewal and cleanup. -- Management shared-key authorization is outermost: a disallowed key must not validate params or open a transaction. `::rpc/allowed-shared-keys` omitted accepts any configured valid key; an empty set accepts none. See `mem:backend/auth-permissions-product-domains` for the product permission boundary. +- Management shared-key authorization is outermost: a disallowed key must not validate params or open a transaction. `::rpc/allowed-shared-keys` omitted accepts any configured valid key; an empty set accepts none. See `mem:backend/permissions` for the product permission boundary. diff --git a/.serena/memories/backend/permissions.md b/.serena/memories/backend/permissions.md new file mode 100644 index 0000000000..e6b9327168 --- /dev/null +++ b/.serena/memories/backend/permissions.md @@ -0,0 +1,7 @@ +# Backend product permissions + +- Start at `app.rpc.permissions` and the owning file, team, project and comment commands. Permission failures normally answer `:not-found` to avoid exposing resource existence. Invitation management deliberately answers `:validation` / `:insufficient-permissions` instead. +- File and project roles require live team membership; leaving or removing a member clears team-scoped roles. The organization-owner fallback grants read-only access without membership only for live resources. Soft-delete filtering in `db/get*` requires `deleted_at` in the selected columns. WebSocket rechecks depend on the same rules; see `mem:backend/websocket-subscriptions`. +- Share-link authorization is page-scoped for comments, viewer bundles and file fragments. A view-only bundle includes only live components transitively referenced by the permitted output, including linked-library dependencies; do not derive those dependencies from excluded pages or deleted components. Root-level fragments are not authorized by a share link. Membership bundles have different scope. +- Invitation management is team-admin only; owner-role invitation tokens require the team owner. With `:admin-console`, `check-send-invitations-policy` gates changes and token issuance through a strict Nitrate lookup, but listing remains team-admin only. The policy lookup runs outside the DB transaction. For registration with an invitation see `mem:backend/auth-sso`. +- Comment checks include login state and file/team policy. Preserve share-link page checks before mutation and avoid bypassing existing permission helpers, including their not-found behavior. For webhook and audit emission see `mem:audit-log`. diff --git a/.serena/memories/backend/websocket-subscriptions.md b/.serena/memories/backend/websocket-subscriptions.md index 842df04f76..2ec676e9a1 100644 --- a/.serena/memories/backend/websocket-subscriptions.md +++ b/.serena/memories/backend/websocket-subscriptions.md @@ -2,7 +2,7 @@ - Start at `app.http.websocket` for connection ownership and revalidation, and `app.rpc.notifications` for internal announcements. The connection registry and profile index share one atom, local to the backend instance; each connection's `::ws/state` separately owns its subscriptions. Use the correct namespaces for profile/session fields versus `app.util.websocket` fields: a missing session ID can silently drop every output message. - Access is checked when subscribing and rechecked afterward. Mutations announce permission changes on the internal bus after commit, so a watcher on another connection sees committed state. A team-level event resolves members in the watcher instead of publishing one event per member. Keep notification helpers outside `app.http.websocket` to avoid the command dependency cycle. -- An announcement triggers a fresh decision; it does not prove access was lost. Check resource existence as well as read permissions, including the organization-owner fallback. A deleted file, project or team must not remain readable through that fallback, while a downgrade to viewer or a live non-member organization owner can remain readable. Team rechecks add an existence gate even though the original team subscription does not. See `mem:backend/auth-permissions-product-domains`. +- An announcement triggers a fresh decision; it does not prove access was lost. Check resource existence as well as read permissions, including the organization-owner fallback. A deleted file, project or team must not remain readable through that fallback, while a downgrade to viewer or a live non-member organization owner can remain readable. Team rechecks add an existence gate even though the original team subscription does not. See `mem:backend/permissions`. - The relay also rechecks on an interval, covering external ownership changes, direct SQL and missed announcements. Reuse one tick through message turns and prioritize it over the subscription channel so busy traffic cannot starve revalidation. Closing the channel ends the relay. Both interval checks and the announcement watcher deliberately fail open on lookup errors; interval checks rethrow interruption. Size the cost before shortening the interval. - Use the dedicated internal revocation topic, never `uuid/zero`: the system topic is piped directly to clients. The bus reaches other backend instances; directly closing locally registered sockets does not. Close functions are idempotent and remove the subscription before later messages can reuse its topic. See `mem:prod-infra/core` and `mem:frontend/websocket-notifications`.