diff --git a/.serena/memories/backend/auth-permissions-product-domains.md b/.serena/memories/backend/auth-permissions-product-domains.md index c7f83fedd0..3209813bff 100644 --- a/.serena/memories/backend/auth-permissions-product-domains.md +++ b/.serena/memories/backend/auth-permissions-product-domains.md @@ -19,7 +19,7 @@ - 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/subtleties`. +- HTTP/session parsing details such as cookie/header precedence, JWT session token versions, and SameSite behavior are in `mem:backend/http-rpc`. ## Permission model @@ -52,4 +52,4 @@ - 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/subtleties` because RPC-level tests may not exercise cookie/header transforms. +- 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/config.md b/.serena/memories/backend/config.md new file mode 100644 index 0000000000..a407886330 --- /dev/null +++ b/.serena/memories/backend/config.md @@ -0,0 +1,5 @@ +# Backend configuration + +- Start at `app.config` for environment coercion and boot validation. For duration settings use hours for whole days (e.g. `168h`, not `7d`). For checks that depend on Clojure assertions, see the startup flag in `mem:backend/testing`; redefining flags at runtime does not restore assertions compiled out at load. +- `app.main` wires `PENPOT_DATABASE_*` into `app.db/create-datasource-config`. Keep driver properties as strings: pgjdbc uses `Properties.getProperty`. A parameter of the same name in `PENPOT_DATABASE_URI` takes precedence; check the URI before diagnosing an ignored setting. +- `prepareThreshold=0` disables server-side prepares, not the driver's cache of parsed queries. A zero query or size limit disables that cache. The configured size is in bytes and rounds up to whole MiB for pgjdbc. Use the schemas and datasource builder for accepted ranges and property names. diff --git a/.serena/memories/backend/core.md b/.serena/memories/backend/core.md index afe661b46a..67244b03e4 100644 --- a/.serena/memories/backend/core.md +++ b/.serena/memories/backend/core.md @@ -4,7 +4,9 @@ JVM Clojure backend. Start in `app.main` for Integrant wiring, `app.rpc.commands ## Focused memories -- RPC wrapper order, config and HTTP middleware: `mem:backend/subtleties`. +- RPC wrapper order, HTTP middleware and session identity: `mem:backend/http-rpc`. +- Environment coercion and PostgreSQL driver settings: `mem:backend/config`. +- Media validation and historical topic links: `mem:backend/subtleties`. - Metric recording, HTTP and JVM sampling, and log-derived counters: `mem:backend/metrics`. - Transaction ownership, after-commit callbacks and advisory locks: `mem:backend/db-transactions`. - RPC concurrency limit declarations, acquisition order and queue diagnosis: `mem:backend/rpc-concurrency`. diff --git a/.serena/memories/backend/http-rpc.md b/.serena/memories/backend/http-rpc.md new file mode 100644 index 0000000000..0c042b74f0 --- /dev/null +++ b/.serena/memories/backend/http-rpc.md @@ -0,0 +1,8 @@ +# HTTP and RPC boundaries + +- Start at `app.rpc/resolve-methods` for command discovery and `wrap` / `wrap-management` for request order. A new command namespace must be registered. `GET` and `HEAD` require a `get-` name; auth is on unless explicitly disabled. Metrics wraps concurrency, so RPC timing includes time spent waiting for a permit. Transaction handling sits inside the wrappers and is controlled by `::db/transaction`. +- Strip qualified client params before merging server auth context; only the server supplies the profile, auth type and token permissions. Malli map schemas are open by default. Keep public creation schemas closed to reject client IDs while allowing internal creation helpers to accept IDs for imports or duplication. See `wrap-params-validation` for JSON coercion and legacy spec fallback. +- 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. diff --git a/.serena/memories/backend/session-expiration.md b/.serena/memories/backend/session-expiration.md index 7efbf49089..0c80e87440 100644 --- a/.serena/memories/backend/session-expiration.md +++ b/.serena/memories/backend/session-expiration.md @@ -38,4 +38,5 @@ - Cookie `SameSite`/`secure` depend on `:cors`, `:strict-session-cookies`, `:secure-session-cookies`; `parse-flags` auto-adds `:disable-secure-session-cookies` for non-localhost HTTP `public-uri`. - Without `PENPOT_SECRET_KEY`, derived subsystem keys change on restart and all sessions/invitations are invalidated. - Read-only DB pool: sessions fall back to `inmemory-manager`, lost on restart, no GC. -- HTTP middleware and cookie/header precedence details: `mem:backend/subtleties`. +- HTTP middleware and cookie/header precedence details: `mem:backend/http-rpc`. +- Session management falls back to an in-memory manager on a read-only DB pool; see `app.http.session`. diff --git a/.serena/memories/backend/subtleties.md b/.serena/memories/backend/subtleties.md index b0e280d968..e72f462ccd 100644 --- a/.serena/memories/backend/subtleties.md +++ b/.serena/memories/backend/subtleties.md @@ -2,14 +2,7 @@ ## RPC exposure and wrappers -- RPC commands are discovered from vars created by `app.util.services/defmethod`; adding a command namespace is not enough unless `backend/src/app/rpc.clj` includes it in `resolve-methods`. -- `GET`/`HEAD` RPC calls are only allowed for method names starting with `get-`. Other methods are method-not-allowed even if they are read-only internally. -- RPC auth defaults to enabled. Public endpoints must set `::auth false` metadata explicitly. -- The wrapper stack does auth before params validation, then auditing/rate/concurrency/metrics/retry/condition handling, with DB transaction handling inside that stack. `::db/transaction` metadata controls transaction wrapping. -- Params with `::sm/params` are decoded/conformed through the JSON transformer and successful IObj results get `:encode/json` metadata. Legacy spec conforming only applies when no Malli params schema exists. Client params are stripped of qualified keys (`d/without-qualified`) before merging with the server auth context, so request bodies cannot override `::profile-id`, `::auth-type`, or `::token-perms`. -- Params schemas are open by default, so undeclared client keys reach the handler unless the map is `:closed true`. Creation commands (`create-file`, `create-project`, `create-team`, `create-team-with-invitations`, `upload-file-media-object`, `create-file-media-object-from-url`, `assemble-file-media-object`) use closed schemas: a client-provided `:id` fails with `:params-validation`. Their internal creation functions still accept an optional explicit `:id` for imports, duplicates and deterministic test fixtures. -- Nil RPC bodies become HTTP 204 unless explicit status metadata is present. Stream bodies default to `application/octet-stream` when no content type is set. -- The upload schema (`media.v/schema:upload`) takes a `:path` from the caller, and a Transit body can tag any string as a `path`, so a command that reads such an upload reads a file the client named. `create-import-binfile-job` avoids that boundary by accepting only a chunked upload (`:upload-id`); the commands that still take a plain file (the legacy `import-binfile`, the media and font uploads) trust it, and the guard belongs where uploads are accepted, not in each command. +- Command registration, validation and wrapper order: `mem:backend/http-rpc`. ## Concurrency limiter (CLIMIT) @@ -26,17 +19,8 @@ ## Config and HTTP/session middleware -- `app.config/config` and `flags` are dynamic `defonce` vars populated from `PENPOT_*` env vars through the shared schema string transformer. Tests and tooling can bind them. -- Duration config values are parsed as ISO-8601 with the `PT` prefix, so a day is written in hours (`:jobs-retention` and `:jobs-user-ttl` default to a week, and an operator writes `168h`): `7d` does not parse, and the value fails validation at boot instead of being silently ignored. -- `app.main` wires `PENPOT_DATABASE_*` into `::db/pool`, and `app.db/create-datasource-config` forwards pgjdbc's own knobs as `dataSourceProperties`, which `Properties.getProperty` silently drops unless the value is a String (hence the `str`). A query parameter of the same name in `PENPOT_DATABASE_URI` (for example `?prepareThreshold=0`) wins over the property: pgjdbc ignores the Properties value when the URL carries it, so the URI is the place to look when a variable seems to do nothing. The prepared statement cache is three optional `PENPOT_DATABASE_PREPARED_STATEMENT_CACHE_*` keys: the threshold is the executions before a statement is server-prepared and accepts `-1` or non-negatives (`{:min -1}`; the driver clamps any other negative to `-1`, so rejecting it only turns a typo into a boot error), its `0` stops server-side prepared statements while the driver's client-side cache of parsed queries stays in use, `..._QUERIES` and `..._SIZE` reject negatives and `0` in either disables that cache, and the size is bytes rounded up to the whole MiB the driver accepts. Do not describe the threshold `0` as disabling the cache: it only stops the server-side prepares. -- `parse-flags` automatically adds `:disable-secure-session-cookies` when `public-uri` is plain HTTP and not localhost. This changes cookie defaults without an explicit env flag. -- The backend sets Clojure `*assert*` globally from the `:backend-asserts` feature flag. Assertion-dependent checks can therefore differ by runtime flags. -- Request body parsing is mostly POST-oriented and supports Transit JSON plus plain JSON. Plain JSON request keys are kebab-decoded before being merged into `:params`. A body the parser cannot read is a client error, classified at the parse site and never by exception class (`clojure.data.json` signals its syntax errors with a bare `java.lang.Exception`): 400 `:validation`/`:malformed-json`, one `warn` line (`malformed request body`) carrying path, peer address and content-type instead of a stack trace, and `penpot_http_malformed_requests_total`. `RequestTooBigException` keeps its 413. -- Response formatting negotiates with `Accept` or `_fmt=json`. Transit is the default for collection/boolean bodies; JSON encoding has special pointer-map handling. -- Auth prefers the session cookie token before the `Authorization` header. Headers may be `Token` or `Bearer`. Only `kid=1`/`ver=1` tokens are decoded as session tokens; anything else is left unauthenticated (legacy v1 tokens were removed). -- Shared-key auth requires `x-shared-key` as ` ` and stores the lowercased key id on the request. If no shared keys are configured it always rejects. Management methods declare the key ids they accept with `::rpc/allowed-shared-keys`; a valid key outside that set answers 403 `:shared-key-not-allowed`, and a method without the metadata accepts any configured key. -- Session management uses DB storage unless the DB pool is read-only, then falls back to the in-memory manager. Sessions use only the v2 UUID model (`http_session_v2`); legacy string ids were removed. -- Session cookies are renewed when `modified-at` is older than the 6h renewal interval. SameSite is `none` for CORS, otherwise strict/lax based on config. Session lifetime config and GC: `mem:backend/session-expiration`. +- Environment values and PostgreSQL connection settings: `mem:backend/config`. +- Request parsing, response negotiation and session auth: `mem:backend/http-rpc`. ## HTTP server self-metrics