mirror of
https://github.com/penpot/penpot.git
synced 2026-11-27 05:10:32 +00:00
621 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d94518ec41 | Merge remote-tracking branch 'origin/staging' into develop | ||
|
|
b0c569d891
|
🐛 Submit the import audit events from the import job (#13150)
* 🐛 Submit the import audit events from the import job Since 2.20 the dashboard imports .penpot files through the :import-binfile job, which submitted no audit event. The outcome of an import and the files it created were lost, so analytics could no longer tell completed imports from failed ones. The job now submits the import-binfile event with the name and props of the legacy RPC event (status, file-ids, file-count, project, version, generated-by, referer), plus the job id, the team id, the package size and the elapsed time. A cancelled job reports the cancelled status. A completed import also submits a create-file event per imported file, as the legacy RPC does. As in the RPC, an import refused by the permission check submits no event. Closes #13148 AI-assisted-by: claude-opus-5-5 * 🐛 Audit import jobs at their terminal transition Run optional terminal hooks in the winning job transaction and use one for import audit events. Preserve the separate import transaction and cover cancellation, rollback, RPC paths, and dispatcher aborts. AI-assisted-by: gpt-6.1-terra * ♻️ Simplify the terminal job hook contract Pass a semantic terminal job to the hook with its final status and decoded parameters, result or error. Adapt the import audit and tests. AI-assisted-by: gpt-6.1-terra * 🐛 Keep import jobs bound to their original team Freeze the destination team when creating an import job and serialize imports with project moves. Use the frozen team for audit and webhook events, and keep compatibility with existing jobs. Select import audit props explicitly to prevent new job parameters from being included in events by default. AI-assisted-by: gpt-6.1-terra * 📚 Document the import team fallback removal Mark the legacy job audit fallback for removal in version 2.21.0. AI-assisted-by: gpt-6.1-terra * 🔧 Validate canonical AI model IDs in commit trailers Require bare lowercase model IDs in AI-assisted-by trailers and cover the validation with tests. Align the commit and PR workflows with the same attribution rules. AI-assisted-by: gpt-6.1-terra --------- Co-authored-by: Andrey Antukh <niwi@niwi.nz> |
||
|
|
a7f66b18f9
|
✨ Honor trusted alternate origins for backend links and OIDC (#11892)
* ✨ Honor trusted alternate origins for backend links and OIDC Add PENPOT_TRUSTED_ORIGINS, an optional list of bare scheme://host[:port] alternate origins. A request whose Origin matches (exact, trimmed and lowercased) uses that origin as the base for links generated while serving it: emails, asset URLs, audit and webhook link fields, and redirects. Unlisted origins, requests without Origin, and background or server-to-server work keep the canonical public-uri (fail-closed). Malformed entries warn at startup and never match. Stamp the trusted origin on the request with a global http middleware that binds config public-uri for the request extent; expose the chain as root-middleware so tests assert it runs before auth and errors. Build every backend link through the canonical cf/get-public-uri. Carry the origin in the signed OIDC state (auth and organization SSO) so the callback, a navigation without Origin, re-applies it with with-public-uri for the token-exchange redirect_uri and every redirect, including logout. Verify the state token once per callback and reuse the claims; build redirect URIs with ensure-path-slash plus join and append-query-param for hash routes. A removed origin does not invalidate states signed before it (up to four hours). Bring MCP OAuth into scope: wrap its routes, stage the origin in the Redis request record at authorize time, and re-apply it in decision so issuer, resource, the approval redirect and the code-exchange iss agree on one base. Keep the log-capture watch installed while waiting for the async rejection record in the save tests; a watch removed first lost late records and read nil. Add a delayed-executor regression test that makes the race deterministic and document the rule in the backend testing memory. Closes #11625 AI-assisted-by: deepseek-v4.1-flash AI-assisted-by: qwen3.7-plus AI-assisted-by: gpt-5.6-luna AI-assisted-by: muse-spark-1.3-contributor * ✨ Serve trusted alternate origins across frontend and backend Let one installation serve a canonical domain plus trusted alternate origins, without letting request headers pick arbitrary link bases. The backend normalizes `PENPOT_TRUSTED_ORIGINS` on load: it drops malformed entries with a warning and warns about HTTP origins outside localhost. It selects the first trusted origin from `X-Penpot-Origin`, then `Origin`, and applies only scheme, host and port to the public URI, keeping the configured path. MCP OAuth keeps the canonical base because its authorize navigation has no usable origin. The frontend reads the same list from `config.js`, filled by the container entrypoint, and selects the browser origin only on an exact match. It sends `X-Penpot-Origin` on RPC calls (including GETs and multipart) and OIDC initiation, not on asset, font or external requests. SSE captures the request bindings, and export jobs store the effective base so the download link uses it after the request ends. A closed export creation schema excludes `:public-uri`, which the backend adds only after validation. Register the OIDC callback for each alias. Removing an alias does not stop already signed OIDC state, queued mail or export jobs from using it. Add regression tests across backend, frontend and the nginx entrypoint, and document the proxy setup, worker upgrade and rollback, and alias retirement. Refs #11625 AI-assisted-by: hy4-flash-free AI-assisted-by: gpt-6-luna AI-assisted-by: gpt-6.2-sol |
||
|
|
dc49d6bed6
|
✨ Add nitrate methods to bring owned teams into an organization (#13119)
* ✨ Add nitrate methods to bring owned teams into an organization Nitrate lets an organization owner add the teams they own, outside any organization, from the Admin Console. Three management methods give it what it needs: - get-owned-teams-detail lists the owned, non-default teams of the current profile with the get-teams-detail fields plus member ids, so Nitrate can count members new to the organization. - count-organization-team-invitations-for-non-members counts, per team, the pending invitations for people outside the organization. - send-organization-setup-sso-emails-for-team sends the SSO email to the people an added team brings in, as add-team-to-organization does. get-teams-detail now shares its row query with the new method. AI-assisted-by: claude-opus-5-5 * ♻️ Rename the team detail row helper apart from its method The private helper shared by get-teams-detail and get-owned-teams-detail had the same name as the get-teams-detail RPC method, which read as one calling the other. It is now get-teams-detail-rows. AI-assisted-by: claude-opus-5-5 * 🔧 Test empty lists in the invitation count Cover count-organization-team-invitations-for-non-members at the method boundary: an empty team-ids list gives no counts, and an empty member-ids list, or one whose profiles give no email, counts every pending invitation of the requested teams. AI-assisted-by: claude-opus-5-5 |
||
|
|
2da9bddd05 | Merge remote-tracking branch 'origin/staging' into develop | ||
|
|
b58f7d2996 |
🐛 Build each file repair on the data left by the previous ones
repair-file built every repair of a pass from the file data taken before the pass. Repairs write whole values (a :mod-component with the whole component, a :set with the whole :shapes vector), so two repairs on the same component or shape attribute undid each other: the last write won, the lost fix came back as an error, and each clash cost another pass. Each repair's changes are now applied before the next repair is built. A private repair-file* returns the data and the changes; repair-file returns the changes, which give the same result when applied in order, and repair-file-until-valid reuses the data instead of applying the batch again (on the backend a second apply wrote an orphan page fragment). Repairs now see what earlier repairs of the pass did, so :ref-shape-not-found does nothing when its shape was removed or its ref shape resolves again; it would otherwise detach a copy that an earlier :invalid-main-instance-id repair had already relinked. Tests stub repair-error, through a multi-arity fn so the JS build can call it, and cover two clashing errors on one component in either order, three missing children fixed in one pass, and repairs on removed shapes. Closes #13239 AI-assisted-by: claude-opus-5-5 |
||
|
|
8bca3f86ee | Merge remote-tracking branch 'origin/develop' into develop | ||
|
|
adb61a9b96 | Merge remote-tracking branch 'origin/staging' into develop | ||
|
|
678fcc071b
|
🐛 Check the page that an add-page change stores (#12675)
* 🐛 Check pages added with a full page value in soft mode An :add-page change can carry a whole page under :page instead of an id and a name. extract-affected-ids reads the page to check from the change's top-level :id, so that form left the new page unchecked and a referential error in it was stored. Collect those page ids after the changes are applied and run the affected check on them in soft mode: log the file id, the page ids and the error codes, and never refuse the save. This is the first step of the two-step rollout. The follow-up moves the page id into extract-affected-ids and makes the check hard. The counters of #12665 decide when to flip it. Relates to #12666 AI-assisted-by: claude-opus-5-5, deepseek-v4.1-flash Signed-off-by: Álvaro Tejero Cantero <alvorithm@teje.ro> * 🐛 Collect the page of a whole-page add-page in the affected check An `:add-page` change that carries the page alone, with its id inside `:page` and none at the top level, escaped the referential check: `extract-affected-ids` read only the top-level `:id`. The schema side (`touched-page-ids`) already reads `(or id (:id page))`; the referential side now does the same. This replaces the separate soft-mode check of the first commit. The page now goes through `validate-file-affected` like any page a save touches, so the deployment's flags decide whether an invalid page is refused (`:file-validation`) or only logged (`:soft-file-validation`), and no second log hint or rollout step is needed. AI-assisted-by: claude-opus-5-5 * 🐛 Check the page an add-page stores, not its top-level id An :add-page that carries the page whole stores it under the id inside :page. extract-affected-ids and touched-page-ids read the top-level :id first, so a change whose two ids differ stored one page and checked another, which does not exist. Both now read the id of the page first. The unit test of the affected check moves to the common validate tests, with a case for the differing ids on the referential and the schema side. The backend test sends that form through update-file as well, and a new test sends the page as a commit group, the way the editor does, and expects the commit under :rejected and no stored page. AI-assisted-by: claude-fable-5-2 * ♻️ Derive the add-page change ID from the page Use the page ID for both redo and undo so the builder cannot emit conflicting IDs. Keep the change format and the library API unchanged. AI-assisted-by: gpt-6.2-sol --------- Signed-off-by: Álvaro Tejero Cantero <alvorithm@teje.ro> Co-authored-by: Andrey Antukh <niwi@niwi.nz> |
||
|
|
e0194ce60a
|
✨ Deliver telemetry audit events independently (#13230)
* ✨ Ship telemetry shadows with a cursor consumer Send anonymized audit events through a dedicated telemetry consumer, including when Nexus or admin-console also persist full events. Keep the legacy payload and cadence of 10,000 events per chunk and three hours between passes. Nexus skips shadows to avoid archiving duplicates. Move shadow deletion to the audit GC. Delete full rows and shadows along independent cursor paths, and expire shadows after seven days even when they have not been sent. Run the deletion paths in parallel with bounded batches, separate time budgets and independent failure handling. Replace the shared consumer catalog with transport definitions and one generic pass runner. Keep the legacy telemetry report and newsletter in the scheduled task, and update the tests, memories and rollout runbooks. Addresses F1 of the audit-log consumer review. AI-assisted-by: deepseek-v4-flash AI-assisted-by: gpt-6.1-terra * 🐛 Address audit log consumer review findings Enable audit log GC by default and document how to pause it during rollout or before registering a consumer that needs a complete replay. Run GC paths in order on the runner thread. Count each committed batch and preserve partial totals on ordinary failures while propagating interruption. Skip full-row payloads in telemetry queries and decoding. Keep the age limit for local retention only, and document the shared pass contract. AI-assisted-by: gpt-6.2-sol * 🐛 Close audit log consumer review findings Verify telemetry counts processed and skipped events in a mixed batch. Clarify how to pause GC, the scope of the replay race, and what the retention warning counts. Remove private Nexus setup from the public upgrade runbook. AI-assisted-by: gpt-6.2-sol * 📚 Simplify the audit log guide Consolidate the guidance on event trust, privacy and delivery. Keep examples that explain why the design works and link to code and runbooks for details. Clarify replay limits and distinguish age-based deletion from missed delivery. AI-assisted-by: gpt-6.2-sol |
||
|
|
932544996f
|
✨ Add a flag that makes file-gc skip its media clean-up (#13220)
The new backend flag `file-change-retention`, off by default, makes file-gc skip its media clean-up (deleted components, unused media objects, and thumbnails). That clean-up roots only in the head and the snapshots, so it would remove media that a kept revision row still names. The file and fragment clean-up still run: revision rows name neither. penpot#13187 keeps revision rows under the same flag. Set the flag only where both are deployed. An instance that rolls back to this release with the flag still set keeps the media its retained history needs. AI-assisted-by: claude-opus-5-5 |
||
|
|
212ee6ef48
|
🐛 Scope components in share-link view-only bundles (#13118)
* 🐛 Scope share-link component reads to the allowed pages A page-scoped share link exposed the primary file's components map in get-view-only-bundle and authorized the file's components fragment in get-file-fragment, leaking the stored shapes of deleted components from pages the link excludes. The share-link bundle now trims the primary file's components to those referenced transitively from the allowed pages and emits them inline; the membership path keeps the full map. The fragment scope check no longer grants the components pointer to share links; allowed page pointers remain readable. AI-assisted-by: inkling-2-small-free * 🐛 Tighten share-link bundle component retention The share-link view-only bundle now carries only live components referenced transitively from the allowed pages; deleted components never travel (their stored shapes are the main vehicle of leaked excluded-page content). This drops the reachability walk at deleted references and removes the duplicated subtree helper in favor of the canonical get-component-shapes. Also adds membership retention and cycle regression tests, and drops the private advisory identifiers from the new test comments. AI-assisted-by: inkling-2-small-free * ♻️ Apply the second review's fixes to the share-link fix Ordering the namespace require so the format gate passes, renaming the working bindings to what they hold, documenting the eager-realize limitation at the realization site, sharing the same-file reference predicate, and switching the fragment scope check to an allowlist of the pages scope. Test markers are anonymized; the walk-through-deleted contract and the full-scope link get dedicated tests; pointer-mapped files assert an inline referenced component and the empty-components form. AI-assisted-by: inkling-2-small-free * ♻️ Apply the third review's minor fixes to the share-link fix Correct the comment about realization reuse, align the new test bindings, and drop the tautological fixture assertions. Cover the fragment scope for excluded pages, membership on pointer-mapped files, and the legacy same-file reference form; make both permission memories state the actual invariants. AI-assisted-by: inkling-2-small-free * 🐛 Scope the share-link library trim to the emitted bundle The library trim walked the primary file's full components map, deleted components included. A deleted component keeps its main-instance subtree in :objects, so a library component instanced only inside those stored shapes was retained in the linked libraries of the view-only bundle and reached anonymous share-link viewers, metadata and stored shapes included. Walk the data the bundle emits instead: pages scoped to the link plus the trimmed components map. Pages still come from the realized file, because pointer-mapped pages only load in their own loader. Covered by a regression test that instances two library components inside a deleted primary component: only the library component the link's page references survives the trim. AI-assisted-by: deepseek-v4.1-flash |
||
|
|
90a06e982b
|
♻️ Rework the audit-log consumers and the jobs substrate (#12701)
* ♻️ Rework audit-log consumers and jobs substrate Fold the implementation, follow-up fixes, migrations and tests into one code commit. AI-assisted-by: gpt-6-luna * 📚 Consolidate 2.20.0 upgrade runbooks Keep the operational upgrade procedure and its supporting runbooks in a separate documentation commit. AI-assisted-by: gpt-6-luna * ♻️ Remove the audit-log flag and derive persistence at boot Persistence now follows the consumer flags instead of a separate switch. app.config computes cf/audit-persist? once at boot from :nexus and :admin-console, and every write site reads that value, so request paths no longer check flags per event. With no consumer enabled no full rows are written; telemetry shadows and webhook deliveries keep their own flags. The frontend wire signal stays :audit-log as a derived value. Update the 2.20 runbooks, memories and the devenv flags to match, and migrate the tests that used to toggle :audit-log directly. AI-assisted-by: hy4-flash-free * 🐛 Accept error-reporting batches and precompute sink flags push-audit-events now accepts crash batches with :error-reporting alone, so the frontend signal from get-environment-data matches a real destination. The reporters receive unhandled-exception events without storing any row. All per-event sink checks read booleans computed once at boot: webhooks, telemetry and error reporting join audit-persist? in app.config. The test fixture and with-audit-config rebind all four values together, and the tests that toggled those flags directly were migrated. Address F2 of the review of the previous commit. F1 stays deferred to a separate plan. AI-assisted-by: hy4-flash-free * 💄 Match the layout cljfmt expects in the flags set The first comment of the varia set sat on its own line after the opening delimiter, and cljfmt joins such a comment to the delimiter line, so the Common Tests lint step failed on common/src/app/common/flags.cljc. Keep the comment on the opening line, the same shape the login and email sets already use. Note in mem:scripts/ci that the backend lint lints ../common/src but does not format-check it, so common has to be passed to scripts/ci as well. AI-assisted-by: deepseek-v4-flash |
||
|
|
b100a5e26f
|
✨ Add viewers so org owners can change member role (#13163) | ||
|
|
7a64142cbc | Merge remote-tracking branch 'origin/staging' into develop | ||
|
|
fff44ec758
|
🐛 Fix shared files 500 on shapes with invalid child ids (#12528)
* 🐛 Fix shared files 500 on shapes with invalid child ids Old files can list in :shapes ids that are not uuids or that point to no shape. Migration 0033 walked them and hit the uuid assert in get-shape, which throws an AssertionError. The shared files list only caught Exception, so that Error broke the whole list with a 500. Make migration 0033 skip those ids, and catch Throwable when loading each shared file, so a broken file is skipped and logged. Closes #12343 AI-assisted-by: claude-opus-5-5 * 🐛 Repair invalid child ids in migration 0033 v2 Skipping invalid child ids in migration 0033 was not enough: the ids stayed in :shapes, so the file still failed schema validation and could not load. Files that already applied the migration would also never run a changed version of it. The migration now repairs each container before the naming walk: string ids are parsed with uuid/coerce, nil and ids that point to no shape are dropped, the duplicate that 0032 adds when a child is listed as a string is removed, and a :shapes list becomes a vector. Only the shapes that change are re-assoc'ed, so a healthy ObjectsMap is not marked as modified and its page is not rewritten. It ships as 0033-normalize-main-instance-names-v2 at the same position in available-migrations, so files that recorded the old id run it again. That position also makes it parse strings before 0035-fix-dangling-children drops the ids it cannot find. The shared files listing restores the interrupt flag when the cause of a skipped file is an InterruptedException. Tests cover children outside the root walk, legacy components, the objects-map wrapper of the unrealized save path, a list turned into a vector, a shape without a :shapes key, a file that applied the old id, and the end-to-end load of a broken shared file. Relates to #12343 AI-assisted-by: claude-opus-5-5 AI-assisted-by: inkling-2-small-free |
||
|
|
efd95dcf0c | Merge remote-tracking branch 'origin/staging' into develop | ||
|
|
a84d76d397
|
🐛 Stop camelCase svg attributes from breaking files (#13132)
* 🐛 Validate the shapes of a page added by an update-file change The backend validates every shape an `:add-obj` or a `:mod-obj` change writes, but an `:add-page` change carries a whole page and its shapes reached the file unchecked. Duplicate page and the undo of a page deletion send that page as the client holds it, so a tab that loaded a file before a migration ran could write the old format back into it. A tab opened before #12006 deployed holds camelCase svg attr keys such as `:fillRule`, and the closed `:svg-attrs` schema rejects them. The file saves, and the next read that migrates it fails the file data check, so the whole file stops opening (#13107). `:add-page` now validates each shape of the page on the backend, as `:add-obj` does for one. AI-assisted-by: claude-opus-5-5 * 🐛 Rerun the svg attr normalization on files that recorded 0035 Files that recorded migration 0035 never run it again, so camelCase svg attr keys written after it ran stay in the file. A tab that loaded a file before 0035 ran could save such keys through an `:add-page` change, and the closed `:svg-attrs` schema then rejects the whole file on its next migrating read (#13107). The svg attr normalization now runs under the id `0037-fix-shape-svg-attrs-and-defs`, and the 0035 id leaves `available-migrations`, as 0021 did when 0035 replaced it. Every file that recorded 0035 migrates again. Kebab input passes through unchanged, so the rerun touches only the keys written after 0035. AI-assisted-by: claude-opus-5-5 * ♻️ Move the 0037 migration tests to their own namespace The svg-attr migration was renamed to 0037, but its tests stayed in the 0035 test namespace under migration-0035-* names. Move the whole section to files_migrations_0037_test.cljc, register the new namespace in the test runner, and rename its tests to match the migration id. Replace the doseq over the two withdrawn ids with two self-contained deftests, one for 0021 and one for 0035. No production code changes. AI-assisted-by: hy4-flash-free * 🐛 Keep the log watch installed until the rejection record arrives The logger swaps the record on an executor thread, after the call that logged it returns. The test removed the watch in the `finally` around `update-file` and only then polled for the record, so under load the record landed on nobody and the test read a nil `:attempts`. AI-assisted-by: deepseek-v4.1-flash * 🐛 Count only update-file calls in the save-test transport log The mocked transport is installed with `set!` and outlives the fixture: a timer another module left pending can still reach it mid-test, as a `:delete-file-object-thumbnails` call did in CI. Filter to the only command persistence sends, `update-file`, so a stray call neither fails the emptiness assertion nor releases a `wait-for` on a save. AI-assisted-by: deepseek-v4.1-flash --------- Co-authored-by: Andrey Antukh <niwi@niwi.nz> |
||
|
|
3f6c69bb6a | Merge remote-tracking branch 'origin/staging' into develop | ||
|
|
e6eb8bcd5a
|
✨ Add pgjdbc prepared statement cache settings (#13099)
* ✨ Add pgjdbc prepared statement cache settings Expose pgjdbc's server-side prepared statement cache as three optional backend variables: PENPOT_DATABASE_PREPARE_THRESHOLD, PENPOT_DATABASE_PREPARED_STATEMENT_CACHE_QUERIES and PENPOT_DATABASE_PREPARED_STATEMENT_CACHE_SIZE (bytes, converted to whole MiB for the driver, rounding up). When unset, the driver defaults apply (5 executions, 256 entries, 5 MiB), so the behavior is unchanged. The values reach Hikari as dataSourceProperties strings, because pgjdbc only reads String values; flushCacheOnDdl stays at its default. Closes #13092 AI-assisted-by: inkling-2-small-free * ♻️ Sync the pool options schema with the code The integrant pool options schema validated a ::connect-timeout option that nothing reads, while the keys the code consumes (::connection-timeout, ::idle-timeout, ::max-lifetime) were missing from it. The schema now declares the three, matching the code and the defaults map. The removed key was not referenced anywhere else. Follow-up to #13092. AI-assisted-by: inkling-2-small-free * ♻️ Rename the prepared statement cache threshold setting Keep the three knobs under one name in the configuration: PENPOT_DATABASE_PREPARED_STATEMENT_CACHE_THRESHOLD PENPOT_DATABASE_PREPARED_STATEMENT_CACHE_QUERIES PENPOT_DATABASE_PREPARED_STATEMENT_CACHE_SIZE The old PENPOT_DATABASE_PREPARE_THRESHOLD read as a verb and was the only one of the three that did not name the prepared statement cache. Fix the documentation of the values: 0 in either cache value disables the cache, not only the size, and -1 prepares a statement from its first execution and forces binary transfer, which is what pgjdbc does. Cover the -1 threshold end to end: it already decoded and validated, but nothing proved that it reaches the driver. The tests also pin 0, so a falsy check cannot silently drop it. Closes #13092 AI-assisted-by: deepseek-v4.1-flash * ♻️ Fix the prepared statement cache contracts The threshold schema accepted any integer, but the driver clamps every negative to -1 and turns on binary transfer, so a typo like -10 changed the wire protocol instead of failing at boot. Both schemas now declare {:min -1}: -1 and the non-negatives stay valid. The tests compared our own dataSourceProperties literals with our own literals, which cannot catch the failure the feature fears (a property the driver ignores). They now read the threshold back from a real connection: 5 with no options, 1 and 0 when configured. The size ceiling is covered one byte over a MiB, and queries=0 too. The docs, the app.db comment and the memory described the threshold 0 as disabling the cache. It does not: 0 stops the server-side prepared statements while the driver's cache of parsed queries stays in use, bounded by the other two values. The same texts lost the pg_prepared_statements pointer (the view only lists the session that runs the query) together with the flushCacheOnDdl and PgBouncer sentences, and the section now carries its version marker. Closes #13092 AI-assisted-by: deepseek-v4.1-flash * 💄 Format the prepared statement cache pool test The continuation arguments of the two with-connection calls were aligned under the options map instead of two spaces past the form, which cljfmt rejects. Local verification missed it because `./scripts/ci backend --test` runs the tests only: lint and format are separate tasks, so the pre-push check is the whole `./scripts/ci backend` or an explicit --lint/--fmt. AI-assisted-by: deepseek-v4.1-flash * ♻️ Address the review of the prepared statement cache The pool startup line shows the three values, so the configured cache is visible without reading the environment back; a nil means the driver default. bytes->mib-ceil uses Math/ceilDiv: the same rounding in one expression, and the size schema already rejects negatives. The cache-limit tests count a closed statement in pg_prepared_statements instead of comparing the property literals. A closed statement stays prepared in the server only while the driver's cache holds it, which is what tells an accepted property from an effective one; the positive case keeps the cache enabled with a sub-MiB size. The config test drops the groups that only exercised the decoder and keeps the ones that pin the accepted range. The manual and the memory note that a query parameter of the same name in PENPOT_DATABASE_URI wins over the variable: pgjdbc ignores the Properties value when the URL carries it. AI-assisted-by: deepseek-v4.1-flash AI-assisted-by: claude-opus-5-5 |
||
|
|
78cfe7fa58 | Merge remote-tracking branch 'origin/staging' into develop | ||
|
|
114ce6ec03
|
✨ Make legacy-db file data read-only (#13102)
legacy-db is no longer a write backend: fdata/upsert! rejects it (:legacy-backend-read-only), handle-persistence stops writing file.data and file_change.data, and the update-params schema of fdata no longer accepts it. Reading old payloads keeps working, and the file-data-backend default stays db. The configuration guide, the backend config (a startup warning reads PENPOT_FILE_DATA_BACKEND=legacy-db as db instead of failing every save) and the storage memories say so, with the upgrade note for deployments that still set the variable. AI-assisted-by: deepseek-v4.1-flash AI-assisted-by: inkling-2-small-free |
||
|
|
d97972c81d
|
🐛 Build the SSO redirect target on the server (#12952)
* 🐛 Build the SSO redirect target on the server The organization SSO flow took the destination URL from the client and redirected to it after the identity provider round-trip, so any authenticated profile could point that redirect at another domain: the server never checked where the URL came from. The RPC now takes the route token of the client (?screen=...¶ms) and the server builds the destination out of it: the public URI plus the query string, parsed and rendered back. The destination can no longer leave the public URI, and the callback checks it again before redirecting, which covers the state tokens minted before the change. The state token also carries the profile that started the flow, so only that session is granted the organization SSO entry: a state prepared by someone else cannot mark the session of the one that completes it. Whenever the RPC receives an organization id (it always comes from the client), it also checks that the profile is a member of the organization or its owner, instead of letting any profile start a flow for an organization it does not belong to. Tests cover the destination builder, a callback that ignores a destination outside the public URI, a state that does not grant the SSO entry to another session, and the organization access check. AI-assisted-by: minimax-m3.1-flash * 🐛 Check the SSO redirect target against the public URI The callback compared the destination with a string prefix, so the two bypasses the advisory documents (a userinfo prefix and a look-alike host) were closed only by the trailing slash of the public URI. The check now compares the parsed origin (scheme, host case-insensitive, port with the default made explicit) and requires the path to be under the base path of the public URI, so neither bypass passes. The client sent `location.search`, the history token, whose leading `?` is URL syntax and no part of a query string. It sends the query string proper now (`screen=…¶ms`) through `rt/get-current-query-string`, and `rt/token->query-string` is the single bridge between the two shapes: every other consumer concatenates the token over the base path. The server puts the separator back when it joins the destination, and trims one that still arrives, so a browser holding the previous bundle keeps its destination while the new one rolls out. Building the destination can no longer break the flow: it catches its own errors and lands on the public URI, which matters in the deployments where the browser origin differs from the configured one. A value that is not a route is ignored with a warning, decided by the keys it parses into (a URL becomes a single key holding the whole URL), and a route with no `screen`, like the root params of the application (`template=…`), stays a usable destination. The organization membership lookup is now shared by the check that gates the SSO flow and the one that raises, so the two cannot drift apart, and the docstring of the RPC lists `:no-organization-access` next to `:no-team-access`. `rt/nav-raw` returns its `:href`/`:uri` through `@event`, as its sibling `rt/navigate` already did. Nothing in the app listens to `::rt/nav-raw`, so the callers behave the same; the SSO test now reads the destination from the event instead of intercepting the helper. Tests cover the two bypasses and the base-path rule, the RPC with an unusable destination, the value that is not a route, the request that carries both ids, an organization that does not exist, the query string the frontend sends, and the two router helpers. AI-assisted-by: minimax-m3.1-flash * ♻️ Deduplicate SSO destination URL building The backend had an unreachable blank check and a one-line wrapper around the URI helper in build-dest-url. On the client, the SSO retry and error flows each assembled the destination from public-uri and the route params. Flatten build-dest-url with a cond and call u/query-string->map directly. Add rt/token->url as the single client helper for absolute route URLs, with tests for both token shapes and for a blank token. Update the routing memory with the new helper contract. AI-assisted-by: hy4-flash-free |
||
|
|
0fda857426
|
🐛 Invalidate all sessions on password recovery (#12967)
* 🐛 Invalidate all sessions on password recovery recover-profile validated the recovery token and updated the password, but never deleted the existing server-side sessions in http_session_v2. A previously captured auth-token kept working after the victim "recovered" the account (GHSA-3j2p-qr45-q365, CWE-613). The command now calls session/invalidate-all for the recovered profile. The command already runs with ::db/transaction true, so the delete joins the same transaction as the password UPDATE: both commit or roll back together. There is no current session to preserve — the RPC is unauthenticated — which is the same contract the profile deletion path uses. Tests in rpc_auth_test.clj pin the behavior: the victim's sessions die, other profiles' sessions survive, and a failed recovery is a no-op. Both invalidation tests failed before the fix. AI-assisted-by: inkling-2-small-free * 🐛 Pin recovery-transaction atomicity after review Review of 92a65f544b found the tests pinned the end state but not the rollback guarantee the fix relies on: the session DELETE joins the password UPDATE in one transaction. Add recover-profile-rollback-keeps-password-and-sessions: send-template throws after the update, so the command must fail with password and sessions both untouched. recover-profile-failure-keeps-sessions now also asserts the password, matching its docstring. The invalidate-all docstring mentions the recovery caller. Addresses review findings M1, M2 and M3. AI-assisted-by: inkling-2-small-free * 🔥 Drop recovery test that never reached the fix The failure test used a token with the :authentication issuer, so tokens/verify rejected it before any write. It passed with or without the invalidation fix and exercised no new code. The rollback test already covers that a failed recovery leaves no partial effects. AI-assisted-by: hy4-flash-free |
||
|
|
c0f746ee34
|
🐛 Apply the invite policy to pending invitations (#13080)
* 🐛 Apply the invite policy to pending invitations * 📎 Code review |
||
|
|
ba0eab57ab
|
🐛 Hide team plan from every member when owner has Enterprise (#13079) | ||
|
|
27784f70ac
|
🐛 Fix custom CJK fonts losing glyphs when converted to TTF (#13074)
FontForge opens a CID-keyed OpenType font as several sub-fonts, and Generate() writes only the active one. Most CJK fonts use this layout, so the TTF used by the render-wasm renderer kept only a few hundred glyphs (the Latin sub-font) and lost its family name. Merge the sub-fonts with CIDFlatten() before generating, both in the backend and in the media-processor. The call is guarded because it fails on fonts that are not CID-keyed. Add a small synthetic CID-keyed font with two sub-fonts as a fixture and check that the converted TTF keeps all its glyphs. Closes #10976 AI-assisted-by: claude-opus-5-5 |
||
|
|
e95007a93b |
🐛 Retry the publish of the websocket delivery assertions
The subscription to the bus reaches redis through an asynchronous agent action, so a message published right after the connection opens can be lost before redis knows the subscription. The delivery assertions of the websocket tests published once and bet on winning that race, which fails on a loaded CI runner. `poll-published!` publishes, drains a window and publishes again only when the window saw nothing, up to three attempts. The assertion still proves that the client receives a message it published, and the negative assertions keep the single drained window they need. A test pins the retry so it does not go back to a single publish. AI-assisted-by: deepseek-v4.1-flash |
||
|
|
86eb0bf805 | Merge remote-tracking branch 'origin/staging' into develop | ||
|
|
7ef8c1cf36 | Merge remote-tracking branch 'origin/staging-2.19.x' into staging | ||
|
|
e23ca02aa2
|
✨ Reference the file data storage object with a foreign key (#12769)
* ✨ Reference the file data storage object with a foreign key The file data pointer lived in `file_data.metadata.storage-ref-id`, a JSON key. The storage GC parsed it to find live references, and nothing stopped it from physically deleting an object a live row still pointed at: a failure in that scan lost the blob. Migration 0159 moves the pointer to a nullable `storage_object_id` column on `file_data`, backfills it from the metadata key, removes the key from the rows it backfills, indexes the column and rebuilds the foreign key to `storage_object(id)` as `NO ACTION DEFERRABLE INITIALLY IMMEDIATE`. `INITIALLY IMMEDIATE` is deliberate: the GC catches the violation inside the chunk transaction, while a deferred check would fire at commit, outside it, and the sweep would never move past the blocked chunk. The column is the only source of truth. The `storage-ref-id` entry is gone from the file metadata schema, and the single point that serializes the metadata drops it, so no write can resurrect it. `upsert!` does not query the row: the pointer of the row being replaced travels in its params, and the object is touched before the row is written. Fragments and snapshots pass nil because a modified pointer always gets a new id; the offload passes its own row; `insert-file!` drops it, since an INSERT never replaces a persisted object. `update-file!` takes the file map read from the database plus the fields to change and merges them, so the pointer comes from the read map and no caller can lose it by building a partial map. A map without `:data` raises `:missing-file-data`: it is not `assert`, which is compiled out in the deployed binary. The params cannot override the pointer or retarget the write with `:id`/`:file-id`. `bfc/file->response` strips the pointer from every response (`get-file`, `create-file`, `duplicate-file`, the view-only bundle, the team access request, the comments read, the library summary, the snapshot read and the debug download). A `file-data` object is authentication-only, so a leaked id would let any logged-in profile fetch the blob from `/assets/by-id`. `get-file-fragment` resolves through the file data backend, so a fragment on cold storage no longer hands nil to `blob/decode`, and answers only the keys of its result schema. The storage GC reference scan, the restore union and `objects-gc` read the column. The offload reads `SELECT fd.*`, so its rows go through a `decode-row` that decodes jsonb metadata and drops a JSON null, which the row schema rejected; a row without a readable object raises `:missing-storage-object` with the file and row ids. A chunk blocked by the foreign key (SQLState 23503) is a real anomaly, since the reference scan should have frozen the object: it stays an error with its own hint and the chunk is retried on the next run until the reference is fixed. The release is a coordinated restart, not a rolling deploy, and not rollback-safe for the rows it writes: the previous code writes and scans the metadata pointer, so a key it writes misses the backfill and removing it loses the reference. `operations/2.20.0-file-data-storage-object-id.md` builds the column, the index and the foreign key online and runs the backfill with every instance stopped, then marks the step as applied; a fresh or small instance does the whole job in the migration. The runbook keeps the validation scan out of the stopped window and adds a lock timeout and retry to the online statements. Tests cover the foreign key shape, the backfill and its corrupt and orphan guards, the rebuild of a missing index and of a wrong, non-deferrable or deferred constraint, the deletion refused by a live reference, the metadata cleanup, the offload row normalizations, the touched objects of the unshare and the restore, the response stripping on every call site and the chunk blocked by the foreign key. The backend memories and the developer guide document the pointer, the GC behavior and the two migration paths. Closes #12768 AI-assisted-by: deepseek-v4.1-flash AI-assisted-by: inkling-2-small-free * 🐛 Hold the file row lock across the migration write `get-file` applies the pending migrations in memory and, when it finds any, persists the result. That write read the row without a lock and `update-file!` is an unconditional UPDATE, so a save that committed in between was overwritten: the saved content, `revn` and `modified-at` went back, the next save from that client failed with `:revn-conflict` and the object the save left became an orphan the storage GC cannot revisit once it is frozen. The read now runs in a transaction of its own (`get-file` calls `get-file*` inside `db/tx-run!` and accepts a cfg map only), so the `file` row lock covers the re-check and the write. `get-file*` reads the row once (`sql:get-file` plus `resolve-applied-migrations`) and completes it with `attach-file-data`; only when a migration is pending it reads the file again under `FOR UPDATE`, re-checks `need-migration?` on that fresh map and persists it (`migrate-file`). The common case stays at one row read and one migrations resolution, the migration case keeps a single decoded copy in the heap, and a row that changed in between is not overwritten. A migration found on the unlocked read is applied in memory only, for the next read to persist. `migrate-file` returns the reattached map when it persists, with the `:storage-object-id` of the row the write left, and the realized map when it does not; `:realize?` is what returns the read fully plain. `fdata/upsert!` answers `{:written ... :storage-object-id ...}` instead of a boolean, `update-file!` propagates it and the migrating read puts it back in the map it returns, so a caller that persists again touches the current object instead of the replaced one. `insert-file!` keeps nil: an INSERT never replaces a persisted object. The write also compares the stored pointer with the caller's value (`IS NOT DISTINCT FROM`) and raises `:stale-file-data-pointer` when it affects no row. Every writer holds the `file` row lock, so a pointer that no longer matches is a protocol violation, not a race to retry. The expected pointer is a separate argument because the storage branch replaces `:storage-object-id` before the upsert, and the check lives in `upsert-in-database`: the `legacy-db` branches do not use that SQL and their count can legitimately be zero. The save, snapshot and restore-backup reads take `FOR UPDATE` instead of `FOR SHARE`: they inherit the lock, and the migration branch asks for the exclusive one in the same transaction, so a shared lock that upgrades deadlocks two concurrent readers. A data read rejects `:lock-for-share?` for the same reason; only row-only reads accept it. `sql:get-file-without-data` is a plain select now, not a CTE, which makes locking legal without loading the data. Realization has a single owner: `attach-file-data` only resolves and decodes, and `get-file*` realizes once per path. The applied migrations no longer travel in the `get-file-with-summary` response, cache hit and cache miss alike. `embed-assets` reads each library without `:realize?`, so its `:components` is an unloaded pointer map; `absorb-assets` walks it with `vals`, `PointerMap.seq` calls `load!` and that raised with no loader bound, so every export with `:merge-libraries` of a library with components failed. The absorb runs under the library's own loader now. The in-place binfile import (`import-file-and-overwrite*`, `::overwrite`, `::bfc/file-id`) had no product caller and cannot carry the previous `storage_object_id`, so overwriting a storage-backed row would leave its object unreclaimed. `import-files!` rejects a cfg with `::bfc/file-id` (`:not-supported`) and the helpers only that path used go with it (`invalidate-thumbnails`, `*reference-file*`, the `::overwrite` id branch of `index-object` and of `save-file!`, the `on-conflict-do-nothing?` flag of the media insert). Tests: a new `file-migration-read-test` pins the single read, the locked re-read, the concurrent save interleaving, the double migration and the read-only path; the upsert tests cover the return shape and the stale pointer; the SQL recorder they share lives in `backend-tests.helpers`, and the save, snapshot, restore and summary sequences follow the new reads. The backend memories document the read contract and the pointer. AI-assisted-by: deepseek-v4.1-flash * 🐛 Harden the get-file guard and skip its read-only transaction The cfg guard of `get-file` was an `assert`, which `app.config` elides when `:backend-asserts` is off, so a deployed binary accepted a bare pool or connection while the docstring promised it raises. It throws `IllegalArgumentException` now, the class the option guards of the same namespace already use, and the existing test expects it instead of `AssertionError`. A read with `:read-only?` applies the pending migrations in memory and writes nothing, so the transaction the migration write needs only costs two round trips there. `get-file` runs it with `db/run!` instead: with a cfg that carries a connection it still joins the caller's transaction, and only the reads that would have opened their own skip it. A lock option needs a read-write transaction from the caller, because PostgreSQL rejects row locks in a read-only one; the docstring states that. Tests: the guard test expects the new class; a cfg marked `::db/read-only` reads a pending migration without persisting it (the config flag that fills that key is legacy, but the key is set by hand); and a read-only read is pinned as not opening a transaction while the same call without the option does. The backend memory documents the split and the guard. AI-assisted-by: deepseek-v4.1-flash |
||
|
|
9c5260314a
|
🐛 Revoke websocket subscriptions when access is revoked (#12189)
* 🐛 Revoke websocket subscriptions when access is revoked GHSA-m53j-2766-6jqw. A websocket subscription was authorized once, when it opened, and that decision was trusted for the rest of the connection's life, so a member whose access was revoked kept receiving live file content as long as the tab stayed open. The revocation travels over the message bus instead of closing the socket from the mutation: the connection registry is local to one backend instance, while the RPC that revokes access runs on whichever instance received the request. Every instance re-verifies the subscriptions it owns with the same `has-read-permissions?` predicates that `:subscribe-file` and `:subscribe-team` authorize with, so a downgrade to viewer keeps its subscription and a non-member organization owner keeps read-only access. Two mechanisms cover each other: - Access-changing mutations announce after the write. delete-team- member, leave-team, update-team-member-role, delete-file, delete-project, move-files, move-project and delete-team announce. delete-share-link is deliberately excluded: a share-link visitor never passes the subscribe permission check, so there is no subscription to revoke. Team-wide changes publish one event per team; the watcher resolves the members itself, and both publishers defer through `db/after-commit` so the watcher never decides from pre-commit state. - Every relay re-checks access every 5 minutes by default (`subscription-revalidation-interval`), driven from the relay loop with `alts!` over the subscription channel and a one-shot tick channel, so a steady stream of edits cannot push the check away forever. Supporting changes: - The registry holds `:connections` and `:by-profile` in one atom, kept consistent by register/unregister in a single swap!; a profile lookup is one map access, and a profile whose last connection leaves is dropped from the index. - `close-file-subscription` and `close-team-subscription` announce the :leave-* message, close the relay channel and purge the bus subscription, and are idempotent. Closing the channel ends the relay loop and its re-check task. - The permission query the re-check uses filters soft-deleted files, projects and teams, matching its sibling queries. - A transient database error fails open: it logs and keeps the subscription; the next tick retries. - The revocation watcher's params schema declared the nitrate client as a bare keyword inside [:map ...], which malli resolved as a registry lookup and which took the whole system build down under enable-backend-asserts. It is now an explicit pair, optional because init-key yields nil with the admin-console flag off. The tests reproduce the leak against the real message bus, including the negative control for the interval re-check. The written records live in mem:backend/websocket-subscriptions. Closes #12155 AI-assisted-by: space-bunny-free AI-assisted-by: muse-spark-1.3-contributor * 🐛 Mirror the subscribe gates in the revocation re-checks Addresses the second review round on PR #12189 (pabloalba). The re-checks only asked whether the profile could read. The membership legs of sql:file-permissions filter soft-deleted rows since the F2 fix, but the organization-owner fallback grants read-only access over HTTP without looking at deleted_at, so a soft-deleted file or team kept an expelled org owner subscribed indefinitely. The re-checks now gate on existence as well: file-readable? and team-readable? require a live row (db/get*, non-throwing, soft-deleted rows excluded) plus the read permission, mirroring the :subscribe-file gates and extending them to teams. Both relays and revalidate-profile-subscriptions use them; the subscribe handlers keep their exact behavior. Also from the same review: - watcher-consumes-revocation-events-from-the-bus no longer races the command's after-commit announcement: it takes access away with a direct row delete and drives the watcher with a synthetic bus event, instead of deleting through the command and publishing a second notify-* that would mask a broken command announcement. - moving-a-project-closes-source-team-subscriptions pins the move-project e2e: the file subscription drops, the source-team subscription survives (membership unchanged). - soft-deleted-file/team-closes-org-owner-subscription cover the new gate with red-before/green-after tests. mem:backend/websocket-subscriptions updated. Closes #12155 AI-assisted-by: inkling-2-small-free * 🐛 Refuse dead teams in resolve-team-id (PR #12189 review) Second review round on PR #12189 (pabloalba). The file re-check added in 87ca7aca53 stops at the file row, but the organization-owner fallback grants read-only access to non-member org owners via Nitrate over HTTP, which knows nothing about Penpot soft-deletion. resolve-team-id resolved the team from unfiltered SQL, so an expelled org owner kept the file subscription open for an indefinitely soft-deleted file, project or team. Now both SQL lookups filter deleted_at, and resolve-team-id checks the team row itself (db/get*, which filters soft-deleted rows) for every caller — teams, projects and files alike. Also from the same review: - file-readable? now uses the same sql:get-minimal-file as the subscribe gate (non-throwing via throw-if-not-exists false), and team-readable? projects id and deleted-at, so db/get* can filter. - The test suite extracts the thrice-duplicated raw delete into delete-team-membership!; a sibling of the fail-open pin now redefs the existence probe to throw; memory and docstring aligned with the code. - docs/technical-guide/developer/architecture/backend.md attributed the websocket to notifications.clj; it now names app.http.websocket as the owner and notifications.clj as the revocation publisher. - mem:backend/auth-permissions-product-domains documents the fallback mechanism and the resolve-team-id contract. Closes #12155 AI-assisted-by: inkling-2-small-free * 🐛 Test resolve-team-id refusal and tidy review findings Third pass over PR #12189 after review-code on 225eb98de2. resolve-team-id now has a direct test: all three branches resolve while rows are live, and file, project and team soft-deletes each refuse their branch — the two new SQL predicates and the final team-row check are all pinned by it. From the same review: - failing-existence-check-keeps-the-subscription and the sibling a-failing-check-keeps-the-subscription are deleted: they could not distinguish a live relay from a dead one. The fail-open policy remains documented in the docstring and the memory; the memory no longer claims the pins exist. - team-readable? projects ::sql/columns like the rest of the backend; the fully-qualified keyword went away with the new alias. - The dead when-not guard in get-organization-owner-viewer-team is removed (resolve-team-id guarantees the row live); the let binding in resolve-team-id no longer shadows the destructured team-id. - docs/technical-guide names rpc/notifications.clj as the publisher and the tree lists the real top-level modules. Closes #12155 AI-assisted-by: inkling-2-small-free * 🐛 Make the revocation tests deterministic Third review round on PR #12189 (pabloalba). Both tests took access away through a command that announces, so the live watcher could close the subscriptions before the test looked: - revocation-closes-subscriptions-that-are-no-longer-authorized asserted an exact count of 2 closes after delete-team-member, and that count reads 0 whenever the watcher got there first. It now removes the member with delete-team-membership!, the raw row delete that publishes nothing, and asserts both subscriptions are still open before calling revalidate-profile-subscriptions. - team-event-closes-every-member-subscription ran delete-team and then published a second notify-team-permissions-changed, so a missing announcement in delete-team still passed. It now soft-deletes the team row (sql:team-members joins team_profile_rel and profile only, so the watcher still resolves every member), asserts nothing closed, and drives one synthetic team event. The command paths stay covered by the announce and end-to-end tests for delete-team-member and delete-team. The file split the reviewer suggested stays the optional follow-up, tracked outside this PR and waiting for the merge. Closes #12155 AI-assisted-by: deepseek-v4.1-flash |
||
|
|
f3c1230b79
|
🐛 Allow OIDC registration with password login disabled (#12974)
* 🐛 Allow OIDC registration with password login disabled The register-profile command rejected every registration without the login-with-password flag, including SSO ones, while the OIDC callback already allowed :oidc-registration as an alternative, so new OIDC users were stuck at the register screen with a 400 registration-disabled error. The gate now branches on the verified token backend: password tokens keep the previous checks, SSO tokens only require :registration or :oidc-registration through a predicate shared with the callback, so the two gates cannot drift apart again. Flags and invitation checks are split into single-responsibility helpers, and tokens without a backend claim are rejected loudly by schema instead of defaulting silently. Covered by regression tests for the SSO matrix, canceled invitations, the missing-backend case and the no-password-fallback, plus a configuration doc note. Closes #12964 AI-assisted-by: Muse Spark 1.3 Contributor * 🐛 Gate SSO registration by provider type, accept invitations Follow up the review on #12974. The SSO registration gate now treats a team invitation token as a substitute for :registration / :oidc-registration, in both the OIDC callback and register-profile, mirroring the password flow: the callback redirects to the register screen when an invitation is present, and register-profile revalidates the invitation row under a row lock before creating the profile when no SSO flag is set, raising :invalid-token instead of creating an account that cannot join a team. The SSO branch is restricted to OIDC-typed backends (oidc-provider-types); a prepared-register token carrying any other backend is rejected with :invalid-token instead of silently taking the SSO rules. The flags and invitation checks are shared by one check-registration helper in register-profile; the prepare command runs flags, then the email-mismatch restriction, then the invitation row lookup, so the password login flag fails closed first. The schema defs are private, the create-profile default uses penpot-backend, the OIDC callback test decodes the redirect token to assert the :prepared-register claims, and the docs and the auth memory state the invitation path for SSO registration. Regression tests cover invitation-only registration, canceled invitations with and without SSO flags, unknown backends, and the double-fault precedence in prepare-register. AI-assisted-by: inkling-2-small-free * 🐛 Require invitation email match for SSO registration Close the hole left by treating any invitation token as a substitute for the SSO registration flags. register-profile now requires the invitation member-email to match the prepared-register email, raising :email-does-not-match-invitation otherwise, mirroring the password flow. The OIDC callback verifies the team-invitation JWT and the email before redirecting to register instead of trusting raw presence. Covered by the requested mismatch regression test plus callback tests for mismatch and garbage tokens. AI-assisted-by: Muse Spark 1.3 Contributor * ♻️ Share registration gate between prepare and register-profile After the email-match fix, check-registration runs flags, email and invitation row in the same order as validate-register-attempt!. The prepare command now calls the shared helper instead of inlining the trio, and the stale docstring rationale is gone, so future invitation rule changes land in one place. AI-assisted-by: Muse Spark 1.3 Contributor |
||
|
|
8715450f53 | Merge remote-tracking branch 'origin/staging' into develop | ||
|
|
679e70e48c |
🐛 Keep file_change kind nullable so rollback keeps writing
Migration 0158 created file_change with kind NOT NULL, which blocks any emergency rollback to the previous version: the old code inserts without kind and every save would fail. kind is still a reserve (reads use label IS NOT NULL), so it stays nullable until the rollback window closes; the NOT NULL comes in a later migration. The runbook keeps parity, the schema and migration tests cover the nullable column and the rollback insert, and the storage memory records the decision. AI-assisted-by: muse-spark-1.3-contributor |
||
|
|
5c45c8ddaf | Merge remote-tracking branch 'origin/staging' into develop | ||
|
|
92c478b0e2 | Merge remote-tracking branch 'origin/merge-staging' into staging | ||
|
|
dc38eaa843
|
🐛 Fix font upload crash and preserve font metadata (#11951)
* 🐛 Fix font upload crash and preserve variant metadata opentype.js 2.0.0 returns no fontSubfamily name for fonts whose Macintosh name table only holds custom records. That made parse-font-weight/parse-font-style call re-seq on nil and crash the upload. A nil or blank variant is now treated as no match in app.common.media, defaulting to weight 400 and style normal. The variant parsing also accepts oblique as italic, and the new parse-font-family helper derives the family from a filename by stripping the known weight/style tokens, separating a style token glued to a weight token ("Roboto-BoldItalic" -> "Roboto"). first-nonblank-string returns the first nonblank candidate, so a blank preferredFamily/preferredSubfamily no longer shadows a valid fontFamily/fontSubfamily. app.main.data.fonts gains resolve-font-metadata and prepare-font-entry. opentype.js values win per field; any missing value falls back to the filename-derived family, weight and style. The parsed and woff2 branches share the same helper, so metadata is preserved instead of collapsing every face to weight 400, and fonts with missing vertical-metric tables upload with no height warning instead of failing. process-upload reports per-file failures (unknown signature, unparseable file, preparation error) with a single bad-font notification instead of silently dropping them, and never errors for per-file failures. The upload now sends :variant-name to create-font-variant, which accepts it as an optional param (ships in 2.20), so the foundry name survives the upload. Closes #10436 AI-assisted-by: deepseek-v4.1-flash AI-assisted-by: muse-spark-1.3-contributor Signed-off-by: CHOI JUNSOO <junsoo1172@gmail.com> * 🐛 Parse glued font style tokens in the font parsers EvaMarco's review on #11951: parse-font-family and parse-font-weight handled glued tokens like "BoldItalic", but parse-font-style did not. For names such as "opensans-bolditalic-webfont.woff2" the three parsers disagreed: the italic face resolved to style normal and collided with the bold-only file on the (family, weight, style) join key. One binary silently overwrote the other during upload, losing one font face without any warning. A new private normalize-font-name helper is applied by all three parsers. It splits a style token glued to a weight token, now with a lookahead boundary so "LightItalic_v2" splits too, and strips a trailing technical suffix (-VF or _v<number>). parse-font-family, parse-font-weight and parse-font-style now interpret the name consistently. Tests cover the three cases from the review, the bold-only control case, and an end-to-end process-upload check that a bold and a bold-italic WOFF2 survive as two variants. Relates to #10436 and PR #11951. AI-assisted-by: inkling-2-small-free * Remove duplicate frontend test registration --------- Signed-off-by: CHOI JUNSOO <junsoo1172@gmail.com> |
||
|
|
a35dd49b6a | Merge branch 'staging-2.19.x' into staging | ||
|
|
12d73d0f63 |
🐛 Fix flaky assertion in climit waiting-count test
The test expected exactly one publication of the :rpc-climit-waiting gauge inside the with-redefs window. The republisher daemon thread, started at component init with no delay and rescheduling every 15 s, publishes the same counter and can land inside that window, so the recorded sequence could be [0 0] and the assertion failed with actual [0 +0] (Backend Tests job in #12979). Assert on the last published value instead of the whole sequence, the contract waiting-last documents and the sibling tests use. AI-assisted-by: inkling-2-small-free |
||
|
|
bcac14a4a8
|
🐛 Skip circular library links on binfile import (#12062)
* 🐛 Skip circular library links on binfile import File import recreated circular library references that the link-file-to-library command already rejects. The v3 importer now skips manifest relations that would close a cycle, or link a file to itself, and logs each skipped link. Closes #12052. AI-assisted-by: muse-spark-1.3-contributor-free 🐛 Address review findings on circular import guard F1 extracts the cycle check into bfc/library-link-status and reuses it in link-file-to-library and v3 import, keeping UI errors intact. F3 orders get-files-rels and manifest relations so the first edge wins deterministically, and documents it. F2 adds a three-node transitive cycle test; F4 asserts file_library_sync has no orphan rows for skipped links and matches rels otherwise. AI-assisted-by: muse-spark-1.3-contributor 🐛 Pass team-id in binfile v3 circular library tests The four circular library relation tests (import-skips-circular, import-skips-transitive-cycle, import-skips-self-referencing, import-keeps-acyclic) called v3/import-files! without ::bfc/team-id. resolve-and-link-libraries asserts (uuid? team-id), so with enable-backend-asserts the tests errored instead of running. Add (assoc ::bfc/team-id (:default-team-id profile)) to each test, mirroring the production RPC import path and the earlier fix in a36193e54b for the other binfile v3 import tests. Verified: 1338 tests, 6910 assertions, 0 failures. AI-assisted-by: mistral-large-4 * 🐛 Guard the v1 import and restore the RPC check order The version 1 importer recreated the circular library references that the version 3 importer already skips, and a user reaches it through `import-binfile` and the import job. It now asks `bfc/library-link-status` before inserting each relation, so a self link or an edge that would close a cycle is skipped and logged, and it processes the relations in sorted order like v3 does. Closes #12052. The version 2 importer stays out on purpose: only the developer REPL reaches it, and a note in the code records the gap. `link-file-to-library` keeps the shared helper but restores the order of the base commit: the self link guard, then the edition permission and team ownership checks, and only then the cycle check. A caller without permission gets `not-found` again instead of the circular error, and a rejected request no longer runs the recursive library query first. Tests: a v1 import that recreates a cycle, the self link error of the command, and the permission check running before the cycle check. AI-assisted-by: deepseek-v4.1-flash * 🐛 Tolerate repeated file entries in the v1 binfile import The v1 exporter unioned the requested files with their libraries without deduplicating, so a package exported from a file inside a library cycle (see #12052) lists that file twice in the metadata. The v1 import created one file per entry, so the second insert hit the primary key of `file` and aborted the whole import with "file already exists". The importer now reads the pair of objects of every entry to keep the stream in sync but imports the first occurrence only, warns about the repeats, and answers with one id per imported file. The v1 export keeps its behavior: it has no caller in the product, and only the tests and the developer REPL use it. Tests: a package with a repeated entry, built with the v1 export from a cyclic library pair, imports the file once and leaves no duplicated rows. AI-assisted-by: deepseek-v4.1-flash |
||
|
|
34c702bc80
|
✨ Add table partitioning for file-change (#12417)
* ✨ Partition file_change by file_id Partition `file_change` by `HASH (file_id)` in 16 partitions, with the same bounds as `file_data`, so a join between them is resolved partition by partition. The primary key becomes `(file_id, id)`, which a partitioned table needs, and every access filters by `file_id`. The new table carries a `kind` column (1 snapshot, 2 revision) as a reserve: the queries still tell them apart by the label, and `kind` takes over when they are rewritten. The payload of a snapshot stays in `file_data`; the `data` column is kept for reading old `legacy-db` payloads. The four snapshot commands require `file-id`, because it prunes the partition. The objects GC locks and deletes by the pair, in batches. The old table is kept as `file_change_legacy` as the way back. The automatic migration refuses to run above 10 GiB or 2M rows and points to the runbook; big instances partition online with that runbook, which copies by id, follows the `updated_at` watermark in delta passes and checks that no row of the source is missing from the target. Closes #12416 AI-assisted-by: deepseek-v4.1-flash * 🐛 Address the review of the file_change partition The production runbook promised a rollback it did not have: the section was a sketch, and its statements could write to the table about to be dropped. The rollback is removed, and so is every comment that described it. `file_change_legacy` stays as a frozen copy of the previous layout. The cutover check now aborts the transaction when a row of the old table is missing in the new one, instead of leaving the decision to the operator. The five secondary indexes of the new table are built after the last delta pass: the bulk and the delta passes only need the primary key, so the batches no longer maintain them. The copy of 0158 is now replayed in a test against the pre-0158 shape with a labelled and an unlabelled row, plus an empty instance that must leave no legacy table behind. The updated_at assertion of the snapshot mutations is bounded by the test clock, and the repair revision stops writing the `features` of the file, like the normal save. AI-assisted-by: deepseek-v4.1-flash * 📎 Fix linter issues * 🐛 Fix stale helper call in rpc_file_snapshot_test The suite does not load: `th/run-pending-tasks!` does not exist in backend-tests.helpers. The pending jobs runner is `run-pending-jobs` (no arguments), the name every other call site of the suite uses. AI-assisted-by: inkling-2-small-free * 📚 Align the partition change with the 2.20.0 milestone 2.19.0 is already shipped; this work targets 2.20.0. The operations file of the partition procedure carries the 2.20.0 prefix, the references that point at it (the migration, the runbook table and the memory) follow, and the RPC doc/changes tags of the snapshot commands record 2.20 as the release that makes `file-id` required. AI-assisted-by: inkling-2-small-free * 🐛 Fix review findings on the partition rebase The 0157 legacy test was missed by the rebase and inserted file_change rows without the new mandatory `kind` column, so the backend suite fails against the migrated schema. The inserts now carry `:kind` (snapshot-kind for the labelled rows, revision-kind for the rest). The post-cutover verification block of the runbook terminates the first query with a semicolon so the block pastes into psql without a syntax error. The guard message of the migration names the step (0158-partition-file-change) instead of "0158", ambiguous since two migrations share that number. Closes #12416 AI-assisted-by: inkling-2-small-free * 🐛 Fix the stale label in the snapshot restore test The rename block of snapshots-crud runs before the restore block, so the restored version is already named "label1-updated" when the restore publishes its message. The command names the version by the label the row has at that moment, not by the one it had when it was created, so the test was asserting a stale value. Assert the current label, and say why in the comment. AI-assisted-by: deepseek-v4.1-flash * ♻️ Split the version event tests into one test per command The workspace version events and the plugin proxy send the file-id of the open file on every snapshot command, because the command needs it to prune the partition of file_change. Both tests checked that with a doseq and t/testing blocks, so a failure named the whole group and not the command that broke. Give each command its own test. The workspace ones share a helper that runs the event and returns the command and params it sends; the plugin ones keep their own mock of rp/cmd!. AI-assisted-by: deepseek-v4.1-flash |
||
|
|
671ff4a05f | Merge remote-tracking branch 'origin/staging' into develop | ||
|
|
e4fcc663c0 | Merge remote-tracking branch 'origin/staging-2.19.x' into staging | ||
|
|
1db1487c7f
|
🐛 Require thread access when marking threads as read (#12894)
* 🐛 Require thread access when marking threads as read mark-all-threads-as-read took any list of thread ids and wrote the read status of the caller on each of them, without checking that the caller can access the file that owns the thread. It was the only comment mutation that did not check permissions, and it took the ids as an unbounded array, so a single request could keep a database connection and a transaction open for a long time. The rpc now resolves the threads in one query and checks the comment permissions of every distinct file, answering not-found when a thread does not exist or is not accessible. Both cases answer the same error on purpose, so the response cannot be used to tell existing threads apart. The status rows are now written with a single insert, keeping the modified-at date one second in the future that makes the thread count as read. Repeated ids are deduped, the command returns nil again like the sibling commands with no result, and the schema limits the number of threads per call to 500 while the dashboard sends the ids in batches of that size. Tests cover access rejection, unknown threads, mixed batches that write nothing, repeated ids, empty lists, marking twice, and the frontend batch split. Relates to GHSA-j4vc-cmf6-jhr7 AI-assisted-by: minimax-m3.1-flash * 🐛 Refresh the unread list when a batch fails The dashboard sends the thread ids in batches of 500 and each batch commits on the server. A failure in a later batch left the unread list stale: the re-read only ran when every batch succeeded, so the threads already marked as read stayed visible as unread. The re-read now runs in both paths. On failure the event is emitted before the error is propagated, so the error toast still shows and the success toast stays limited to a full success. The backend also answers an empty list without opening a transaction, since there is nothing to check and nothing to write. Relates to GHSA-j4vc-cmf6-jhr7 AI-assisted-by: deepseek-v4.1-flash |
||
|
|
8510daef52
|
🐛 Restrict the team invitation token and list to admins (#12892)
* 🐛 Restrict the team invitation token and list to admins The token of a team invitation is a bearer credential: whoever holds it accepts the invitation with the role of the invitation row. The RPC that mints it only required edition permissions, while the rest of the invitation commands require admin, so a team editor could get the token of any pending invitation, including the ones that grant the owner role. The token now requires admin, and the token of an owner invitation is restricted to the team owner: an admin cannot create nor promote an owner invitation, so it cannot keep its token either. It reuses the error code already used for that rule. Minting the token now leaves an audit event named as an action, carrying the granted role and the id of the invitation, so the extraction does not go unnoticed. The list of pending invitations is admin only as well: it carries the email of the invited person and the role offered, and the dashboard was painting those emails to any member. The frontend catches the permission error and shows the permission notice instead, and the copy action is not offered for an owner invitation, which the backend rejects for an admin. The five invitation commands now answer with the same permission error, so they speak one language. Relates to GHSA-4mmc-j8rh-74pf AI-assisted-by: minimax-m3.1-flash * 🐛 Clear the cached invitations and gate the list on team admin The pending invitations are a team admin only list. The dashboard still offered the entry to every member and keyed the section on the invite policy of the organization, so a team admin blocked by that policy saw the no-permission notice although the backend lets them list. - `fetch-invitations` answers a denied refetch with an `invitations-fetched` event carrying an empty list, so a demoted admin does not keep the cached emails and the header no longer paints the invite button from a stale list. - The header tabs and the team options dropdown hide the invitations entry without `:is-admin`, which already includes the team owner. - `invitations-section-content` keys the section on `:is-admin`, and the invite policy only gates the invite actions: resending keeps the `can-invite?` check, deleting and row selection only need team admin. AI-assisted-by: deepseek-v4.1-flash |
||
|
|
0420db1ca9
|
🐛 Apply the share-link page scope to the comment queries and writes (#12888)
* 🐛 Apply the share-link page scope to the comment queries and writes A share link can be restricted to a subset of the pages of a file, and the comment queries enforced that scope. But the RPC that resolves the profiles of the commenters authorized the request with check-comment-permissions! and dropped the returned perms, so its query filtered only by file id. The holder of a page scoped link got the id, email, fullname and photo of every profile that commented on any page of the file, including the pages the owner left out of the link. The query now takes the pages of the share link and only selects the authors of the threads on them. The profile of the caller is still added, so the viewer keeps its own avatar. The scope was missing as well on the comment writes that take a page id or a thread id: create-comment-thread accepted a page outside the link, create-comment accepted a thread of an unshared page, and update-comment-thread, update-comment-thread-position and update-comment-thread-frame accepted a thread of an unshared page. They now raise not-found, the same way the comment queries already did. Replying to a thread of an unshared page also sent the emails to the thread participants. The page scope rule now lives in one place: share-link-pages returns the pages granted by a share link and check-page-scope raises not-found when a page is outside of it, so get-comment-threads reuses the helper instead of checking the pages inline. The docstring of get-profiles-for-file-comments said that it returns the participants of all the comment threads of the file, which is not true anymore for a share link. The docs are public, so the text and the changes list are updated. The tests of the share link page scope are hardened: the setup asserts that the comment threads are created, the membership case has a second commenter so it can no longer pass for the wrong reason, and the link without pages, the allowed paths of the thread updates and the who-comment=team denial are covered. Relates to GHSA-89cq-3wv7-987r AI-assisted-by: minimax-m3.1-flash * 🐛 Enforce the share-link page scope on the remaining comment writes Check the page scope of the share link before mutating in the four comment writes that still skipped it: update-comment-thread-status, update-comment, delete-comment-thread and delete-comment. The check runs before the ownership checks, so an out-of-scope write fails with not-found and the response does not reveal that the comment or thread exists. Load the file in create-comment only after the permissions and page scope checks, matching create-comment-thread, so a rejected reply does not load the file data. Cover the denial and the in-scope paths of the four commands, and the fail-closed case of a link without pages on the comment reads. Move the outsider thread creation after the profiles assertion so the caller-union assertion fails when the union is removed. Document the page scope invariant in the backend permissions memory. AI-assisted-by: deepseek-v4.1-flash |
||
|
|
4874da450f
|
🐛 Escape SVG values and sanitize every SVG upload (#12887)
* 🐛 Escape SVG values and sanitize every SVG upload The SVG sanitizer removed dangerous elements and attributes by name and then wrote the tree back with clojure.xml/emit, which escapes nothing. A payload hidden in an attribute value or in a text node became live markup again: an id of "x' onload='alert(1)'" was stored as a real onload handler, and an entity encoded script tag was stored as a real script element. Write the filtered tree with a serializer that escapes text and attribute values, and route every path that stores an uploaded SVG through it. The thumbnail writers (create-file-object-thumbnail and create-file-thumbnail) and the organization logo stored the upload untouched, so they could plant live markup in a public bucket. The filter only knows about SVG elements, so it also accepted documents that are not SVG at all: a page with an iframe or a meta refresh was stored as an image. The sanitizer now rejects any document whose root is not an svg element in the SVG namespace, and it compares the scheme of an url the way the browser does, so a scheme split with a tab or a line break no longer slips through the javascript: filter. The attributes are written sorted by name, because the parser hands them over in the reverse order of the document and the output changed on every sanitization. The profile picture of an identity provider is not stored either when it is an SVG: the avatar is always rendered as an image, so an SVG would only add the risk of keeping live markup in the storage. The dimensions of an SVG are now read from its local name, so an SVG with a namespace prefix can be uploaded like any other. The logo had no size limit and the sanitizer reads the whole file, so it now honors the media max file size. The output shape changes with it: no line breaks, double quotes, and the single quote of an attribute value escaped as an entity. The hash of every stored SVG object changes with it. The media tests use cuerdas.core instead of clojure.string, as the rest of the codebase does. Relates to GHSA-qwhj-rchj-58mg AI-assisted-by: minimax-m3.1-flash * 🐛 Drop non-SVG namespace subtrees in the SVG sanitizer The sanitizer only checked the namespace of the root, so a child could rebind xmlns to XHTML and smuggle live HTML (iframe/srcdoc/meta) past the blocklist. The serializer escapes attribute values, but the browser decodes them again, so srcdoc stays live. Track the namespace bindings through the recursion and drop any element that is not in the SVG namespace, with its subtree. The root is validated up front with the same model, so a document that is not an svg document is rejected with an honest hint instead of a misleading one. The default namespace is stored under a namespaced key, because a prefix literally named `default` collided with the internal key and re-opened the same hole through a prefixed binding. The attribute filter now keeps `xmlns`/`xmlns:*` declarations, which are not event handlers, so a prefix named like one does not end up undeclared in the output. The blocklist also drops HTML-only elements written in the svg namespace (iframe, meta, embed, link, base). Add regression tests for the child rebinding, for the prefixed variants, for the `default` prefix, for the root local name, for the create-file-media-object-from-url path (mocked download), and for the HTML-only tags. Assert double-quoted attributes in the clean content test. Relates to GHSA-qwhj-rchj-58mg AI-assisted-by: longcat-2.5-free |
||
|
|
c39e3e8301
|
✨ Strictly validate uploads against file bytes on disk (#12801)
* ✨ Strictly validate uploads against file bytes on disk Sniff the real content type of every upload with simplemagic magic bytes instead of trusting the client-supplied mtype header. Declared types outside the allowlist keep the not-allowed code; allowed declarations whose bytes differ are rejected as mismatch. Covers SVG by probing its root tag over leading bytes (magic never matches XML text), TTF/OTF by magic name and WOFF/WOFF2 by four-cc. Read the real file size from disk instead of trusting the declared :size. Files over the limit are rejected even when the declared size lies downwards, and small files pass even when it lies upwards. Run the path check first everywhere so forged server paths keep the params-validation code. Recheck from-url downloads after the write, with a declared-only fast fail at header time. Thread the assembled path through font validation. Refresh the affected tests around real and sparse fixture files, including a PNG-as-font chunked-upload rejection case. Closes #12796 AI-assisted-by: muse-spark-1.3-contributor * 🐛 Accept BOM-prefixed SVG uploads and cover WOFF/WOFF2/OTF/WEBP Address review comments on #12801: - SVG files saved with a UTF-8 BOM were rejected as :media-type-mismatch: read-head kept U+FEFF and the <svg probe never ran. A leading BOM is now stripped before the probe, and a generic XML sniff (application/xml, text/xml) is treated as "no magic evidence" for declared image/svg+xml, so the root-tag probe decides whether the file opens with an <svg root. - sniff-match?/svg-file? docstrings claimed the magic database never matches SVG; simplemagic 1.17 does match an SVG with an XML prolog as image/svg+xml. Reworded to match reality. - Added matching-pass tests for WOFF, WOFF2, OTF and WEBP (they hit the read-four-cc, magic-name and direct magic branches) and three BOM SVG regression cases. AI-assisted-by: inkling-2-small-free |
||
|
|
e1f924cf00 |
🐛 Send organization invitations to unregistered emails (#12937)
send-template drops nil values before enqueuing the mail job, but the invite-to-organization schema required the :user-name key. Inviting an email with no Penpot account left :user-name nil, the key was dropped and the job failed its schema check, so the invitation email was never sent. :user-name is now optional in invite-to-organization and in renewal-notice, which has the same shape. New test renders both templates through the queue with a nil :user-name. AI-assisted-by: claude-opus-5-5 |