diff --git a/.changeset/32164-permission-set-doors-take-a-package.md b/.changeset/32164-permission-set-doors-take-a-package.md new file mode 100644 index 00000000000..757c17c3fc5 --- /dev/null +++ b/.changeset/32164-permission-set-doors-take-a-package.md @@ -0,0 +1,81 @@ +--- +'@objectstack/core': patch +'@objectstack/plugin-security': patch +'@objectstack/runtime': patch +--- + +feat(plugin-security, runtime, core)!: the permission-set grant, clone and activation doors take a package, and a grant is unique per package (#32164) + +Clause-②: no (narrowing) +- Widening, at the grant, clone and activation doors: a permission set two packages hold, addressed with no package: FROM read as absent (the grant's `400 reference_not_found`, the clone and activation doors' `404`) TO `409 RESOURCE_CONFLICT` naming the holders; addressed with a package that holds it (`permission_set_package` on the grant, `?package=` on clone and activation): FROM the package dropped TO exactly that package's set. +- Widening, the grant's unique key: FROM one grant per `(user_id, permission_set, organization_id)` TO one per `(user_id, permission_set, permission_set_package, organization_id)`, so one user may hold both packages' sets of one name in one organization. A grant naming no package stays one per `(user_id, permission_set, organization_id)` through the guard the preceding PR builds, except on `driver-memory` (declared below). +- Narrowing (F3), a named package that does not hold the set, at any holder count: FROM the grant or audience-binding suggestion re-stamped to the holder (one holder) or stored with no package (two holders), a system column-only bind landing as written, and `?package=` dropped at the clone and activation doors (one holder: the holder's set) TO `409 RESOURCE_CONFLICT`, reason `not-held-by-qualifier`, naming the holders, with nothing stored or switched. +- Narrowing, an audience-binding suggestion naming a holder outside the reach of the package that made it (not that package, a dependency or a kernel package): FROM re-stamped by the rule's answer (no package) TO `409 RESOURCE_CONFLICT`, reason `outside-closure`, naming that holder, nothing stored. +- Narrowing, the agent-account ceiling (ADR-0151 D3) for a set two packages hold: FROM read by the bare name, which the rule refuses, so no breach was found and the grant or position was admitted TO the set the row would hold (the grant's own package, a position's sets from the package that declared it) judged, and a read the rule still refuses judging every holder of the name: a breach of any refuses the write. +- Narrowing, the query sets are closed: FROM any query parameter dropped without a word TO `400 VALIDATION_ERROR` before any lookup, at the clone door and at the activation door for all six of its types (`position`, `permission`, `sharing_rule`, `webhook`, `queue`, `assignment_rule`), for anything but `package` on `permission`, and for a repeated or blank `package`. +- Narrowing, a clone target name two packages hold: FROM free (the reader answers nothing for a refused name, so the copy was saved) TO taken, `409`, as a name one package holds already was. +- Narrowing, the activation ledger for a permission set two packages hold: switching a holder on while a ledger row naming no package, or naming a package that no longer serves the name, keeps it off: FROM (reachable only after #31698 PR-2) that row re-addressed to the holder, which re-armed the other holder too TO `409 RESOURCE_CONFLICT` naming that row, nothing written (ADR-0150 red line 1). The same with one holder when the name has more than one row, which no first-party writer makes. A disabled package still holds the name here, as the rule counts it. +- Moved, refused either way: a second grant of one set to one user in one organization whose row record validation would also refuse: FROM `400 VALIDATION_FAILED` (the store's key answered after validation) TO the one-grant check's `409`, nothing stored either way. So does a second grant that a grant-table hook at the default priority (100), an app's own, would refuse: FROM that hook's refusal TO the same `409` (the check runs at priority 50). Every refusal of the platform's grant-table hooks, and the engine's answer for a holder the caller cannot read, keep their precedence. + +Metadata-protocol: none + + + +**BREAKING** for a writer that sends `permission_set_package` naming a package that does not hold the permission set (or, on a suggestion, a holder outside the suggesting package's reach), and for a request carrying a query parameter to the clone door or to the activation door, for any of its six types. No first-party writer sends either: the boot backfill and `os migrate stored-references bind` write only a holder, and the Console sends no query to these doors. + +ADR-0150 D3/D4/D5/D8, child of #31527. The last of three PRs for #32164: the first taught `driver-sql`'s widening arm the superseded grant key's 18.0, shadow-carried (its key read or not) and not-yet-physical forms; the second builds the grant's package-less guard at schema sync, on every kernel that runs the table's DDL, and lists it in `os migrate duplicates`. A permission set is identified by `(package, name)` (D4). Until #31698 PR-2 a real registry cannot hold two packages' sets of one name, so every two-holder answer below is reachable only after that; every one-holder answer is unchanged, except the narrowings declared above. + +**The grant: `sys_user_permission_set` through the engine and `/data`.** + +- A set two packages hold, named with no package, at the data door (a non-system writer): FROM `400 VALIDATION_FAILED`, `reference_not_found` at `permission_set` ("There is no permission set named …") TO `409 RESOURCE_CONFLICT` with the D3 sentence naming every holder. The thrown error is core's `PackageScopedNameRefusedError` (`.refusal.candidates` structured). The `/data` body carries the sentence; structured candidates on `/data` are #32250. Nothing is stored. +- The same, naming a holder in `permission_set_package`: FROM the same `400` (non-system) or stored with no package (system) TO stored with exactly that package. +- Naming a package that does not hold the set (F3), at any holder count, for any writer: FROM stored with the seam's answer (one holder: re-stamped to the holder; two holders: no package) TO `409 RESOURCE_CONFLICT`, reason `not-held-by-qualifier`, naming the holders (an environment-authored set names the environment). Nothing is stored. +- A system update writing `permission_set_package` alone (a column-only bind): naming a holder, unchanged (lands as written). Naming a non-holder: FROM landed as written TO `409 not-held-by-qualifier`, the row unchanged. +- A system insert naming a package for a name nothing holds: FROM the package replaced by none TO kept as written. There is no holder to refuse it against, and every reader reads a package that does not serve the name as no package, so it confers nothing. +- A system insert naming a package before the boot seals the holders: FROM the package replaced by none TO kept unjudged (the boot backfill reads a stale one as no package). +- Unchanged: a name nothing holds is the `400` it was for a non-system writer, with or without a package; a set one package holds, named with no package or with its holder, is stored stamped with that holder; a non-system update's `permission_set_package` is still dropped by the engine's `readonly` update strip, never stored and never judged; an echo of the stored package chooses nothing; a rename re-stamps as before. + +**The audience-binding suggestion: `sys_audience_binding_suggestion` (R3).** The same stamp serves its `permission_set_package`, asked from the suggestion's own `package_id`. The table is system-write only, and `os migrate stored-references bind --table sys_audience_binding_suggestion` writes through the stamp. + +- A system insert naming a package that does not hold the set: FROM re-stamped by the rule's answer TO `409 RESOURCE_CONFLICT`, `not-held-by-qualifier`. Nothing is stored. +- A system update writing `permission_set_package` alone, naming a non-holder: FROM landed as written TO the same `409`, the row unchanged. +- A system insert naming one of two holders in the suggester's reach: FROM no package (the rule refuses the bare name) TO kept as written. +- A system insert or column-only update naming a holder outside the suggester's reach (not the suggesting package, a dependency it declares or a kernel package): FROM re-stamped by the rule's answer (no package), or landed as written TO `409 RESOURCE_CONFLICT`, reason `outside-closure`, naming that holder. Nothing is stored. The rule alone never binds such a holder, so neither does a writer. + +**The activation door: `POST /security/_activation/:type/:name`.** + +- A permission set two packages hold, no package named: FROM `404 RESOURCE_NOT_FOUND` ("… has no definition — there is nothing to switch off") TO `409 RESOURCE_CONFLICT`, the D3 sentence, `details.candidates: [{ kind: 'package', packageId }, …]`. Nothing is written. +- `?package=PKG`, a holder: FROM the query dropped (the same `404`) TO exactly PKG's set switched, through PKG's own ledger row. The permission ledger is now addressed by `(package, name)`, the ledger's declared key: each holder keeps its own row, so switching one holder's set never touches the other's, and both stay independently switchable. The readers already read each row by its package (a row naming no package, or naming one that no longer serves the name, is read by the name alone, ADR-0150 D3: with two package holders and no environment set of the name it switches both off). Every other type keeps the name-addressed store. +- Switching a holder on while a row naming no package, or naming a package that no longer serves the name, keeps it off (two holders): `409 RESOURCE_CONFLICT` naming that row, nothing written. Switching it off writes the holder's own row and leaves that row as it is. With one holder, such a row, when it is the name's only row, is the holder's and the write takes it over, as before, whatever the holder is: a package, or the environment (an environment-authored set, an overlay included). The row the door writes for an environment-authored set names no package, where it named the overlay provenance `sys_metadata` before; every reader reads both as no package. +- A package and the environment both holding a name: the name alone resolves to the environment's set (the D3 rule for a caller with no package), so a row naming no package, or stamped with the overlay provenance `sys_metadata`, is the environment's own switch. Switching the environment's set writes that row (a `sys_metadata` row is re-addressed to name no package, never doubled), and the package's set keeps its own row. +- A package that is disabled still holds the name for these rules, as the D3 rule counts it (the catalog does not serve its set): with it, the name has two holders, so the bare name is `409` naming both, and switching the served holder on while a row naming no package keeps it off is the `409` above. `?package=` naming the disabled package is `409 not-held-by-qualifier` naming the holders the catalog serves. With one holder and more than one row for the name (no first-party writer makes one: the name-addressed store kept one row per name), switching on while another row keeps it off: FROM the first row found re-addressed TO the same `409`. +- A write that would re-address a row switched off for another holder is refused `409`, nothing written. The address rule above never picks one; the refusal stands against a concurrent write or a later reader change. +- `?package=PKG`, a non-holder: FROM the query dropped (one holder: `200` on the holder's set) TO `409 not-held-by-qualifier` naming the holders. Nothing is written. +- Any other query parameter, on any of the six types, and a repeated or blank `package`: FROM dropped without a word TO `400 VALIDATION_ERROR` (AGENTS route rule 5) before any lookup. The closed set is `package` for `permission` and nothing for every other type. +- The body stays `{ enabled? }`: a `package` key in the body is still `400 unknown_field`. + +**The clone door: `POST /security/permission-sets/:name/clone`.** + +- A source two packages hold, no package named: FROM `404 RESOURCE_NOT_FOUND` ("… there is nothing to clone") TO `409 RESOURCE_CONFLICT` with `details.candidates`. Nothing is saved. +- `?package=PKG` names the SOURCE's package (the body's `package` still names where the copy lands): FROM the query dropped TO exactly PKG's set copied, landing by the existing rule (a read-only package's copy lands in its pair). A non-holder is `409 not-held-by-qualifier`. +- A target name two packages hold: FROM not taken (the reader's by-name read answers nothing for a refused name), so the copy was saved TO `409`, taken, as a name one package holds already was. Nothing is saved. +- Any other query parameter, and a repeated or blank `package`: FROM dropped TO `400 VALIDATION_ERROR`, before the body and any lookup. + +**The grant's unique key (schema face, every driver).** + +- FROM `(user_id, permission_set, organization_id)`, `unique: 'organization'` TO `(user_id, permission_set, permission_set_package, organization_id)`, `unique: 'global'`: one user may hold both packages' sets of one name in one organization. +- A grant naming no package (a NULL `permission_set_package`) is exempt from that key; the guard `uniq_sys_user_permission_set_packageless` keeps those to one per `(user_id, permission_set, organization_id)` (built at schema sync by the preceding PR). Among grants naming no package the guard admits nothing the old key refused, with a non-null and with a NULL organization: the key and the guard together measured side by side with the old key on SQLite, PostgreSQL 16 and MariaDB 10.11; on MySQL 8.0 the guard alone (`main`'s CI, for the preceding PR), the key and the guard together first running there on `main`'s push; and pinned, not run, for a real mongod, whose suite runs only where `OS_TEST_MONGODB_MEMORY_SERVER_ENABLED=1` is set, which no CI job does. The old key's plain key parts exempted a NULL organization too; a table `driver-sql` builds has a NOT NULL organization column. +- One grant of a set per user and organization, through the engine, as before: a second grant of one set to one user in one organization is refused unless the two name two different packages that each hold the set, the one pair the wider key exists to admit. The two keys alone do not refuse every such second grant, so the engine's write seam judges each grant insert, and each update that moves its user, set, organization or package, read in the writer's transaction, and refuses with the answer the old key gave: the engine's duplicate-record refusal (`DUPLICATE_RECORD`, `409` in-process; `409 UNIQUE_VIOLATION`, "A record with this value already exists", on the wire). It runs after every refusal the grant table's hooks make (the set's name, the agent ceiling set, the holder's membership, the AI service account's ceiling), so a second grant one of those refuses keeps that answer, as while the store's key answered last; and it steps aside on a holder a non-system write names that the caller's own read does not return, which the engine's reference check answers as a user that does not exist (`400 VALIDATION_FAILED`, `reference_not_found` at `user_id`), as before, whatever grants that user holds. Declared precedence: it runs at priority 50, before any hook at the default priority (100), an app's own included, and before record validation and the engine's reference check of the row's other references, so a second grant whose row those would also refuse moves FROM that hook's refusal or `400 VALIDATION_FAILED` (the store's key answered after them) TO the `409` above; nothing is stored either way. Measured on SQLite; the seam reads through the engine, so it is the same on every driver. Declared limit: a row written below the engine, two writes racing, two rows of one batch insert, and a write with no organization on the row or in its session, are held by the keys alone (pinned per driver: SQLite, PostgreSQL 16, MariaDB 10.11 and `driver-memory` measured, Mongo pinned, not run). +- The boot backfill binds a grant naming no package to its one holder one row at a time. A row whose bind would make such a second grant (a row the keys alone admitted, as declared above): FROM not reachable (the old key refused the second row of one user, set and organization, and a bind of the package column could not violate it) TO that row left with no package and reported as `duplicated` (the report gains `duplicated: { id, name, packageId }[]`, logged at warn), and the walk goes on. A dry run reports such a row as `duplicated`, not `bound`. +- Upgrading: the old three-column index retires only once the guard stands. On SQL that is the next sync that runs safe drift (dev `autoMigrate: 'safe'`, or `os migrate apply`) as one `replace_unique_index`, categorized `safe`; until then it keeps refusing what it refused. Where an 18.0 database built it in the NULL-safe COALESCE form, it is retired only on a certified table, whose tenant column holds no NULL, and kept everywhere else. On Mongo it retires in the same sync that builds the guard. A server with no form for the guard (MySQL before 8.0.13, MariaDB before 10.3) keeps the old key, as the preceding PR declares. +- Declared limit: a MySQL or MariaDB store whose old key is carried by a #11627 hash shadow keeps the three-column key. The driver builds that carrier, an INVISIBLE generated column `uniq_sys_user_permission_set_ac248331__hash` under a UNIQUE key, only where the server refused the direct key (a key part stored as TEXT); a table this release creates keys the three columns directly, `permission_set` as a keyed `varchar(100)`. The widening arm keeps such a carrier and offers nothing, as it does one whose generation expression cannot be read (the first PR), because `replace_unique_index` retires no shadow column. That store keeps refusing one user a second package's set of the same name in one organization. Remedy by hand, once `uniq_sys_user_permission_set_packageless` stands (`os migrate duplicates` lists it): `ALTER TABLE sys_user_permission_set DROP INDEX uniq_sys_user_permission_set_ac248331, DROP COLUMN uniq_sys_user_permission_set_ac248331__hash`. The wider key is already built beside it, so nothing else is needed. +- Declared limit: `driver-memory` builds no guard (no raw-SQL seam; the activation ledger's guard has the same exemption). Measured: its unique check treats a NULL as distinct, so the driver alone admits two package-less grants of one set for one user in one organization, where the old key refused the second. Through the engine the write seam above refuses the second, as on every driver. A pin asserts the driver's own admission (`memory-user-permission-set-packageless.test.ts`). + +**The agent-account ceiling (ADR-0151 D3).** An AI service account may not hold a set above the agent ceiling, judged at the grant and at the position assignment. + +- The set judged: FROM the bare name (with two holders the rule refuses it, which answered no breach) TO the set the row would hold, read as the authorization resolver reads it: a grant at the package it stores, a position's sets from the package that declared the position. With one holder, unchanged. +- A read the rule still refuses (two holders, none placed): FROM no breach TO every holder of the name the catalog serves judged; a breach of any refuses the write (`400 VALIDATION_FAILED`, as for any breaching set). + +**In-process APIs.** + +- `@objectstack/core`: the refused arm of `SecurityCatalogResolution` (what `resolveCatalogReference` and `SecurityCatalogReader.resolveReference` answer) gains an optional `holders: readonly PackageScopedHolder[]`, the candidates structured, in the same order as `candidates`. FROM absent TO present on every refusal the reader answers. Additive: a resolved or not-found answer has none, and an implementer of the type may omit it. diff --git a/content/docs/permissions/authorization.mdx b/content/docs/permissions/authorization.mdx index 46f0e179500..0469cad0bc4 100644 --- a/content/docs/permissions/authorization.mdx +++ b/content/docs/permissions/authorization.mdx @@ -439,7 +439,24 @@ in the security catalog, or the route answers `404`. That covers a position or permission set the environment authored through the metadata door as well as one a package ships: the ledger row records the package when there is one and leaves `package_id` empty when there is none, and the resolver honours both -alike, because it keys the row by type and name. A write the ledger refuses +alike, because it keys the row by type and name. For a permission set two +packages hold, `?package=` names one (ADR-0150 D3): without it the route +answers `409` `RESOURCE_CONFLICT` with `details.candidates`, a package that does +not hold the set answers `409` too, and the row records the named package. +Each holder keeps its own row (the permission ledger is keyed by package and +name), so switching one package's set never touches the other's. A row that +names no package, or a package that no longer serves the name, is read by the +name alone: while two packages hold the name and the environment does not, it +switches off every holder, and switching a holder on while such a row stands +answers `409`, and nothing is written. Where the environment holds the name +beside a package, the name alone is the environment's set: a row naming no +package, or stamped `sys_metadata` (the overlay's provenance), is the +environment's own switch, and a row naming a package that no longer serves the +name keeps the environment's set off the same way. A disabled package still counts as a holder here. With one holder, a +package or the environment, such a row is the holder's and the write takes it +over. `package` is the only query parameter, and only +for `permission`; any other, or a repeated or blank one, answers `400` +before any lookup. A write the ledger refuses answers with the status its code means: a record validation failure is `400` `VALIDATION_FAILED`, a hook's refusal keeps its own pair, and a store failure is `503` `SERVICE_UNAVAILABLE`. It is the same authority diff --git a/content/docs/permissions/permission-sets.mdx b/content/docs/permissions/permission-sets.mdx index 78bd1edbcd8..23dedd36e68 100644 --- a/content/docs/permissions/permission-sets.mdx +++ b/content/docs/permissions/permission-sets.mdx @@ -257,6 +257,20 @@ The position's definition is the only binding that grants: the retired `sys_position_permission_set` junction object is no longer registered, and a row an older database still holds confers nothing. +A set is identified by its package and its name (ADR-0150 D4), so a direct +grant can name the owning package in `permission_set_package`. A set one +package holds needs none: the grant is stored with that package. A set two +packages hold, granted with no package, is refused `409` `RESOURCE_CONFLICT`, +and the message names every holder. A package that does not hold the set is +refused `409` whatever the number of holders, and nothing is stored. One user +holds one grant of a set per organization, as before, except that when two +packages hold the set the user may hold each package's set once. A second +grant written through the engine is refused as a duplicate record (`409` +`UNIQUE_VIOLATION` on the wire). Below the engine the store's indexes keep one +grant per set, package and organization, and one grant that names no package +per set and organization; the in-memory driver (`driver-memory`) builds no +index for grants that name no package. + The assignment writes are **governed** (ADR-0090 D12): tenant-level admins pass through to the ordinary checks; a delegated admin needs a covering `adminScope`; plain CRUD on the tables grants nothing by itself. A position's @@ -472,6 +486,13 @@ the source never reach the copy. a new snake_case machine name: a name failing that rule answers `400`, and a name any permission set already uses (the source's own included) answers `409` `RESOURCE_CONFLICT`. An unknown source answers `404`. +- **Two packages' sets of one name (ADR-0150 D3).** `?package=` names + the source's package; the body's `package` still names where the copy lands. + When two packages hold a set of the source's name, a clone with no + `?package=` answers `409` `RESOURCE_CONFLICT` with `details.candidates`, and + a package that does not hold the set answers `409` too. A target name two + packages hold is taken (`409`). `package` is the only query parameter: any + other, or a repeated or blank one, answers `400`. - **Every permission facet is copied** — `objects`, `fields`, `systemPermissions`, `tabPermissions`, `rowLevelSecurity`, `description`. - **The server drops a declared set of keys**: the package provenance diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 276fa926dc8..f31faa21519 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -137,11 +137,12 @@ bugs — it is the protection or the side effect that silently does not happen. | 22 | Strict-drop refusal never fires | objectql | Lose: a caller that opted into loud refusal gets **silence** — strict refuses exactly what the strip would have taken, and the strip took nothing. Two exceptions, both judged in every context: a `formula` value, which the `computed` strip takes from every caller, and a value for a stored field that declares `expression` when it differs from the value the engine computes in its place (`stored_expression`), so strict still refuses both | `insert`, `packages/objectql/src/readonly-strict-errors.ts#READONLY_CLASS_REASONS` | | 23 | **Referential-integrity check skipped** — except a `runAs: 'system'` flow's record writes, which keep it | objectql | Get: writes proceed against unreachable/unresolvable targets — a seed replay, an import, a restore or a cascade may store a reference to a row that does not exist yet. Lose: an `isSystem` caller can write a **dangling reference**. A flow run's elevated context (`resolveRunDataContext`) carries an internal mark that keeps the check, so a flow's `create_record` / `update_record` naming a row that does not exist is refused `400 VALIDATION_FAILED` / `reference_not_found`, as on the user path; its authorization elevation is unchanged. A write the flow's write sets off (a hook's `ctx.api`, its `sudo()`, a cascade leg of a flow's delete) spreads the run's context and is checked as the flow's own, as on the user path. The mark is a symbol no flow definition or request can spell, and `ExecutionContextSchema.parse` drops it. Where a system write runs the check (a flow run's), it runs after the record's validation rules, as before; every other write runs it before them. An update's check does not judge again a value every row it lands on already stores; a system write compares those rows as stored, every other write only as the caller may read them, so a column the caller cannot read forgives nothing | `assertReferencesResolve`, `referencesCheckedBeforeRules`, `storedReferencesCallerReads` | | 23b | **Position-catalog check skipped** — a `sys_user_position` write whose `position` names no position in the security catalog is not refused | plugin-security | Get: a system writer can store an assignment naming no position — the seed loader writes `stack.data` from `AppPlugin.start()` under a system context, as invitation acceptance and the platform's own bootstraps do. Lose: such a row grants nothing and nothing says so. A non-system insert, or a non-system update that changes `position`, is refused `400 VALIDATION_FAILED` / `reference_not_found` instead when the security catalog holds no position of that name: the environment registry (ADR-0131 D3), one per deployment, which takes no organization, so a name only a `sys_position` row carries — any organization's — is refused like one nobody carries. It is the same stand-down as the engine's referential-integrity check for a lookup column | `assertPositionNamesCatalogRow` | -| 23c | **Grant-name catalog check skipped** — a `sys_user_permission_set` write whose `permission_set` names no permission set in the security catalog is not refused | plugin-security | Get: a system writer can store a grant naming a set not yet registered — seed replay and boot provisioning may write the grant before the definition it names is registered. Lose: such a row grants nothing and nothing says so. A non-system insert, or a non-system update that changes `permission_set`, is refused `400 VALIDATION_FAILED` / `reference_not_found` instead when the security catalog holds no set by that name; a grant that names no set at all is refused `required` for every caller. The grant names its set by name alone, and nothing derives the name from `permission_set_id` (ADR-0131 D4, D10) | `packages/plugins/plugin-security/src/grant-permission-set-name.ts#onInsert`, `packages/plugins/plugin-security/src/grant-permission-set-name.ts#onUpdate` | +| 23c | **Grant-name catalog check skipped** — a `sys_user_permission_set` write whose `permission_set` names no permission set in the security catalog is not refused | plugin-security | Get: a system writer can store a grant naming a set not yet registered — seed replay and boot provisioning may write the grant before the definition it names is registered. Lose: such a row grants nothing and nothing says so. A non-system insert, or a non-system update that changes `permission_set`, is refused `400 VALIDATION_FAILED` / `reference_not_found` instead when the security catalog holds no set by that name, and `409 RESOURCE_CONFLICT` naming the holders when two packages hold it and the write names neither, or names a package that does not hold it (ADR-0150 D3/D5, #32164); a grant that names no set at all is refused `required` for every caller. The grant names its set by name, and by package in `permission_set_package` when it names one (ADR-0150 D4); nothing derives the name from `permission_set_id` (ADR-0131 D4, D10) | `packages/plugins/plugin-security/src/grant-permission-set-name.ts#onInsert`, `packages/plugins/plugin-security/src/grant-permission-set-name.ts#onUpdate` | | 23d | **Grant-holder membership check skipped** — a `sys_user_position` or `sys_user_permission_set` write naming a user with no `sys_member` row in the row's organization is not refused | plugin-security | Get: a system writer can store such a grant — invitation acceptance writes the membership and its placement together, and seed replay, the organization-admin reconcile and the platform bootstraps write grants as the system. Lose: such a row takes effect once its user is admitted to the organization. A non-system insert, or a non-system update that moves `user_id` or `organization_id`, is refused `400 VALIDATION_FAILED` / `reference_not_found` at `user_id` instead, for every caller, a platform administrator included; the membership is read as `{ isSystem: true, tenantId }` with `tenantId` the row's own organization, never another one. A row stored with no organization is not judged. Under `single`, 18.0 stamps a new grant with the Default Organization, so such a row is one an earlier release wrote | `packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts#onInsert`, `packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts#onUpdate` | | 23e | **A `secret` field takes a stored reference as given** — a value already spelled `secret:` is stored unchanged | objectql | Get: a system writer may copy a `secret:` reference onto a record as it stands (seed replay, a migration). Every other caller may only seal a new value or keep its own record's ref, and its own is the value it reads in that column: on a create any such value is refused, and on an update it would be kept only where every record the write lands on serves exactly that reference to this caller's own read door. The read path serves a `secret` column masked to every caller, so every reference such a caller sends is refused `400 VALIDATION_ERROR` before anything is written, with one answer whatever it names and whatever the column holds; an echoed read mask still leaves the column as it is. Lose: the check that the reference is the record's own — a system writer that copies one is trusted to mean it. Inbound HTTP never carries the flag | `encryptSecretFields` | | 23f | **Agent ceiling grant check skipped** — a `sys_user_permission_set` write naming an MCP agent ceiling set is not refused | plugin-security | Get: a system writer that is not a seed is not judged. The platform-admin promotion and the organization-admin reconcile name their sets in code, and neither is a ceiling; the self-registration grant writes the configured `audience.selfRegistrationPermissionSet`, which the audience validation (`assertAudienceConfig`, plugin-auth) refuses when it names an agent ceiling set; an identity-provider group mapping is refused at its save, and its projected grant again before each write, when its set is outside the organization boundary; the development-only demo-staff seed grants only sets its stack declares, and no stack declares an agent ceiling's name. Lose: nothing on this table — a seed write (`seedReplay`: a stack's `data`, a published `seed` item) is judged like a non-system one. A non-system or seed insert, or such an update whose resulting row names one, is refused `400 VALIDATION_FAILED` / `invalid_value` at `permission_set`, for every caller, a platform administrator included; a `sys_user_position` write naming a position whose definition names one is refused `invalid_value` at `position` for every writer, a system one included, except a system update that leaves the position as stored; a delete is not judged (ADR-0090 D10). These hooks, the metadata door's position gate and the `SecurityPlugin` baseline check are the doors that hold the rule; they do not judge a position a person holds without an assignment row, or a position definition that reaches the security catalog without passing the metadata door, and whether the read side refuses those is a separate decision with the maintainer (the security seat, #32004) | `packages/plugins/plugin-security/src/agent-ceiling-grant-refusal.ts#judges` | | 23g | **AI service account grant check skipped** — a `sys_user_permission_set` or `sys_user_position` write giving an AI service account a set above the agent ceiling is not refused | plugin-security | Get: a system writer is not judged. The organization-admin reconcile binds nothing for an account, and the platform bootstraps grant only people. Lose: seed replay writes the grants its stack declares, unjudged, so a seed that gives an account a set carrying View All, Modify All, transfer, restore, purge, a system permission or an admin scope stores it; those bits are still cleared when the account's sets are evaluated (`packages/plugins/plugin-security/src/agent-ceiling-clamp.ts`). A non-system insert, or a non-system update whose resulting row gives an account such a set (directly, or through a position binding one), is refused `400 VALIDATION_FAILED` / `invalid_value` at `permission_set` or `position`, for every caller, a platform administrator included; the holder's `sys_user` row is read as the system only when the caller's own door reads it; a delete is not judged | `packages/plugins/plugin-security/src/agent-account-grant-refusal.ts#onInsert`, `packages/plugins/plugin-security/src/agent-account-grant-refusal.ts#onUpdate` | +| 23h | **A grant's package column, sent on an update, is judged rather than ignored** — a system writer's `permission_set_package` reaches the package stamp | plugin-security | Get: the boot backfill and `os migrate stored-references bind` bind a grant to the package that holds its set by writing the column alone (ADR-0150 D8 R1), and a package that holds the set lands as written. Lose: nothing a holder could not already do — a named package that does not hold the set is refused `409 RESOURCE_CONFLICT`, `not-held-by-qualifier`, naming the holders, at any holder count, and the row is left as it was (#32164, F3); on insert every writer's named package is judged the same way. The same stamp serves `sys_audience_binding_suggestion` (R3, its `permission_set_package` beside `permission_set_name`): a system insert or column-only update there naming a package that does not hold the set, FROM re-stamped (insert) or landed as written (update) TO the same `409`, the row left as it was; `os migrate stored-references bind --table sys_audience_binding_suggestion` writes through it. A non-system update's `permission_set_package` never reaches the stamp: the engine's `readonly` update strip drops it, so it is never stored and never judged. The same seam keeps one grant of a set per user and organization, as the grant's key before #32164 did (two packages' sets of one name excepted): on an update it judges the package the row stores after the write, a system writer's value or else the stored one, and it reads the other grants of the same user, set and organization as the system, in the writer's transaction, answering only the old key's duplicate-record refusal (`409`), never a row. It runs after the grant table's other refusals, and for a non-system write it steps aside on a holder the write names that the caller's own read does not return: the engine's reference check answers that holder as a user that does not exist (#29029) | `packages/plugins/plugin-security/src/stored-permission-set-package-stamp.ts#onUpdate`, `#oneGrantOnUpdate`, `#holderLeftToEngine` | | 24 | Tenant-audit warning silenced; `bypassTenantAudit` threaded to the driver | objectql | Get: unscoped system writes stop warning. Lose: the signal that would flag a genuine user-path scoping bug | `buildDriverOptions` | | 25 | Engine-owned / append-only write guard bypassed | plugin-security | Get: generic writes to `managedBy` engine-owned objects. Except app-automation's elevation on a ledger: an update, delete, transfer, restore or purge of an object declared `managedBy: 'append-only'` from app-automation's elevation (a flow run's, an app-authored hook's, an action body's, read by `elevationSource`) is refused `PERMISSION_DENIED` ahead of the short-circuit, by the same predicate, in `assertAppAutomationAppendOnlyWriteAllowed`; so is such a context's delete of a record a ledger row references, whose reference clean-up would change that row; an insert is not judged by this check; the platform's own writers, whose system context carries neither a run nor the mark, are unchanged | `packages/plugins/plugin-security/src/system-write-guard.ts#isUserContextWrite`, `packages/plugins/plugin-security/src/system-write-guard.ts#assertEngineOwnedWriteAllowed`, `packages/plugins/plugin-security/src/flow-system-identity-write-refusal.ts#elevationSource` | | 26 | Identity write guard bypassed (ADR-0092) | plugin-auth | Get: direct writes to identity tables through the generic data path | `packages/plugins/plugin-auth/src/identity-write-guard.ts#isUserContextWrite` | @@ -613,6 +614,9 @@ and CI refuses one that differs from what the tree produces. | `packages/plugins/plugin-security/src/security-plugin-read-filter.ts#getReadFilter` | 1 | 3 | | `packages/plugins/plugin-security/src/security-plugin-security-service.ts#registerSecurityService` | 3 | 7 | | `packages/plugins/plugin-security/src/security-plugin-write-tenant-wall.ts#writeWallVerdict` | 1 | 6c | +| `packages/plugins/plugin-security/src/stored-permission-set-package-stamp.ts#holderLeftToEngine` | 1 | 23h | +| `packages/plugins/plugin-security/src/stored-permission-set-package-stamp.ts#onUpdate` | 1 | 23h | +| `packages/plugins/plugin-security/src/stored-permission-set-package-stamp.ts#oneGrantOnUpdate` | 1 | 23h | | `packages/plugins/plugin-security/src/suggested-audience-bindings.ts#assertDeploymentAuthority` | 1 | 58 | | `packages/plugins/plugin-security/src/system-write-guard.ts#isUserContextWrite` | 1 | 25 | | `packages/plugins/plugin-sharing/src/rule-hooks.ts#bindRuleHooks` | 1 | 31 | diff --git a/docs/qa/platform-checklist/areas/access-security.json b/docs/qa/platform-checklist/areas/access-security.json index e7ad15b6818..6b1c0246fd1 100644 --- a/docs/qa/platform-checklist/areas/access-security.json +++ b/docs/qa/platform-checklist/areas/access-security.json @@ -4029,10 +4029,10 @@ }, { "id": "access-security.security-catalog-activation-and-clone-doors", - "title": "Security-catalog doors new on v18: POST /security/_activation/:type/:name switches a position or permission set off and on (holders lose and regain its grants), and POST /security/permission-sets/:name/clone copies a set with its refusal arms", + "title": "Security-catalog doors new on v18: POST /security/_activation/:type/:name switches a position or permission set off and on (holders lose and regain its grants), and POST /security/permission-sets/:name/clone copies a set with its refusal arms; both take ?package= for a permission set and refuse any other query", "since": "v18", "status": "active", - "revision": 3, + "revision": 4, "priority": "P1", "surface": "api", "personas": [ @@ -4051,7 +4051,8 @@ "as admin POST /api/v1/security/_activation/position/POSITION {enabled:false}; as the member re-read GET /api/v1/auth/me/permissions (or a record the position grants)", "POST the same with {enabled:true}; re-read", "POST /api/v1/security/_activation/position/everyone {enabled:false}; and for an unknown name", - "POST /api/v1/security/permission-sets/SOURCE/clone {name:\"qa_clone_set\", label:\"QA clone\"}; repeat with the same name; with the source's own name; with a bad body; as the member; anonymously" + "POST /api/v1/security/permission-sets/SOURCE/clone {name:\"qa_clone_set\", label:\"QA clone\"}; repeat with the same name; with the source's own name; with a bad body; as the member; anonymously", + "as admin POST /api/v1/security/_activation/permission/SET?package=HOLDER {enabled:false}, then {enabled:true}; the same with ?package=NOT_A_HOLDER, with ?foo=1, with ?package= (blank) and with package repeated; POST /api/v1/security/permission-sets/SOURCE/clone?package=NOT_A_HOLDER and ?foo=1 with a valid body" ], "acceptance": [ { @@ -4077,6 +4078,18 @@ "oracle": "api", "verify": "status + code per arm and the cloned set's keys", "evidence": "one line per arm + the clone body" + }, + { + "clause": "the query is closed: `?package=` naming the set's holder answers as the same write without it; a package that does not hold the set → 409 RESOURCE_CONFLICT (`not-held-by-qualifier`, the holder named in details.candidates) with nothing written or saved; any other query parameter, at either door and for every activation type, or a blank or repeated `package` → 400 VALIDATION_ERROR before any lookup", + "oracle": "api", + "verify": "status + code per arm, and the ledger / the clone target read after each refusal", + "evidence": "one line per arm" + }, + { + "clause": "a permission set two packages hold (ADR-0150 D3; a real registry holds one only after #31698 PR-2, so this clause is the pin alone): no `?package=` → 409 RESOURCE_CONFLICT naming both holders; `?package=` a holder → exactly that holder's set (its own ledger row, the other holder's untouched); a ledger row naming no package or a stale package keeps both off and switching one on is 409; a disabled package still counts as a holder; with one holder (a package or the environment) the name's only row is the holder's and the write takes it over; a clone target name two packages hold is taken (409)", + "oracle": "test", + "verify": "run packages/runtime/src/domains/permission-set-package-doors.test.ts with its package's vitest (`pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/domains/permission-set-package-doors.test.ts`); ≥1 test and 0 failed", + "evidence": "the vitest summary line with the subject sha" } ], "traps": [ @@ -4084,13 +4097,15 @@ ], "automated": { "kind": "dogfood", - "ref": "packages/qa/dogfood/test/catalog-activation-door.dogfood.test.ts + packages/qa/dogfood/test/permission-set-clone-door.dogfood.test.ts + packages/runtime/src/domains/catalog-activation-door.test.ts + packages/runtime/src/domains/permission-set-clone.test.ts. Per clause, at the api oracle's layer (in-process HTTP on a booted showcase): acceptance[1] — catalog-activation-door: a declared position switches off 200 with one deployment-level row, the resolver stops granting through it and grants again once it is back on. acceptance[2] — the same file: the audience anchors everyone and guest are refused 400 naming the anchor, with no ledger row; an undeclared name is 404 and writes nothing; a type with no switch is 400. acceptance[3] — permission-set-clone-door: a manage_metadata holder clones a packaged set 200 with the facets and without adminScope / isDefault / packageId; another set's name and the source's own name are 409 RESOURCE_CONFLICT; an unknown source 404; a bad name 400; the closed body (a key missing, or an extra key) 400 VALIDATION_FAILED with nothing saved; a member without manage_metadata 403 PERMISSION_DENIED; an anonymous caller 401. The unit files hold the same arms on the domain handler over fakes. acceptance[0] is the pin run itself" + "ref": "packages/qa/dogfood/test/catalog-activation-door.dogfood.test.ts + packages/qa/dogfood/test/permission-set-clone-door.dogfood.test.ts + packages/runtime/src/domains/catalog-activation-door.test.ts + packages/runtime/src/domains/permission-set-clone.test.ts. Per clause, at the api oracle's layer (in-process HTTP on a booted showcase): acceptance[1] — catalog-activation-door: a declared position switches off 200 with one deployment-level row, the resolver stops granting through it and grants again once it is back on. acceptance[2] — the same file: the audience anchors everyone and guest are refused 400 naming the anchor, with no ledger row; an undeclared name is 404 and writes nothing; a type with no switch is 400. acceptance[3] — permission-set-clone-door: a manage_metadata holder clones a packaged set 200 with the facets and without adminScope / isDefault / packageId; another set's name and the source's own name are 409 RESOURCE_CONFLICT; an unknown source 404; a bad name 400; the closed body (a key missing, or an extra key) 400 VALIDATION_FAILED with nothing saved; a member without manage_metadata 403 PERMISSION_DENIED; an anonymous caller 401. The unit files hold the same arms on the domain handler over fakes. acceptance[0] is the pin run itself. acceptance[4] (the closed query, one holder) and acceptance[5] (two holders): packages/runtime/src/domains/permission-set-package-doors.test.ts, at the domain handler over a stand-in registry (#32164); acceptance[4] is not yet pinned over HTTP on a booted showcase" }, "source": [ "packages/runtime/src/domains/catalog-activation.ts#handleCatalogActivationWrite", "packages/runtime/src/domains/permission-set-clone.ts#handlePermissionSetCloneWrite", + "packages/runtime/src/domains/catalog-activation.ts#planPermissionSetLedgerWrite", "packages/runtime/src/domains/permission-set-clone.ts#PERMISSION_SET_CLONE_DROPPED_KEYS", - "v18 changesets (.changeset/pre/, consumed into 18.0.0-next.*): 15204-s2c-catalog-activation-door, 15204-catalog-activation-environment-authored, 15204-s2b-plugin-sharing-ledger-deactivation, 15204-permission-set-clone-door" + "v18 changesets (.changeset/pre/, consumed into 18.0.0-next.*): 15204-s2c-catalog-activation-door, 15204-catalog-activation-environment-authored, 15204-s2b-plugin-sharing-ledger-deactivation, 15204-permission-set-clone-door", + "#32164 changeset: .changeset/32164-permission-set-doors-take-a-package.md" ], "history": [ { @@ -4110,6 +4125,12 @@ "date": "2026-10-27", "change": "Access-security pin upgrade, slice 3 (#26571; Tier 1 record #26468 scored the item PARTIAL). Pinned over HTTP the arms only the unit layer reached: acceptance[2]'s everyone / guest 400 (catalog-activation-door), and acceptance[3]'s source's-own-name 409, closed-body 400 and anonymous 401 (permission-set-clone-door). No clause or status changed", "ref": "#26571" + }, + { + "revision": 4, + "date": "2026-11-12", + "change": "#32164 (ADR-0150 D3/D4/D5/D8): both doors take `?package=` for a permission set and refuse any other query parameter. Added the steps and acceptance[4] (the closed query and a non-holder, reachable on one holder) and acceptance[5] (two holders, pin only until #31698 PR-2). Earlier clauses unchanged", + "ref": "#32164" } ] }, diff --git a/packages/core/src/security/security-catalog.test.ts b/packages/core/src/security/security-catalog.test.ts index bb5f7910a96..d0f886f766c 100644 --- a/packages/core/src/security/security-catalog.test.ts +++ b/packages/core/src/security/security-catalog.test.ts @@ -381,6 +381,8 @@ describe('security catalog read — permission sets by (package, name) through t if (answer.status === 'refused') { expect(answer.message).toContain(P); expect(answer.message).toContain('declared_set'); + // [#32164] The same candidate, structured. + expect(answer.holders).toEqual([{ kind: 'environment' }]); } expect(await resolveCatalogReference(reader, 'permission', 'nowhere_set', at())).toEqual({ status: 'not-found' }); }); @@ -498,6 +500,17 @@ describe('security catalog read — permission sets by (package, name) through t if (answer.status === 'refused') expect(answer.candidates).toEqual([expect.stringContaining(Q), expect.stringContaining(R)]); }); + it('[#32164] a refusal carries its candidates structured beside the display strings, in the same order', async () => { + const reader = createSecurityCatalogReader({ registry: stored(), metadata: metadata({}) }); + const answer = await resolveCatalogReference(reader, 'permission', 'shared'); + expect(answer.status).toBe('refused'); + if (answer.status !== 'refused') return; + expect(answer.holders).toEqual([{ kind: 'package', packageId: Q }, { kind: 'package', packageId: R }]); + expect(answer.candidates).toEqual([`package "${Q}"`, `package "${R}"`]); + // A resolution that is not a refusal carries no holders member. + expect(await resolveCatalogReference(reader, 'permission', 'q_only')).not.toHaveProperty('holders'); + }); + it('a null column with one holder resolves by D3, as today; a writer\'s package is the D3 caller (R3)', async () => { const r = stored(); const reader = createSecurityCatalogReader({ registry: r, metadata: metadata({}) }); diff --git a/packages/core/src/security/security-catalog.ts b/packages/core/src/security/security-catalog.ts index 124dc9eb62f..fe434418a4b 100644 --- a/packages/core/src/security/security-catalog.ts +++ b/packages/core/src/security/security-catalog.ts @@ -329,8 +329,19 @@ export type SecurityCatalogResolution = | { readonly status: 'refused'; readonly reason: string; + /** Every candidate, each as one display string (`package "com.acme.crm"`) — what a report prints. */ readonly candidates: readonly string[]; readonly message: string; + /** + * [ADR-0150 D3/D5, #32164] The same candidates, structured, in the same + * order — what a door answers a `409 RESOURCE_CONFLICT` with + * (`candidates: [{ kind: 'package', packageId }]`, the shape `/actions` + * and the activation door's declaration types answer), so no caller + * parses a display string back into a package id. Every refusal + * {@link createSecurityCatalogReader} builds carries it; optional so a + * hand-made reader's refusal stays well-typed without it. + */ + readonly holders?: readonly PackageScopedHolder[]; }; /** The catalog read. Its members answer the same question, so they never disagree. */ @@ -621,6 +632,7 @@ export function createSecurityCatalogReader(sources: SecurityCatalogSources): Se reason: outcome.reason, candidates: outcome.candidates.map(describePackageScopedHolder), message: outcome.message, + holders: outcome.candidates, }; } if (outcome.status === 'resolved') { @@ -651,6 +663,7 @@ export function createSecurityCatalogReader(sources: SecurityCatalogSources): Se reason: refusal.reason, candidates: refusal.candidates.map(describePackageScopedHolder), message: packageScopedRefusalMessage(refusal), + holders: refusal.candidates, }; }; diff --git a/packages/drivers/driver-memory/src/memory-user-permission-set-packageless.test.ts b/packages/drivers/driver-memory/src/memory-user-permission-set-packageless.test.ts index 238b6604656..3899a984c8c 100644 --- a/packages/drivers/driver-memory/src/memory-user-permission-set-packageless.test.ts +++ b/packages/drivers/driver-memory/src/memory-user-permission-set-packageless.test.ts @@ -89,6 +89,21 @@ describe('[#32164] driver-memory and the grant key that gained its package colum expect(await now.count('sys_user_permission_set')).toBe(2); }); + // [#32164, red-line review E2] The driver alone, and every driver alike: + // a packaged grant beside a package-less one of the same set, user and + // organization is admitted, where the old key refused it. The engine's write + // seam refuses that row above the driver (`plugin-security`'s + // `stored-permission-set-package-stamp.ts`); this pin names the driver's own + // answer, so a later guard turns it red. + it('the driver alone admits a packaged grant beside a package-less one, where the old key refused it', async () => { + expect(await lands(old, { id: 'n', permission_set_package: null, organization_id: 'org_1' })).toBe(true); + expect(await lands(old, { id: 'm', permission_set_package: 'com.acme.crm', organization_id: 'org_1' })).toBe(false); + + expect(await lands(now, { id: 'n', permission_set_package: null, organization_id: 'org_1' })).toBe(true); + expect(await lands(now, { id: 'm', permission_set_package: 'com.acme.crm', organization_id: 'org_1' })).toBe(true); + expect(await now.count('sys_user_permission_set')).toBe(2); + }); + it('CONTROL — a NULL organization was exempt under the old key too', async () => { expect(await lands(old, { id: 'z1', permission_set_package: null, organization_id: null })).toBe(true); expect(await lands(old, { id: 'z2', permission_set_package: null, organization_id: null })).toBe(true); diff --git a/packages/drivers/driver-mongodb/src/mongodb-user-permission-set-packageless.test.ts b/packages/drivers/driver-mongodb/src/mongodb-user-permission-set-packageless.test.ts index 660af353db7..51cf46afbe8 100644 --- a/packages/drivers/driver-mongodb/src/mongodb-user-permission-set-packageless.test.ts +++ b/packages/drivers/driver-mongodb/src/mongodb-user-permission-set-packageless.test.ts @@ -242,12 +242,18 @@ describe.skipIf(!sharedMongod)('the package-less grant index — against a real expect(await outcome(() => coll(driver).insertOne(grant('f', { organization_id: 'org_1', permission_set_package: 'com.acme.crm' })))).toBe(11000); }); - it('admits nothing the old key refused, with a non-null and a missing organization (epic condition 1)', async () => { + // [#32164, red-line review E2] The last two rows: what the store alone + // admits that the old key refused, a packaged grant beside a package-less + // one; the engine's write seam refuses it above the store + // (`plugin-security`'s `stored-permission-set-package-stamp.ts`). + it('among package-less grants admits nothing the old key refused, with a non-null and a missing organization (epic condition 1); the store alone admits a packaged grant beside a package-less one', async () => { const rows: Array<[string, Record]> = [ ['n1', { organization_id: 'org_2' }], ['n2', { organization_id: 'org_2' }], ['z1', {}], ['z2', {}], + ['m1', { organization_id: 'org_2', permission_set_package: 'com.acme.crm' }], + ['m2', { organization_id: 'org_2', permission_set_package: 'com.acme.crm' }], ]; const answers: Array<{ id: string; old: 'ok' | number; now: 'ok' | number }> = []; for (const [id, extra] of rows) { @@ -263,6 +269,8 @@ describe.skipIf(!sharedMongod)('the package-less grant index — against a real // Both keys exempt a grant missing its organization (NULL-distinct, #29278). { id: 'z1', old: 'ok', now: 'ok' }, { id: 'z2', old: 'ok', now: 'ok' }, + { id: 'm1', old: 11000, now: 'ok' }, + { id: 'm2', old: 11000, now: 11000 }, ]); }); }); diff --git a/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.live-mysql.test.ts b/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.live-mysql.test.ts index 231589a2f56..72d42213cf5 100644 --- a/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.live-mysql.test.ts +++ b/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.live-mysql.test.ts @@ -130,17 +130,24 @@ describe.skipIf(!MYSQL_URL)('grant package-less index on a LIVE MySQL / MariaDB' expect(log.error).not.toHaveBeenCalled(); }); - it('admits nothing the old key refused, with a non-null and a null organization (epic condition 1)', async () => { + // [#32164, red-line review E2] The last row: what the store alone + // admits that the old key refused, a packaged grant beside a package-less + // one; the engine's write seam refuses it above the store + // (`plugin-security`'s `stored-permission-set-package-stamp.ts`). + it('among package-less grants admits nothing the old key refused, with a non-null and a null organization (epic condition 1); the store alone admits a packaged grant beside a package-less one', async () => { expect(await ensureUserPermissionSetPackagelessIndex(exec, quietLogger(), { client: 'mysql2' })).toEqual({ status: 'created' }); - const rows: Array<[string, string | null]> = [ - ['n1', 'org_1'], - ['n2', 'org_1'], - ['z1', null], - ['z2', null], + const rows: Array<[string, string | null, string | null]> = [ + ['n1', null, 'org_1'], + ['n2', null, 'org_1'], + ['z1', null, null], + ['z2', null, null], + // The fixture builds the guard alone, not the declared key, so only + // the packaged row beside n1 is read here. + ['m1', 'com.acme.crm', 'org_1'], ]; const answers: Array<{ id: string; old: boolean; now: boolean }> = []; - for (const [id, org] of rows) { - answers.push({ id, old: await insertInto(OLD_KEY_TABLE, id, null, org), now: await insert(id, null, org) }); + for (const [id, pkg, org] of rows) { + answers.push({ id, old: await insertInto(OLD_KEY_TABLE, id, pkg, org), now: await insert(id, pkg, org) }); } expect(answers).toEqual([ { id: 'n1', old: true, now: true }, @@ -149,6 +156,7 @@ describe.skipIf(!MYSQL_URL)('grant package-less index on a LIVE MySQL / MariaDB' // key admitted a second platform-wide grant, and so does this index. { id: 'z1', old: true, now: true }, { id: 'z2', old: true, now: true }, + { id: 'm1', old: false, now: true }, ]); }); diff --git a/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.live-postgres.test.ts b/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.live-postgres.test.ts index 0012923dcad..4f0e06f2c58 100644 --- a/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.live-postgres.test.ts +++ b/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.live-postgres.test.ts @@ -164,17 +164,23 @@ describe.skipIf(!PG_URL)('grant package-less index on a LIVE PostgreSQL', () => } }); - it('admits nothing the old key refused, with a non-null and a null organization (epic condition 1)', async () => { + // [#32164, red-line review E2] The last two rows: what the store alone + // admits that the old key refused, a packaged grant beside a package-less + // one; the engine's write seam refuses it above the store + // (`plugin-security`'s `stored-permission-set-package-stamp.ts`). + it('among package-less grants admits nothing the old key refused, with a non-null and a null organization (epic condition 1); the store alone admits a packaged grant beside a package-less one', async () => { expect(await ensureUserPermissionSetPackagelessIndex(exec, quietLogger(), { client: 'pg' })).toEqual({ status: 'created' }); - const rows: Array<[string, string | null]> = [ - ['n1', 'org_1'], - ['n2', 'org_1'], - ['z1', null], - ['z2', null], + const rows: Array<[string, string | null, string | null]> = [ + ['n1', null, 'org_1'], + ['n2', null, 'org_1'], + ['z1', null, null], + ['z2', null, null], + ['m1', 'com.acme.crm', 'org_1'], + ['m2', 'com.acme.crm', 'org_1'], ]; const answers: Array<{ id: string; old: boolean; now: boolean }> = []; - for (const [id, org] of rows) { - answers.push({ id, old: await insertInto(OLD_KEY_TABLE, id, null, org), now: await insert(id, null, org) }); + for (const [id, pkg, org] of rows) { + answers.push({ id, old: await insertInto(OLD_KEY_TABLE, id, pkg, org), now: await insert(id, pkg, org) }); } expect(answers).toEqual([ { id: 'n1', old: true, now: true }, @@ -183,6 +189,8 @@ describe.skipIf(!PG_URL)('grant package-less index on a LIVE PostgreSQL', () => // the old key admitted a second platform-wide grant, and so does this index. { id: 'z1', old: true, now: true }, { id: 'z2', old: true, now: true }, + { id: 'm1', old: false, now: true }, + { id: 'm2', old: false, now: false }, ]); }); diff --git a/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.test.ts b/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.test.ts index 549edb025ec..6df17f78d35 100644 --- a/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.test.ts +++ b/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.test.ts @@ -130,11 +130,17 @@ describe('sys_user_permission_set: one package-less grant per (user_id, permissi }); /** - * Epic condition 1: nothing the old key refused is admitted. Measured side by - * side over the same rows, with a null and a non-null organization: the old + * Epic condition 1, measured side by side over the same rows, with a null + * and a non-null organization: among grants that name no package, the old * three-column key and the new key plus this index answer every row alike. + * + * [#32164, red-line review E2] What the store alone admits that the old key + * refused: a grant naming a package beside one naming none, for one user, + * set and organization. The engine's write seam refuses that row above the + * store (`plugin-security`'s `stored-permission-set-package-stamp.ts`); + * this pin names the store's own answer, so a later guard turns it red. */ - it('admits nothing the old key refused, with a non-null and a null organization (epic condition 1)', async () => { + it('among package-less grants admits nothing the old key refused, with a non-null and a null organization (epic condition 1); the store alone admits a packaged grant beside a package-less one', async () => { const old = new DatabaseSync(':memory:'); try { createTable(old, OLD_INDEX_DDL); @@ -146,6 +152,8 @@ describe('sys_user_permission_set: one package-less grant per (user_id, permissi ['n2', null, 'org_1'], // a second package-less grant in one organization ['z1', null, null], ['z2', null, null], // a second package-less platform-wide grant + ['m1', 'com.acme.crm', 'org_1'], // a packaged grant beside n1 + ['m2', 'com.acme.crm', 'org_1'], // that package twice ]; const answers = rows.map(([id, pkg, org]) => ({ id, old: insertOld(id, pkg, org), now: insert(id, pkg, org) })); @@ -156,6 +164,9 @@ describe('sys_user_permission_set: one package-less grant per (user_id, permissi // the second platform-wide grant, and so does this index — no new admission. { id: 'z1', old: true, now: true }, { id: 'z2', old: true, now: true }, + // The store alone: admitted beside n1, where the old key refused it. + { id: 'm1', old: false, now: true }, + { id: 'm2', old: false, now: false }, ]); } finally { old.close(); diff --git a/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.ts b/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.ts index 5e1bb8ae315..5d8d428b95b 100644 --- a/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.ts +++ b/packages/metadata-protocol/src/migrations/user-permission-set-packageless-index.ts @@ -7,19 +7,16 @@ * * ## What is broken without it * - * A permission set is identified by `(package, name)` (ADR-0150 D4), so - * ADR-0150 gives the grant the key `(user_id, permission_set, - * permission_set_package, organization_id)`: one user may hold both packages' - * sets of one name in one organization. `permission_set_package` is NULL on - * every grant of a set the environment authored, the platform registered, or - * two packages hold with no binding yet (the column's documented "empty", never - * a sentinel), and a SQL UNIQUE treats NULLs as distinct, so for exactly those - * grants that key constrains nothing. The key it replaces, `(user_id, - * permission_set, organization_id)`, holds them to one. Two of them would grant - * the same set twice, and a revoke that deletes one would leave the other - * granting. This index lands before the grant's declared key is widened; while - * the declared key is still the three-column one, that key refuses everything - * this index would. + * A permission set is identified by `(package, name)` (ADR-0150 D4), so the + * grant's declared key is `(user_id, permission_set, permission_set_package, + * organization_id)`: one user may hold both packages' sets of one name in one + * organization. `permission_set_package` is NULL on every grant of a set the + * environment authored, the platform registered, or two packages hold with no + * binding yet (the column's documented "empty", never a sentinel), and a SQL + * UNIQUE treats NULLs as distinct, so for exactly those grants the declared key + * constrains nothing. The key it replaced, `(user_id, permission_set, + * organization_id)`, held them to one. Two of them would grant the same set + * twice, and a revoke that deletes one would leave the other granting. * * ## Why THIS route * diff --git a/packages/plugins/plugin-security/src/agent-account-grant-refusal.test.ts b/packages/plugins/plugin-security/src/agent-account-grant-refusal.test.ts index d5e9bcba4c0..861813b4ca9 100644 --- a/packages/plugins/plugin-security/src/agent-account-grant-refusal.test.ts +++ b/packages/plugins/plugin-security/src/agent-account-grant-refusal.test.ts @@ -24,7 +24,7 @@ import { SqlDriver } from '@objectstack/driver-sql'; import { resolveThrownHttpError } from '@objectstack/types'; import type { PermissionSet } from '@objectstack/spec/security'; import { SysUser } from '@objectstack/platform-objects/identity'; -import { bindSecurityCatalogReader } from '@objectstack/core'; +import { bindSecurityCatalogReader, createSecurityCatalogReader } from '@objectstack/core'; import { SecurityPlugin } from './security-plugin.js'; import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; @@ -206,6 +206,23 @@ describe('[ADR-0151 D3] a set above the agent ceiling is refused for an AI servi expect((await rows(h, 'sys_user_position', { user_id: 'u_bot' })).map((r) => r.position)).toEqual([SAFE_POSITION]); }); + // [#32164, contract review 6817263634 should-fix A] The one-grant check runs after this refusal. + // BASE (ec39bd8e5): it answered first, 409 DUPLICATE_RECORD. CONTROL: within the ceiling it is the check's 409. + it('[#32164] the account already holds the breaching set: a second grant of it is refused for the ceiling (400), not as a second grant', async () => { + const h = await boot(); + await h.engine.insert('sys_user_permission_set', { id: 'held', user_id: 'u_bot', permission_set: BREACHING_SET, organization_id: ORG }, { context: SYS }); + expectAccountRefusal(await refusalOf(() => grant(h, 'u_bot', BREACHING_SET)), 'permission_set', BREACHING_SET); + const person: any = await grant(h, 'u_person', BREACHING_SET); + expectAccountRefusal(await refusalOf(() => h.engine.update( + 'sys_user_permission_set', { id: person.id, user_id: 'u_bot' }, { context: PLATFORM_ADMIN } as any, + )), 'permission_set', BREACHING_SET); + expect((await rows(h, 'sys_user_permission_set', { user_id: 'u_bot' })).map((r) => r.id)).toEqual(['held']); + + // CONTROL: within the ceiling, the second grant is the one-grant check's refusal. + await h.engine.insert('sys_user_permission_set', { id: 'held_safe', user_id: 'u_bot', permission_set: SAFE_SET, organization_id: ORG }, { context: SYS }); + expect(envelopeOf(await refusalOf(() => grant(h, 'u_bot', SAFE_SET)))).toMatchObject({ status: 409, code: 'DUPLICATE_RECORD' }); + }); + it('CONTROL: a person is assigned the breaching set and the breaching position, as before', async () => { const h = await boot(); await grant(h, 'u_person', BREACHING_SET); @@ -271,3 +288,116 @@ describe('[ADR-0151 D3] a set above the agent ceiling is refused for an AI servi expect(warn.mock.calls[0]?.[0]).toContain('is NOT refused'); }); }); + +/** + * [#32164, red-line review E3] The set an account would hold is read the way + * the authorization resolver reads the row: a grant at the package it stores + * (ADR-0150 D8 R1), a position's sets from the package that declared the + * position (ADR-0150 D3/D7). A read the rule refuses (two holders, none + * placed) fails closed. BASE: the bare name was read, two holders refused it, + * and a refused read answered no breach, so either holder's set was admitted. + */ +describe('[E3] two packages hold one name: the account is judged on the set it would hold', () => { + const CRM = 'com.acme.crm'; + const HR = 'com.acme.hr'; + /** CRM's set of this name is within the ceiling, HR's is above it. */ + const TWO = 'qa_shared_lead'; + const def = (name: string, packageId: string, breaching: boolean) => ({ + name, + label: name, + objects: { crm_lead: breaching ? { allowRead: true, viewAllRecords: true } : { allowRead: true, allowEdit: true } }, + _packageId: packageId, + }); + /** Each package's position binding `TWO` by name, read from its own package. */ + const CRM_POSITION = 'crm_lead_clerk'; + const HR_POSITION = 'hr_lead_chief'; + + function standIn(opts: { hrBreaches: boolean }) { + const sets: Record> = { + [CRM]: def(TWO, CRM, false), + [HR]: def(TWO, HR, opts.hrBreaches), + }; + const positions: Record> = { + [CRM_POSITION]: { name: CRM_POSITION, label: CRM_POSITION, permissionSets: [TWO], _packageId: CRM }, + [HR_POSITION]: { name: HR_POSITION, label: HR_POSITION, permissionSets: [TWO], _packageId: HR }, + }; + const manifests = [CRM, HR].map((id) => ({ manifest: { id, namespace: id.split('.').pop() } })); + return { + getItem: (type: string, name: string) => + type === 'permission' ? (name === TWO ? sets[CRM] : undefined) : type === 'position' ? positions[name] : undefined, + listItems: (type: string) => (type === 'permission' ? [sets[CRM], sets[HR]] : type === 'position' ? Object.values(positions) : []), + isPackageDisabled: () => false, + packageScopedHoldersOf: (type: string, name: string) => (type === 'permission' && name === TWO ? [CRM, HR] : []), + getPackageScopedItem: (type: string, name: string, packageId: string) => + type === 'permission' && name === TWO ? sets[packageId] : undefined, + getEnvironmentScopedItem: () => undefined, + getArtifactItem: (type: string, name: string, packageId: string) => + type === 'position' && positions[name]?._packageId === packageId ? positions[name] : undefined, + getPackage: (id: string) => manifests.find((m) => m.manifest.id === id), + getAllPackages: () => manifests, + bareNameHoldersAreSealed: true, + }; + } + + function handlers(opts: { hrBreaches: boolean }) { + const bound: Record Promise> = {}; + const engine = { + registerHook: (event: string, handler: any) => { bound[event] = handler; }, + find: vi.fn(async () => [{ id: 'u_bot', principal_kind: 'agent' }]), + getSchema: (name: string) => ({ name }), + }; + bindSecurityCatalogReader(engine, createSecurityCatalogReader({ + registry: standIn(opts) as never, + metadata: { get: async () => undefined, list: async () => [] }, + })); + expect(registerAgentAccountGrantRefusal(engine)).toBe(true); + return bound; + } + + const ctxOf = (object: string, data: Record, previous?: Record) => ({ + object, + session: { userId: 'u_caller' }, + input: { data, ...(previous ? { id: previous.id } : {}) }, + ...(previous ? { previous } : {}), + api: { object: () => ({ find: async () => [{ id: 'u_bot' }] }) }, + }); + + it('a grant naming the package whose set breaches is refused; naming the one within the ceiling is admitted', async () => { + const h = handlers({ hrBreaches: true }); + const refused = await refusalOf(() => + h.beforeInsert!(ctxOf('sys_user_permission_set', { user_id: 'u_bot', permission_set: TWO, permission_set_package: HR }))); + const env = expectAccountRefusal(refused, 'permission_set', TWO); + expect(env.fields[0].message).toContain('objects.crm_lead.viewAllRecords'); + await expect(h.beforeInsert!(ctxOf('sys_user_permission_set', { user_id: 'u_bot', permission_set: TWO, permission_set_package: CRM }))) + .resolves.toBeUndefined(); + }); + + it('an update keeps the stored package: moving an HR grant onto the account is refused, a CRM grant is admitted', async () => { + const h = handlers({ hrBreaches: true }); + const hrRow = { id: 'g1', user_id: 'u_person', permission_set: TWO, permission_set_package: HR }; + expectAccountRefusal( + await refusalOf(() => h.beforeUpdate!(ctxOf('sys_user_permission_set', { user_id: 'u_bot' }, hrRow))), + 'permission_set', TWO, + ); + const crmRow = { ...hrRow, id: 'g2', permission_set_package: CRM }; + await expect(h.beforeUpdate!(ctxOf('sys_user_permission_set', { user_id: 'u_bot' }, crmRow))).resolves.toBeUndefined(); + }); + + it('a grant whose read the rule refuses (no package placed) fails closed: refused when either holder\'s set breaches; CONTROL: admitted when neither does', async () => { + const refused = await refusalOf(() => + handlers({ hrBreaches: true }).beforeInsert!(ctxOf('sys_user_permission_set', { user_id: 'u_bot', permission_set: TWO }))); + expectAccountRefusal(refused, 'permission_set', TWO); + await expect(handlers({ hrBreaches: false }).beforeInsert!(ctxOf('sys_user_permission_set', { user_id: 'u_bot', permission_set: TWO }))) + .resolves.toBeUndefined(); + }); + + it('a position binding the name is judged on its own package\'s set: HR\'s position refused, CRM\'s admitted', async () => { + const h = handlers({ hrBreaches: true }); + const env = expectAccountRefusal( + await refusalOf(() => h.beforeInsert!(ctxOf('sys_user_position', { user_id: 'u_bot', position: HR_POSITION }))), + 'position', HR_POSITION, + ); + expect(env.fields[0].message).toContain(`'${TWO}'`); + await expect(h.beforeInsert!(ctxOf('sys_user_position', { user_id: 'u_bot', position: CRM_POSITION }))).resolves.toBeUndefined(); + }); +}); diff --git a/packages/plugins/plugin-security/src/agent-account-grant-refusal.ts b/packages/plugins/plugin-security/src/agent-account-grant-refusal.ts index 351cf8c3a65..0a829dae02a 100644 --- a/packages/plugins/plugin-security/src/agent-account-grant-refusal.ts +++ b/packages/plugins/plugin-security/src/agent-account-grant-refusal.ts @@ -21,9 +21,15 @@ * * - `sys_user_permission_set`: the set the row holds AFTER the write (the * payload's `permission_set`, else the stored one), read the way every - * by-name grant reader reads it (`grantSetNameOf`); + * by-name grant reader reads it (`grantSetNameOf`), at the package the row + * stores (`permission_set_package`, ADR-0150 D8 R1); * - `sys_user_position`: every set the position the row holds after the - * write binds in its catalog definition. + * write binds in its catalog definition, each read from that position + * (ADR-0150 D3), as the authorization resolver reads it. + * + * [#32164] A set read the rule refuses (two holders, none placed) fails + * closed: every holder of the name the catalog serves is judged, and a breach + * of any refuses the write. * * For an INSERT (one dispatch per row) and an UPDATE (one dispatch per * matched row, with that row's stored image as `previous`). The holder is the @@ -66,7 +72,15 @@ * code (ADR-0112). */ -import { isAgentAccountRow, securityCatalogReaderOf, type SecurityCatalogReader } from '@objectstack/core'; +import { + isAgentAccountRow, + resolveCatalogReference, + securityCatalogReaderOf, + storedPermissionSetScope, + type SecurityCatalogEntry, + type SecurityCatalogReader, + type SecurityCatalogReferenceScope, +} from '@objectstack/core'; import type { FieldErrorCode } from '@objectstack/spec/api'; import { classifyFilterToken, isPlainRecord } from '@objectstack/spec/data'; import { validationFailure } from '@objectstack/types'; @@ -84,6 +98,8 @@ export const AGENT_ACCOUNT_GRANT_HOOK_PACKAGE = 'plugin-security:agent-account-g const HOOK_PRIORITY = 45; const HOLDER_FIELD = 'user_id'; +/** [ADR-0150 D8 R1] The grant's package column, which the resolver reads the set by. */ +const GRANT_PACKAGE_FIELD = 'permission_set_package'; const USER_OBJECT = 'sys_user'; /** The grant objects judged, each with the column its refusal is at. */ @@ -212,19 +228,36 @@ async function isAgentAccount(engine: AgentAccountGrantEngine, userId: string, t return Array.isArray(rows) && rows.some((r: any) => String(r?.id) === userId && isAgentAccountRow(r)); } -/** The ceiling breaches of the set `name`, per its catalog definition; `[]` when the catalog holds none. */ -async function setBreaches(catalog: SecurityCatalogReader, name: string): Promise { - const entry = await catalog.resolve('permission', name); - return entry ? agentCeilingBreaches(entry.definition) : []; +/** + * The ceiling breaches of the set `name`, read the way the authorization + * resolver reads the reference (`scope`: a grant's stored package column, or + * the position that binds it — ADR-0150 D3/D8), per its catalog definition; + * `[]` when the catalog holds none. + * + * [#32164] A read the rule refuses (two holders, none named) places no set, + * so it fails CLOSED: every holder of the name the catalog serves is judged, + * and a breach of any refuses the write. Before #32164 the bare name was read, + * and a refused read answered no breach. + */ +async function setBreaches(catalog: SecurityCatalogReader, name: string, scope?: SecurityCatalogReferenceScope): Promise { + const answer = await resolveCatalogReference(catalog, 'permission', name, scope); + if (answer.status === 'resolved') return agentCeilingBreaches(answer.entry.definition); + if (answer.status === 'not-found') return []; + const breaches = new Set(); + for (const entry of await catalog.list('permission')) { + if (entry.name !== name) continue; + for (const breach of agentCeilingBreaches(entry.definition)) breaches.add(breach); + } + return [...breaches]; } -/** The sets the position `name` binds that breach the ceiling, per the catalog definitions. */ +/** The sets the position `name` binds that breach the ceiling, each read from the position (ADR-0150 D3), per the catalog definitions. */ async function positionBreachingSets(catalog: SecurityCatalogReader, name: string): Promise { - const entry = await catalog.resolve('position', name); + const entry: SecurityCatalogEntry | undefined = await catalog.resolve('position', name); const bound = Array.isArray(entry?.definition?.permissionSets) ? entry!.definition.permissionSets : []; const out: AgentAccountBreachingSet[] = []; for (const setName of new Set(bound.filter((n): n is string => typeof n === 'string' && n !== ''))) { - const breaches = await setBreaches(catalog, setName); + const breaches = await setBreaches(catalog, setName, entry ? { position: entry } : undefined); if (breaches.length > 0) out.push({ name: setName, breaches }); } return out; @@ -240,6 +273,8 @@ async function judge( const userId = idOf(image[HOLDER_FIELD]); if (userId === undefined) return; const isGrant = ctx.object === GRANT_OBJECT; + // [#32164] The grant is read by the package it stores, as the resolver reads it. + const scope = isGrant ? storedPermissionSetScope(image[GRANT_PACKAGE_FIELD]) : undefined; const value = isGrant ? grantSetNameOf(image) : nameOf(image[POSITION_FIELD]); if (value === undefined) return; const catalog = securityCatalogReaderOf(engine); @@ -252,7 +287,7 @@ async function judge( let breaching: AgentAccountBreachingSet[]; try { breaching = isGrant - ? [{ name: value, breaches: await setBreaches(catalog, value) }].filter((s) => s.breaches.length > 0) + ? [{ name: value, breaches: await setBreaches(catalog, value, scope) }].filter((s) => s.breaches.length > 0) : await positionBreachingSets(catalog, value); } catch (e) { logger?.warn?.( @@ -286,6 +321,13 @@ async function onUpdate(engine: AgentAccountGrantEngine, ctx: any, logger: Logge [HOLDER_FIELD]: hasOwn(data, HOLDER_FIELD) ? (data as any)[HOLDER_FIELD] : previous[HOLDER_FIELD], [valueField]: hasOwn(data, valueField) ? (data as any)[valueField] : previous[valueField], }; + if (ctx.object === GRANT_OBJECT) { + // [#32164] The package the row stores after the write: a re-name's, which + // the package stamp (priority 40) has written by now; otherwise the stored + // one — a caller's own value of the readonly column is stripped. + const renamed = hasOwn(data, valueField) && (data as any)[valueField] !== previous[valueField]; + image[GRANT_PACKAGE_FIELD] = renamed ? (data as any)[GRANT_PACKAGE_FIELD] : previous[GRANT_PACKAGE_FIELD]; + } await judge(engine, ctx, image, logger); } diff --git a/packages/plugins/plugin-security/src/grant-holder-membership-refusal.test.ts b/packages/plugins/plugin-security/src/grant-holder-membership-refusal.test.ts index 5ced75f2355..fb11062ce55 100644 --- a/packages/plugins/plugin-security/src/grant-holder-membership-refusal.test.ts +++ b/packages/plugins/plugin-security/src/grant-holder-membership-refusal.test.ts @@ -25,7 +25,7 @@ import { describe, it, expect, afterEach, vi } from 'vitest'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; -import { resolveThrownHttpError } from '@objectstack/types'; +import { isUniqueViolationError, resolveThrownHttpError } from '@objectstack/types'; import type { PermissionSet } from '@objectstack/spec/security'; import { ORGANIZATION_ADMIN } from '@objectstack/spec/identity'; import { defaultPermissionSets } from './objects/default-permission-sets.js'; @@ -570,6 +570,64 @@ describe('a refused grant holder the caller cannot read is answered as a holder }); } + // [#32164, contract review 6817263634 should-fix A] The one-grant check steps aside on the same holders. + // BASE (ec39bd8e5): it answered first, 409 DUPLICATE_RECORD. CONTROL: a holder the caller reads gets the 409. + describe('[#32164] a holder the caller cannot read that already holds the set: the same one answer, never a 409', () => { + const SET = 'qa_rep_set'; + const held = async (h: Harness, user: string) => h.engine.insert( + 'sys_user_permission_set', { id: `held_${user}`, user_id: user, permission_set: SET, organization_id: ORG_A }, + { context: { isSystem: true, tenantId: ORG_A } } as any, + ); + + it('an insert naming it: one answer in every store, the reference refusal at user_id; nothing new is stored', async () => { + const answers = new Map(); + for (const store of STORES) { + const h = await bootWith(store); + if (store !== 'no such user') await held(h, HOLDER); + answers.set(store, await refusalOf(() => h.engine.insert( + 'sys_user_permission_set', { user_id: HOLDER, permission_set: SET }, { context: OWN_ROW_ADMIN_A } as any, + ))); + expect(await rowsOf(h, 'sys_user_permission_set', { user_id: HOLDER }), store).toHaveLength(store === 'no such user' ? 0 : 1); + } + expectOneHolderAnswer(answers); + }); + + it('an update by id moving a grant onto it: one answer in every store; the stored row is untouched', async () => { + const answers = new Map(); + for (const store of STORES) { + const h = await bootWith(store); + if (store !== 'no such user') await held(h, HOLDER); + await held(h, 'u_member_a'); + answers.set(store, await refusalOf(() => h.engine.update( + 'sys_user_permission_set', { id: 'held_u_member_a', user_id: HOLDER }, { context: OWN_ROW_ADMIN_A } as any, + ))); + const [stored] = await rowsOf(h, 'sys_user_permission_set', { id: 'held_u_member_a' }); + expect(stored?.user_id, store).toBe('u_member_a'); + } + expectOneHolderAnswer(answers); + }); + + it('CONTROL: a holder the caller reads that already holds the set is refused as a second grant: the engine\'s 409 duplicate-record refusal', async () => { + const h = await bootWith('member here'); + await held(h, 'u_member_a'); + const err = await refusalOf(() => h.engine.insert( + 'sys_user_permission_set', { user_id: 'u_member_a', permission_set: SET }, { context: OWN_ROW_MEMBER_A } as any, + )); + expect(envelopeOf(err)).toMatchObject({ status: 409, code: 'DUPLICATE_RECORD' }); + expect(isUniqueViolationError(err)).toBe(true); + expect(await rowsOf(h, 'sys_user_permission_set', { user_id: 'u_member_a' })).toHaveLength(1); + }); + + it('one partial batch: each row is judged on the holder it names, as written; a readable non-member is refused on membership, nothing stored', async () => { + const h = await bootWith('member elsewhere'); + const rows = [' u_admin_a', 'u_admin_a'].map((user_id) => ({ user_id, permission_set: SET })); + const err = await refusalOf(() => (h.engine as any).insertMany('sys_user_permission_set', rows, { context: OWN_ROW_ADMIN_A })); + expectMembershipRefusal(err); + expect(envelopeOf(err).fields[0]?.constraint?.target).toBe('sys_member'); + expect(await rowsOf(h, 'sys_user_permission_set', {})).toEqual([]); + }); + }); + it("a holder the caller cannot read is read only through the caller's own door, projected to its id, and no membership is read for it", async () => { for (const store of STORES) { const h = await bootWith(store); diff --git a/packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts b/packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts index 7353ee5aaaa..5fb1604e101 100644 --- a/packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts +++ b/packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts @@ -327,7 +327,7 @@ function memoOf(store: WeakMap>, ctx: any): Map, object: string): boolean { if (typeof engine.getSchema !== 'function') return false; const def = (engine.getSchema(object) as { fields?: Record } | undefined)?.fields?.[HOLDER_FIELD]; if (!def || def.readonly === true) return false; @@ -361,10 +361,12 @@ async function callerReadsHolder(ctx: any, holder: unknown, userId: string): Pro /** * Is `holder` — a value this write NAMES — one the caller cannot read? Then * the engine's reference check answers it, and this hook judges nothing for - * it (see *A holder the caller cannot read*). + * it (see *A holder the caller cannot read*). Exported for the grant's + * one-grant check (`stored-permission-set-package-stamp.ts`), which steps + * aside on the same holders for the same reason. */ -async function holderLeftToReferenceCheck( - engine: MembershipEngine, +export async function holderLeftToReferenceCheck( + engine: Pick, ctx: any, holder: unknown, userId: string, diff --git a/packages/plugins/plugin-security/src/grant-permission-set-name.test.ts b/packages/plugins/plugin-security/src/grant-permission-set-name.test.ts index 4c1894a0b52..4a2ba7347d1 100644 --- a/packages/plugins/plugin-security/src/grant-permission-set-name.test.ts +++ b/packages/plugins/plugin-security/src/grant-permission-set-name.test.ts @@ -7,11 +7,14 @@ * as an undeclared field; a non-system write naming a set the security * catalog does not hold is refused, and a grant that carries no name is * refused as `required`. One grant per user, set and organization: the - * declared unique index (`unique: 'organization'`) refuses a second on every - * write path, so a revoke leaves no grant of that set in force. Its - * organization key part is the plain column since ADR-0131 D1 (the tenant - * column is NOT NULL), so on the pre-18 nullable column this harness models a - * grant with no organization is exempt, like a NULL in any key part. + * declared key `(user_id, permission_set, permission_set_package, + * organization_id)` (`unique: 'global'`, ADR-0150 D4) and, for the grants that + * name no package, the package-less guard `metadata-protocol` builds at + * schema sync (#32164) refuse a second on every write path, so a revoke + * leaves no grant of that set in force. The organization key part is the plain + * column since ADR-0131 D1 (the tenant column is NOT NULL), so on the pre-18 + * nullable column this harness models a grant with no organization is exempt, + * like a NULL in any key part. * * Measured on a REAL `ObjectQL` engine over a real SQL driver with the REAL * `SecurityPlugin` started on it the way a kernel composition does, because @@ -44,6 +47,10 @@ import { registerGrantPermissionSetNameHooks, } from './grant-permission-set-name.js'; import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js'; +import { + ensureUserPermissionSetPackagelessIndex, + resolveUserPermissionSetIndexSeam, +} from '@objectstack/metadata-protocol'; import { provisionRigUsers } from './__tests__/rig-users.testkit.js'; // --------------------------------------------------------------------------- @@ -395,8 +402,20 @@ describe('a system writer', () => { // One grant per user, set and organization (seat answers on #15211: Q5 A, Q-S3a) // --------------------------------------------------------------------------- -describe('one grant per user, set and organization — the declared unique \'organization\' index', () => { +describe('one grant per user, set and organization — the declared key and the package-less guard', () => { const ORG = 'org_dup'; + /** + * The harness with the package-less guard built as the schema-sync + * migration builds it (#32164). The catalog here is the environment's, so + * every grant names no package and the guard is what keeps them to one. + */ + const bootGuarded = async (): Promise => { + const h = await boot(); + const seam = resolveUserPermissionSetIndexSeam(h.engine); + expect(await ensureUserPermissionSetPackagelessIndex(seam?.exec, h.ctx.logger, { client: seam?.client })) + .toEqual({ status: 'created' }); + return h; + }; const grantsOfSet = async (h: Harness, userId: string, set: string) => (await grantsOf(h, userId)).filter((g) => g.permission_set === set); /** The engine's envelope, and what the data doors answer it with on the wire. */ @@ -408,7 +427,7 @@ describe('one grant per user, set and organization — the declared unique \'org const knexOf = (h: Harness): any => (h.engine as any).getDriver('sys_user_permission_set').knex; it('NEGATIVE — a second organization-scoped grant is refused 409 (UNIQUE_VIOLATION on the wire); the revoke of the one leaves none in force', async () => { - const h = await boot(); + const h = await bootGuarded(); await h.engine.insert('sys_member', { id: 'mem_d1', user_id: 'u_d1', organization_id: ORG, role: 'member' }, { context: SYS } as any); await h.engine.insert('sys_user_permission_set', { id: 'ups_d1', user_id: 'u_d1', permission_set: 'qa_alpha', organization_id: ORG }, { context: ADMIN } as any); const err = await refusalOf(() => h.engine.insert( @@ -421,15 +440,30 @@ describe('one grant per user, set and organization — the declared unique \'org expect(await grantsOfSet(h, 'u_d1', 'qa_alpha')).toEqual([]); }); - it('a second grant with no organization is NOT refused by the index on a pre-18 nullable column: the plain organization key part exempts it (ADR-0131 D1)', async () => { + // [#32164, red-line review E2] Through the engine the write seam's + // one-grant check refuses the second grant whatever the store's indexes + // are; below the engine the declared key alone admits it. + it('CONTROL — without the guard (driver-memory\'s declared limit; a SQL table before its guard is built): the engine refuses a second package-less grant (the one-grant check), the declared key alone admits it below the engine', async () => { const h = await boot(); + await h.engine.insert('sys_member', { id: 'mem_g1', user_id: 'u_d1', organization_id: ORG, role: 'member' }, { context: SYS } as any); + await h.engine.insert('sys_user_permission_set', { id: 'ups_g1', user_id: 'u_d1', permission_set: 'qa_alpha', organization_id: ORG }, { context: ADMIN } as any); + const err = await refusalOf(() => h.engine.insert( + 'sys_user_permission_set', { id: 'ups_g2', user_id: 'u_d1', permission_set: 'qa_alpha', organization_id: ORG }, { context: SYS } as any, + )); + expect(duplicateShape(err)).toEqual(DUPLICATE); + await knexOf(h)('sys_user_permission_set').insert({ id: 'ups_g2', user_id: 'u_d1', permission_set: 'qa_alpha', organization_id: ORG }); + expect((await grantsOfSet(h, 'u_d1', 'qa_alpha')).map((g) => g.permission_set_package)).toEqual([null, null]); + }); + + it('a second grant with no organization is NOT refused by the index on a pre-18 nullable column: the plain organization key part exempts it (ADR-0131 D1)', async () => { + const h = await bootGuarded(); await h.engine.insert('sys_user_permission_set', { id: 'ups_p1', user_id: 'u_p1', permission_set: 'qa_alpha', organization_id: null }, { context: ADMIN } as any); await knexOf(h)('sys_user_permission_set').insert({ id: 'ups_p2', user_id: 'u_p1', permission_set: 'qa_alpha', organization_id: null }); expect((await grantsOfSet(h, 'u_p1', 'qa_alpha')).map((g) => g.id).sort()).toEqual(['ups_p1', 'ups_p2']); }); it('NEGATIVE — the index refuses an organization duplicate on paths no hook sees: a two-row batch insert stores nothing, and raw SQL beneath the engine is refused', async () => { - const h = await boot(); + const h = await bootGuarded(); await h.engine.insert('sys_member', { id: 'mem_b1', user_id: 'u_b1', organization_id: ORG, role: 'member' }, { context: SYS } as any); const err = await refusalOf(() => h.engine.insert( 'sys_user_permission_set', @@ -450,7 +484,7 @@ describe('one grant per user, set and organization — the declared unique \'org }); it('NEGATIVE — an update that makes an organization duplicate (re-naming the set) is refused 409 and the row is untouched', async () => { - const h = await boot(); + const h = await bootGuarded(); await h.engine.insert('sys_member', { id: 'mem_u1', user_id: 'u_u1', organization_id: ORG, role: 'member' }, { context: SYS } as any); await h.engine.insert('sys_user_permission_set', { id: 'ups_u1', user_id: 'u_u1', permission_set: 'qa_alpha', organization_id: ORG }, { context: ADMIN } as any); await h.engine.insert('sys_user_permission_set', { id: 'ups_u2', user_id: 'u_u1', permission_set: 'qa_beta', organization_id: ORG }, { context: ADMIN } as any); @@ -462,7 +496,7 @@ describe('one grant per user, set and organization — the declared unique \'org }); it('CONTROL — one set to one user in two organizations and platform-wide, two users of one set (a batch and raw SQL alike), and an edit of a held grant all land', async () => { - const h = await boot(); + const h = await bootGuarded(); for (const org of ['org_c1', 'org_c2']) { await h.engine.insert('sys_member', { id: `mem_${org}`, user_id: 'u_c1', organization_id: org, role: 'member' }, { context: SYS } as any); await h.engine.insert('sys_user_permission_set', { user_id: 'u_c1', permission_set: 'qa_alpha', organization_id: org }, { context: ADMIN } as any); diff --git a/packages/plugins/plugin-security/src/grant-permission-set-name.ts b/packages/plugins/plugin-security/src/grant-permission-set-name.ts index 6caced92d8a..441fa77ce5d 100644 --- a/packages/plugins/plugin-security/src/grant-permission-set-name.ts +++ b/packages/plugins/plugin-security/src/grant-permission-set-name.ts @@ -31,6 +31,34 @@ * - an UPDATE whose payload carries `permission_set` with a value other than * the one the matched row already stores (an echo is not a new name). * + * ## A name two packages hold, and a grant that names its package (ADR-0150 D3/D5, #32164) + * + * A permission set is identified by `(package, name)` (ADR-0150 D4), so after + * the narrowing two packages may each ship a set of one name. Asked with no + * package, that name is the D3 refusal: the catalog picks neither. That is an + * answer about the name — two sets, nothing picked — never "no such set", so it + * is refused as what it is: `409 RESOURCE_CONFLICT`, core's + * `PackageScopedNameRefusedError`, whose sentence names every candidate. + * (The data door carries that sentence and not yet the structured candidates: + * #32250.) + * + * An INSERT may name the package beside the name, in the grant's own + * `permission_set_package` column (ADR-0150 D8 row R1). The grant then holds + * exactly that package's set: + * + * - the package holds the name ⇒ accepted, whatever any other package holds; + * - it does not ⇒ refused `409 RESOURCE_CONFLICT`, reason + * `not-held-by-qualifier`, naming the holders (the D5 sentence the exact + * `/meta` qualifier answers) — at any holder count, so a writer is never + * moved to another package's set behind its back (epic red line 1; the + * stamp seam refuses the same write, `stored-permission-set-package-stamp.ts`); + * - nothing holds the name at all ⇒ the `400` below, as for a grant naming no + * package. + * + * An UPDATE is judged by its name alone: the engine strips a non-system + * caller's value of the `readonly` column after the before-phase, so the + * package a non-system update sends is never stored and never judged. + * * The predicate is the one `position-catalog-refusal.ts` applies to * `sys_user_position.position`: a DEACTIVATED set is still a set, so a grant * naming it is accepted and stops granting through the activation ledger. @@ -73,12 +101,19 @@ * * ## One grant per user, set and organization * - * Not judged here. The declared unique index (`user_id`, `permission_set`, - * `organization_id`) is `unique: 'organization'`, whose organization key part - * is NULL-safe (ADR-0120 D3), so it refuses a second grant of one set to one - * user in one organization AND a second platform-wide grant (organization - * NULL), for every writer and every write path: a duplicate confers nothing - * more, but a revoke that deletes one row would leave the other granting. + * Not judged here. Since ADR-0150 D4 a set is `(package, name)`, so the + * declared unique index is (`user_id`, `permission_set`, + * `permission_set_package`, `organization_id`), `unique: 'global'`: one user + * may hold both packages' sets of one name in one organization, and a second + * grant of one package's set is refused, for every writer and every write path. + * A grant whose package column is empty is held to one per (`user_id`, + * `permission_set`, `organization_id`) by the runtime-built partial index + * `uniq_sys_user_permission_set_packageless` (metadata-protocol's + * `user-permission-set-packageless-index.ts`), because a unique index treats + * empty values as distinct. A duplicate confers nothing more, but a revoke that + * deletes one row would leave the other granting. Every key part is a plain + * column (ADR-0131 D1), so a grant whose organization is empty (a platform-wide + * grant) is exempt from both indexes, as it was from the key before them. * * ## Hooks, not a middleware * @@ -91,12 +126,23 @@ * D10 (names first, then the id column goes). */ -import { securityCatalogReaderOf, type SecurityCatalogReader } from '@objectstack/core'; +import { + PackageScopedNameRefusedError, + catalogEntryAddress, + packageScopedRefusalMessage, + resolveCatalogReference, + securityCatalogReaderOf, + type PackageScopedHolder, + type PackageScopedRefusal, + type SecurityCatalogEntry, + type SecurityCatalogReader, +} from '@objectstack/core'; import { MCP_AGENT_PERMISSION_SETS } from '@objectstack/spec/ai'; import type { FieldErrorCode } from '@objectstack/spec/api'; import { isPlainRecord } from '@objectstack/spec/data'; import { validationFailure } from '@objectstack/types'; import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; +import { PERMISSION_SET_PACKAGE_COLUMN } from './stored-permission-set-package-backfill.js'; /** The grant object this module judges. */ export const GRANT_OBJECT = 'sys_user_permission_set'; @@ -209,13 +255,86 @@ interface GrantNameEngine { type GrantNameLogger = { warn?: (msg: string, meta?: any) => void } | undefined; -/** Refuse `name` when the bound catalog holds no permission set by it (module note). */ -async function assertNameInCatalog(engine: GrantNameEngine, name: string, logger: GrantNameLogger): Promise { +/** + * [ADR-0150 D3/D5, #32164] The catalog's answer for the set a grant names: by + * its name alone, or — `packageId` given — exactly that package's set (module + * note, "A name two packages hold"). + * + * - `resolved`: the set the grant holds. + * - `not-found`: no holder of the name anywhere. + * - `refused`: the D3 refusal of the bare name (two holders), or a named + * package that does not hold it (`not-held-by-qualifier`, naming the + * holders). Every candidate is structured. + * + * The named package is matched against the catalog's own per-holder entries + * (`list`, one per `(package, name)`) — never through the stored-column scope, + * whose stale-column arm reads a package that does not hold the name as no + * package and would pick the other holder. + */ +export async function judgeGrantSet( + catalog: SecurityCatalogReader, + name: string, + packageId?: string, +): Promise< + | { readonly status: 'resolved'; readonly entry: SecurityCatalogEntry } + | { readonly status: 'not-found' } + | { readonly status: 'refused'; readonly refusal: PackageScopedRefusal } +> { + if (packageId === undefined) { + const answer = await resolveCatalogReference(catalog, PERMISSION_SET_CATALOG_TYPE, name); + if (answer.status !== 'refused') return answer; + return { + status: 'refused', + refusal: { + status: 'refused', + reason: answer.reason as PackageScopedRefusal['reason'], + type: PERMISSION_SET_CATALOG_TYPE, + name, + callerPackageId: null, + candidates: answer.holders ?? [], + message: answer.message, + }, + }; + } + // [SF7] A holder's package is read as core's `catalogEntryAddress` reads it: + // the `sys_metadata` provenance sentinel is no package, so a grant naming it + // holds nothing (the stamp seam's reading too) and a refusal names the + // environment, never the sentinel. + const holders = (await catalog.list(PERMISSION_SET_CATALOG_TYPE)).filter((e) => e.name === name); + const exact = holders.find((e) => catalogEntryAddress(e).packageId === packageId); + if (exact) return { status: 'resolved', entry: exact }; + if (holders.length === 0) return { status: 'not-found' }; + const candidates: PackageScopedHolder[] = holders.map((e) => { + const holder = catalogEntryAddress(e).packageId; + return holder !== null ? { kind: 'package', packageId: holder } : { kind: 'environment' }; + }); + const base = { + status: 'refused' as const, + reason: 'not-held-by-qualifier' as const, + type: 'permission' as const, + name, + callerPackageId: packageId, + candidates, + }; + return { status: 'refused', refusal: { ...base, message: packageScopedRefusalMessage(base) } }; +} + +/** + * Refuse a grant whose set the bound catalog does not resolve (module note): + * `400` when nothing holds the name, `409` when the name is refused or the + * named package does not hold it. + */ +async function assertNameInCatalog( + engine: GrantNameEngine, + name: string, + logger: GrantNameLogger, + packageId?: string, +): Promise { const catalog = securityCatalogReaderOf(engine); if (!catalog) return; - let held: boolean; + let answer: Awaited>; try { - held = (await catalog.resolve(PERMISSION_SET_CATALOG_TYPE, name)) !== undefined; + answer = await judgeGrantSet(catalog, name, packageId); } catch (e) { logger?.warn?.( `[security] the security catalog could not be read, so a ${GRANT_OBJECT} write was NOT checked for a ` + @@ -224,7 +343,17 @@ async function assertNameInCatalog(engine: GrantNameEngine, name: string, logger ); return; } - if (!held) throw grantSetNotInCatalogError(name, await setsLabelled(catalog, name, logger)); + if (answer.status === 'resolved') return; + if (answer.status === 'refused') throw new PackageScopedNameRefusedError(answer.refusal); + throw grantSetNotInCatalogError(name, await setsLabelled(catalog, name, logger)); +} + +/** The package an insert names beside the set (`permission_set_package`), trimmed; blank or absent names none. */ +function namedPackage(data: Record): string | undefined { + const value = data[PERMISSION_SET_PACKAGE_COLUMN]; + if (typeof value !== 'string') return undefined; + const trimmed = value.trim(); + return trimmed === '' ? undefined : trimmed; } const AGENT_CEILING_SETS: ReadonlySet = new Set(MCP_AGENT_PERMISSION_SETS); @@ -269,7 +398,7 @@ async function onInsert(engine: GrantNameEngine, ctx: any, logger: GrantNameLogg const data = ctx?.input?.data; if (!isPlainRecord(data)) return; const name = judgedName(data[GRANT_SET_NAME_FIELD]); - if (name !== undefined) await assertNameInCatalog(engine, name, logger); + if (name !== undefined) await assertNameInCatalog(engine, name, logger, namedPackage(data)); } /** diff --git a/packages/plugins/plugin-security/src/grant-permission-set-package.test.ts b/packages/plugins/plugin-security/src/grant-permission-set-package.test.ts new file mode 100644 index 00000000000..16da4a0dc66 --- /dev/null +++ b/packages/plugins/plugin-security/src/grant-permission-set-package.test.ts @@ -0,0 +1,417 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D3/D5/D8, #32164] A grant of a permission set two packages hold, + * and a grant that names its package in `permission_set_package`. + * + * Measured on a REAL `ObjectQL` engine over a real SQL driver, with the two + * pieces that judge a grant's package registered on it as the plugin registers + * them: the grant-name hook (`grant-permission-set-name.ts`, non-system + * writers, through the security catalog) and the package stamp seam + * (`stored-permission-set-package-stamp.ts`, every writer, through the + * registry's holders). A stand-in registry serves both — the catalog reader is + * built over it with `createSecurityCatalogReader` and bound to the engine — + * because a name two packages hold cannot be registered on a real registry + * before the narrowing (#31698 PR-2); the one-holder CONTROLs are what a real + * environment answers today. + * + * Every refusal is read by its envelope (`resolveThrownHttpError`, and + * `mapDataError` for the data door's wire body), and every refusal asserts + * nothing was stored. + * + * BASE (main e40f2df2), for each moved answer — the FROM → TO is the changeset's: + * - two holders, no package named: 400 VALIDATION_FAILED `reference_not_found` + * ("There is no permission set named …") → 409 RESOURCE_CONFLICT naming both; + * - two holders, a holder named: the same 400 → stored with that package; + * - one holder, another package named: stored and re-stamped to the holder + * (system) or stored as sent (non-system) → 409 `not-held-by-qualifier` (F3). + */ + +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { bindSecurityCatalogReader, createSecurityCatalogReader } from '@objectstack/core'; +import { isUniqueViolationError, mapDataError, resolveThrownHttpError } from '@objectstack/types'; + +import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; +import { judgeGrantSet, registerGrantPermissionSetNameHooks } from './grant-permission-set-name.js'; +import { registerPermissionSetPackageStamp } from './stored-permission-set-package-stamp.js'; + +const ORG = 'org_a'; +const SYS = { isSystem: true, tenantId: ORG } as const; +const ADMIN = { userId: 'u_admin', tenantId: ORG } as const; +const GRANTS = 'sys_user_permission_set'; + +const CRM = 'com.acme.crm'; +const HR = 'com.acme.hr'; +const OTHER = 'com.acme.other'; +/** Held by CRM alone. */ +const ONE = 'crm_sales_rep'; +/** Held by CRM and HR. */ +const TWO = 'shared_reader'; +/** Held by the environment alone. */ +const ENV = 'env_auditor'; + +const holders: Record = { [ONE]: [CRM], [TWO]: [CRM, HR] }; +const itemOf = (name: string, packageId?: string) => ({ name, label: name, objects: {}, ...(packageId ? { _packageId: packageId } : {}) }); + +/** One stand-in serving the catalog reader's reads and the stamp seam's. */ +function standInRegistry() { + const manifests = [CRM, HR, OTHER].map((id) => ({ manifest: { id, namespace: id.split('.').pop() } })); + return { + // The by-name reads the catalog reader also carries. + getItem: (type: string, name: string) => + type === 'permission' ? (holders[name] ? itemOf(name, holders[name][0]) : name === ENV ? itemOf(ENV) : undefined) : undefined, + listItems: (type: string) => (type === 'permission' ? [itemOf(ONE, CRM), itemOf(TWO, CRM), itemOf(TWO, HR), itemOf(ENV)] : []), + isPackageDisabled: () => false, + // The package-scoped reads. + packageScopedHoldersOf: (type: string, name: string) => (type === 'permission' ? holders[name] ?? [] : []), + getPackageScopedItem: (type: string, name: string, packageId: string) => + type === 'permission' && (holders[name] ?? []).includes(packageId) ? itemOf(name, packageId) : undefined, + getEnvironmentScopedItem: (type: string, name: string) => (type === 'permission' && name === ENV ? itemOf(ENV) : undefined), + getArtifactItem: () => undefined, + getPackage: (id: string) => manifests.find((m) => m.manifest.id === id), + getAllPackages: () => manifests, + bareNameHoldersAreSealed: true, + }; +} + +const engines: ObjectQL[] = []; +afterEach(async () => { + vi.restoreAllMocks(); + while (engines.length) { + try { await engines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +async function boot(opts: { seamReads?: boolean } = {}): Promise { + const engine = new ObjectQL(); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + true, + ); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.grant-permission-set-package', + name: 'Grant permission-set package', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [SysUserPermissionSet], + } as any); + await engine.syncSchemas(); + engines.push(engine); + + const registry = standInRegistry(); + const metadata = { get: async () => undefined, list: async () => [] }; + expect(bindSecurityCatalogReader(engine, createSecurityCatalogReader({ registry: registry as never, metadata }))).toBe(true); + expect(registerGrantPermissionSetNameHooks(engine as never)).toBe(true); + expect(registerPermissionSetPackageStamp({ + registry: registry as never, + getSchema: engine.getSchema.bind(engine), + registerHook: engine.registerHook.bind(engine), + unregisterHooksByPackage: engine.unregisterHooksByPackage.bind(engine), + ...(opts.seamReads === false ? {} : { find: engine.find.bind(engine) }), + })).toBe(true); + vi.spyOn((engine as any).logger, 'warn').mockImplementation(() => undefined); + return engine; +} + +const grant = (id: string, set: string, extra: Record = {}) => ({ + id, user_id: `u_${id}`, permission_set: set, organization_id: ORG, ...extra, +}); + +async function stored(engine: ObjectQL): Promise> { + const rows = (await engine.find(GRANTS, { where: {}, context: SYS })) as Array>; + return Object.fromEntries(rows.map((r) => [r.id as string, r.permission_set_package ?? null])); +} + +async function refusalOf(run: () => Promise): Promise { + try { + await run(); + } catch (e) { + return e; + } + throw new Error('expected the write to be refused, but it succeeded'); +} + +/** The refusal as both HTTP doors read it, and the data door's wire body. */ +function conflictOf(err: any) { + const thrown = resolveThrownHttpError(err); + const wire = mapDataError(err, GRANTS); + return { + envelope: [thrown.code, thrown.status], + wire: [wire.status, wire.body.code], + reason: err?.refusal?.reason, + callerPackageId: err?.refusal?.callerPackageId, + candidates: err?.refusal?.candidates, + message: String(err?.message ?? ''), + }; +} + +describe('a set two packages hold (ADR-0150 D3)', () => { + it('named with no package: 409 RESOURCE_CONFLICT naming both holders, at the data door and for a system writer; nothing stored', async () => { + const engine = await boot(); + const err = conflictOf(await refusalOf(() => engine.insert(GRANTS, grant('a1', TWO), { context: ADMIN } as any))); + expect(err).toMatchObject({ + envelope: ['RESOURCE_CONFLICT', 409], + wire: [409, 'RESOURCE_CONFLICT'], + reason: 'ambiguous-in-environment', + callerPackageId: null, + candidates: [{ kind: 'package', packageId: CRM }, { kind: 'package', packageId: HR }], + }); + expect(err.message).toContain(`package "${CRM}"`); + expect(err.message).toContain(`package "${HR}"`); + expect(await stored(engine)).toEqual({}); + }); + + it('a system writer naming no package is not judged by the name hook: the grant is stored package-less (the boot backfill reports it)', async () => { + const engine = await boot(); + await engine.insert(GRANTS, grant('s1', TWO), { context: SYS } as any); + expect(await stored(engine)).toEqual({ s1: null }); + }); + + it('naming a holder in permission_set_package: stored with exactly that package — non-system and system writers alike', async () => { + const engine = await boot(); + await engine.insert(GRANTS, grant('h1', TWO, { permission_set_package: HR }), { context: ADMIN } as any); + await engine.insert(GRANTS, grant('h2', TWO, { permission_set_package: CRM }), { context: SYS } as any); + // One user may hold both packages' sets of one name in one organization (the 4-column key). + await engine.insert(GRANTS, grant('h3', TWO, { user_id: 'u_h1', permission_set_package: CRM }), { context: ADMIN } as any); + expect(await stored(engine)).toEqual({ h1: HR, h2: CRM, h3: CRM }); + }); + + it('naming a package that does not hold it: 409 not-held-by-qualifier naming the holders — hook and seam alike; nothing stored', async () => { + const engine = await boot(); + for (const context of [ADMIN, SYS]) { + const err = conflictOf(await refusalOf(() => + engine.insert(GRANTS, grant('x1', TWO, { permission_set_package: OTHER }), { context } as any))); + expect(err).toMatchObject({ + envelope: ['RESOURCE_CONFLICT', 409], + wire: [409, 'RESOURCE_CONFLICT'], + reason: 'not-held-by-qualifier', + callerPackageId: OTHER, + candidates: [{ kind: 'package', packageId: CRM }, { kind: 'package', packageId: HR }], + }); + } + expect(await stored(engine)).toEqual({}); + }); +}); + +/** + * [#32164, red-line review E2] A second grant of one user, set and + * organization that the key before #32164 refused is refused at the write + * seam, and answers what the store's own unique violation answers: the same + * envelope at both doors and the same wire body. + */ +describe('[E2] a second grant of a set to one user in one organization', () => { + const asWire = (err: any) => { + const thrown = resolveThrownHttpError(err); + const wire = mapDataError(err, GRANTS); + return { envelope: [thrown.code, thrown.status], wire: [wire.status, wire.body.code, wire.body.error] }; + }; + + it('reads as the store\'s own unique violation: the seam\'s refusal and the declared key\'s, envelope and wire alike', async () => { + // The declared key's own refusal: the same package's set twice, measured + // with the seam's reads off so the store answers. + const bare = await boot({ seamReads: false }); + await bare.insert(GRANTS, grant('k1', TWO, { permission_set_package: HR }), { context: SYS } as any); + const store = await refusalOf(() => + bare.insert(GRANTS, grant('k2', TWO, { user_id: 'u_k1', permission_set_package: HR }), { context: SYS } as any)); + expect(store?.name).toBe('DuplicateRecordError'); + + const engine = await boot(); + await engine.insert(GRANTS, grant('k1', TWO, { permission_set_package: HR }), { context: SYS } as any); + const seam = await refusalOf(() => + engine.insert(GRANTS, grant('k2', TWO, { user_id: 'u_k1', permission_set_package: HR }), { context: SYS } as any)); + expect(asWire(seam)).toEqual(asWire(store)); + expect(asWire(seam)).toEqual({ + envelope: ['DUPLICATE_RECORD', 409], + wire: [409, 'UNIQUE_VIOLATION', 'A record with this value already exists'], + }); + // The in-process reading: the same class name, code, status, object and sentence. + expect({ name: seam.name, code: seam.code, status: seam.status, object: seam.object, message: seam.message }) + .toEqual({ name: store.name, code: store.code, status: store.status, object: store.object, message: store.message }); + expect(isUniqueViolationError(seam)).toBe(true); + expect(await stored(engine)).toEqual({ k1: HR }); + }); + + it('at the data door: beside a grant that names no package, a stamped second grant of a one-holder set is refused 409 UNIQUE_VIOLATION; nothing stored', async () => { + const engine = await boot(); + await engine.insert(GRANTS, grant('m1', ONE, { permission_set_package: null }), { context: SYS } as any); + await (engine as any).getDriver(GRANTS).knex(GRANTS).where({ id: 'm1' }).update({ permission_set_package: null }); + const err = await refusalOf(() => engine.insert(GRANTS, grant('m2', ONE, { user_id: 'u_m1' }), { context: ADMIN } as any)); + expect(asWire(err)).toEqual({ + envelope: ['DUPLICATE_RECORD', 409], + wire: [409, 'UNIQUE_VIOLATION', 'A record with this value already exists'], + }); + expect(await stored(engine)).toEqual({ m1: null }); + }); + + it('CONTROL: a row repeating a stored id is left to the store\'s own refusal, not the second-grant check', async () => { + const engine = await boot(); + await engine.insert(GRANTS, grant('r1', ONE), { context: SYS } as any); + const err = await refusalOf(() => engine.insert(GRANTS, grant('r1', ONE), { context: SYS } as any)); + expect({ name: err?.name, code: err?.code }).toEqual({ name: 'DuplicateRecordError', code: 'DUPLICATE_RECORD' }); + // The driver's own refusal on `cause` (the seam's own carries no driver code). + expect(String(err?.cause?.code)).toMatch(/^SQLITE_CONSTRAINT/); + expect(await stored(engine)).toEqual({ r1: CRM }); + }); + + it('CONTROL: the two holders\' sets once each, for one user in one organization, are both stored', async () => { + const engine = await boot(); + await engine.insert(GRANTS, grant('p1', TWO, { permission_set_package: CRM }), { context: ADMIN } as any); + await engine.insert(GRANTS, grant('p2', TWO, { user_id: 'u_p1', permission_set_package: HR }), { context: ADMIN } as any); + expect(await stored(engine)).toEqual({ p1: CRM, p2: HR }); + }); + + // Declared precedence (changeset, "Moved, refused either way"): `reason` is 600 characters, past its maxLength 500. + const invalid = { reason: 'r'.repeat(600) }; + it('a second grant whose row record validation also refuses: FROM 400 VALIDATION_FAILED TO the one-grant 409, system and non-system writers alike; nothing stored', async () => { + // FROM: with the seam's reads off, the store's key answers last, after validation. + const bare = await boot({ seamReads: false }); + await bare.insert(GRANTS, grant('v1', ONE), { context: SYS } as any); + const before = await refusalOf(() => bare.insert(GRANTS, grant('v2', ONE, { user_id: 'u_v1', ...invalid }), { context: SYS } as any)); + expect(asWire(before).envelope).toEqual(['VALIDATION_FAILED', 400]); + for (const context of [SYS, ADMIN]) { + const engine = await boot(); + await engine.insert(GRANTS, grant('v1', ONE), { context: SYS } as any); + const err = await refusalOf(() => engine.insert(GRANTS, grant('v2', ONE, { user_id: 'u_v1', ...invalid }), { context } as any)); + expect(asWire(err)).toEqual({ envelope: ['DUPLICATE_RECORD', 409], wire: [409, 'UNIQUE_VIOLATION', 'A record with this value already exists'] }); + expect(await stored(engine)).toEqual({ v1: CRM }); + } + }); + + it('CONTROL: the same invalid row with no grant beside it is still 400 VALIDATION_FAILED, system and non-system writers alike', async () => { + for (const context of [SYS, ADMIN]) { + const engine = await boot(); + const err = await refusalOf(() => engine.insert(GRANTS, grant('v2', ONE, invalid), { context } as any)); + expect(asWire(err).envelope).toEqual(['VALIDATION_FAILED', 400]); + expect(await stored(engine)).toEqual({}); + } + }); +}); + +describe('a set one package holds — CONTROL, every answer as before', () => { + it('naming no package: stored, stamped with the holder (non-system and system)', async () => { + const engine = await boot(); + await engine.insert(GRANTS, grant('c1', ONE), { context: ADMIN } as any); + await engine.insert(GRANTS, grant('c2', ONE), { context: SYS } as any); + expect(await stored(engine)).toEqual({ c1: CRM, c2: CRM }); + }); + + it('naming the holder itself: stored with it', async () => { + const engine = await boot(); + await engine.insert(GRANTS, grant('c3', ONE, { permission_set_package: CRM }), { context: ADMIN } as any); + await engine.insert(GRANTS, grant('c4', ONE, { permission_set_package: ` ${CRM} ` }), { context: SYS } as any); + expect(await stored(engine)).toEqual({ c3: CRM, c4: CRM }); + }); + + it('a name nothing holds: still the 400 reference_not_found, whatever package is named', async () => { + const engine = await boot(); + for (const extra of [{}, { permission_set_package: CRM }]) { + const thrown = resolveThrownHttpError(await refusalOf(() => + engine.insert(GRANTS, grant('n1', 'no_such_set', extra), { context: ADMIN } as any))); + expect([thrown.code, thrown.status]).toEqual(['VALIDATION_FAILED', 400]); + expect((thrown.details?.fields as any[])?.[0]).toMatchObject({ field: 'permission_set', code: 'reference_not_found' }); + } + expect(await stored(engine)).toEqual({}); + }); +}); + +describe('F3 — a named non-holder is refused at any holder count (the one declared narrowing)', () => { + it('one holder, another package named: 409 not-held-by-qualifier — never stored as sent, never re-stamped', async () => { + const engine = await boot(); + for (const context of [ADMIN, SYS]) { + const err = conflictOf(await refusalOf(() => + engine.insert(GRANTS, grant('f1', ONE, { permission_set_package: HR }), { context } as any))); + expect(err).toMatchObject({ + envelope: ['RESOURCE_CONFLICT', 409], + reason: 'not-held-by-qualifier', + callerPackageId: HR, + candidates: [{ kind: 'package', packageId: CRM }], + }); + } + expect(await stored(engine)).toEqual({}); + }); + + it('an environment-only set, a package named: 409 naming the environment', async () => { + const engine = await boot(); + for (const context of [ADMIN, SYS]) { + const err = conflictOf(await refusalOf(() => + engine.insert(GRANTS, grant('e1', ENV, { permission_set_package: CRM }), { context } as any))); + expect(err).toMatchObject({ reason: 'not-held-by-qualifier', callerPackageId: CRM, candidates: [{ kind: 'environment' }] }); + } + await engine.insert(GRANTS, grant('e2', ENV), { context: ADMIN } as any); + expect(await stored(engine)).toEqual({ e2: null }); + }); + + it('a column-only bind (a system update sending the package alone): a holder binds, a non-holder is refused and the row is untouched', async () => { + const engine = await boot(); + await engine.insert(GRANTS, grant('b1', TWO), { context: SYS } as any); + await engine.insert(GRANTS, grant('b2', ONE), { context: SYS } as any); + + await engine.update(GRANTS, { id: 'b1', permission_set_package: HR }, { context: SYS } as any); + const err = conflictOf(await refusalOf(() => + engine.update(GRANTS, { id: 'b2', permission_set_package: HR }, { context: SYS } as any))); + expect(err).toMatchObject({ reason: 'not-held-by-qualifier', callerPackageId: HR, candidates: [{ kind: 'package', packageId: CRM }] }); + expect(await stored(engine)).toEqual({ b1: HR, b2: CRM }); + }); +}); + +describe('what an update keeps', () => { + it('an echo of the stored package chooses nothing: an unrelated edit lands and the package stays', async () => { + const engine = await boot(); + await engine.insert(GRANTS, grant('u1', TWO, { permission_set_package: HR }), { context: SYS } as any); + await engine.update(GRANTS, { id: 'u1', permission_set_package: HR, reason: 'renewed' }, { context: SYS } as any); + await engine.update(GRANTS, { id: 'u1', permission_set_package: HR, reason: 'again' }, { context: ADMIN } as any); + expect(await stored(engine)).toEqual({ u1: HR }); + }); + + it('a non-system update\'s package value is never stored or judged: the readonly column keeps its value', async () => { + const engine = await boot(); + await engine.insert(GRANTS, grant('u2', ONE), { context: SYS } as any); + await engine.update(GRANTS, { id: 'u2', permission_set_package: OTHER, reason: 'edited' }, { context: ADMIN } as any); + expect(await stored(engine)).toEqual({ u2: CRM }); + }); + + it('a rename to a two-holder name re-stamps package-less (CONTROL: as before)', async () => { + const engine = await boot(); + await engine.insert(GRANTS, grant('u3', ONE), { context: SYS } as any); + await engine.update(GRANTS, { id: 'u3', permission_set: TWO }, { context: SYS } as any); + expect(await stored(engine)).toEqual({ u3: null }); + }); +}); + +describe('[SF7] the overlay provenance sentinel is no package', () => { + /** A set whose catalog entry carries `sys_metadata` as its package: an overlay row's provenance, not a holder. */ + const OVERLAID = 'overlaid_auditor'; + const SENTINEL = 'sys_metadata'; + const overlayCatalog = () => createSecurityCatalogReader({ + registry: { + getItem: (type: string, name: string) => (type === 'permission' && name === OVERLAID ? itemOf(OVERLAID, SENTINEL) : undefined), + listItems: (type: string) => (type === 'permission' ? [itemOf(OVERLAID, SENTINEL)] : []), + isPackageDisabled: () => false, + getPackage: () => undefined, + getAllPackages: () => [], + } as never, + metadata: { get: async () => undefined, list: async () => [] }, + }); + + it('a grant naming the sentinel holds nothing: refused not-held-by-qualifier, the holder named as the environment', async () => { + const answer = await judgeGrantSet(overlayCatalog(), OVERLAID, SENTINEL); + expect(answer).toMatchObject({ + status: 'refused', + refusal: { reason: 'not-held-by-qualifier', candidates: [{ kind: 'environment' }] }, + }); + // The caller's own qualifier is echoed; the holder it lists is the environment. + const message = answer.status === 'refused' ? answer.refusal.message : ''; + expect(message).toContain('the environment'); + expect(message.split(`package "${SENTINEL}"`)).toHaveLength(2); + }); + + it('a refusal for another package names the environment, never the sentinel; CONTROL: the bare name resolves', async () => { + const other = await judgeGrantSet(overlayCatalog(), OVERLAID, OTHER); + expect(other).toMatchObject({ status: 'refused', refusal: { candidates: [{ kind: 'environment' }] } }); + expect(await judgeGrantSet(overlayCatalog(), OVERLAID)).toMatchObject({ status: 'resolved', entry: { name: OVERLAID } }); + }); +}); diff --git a/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts b/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts index 252cbc42429..17fd2efbd08 100644 --- a/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts +++ b/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts @@ -392,17 +392,44 @@ describe('[ADR-0150 D8 R1] permission_set_package — only a system writer write expect(await storedPackage(engine, created.id)).toBe(QA_PKG); }); - it(`${who} inserting a grant that carries the column stores the seam's answer, not the payload's`, async () => { + // [#32164, F3] BASE (main e40f2df2): the forged package was replaced by the + // seam's answer and the grant stored as QA_PKG's. A package that does not + // hold the set is now refused, never re-stamped (epic red line 1). + it(`${who} inserting a grant that carries a package not holding its set is refused 409, and nothing is stored`, async () => { const { engine } = await sealed(); - const created: any = await engine.insert(GRANT, TABLES[GRANT]({ permission_set_package: FORGED }), { context: { ...caller } } as never); + const err: any = await engine + .insert(GRANT, TABLES[GRANT]({ permission_set_package: FORGED }), { context: { ...caller } } as never) + .catch((e: unknown) => e); + expect(err?.code, String(err?.message ?? err)).toBe('RESOURCE_CONFLICT'); + expect(err?.refusal).toMatchObject({ reason: 'not-held-by-qualifier', callerPackageId: FORGED, candidates: [{ kind: 'package', packageId: QA_PKG }] }); + expect(await engine.find(GRANT, { where: {}, context: { isSystem: true } } as never)).toEqual([]); + }); + + it(`${who} inserting a grant that names the holder stores it`, async () => { + const { engine } = await sealed(); + const created: any = await engine.insert(GRANT, TABLES[GRANT]({ permission_set_package: QA_PKG }), { context: { ...caller } } as never); expect(await storedPackage(engine, created.id)).toBe(QA_PKG); }); } - it('a system update writing the column alone — the backfill\'s and the reviewed bind\'s write — lands as written', async () => { + // [#32164, F3] BASE (main e40f2df2): a system update writing a package that + // does not hold the set landed as written. The backfill and the reviewed + // bind only ever write a holder (the bind re-asks the rule and requires the + // package among its candidates), so their write still lands; a non-holder is + // refused, the column unchanged. + it('a system update writing the column alone — the backfill\'s and the reviewed bind\'s write — lands when it names a holder; a non-holder is refused', async () => { const { engine } = await sealed(); const created: any = await engine.insert(GRANT, TABLES[GRANT](), SYS); - await engine.update(GRANT, { permission_set_package: BOUND }, { where: { id: created.id }, context: { isSystem: true } } as never); - expect(await storedPackage(engine, created.id)).toBe(BOUND); + // A grant written before the seal, package-less, as the backfill finds it. + await (engine as any).getDriver(GRANT).knex(GRANT).where({ id: created.id }).update({ permission_set_package: null }); + await engine.update(GRANT, { permission_set_package: QA_PKG }, { where: { id: created.id }, context: { isSystem: true } } as never); + expect(await storedPackage(engine, created.id)).toBe(QA_PKG); + + const err: any = await engine + .update(GRANT, { permission_set_package: BOUND }, { where: { id: created.id }, context: { isSystem: true } } as never) + .catch((e: unknown) => e); + expect(err?.code, String(err?.message ?? err)).toBe('RESOURCE_CONFLICT'); + expect(err?.refusal).toMatchObject({ reason: 'not-held-by-qualifier', callerPackageId: BOUND }); + expect(await storedPackage(engine, created.id)).toBe(QA_PKG); }); }); diff --git a/packages/plugins/plugin-security/src/objects/sys-user-permission-set.object.ts b/packages/plugins/plugin-security/src/objects/sys-user-permission-set.object.ts index 774a1959950..4bfc5408c37 100644 --- a/packages/plugins/plugin-security/src/objects/sys-user-permission-set.object.ts +++ b/packages/plugins/plugin-security/src/objects/sys-user-permission-set.object.ts @@ -15,10 +15,13 @@ import { F, P } from '@objectstack/spec'; * * The same permission set can be granted independently in each org context * the user belongs to, and once in each: the declared unique index is - * (`user_id`, `permission_set`, `organization_id`), `unique: 'organization'`, - * so its organization key part is NULL-safe (ADR-0120 D3) and a second - * platform-wide grant (organization NULL) is refused too — by the index, for - * every writer and write path. [ADR-0131 D10, C7b] The legacy + * (`user_id`, `permission_set`, `permission_set_package`, `organization_id`) + * (ADR-0150 D4, #32164: a set is identified by its package and name), and a + * grant naming no package is held to one per user, set and organization by + * the runtime partial index `uniq_sys_user_permission_set_packageless` — for + * every writer and write path. Every key part is a plain column (ADR-0131 D1), + * so a platform-wide grant (organization NULL) is exempt from both, as it was + * from the three-column key before them. [ADR-0131 D10, C7b] The legacy * `permission_set_id` column is retired: the v18 ceremony's verified rewrite * names every grant from it, then its column-drops step drops it. * @@ -131,8 +134,9 @@ export const SysUserPermissionSet = ObjectSchema.create({ readonly: true, maxLength: 255, description: - 'The app the permission set comes from. Filled in by the platform; empty when the set was created here, ' + - 'or when more than one app provides a set of that name.', + 'The app the permission set comes from. A grant names it to choose between apps that provide a set of ' + + 'the same name; otherwise the platform fills it in. Empty when the set was created here, or when more than ' + + 'one app provides a set of that name and the grant names none.', }), // Provenance, not a business link: the platform writes it, a caller does @@ -298,9 +302,21 @@ export const SysUserPermissionSet = ObjectSchema.create({ ], indexes: [ - // One grant of a set to a user per organization, platform-wide (NULL) - // included (the module note): a duplicate would keep a revoked grant in force. - { fields: ['user_id', 'permission_set', 'organization_id'], unique: 'organization' }, + // [ADR-0150 D4, #32164] One grant of a set to a user per organization: a + // duplicate would keep a revoked grant in force. A set is (package, name), + // so the key carries the package column, and one user may hold both + // packages' sets of one name. `unique: 'global'` materializes exactly the + // listed columns — what `'organization'` materialized here too, since the + // organization column is listed (ADR-0131 D1) — and it is the spelling the + // drivers' widening arms retire the old three-column key under, + // create-before-drop. Every key part is a plain, NULL-distinct column, so + // a grant whose package column is empty is held to one per (user_id, + // permission_set, organization_id) by a runtime partial index beside this + // one, `uniq_sys_user_permission_set_packageless` (metadata-protocol's + // `user-permission-set-packageless-index.ts`; driver-mongodb's runtime-owned + // uniques), which the declared surface cannot spell. A grant whose + // organization is empty is exempt from both, as it was from the key before. + { fields: ['user_id', 'permission_set', 'permission_set_package', 'organization_id'], unique: 'global' }, { fields: ['user_id'] }, { fields: ['organization_id'] }, ], diff --git a/packages/plugins/plugin-security/src/stored-permission-set-package-backfill.test.ts b/packages/plugins/plugin-security/src/stored-permission-set-package-backfill.test.ts index 320c7f06e2f..a2905bf2b5b 100644 --- a/packages/plugins/plugin-security/src/stored-permission-set-package-backfill.test.ts +++ b/packages/plugins/plugin-security/src/stored-permission-set-package-backfill.test.ts @@ -136,6 +136,12 @@ async function seedGrants(engine: ObjectQL): Promise { } } +/** Write a grant row below the engine (no hook runs): the store's own indexes alone judge it. */ +async function rawGrant(engine: ObjectQL, row: Record): Promise { + await (engine as any).getDriver(GRANTS.object).knex(GRANTS.object) + .insert({ permission_set_package: null, organization_id: ORG, ...row }); +} + async function packagesById(engine: ObjectQL, object: string): Promise> { const rows = (await engine.find(object, { where: {}, context: SYSTEM_CTX })) as Array>; return Object.fromEntries(rows.map((r) => [String(r.id), r.permission_set_package ?? null])); @@ -184,6 +190,34 @@ describe('R1 — a grant gains the package that holds its permission set', () => expect(report.unpackaged).toEqual([{ name: ENV_SET, rows: 1, holder: 'environment' }]); }); + // [#32164, red-line review E2] BASE: one row's unique violation threw out of + // the walk, the run ended ("did not finish … the next boot tries again"), + // and every boot stopped at the same row, so later rows were never bound. + it.each([['with the write seam', true], ['below it (the store\'s own key)', false]] as const)( + 'a row whose bind would make a second grant of one user, set and organization is reported as duplicated and left null; the walk goes on (%s)', + async (_label, seam) => { + const engine = await boot(); + if (seam) { + expect(registerPermissionSetPackageStamp({ + registry: Object.assign(standInRegistry(), { bareNameHoldersAreSealed: true }), + getSchema: engine.getSchema.bind(engine), + registerHook: engine.registerHook.bind(engine), + unregisterHooksByPackage: engine.unregisterHooksByPackage.bind(engine), + find: engine.find.bind(engine), + })).toBe(true); + } + await rawGrant(engine, { id: 'a0', user_id: 'u_a', permission_set: ONE_HOLDER }); + await rawGrant(engine, { id: 'a1', user_id: 'u_a', permission_set: ONE_HOLDER, permission_set_package: CRM }); + await rawGrant(engine, { id: 'b0', user_id: 'u_b', permission_set: ONE_HOLDER }); + + const report = await backfillStoredPermissionSetPackages(engine, GRANTS, permissionSetHolderOf(standInRegistry())); + + expect(await packagesById(engine, GRANTS.object)).toEqual({ a0: null, a1: CRM, b0: CRM }); + expect(report.duplicated).toEqual([{ id: 'a0', name: ONE_HOLDER, packageId: CRM }]); + expect(report.bound).toEqual([{ name: ONE_HOLDER, rows: 1, packageId: CRM }]); + }, + ); + it('a second run writes no row and reports the same ambiguous and unheld names', async () => { const engine = await boot(); await seedGrants(engine); @@ -212,6 +246,23 @@ describe('R1 — a grant gains the package that holds its permission set', () => expect((await packagesById(engine, GRANTS.object)).g1).toBeNull(); }); + // [#32164, contract review 6817263634 nit] BASE (ec39bd8e5): the dry run + // counted the row the write reports as `duplicated` as `bound`. + it('a dry run reports a row whose bind would be a second grant as duplicated, as the write does, and writes nothing', async () => { + const engine = await boot(); + await rawGrant(engine, { id: 'a0', user_id: 'u_a', permission_set: ONE_HOLDER }); + await rawGrant(engine, { id: 'a1', user_id: 'u_a', permission_set: ONE_HOLDER, permission_set_package: CRM }); + await rawGrant(engine, { id: 'b0', user_id: 'u_b', permission_set: ONE_HOLDER }); + const update = vi.spyOn(engine, 'update'); + + const report = await backfillStoredPermissionSetPackages(engine, GRANTS, permissionSetHolderOf(standInRegistry()), { dryRun: true }); + + expect(update).not.toHaveBeenCalled(); + expect(report.duplicated).toEqual([{ id: 'a0', name: ONE_HOLDER, packageId: CRM }]); + expect(report.bound).toEqual([{ name: ONE_HOLDER, rows: 1, packageId: CRM }]); + expect(await packagesById(engine, GRANTS.object)).toEqual({ a0: null, a1: CRM, b0: null }); + }); + it('writes only the package column: the grant\'s other columns are untouched', async () => { const engine = await boot(); await seedGrants(engine); @@ -376,10 +427,21 @@ describe('the boot run', () => { }); }); -describe('no unique key widens: the package column sits beside the keys, never in them', () => { - it('every index of both tables is byte-identical to the one before the column', () => { +/** + * [#32164, ADR-0150 D4] The grant's key gains its package column — one user may + * hold both packages' sets of one name — and the suggestion's key is untouched. + * BASE (main e40f2df2): the grant key was (`user_id`, `permission_set`, + * `organization_id`), `unique: 'organization'`, and refused a second grant of + * one name whatever either row's package said. Two package-less grants of one + * name stay refused by the runtime partial index metadata-protocol builds at + * schema sync (`user-permission-set-packageless-index.ts`, pinned per dialect + * there); this engine is not booted through it, so the declared key alone is + * measured here. + */ +describe('the grant key gains its package column; the suggestion key is untouched', () => { + it('the declared indexes: the grant\'s unique is global over four columns, the suggestion\'s as before', () => { expect(JSON.stringify(SysUserPermissionSet.indexes)).toBe(JSON.stringify([ - { fields: ['user_id', 'permission_set', 'organization_id'], unique: 'organization' }, + { fields: ['user_id', 'permission_set', 'permission_set_package', 'organization_id'], unique: 'global' }, { fields: ['user_id'], unique: false }, { fields: ['organization_id'], unique: false }, ])); @@ -390,17 +452,16 @@ describe('no unique key widens: the package column sits beside the keys, never i ])); }); - it('the store still refuses a second grant of one set to one user, whatever either row\'s package column says', async () => { + it('the store refuses a second grant of one package\'s set to one user, and admits the other package\'s set beside it', async () => { const engine = await boot(); - await engine.insert(GRANTS.object, grant('k1', ONE_HOLDER, { user_id: 'u_k' }), { context: SYS_ORG }); - // Both null: the case a widened key would quietly let through. - await expect(engine.insert(GRANTS.object, grant('k2', ONE_HOLDER, { user_id: 'u_k' }), { context: SYS_ORG })).rejects.toThrow(); - // One differs only in the new column: still the same grant. + await engine.insert(GRANTS.object, grant('k1', TWO_HOLDERS, { user_id: 'u_k', permission_set_package: CRM }), { context: SYS_ORG }); await expect( - engine.insert(GRANTS.object, grant('k3', ONE_HOLDER, { user_id: 'u_k', permission_set_package: CRM }), { context: SYS_ORG }), + engine.insert(GRANTS.object, grant('k2', TWO_HOLDERS, { user_id: 'u_k', permission_set_package: CRM }), { context: SYS_ORG }), ).rejects.toThrow(); - const rows = (await engine.find(GRANTS.object, { where: { user_id: 'u_k' }, context: SYSTEM_CTX })) as unknown[]; - expect(rows).toHaveLength(1); + // BASE: refused by the three-column key. The other package's set is another set. + await engine.insert(GRANTS.object, grant('k3', TWO_HOLDERS, { user_id: 'u_k', permission_set_package: HR }), { context: SYS_ORG }); + const rows = (await engine.find(GRANTS.object, { where: { user_id: 'u_k' }, context: SYSTEM_CTX })) as Array>; + expect(rows.map((r) => r.permission_set_package).sort()).toEqual([CRM, HR]); }); }); @@ -422,6 +483,7 @@ describe('the write seam stamps the package column on every write that names a s getSchema: engine.getSchema.bind(engine), registerHook: engine.registerHook.bind(engine), unregisterHooksByPackage: engine.unregisterHooksByPackage.bind(engine), + find: engine.find.bind(engine), })).toBe(true); return engine; } @@ -447,7 +509,8 @@ describe('the write seam stamps the package column on every write that names a s declared.add(GRANTS.object); expect(write(insert, { permission_set: ONE_HOLDER })).toEqual({ permission_set: ONE_HOLDER, [GRANTS.packageColumn]: CRM }); expect(write(insert, { permission_set: TWO_HOLDERS })).toEqual({ permission_set: TWO_HOLDERS }); - expect(write(insert, { permission_set: TWO_HOLDERS, [GRANTS.packageColumn]: HR })).toEqual({ permission_set: TWO_HOLDERS, [GRANTS.packageColumn]: null }); + // [#32164] A writer naming a package that holds the name keeps it (BASE: replaced by null). + expect(write(insert, { permission_set: TWO_HOLDERS, [GRANTS.packageColumn]: HR })).toEqual({ permission_set: TWO_HOLDERS, [GRANTS.packageColumn]: HR }); }); it('R1: an insert takes the one package holder; a refused, environment or unheld name stays null', async () => { @@ -458,12 +521,29 @@ describe('the write seam stamps the package column on every write that names a s expect(await packagesById(engine, GRANTS.object)).toEqual({ w1: CRM, w2: null, w3: null, w4: null }); }); - it('R1: a writer\'s own package value is replaced by the rule\'s answer — a system writer\'s too', async () => { + // [#32164] BASE (main e40f2df2): every writer's own package value was + // replaced by the rule's answer — f1 and f2 stored null, f3 was re-stamped + // to CRM without a word. A writer naming a package now keeps it when that + // package holds the name, and is refused when it does not, at any holder + // count (the 409 envelope is pinned in `grant-permission-set-package.test.ts`). + it('R1: a writer\'s own package value is kept when it holds the name — a system writer\'s too — and a non-holder is refused, never re-stamped', async () => { const engine = await stamped(); await engine.insert(GRANTS.object, grant('f1', TWO_HOLDERS, { permission_set_package: HR }), { context: { userId: 'u_admin', tenantId: ORG } }); - await engine.insert(GRANTS.object, grant('f2', TWO_HOLDERS, { permission_set_package: HR }), { context: SYS_ORG }); - await engine.insert(GRANTS.object, grant('f3', ONE_HOLDER, { permission_set_package: HR }), { context: SYS_ORG }); - expect(await packagesById(engine, GRANTS.object)).toEqual({ f1: null, f2: null, f3: CRM }); + await engine.insert(GRANTS.object, grant('f2', TWO_HOLDERS, { permission_set_package: HR, user_id: 'u_f2' }), { context: SYS_ORG }); + await expect( + engine.insert(GRANTS.object, grant('f3', ONE_HOLDER, { permission_set_package: HR }), { context: SYS_ORG }), + ).rejects.toMatchObject({ code: 'RESOURCE_CONFLICT', refusal: { reason: 'not-held-by-qualifier', callerPackageId: HR } }); + expect(await packagesById(engine, GRANTS.object)).toEqual({ f1: HR, f2: HR }); + }); + + // [#32164 SF4] BASE (main e40f2df2): the named package was replaced by none. + // Nothing holds the name, so there is no holder to refuse it against: it is + // kept as written, and every reader reads a package that does not serve the + // name as no package (the stored column's stale arm). + it('R1 (SF4): a system insert naming a package for a name nothing holds keeps it as written', async () => { + const engine = await stamped(); + await engine.insert(GRANTS.object, grant('s4', NOBODY, { permission_set_package: HR }), { context: SYS_ORG }); + expect((await packagesById(engine, GRANTS.object)).s4).toBe(HR); }); it('R1: a rename re-stamps the column and never keeps the old package; a write that names no set leaves it', async () => { @@ -485,9 +565,137 @@ describe('the write seam stamps the package column on every write that names a s expect(await packagesById(engine, SUGGESTIONS.object)).toEqual({ t1: D, t2: null, t3: P, t4: null }); }); + // [#32164 MF2] F3 reaches R3 through the same seam. BASE (main e40f2df2): a + // system insert naming a non-holder was re-stamped by the rule's answer, and a + // column-only update naming one landed as written. Both are now 409 + // not-held-by-qualifier, nothing stored. The table is system-write only, and + // `os migrate stored-references bind --table sys_audience_binding_suggestion` + // writes through this hook. + it('R3 (F3): a system insert or column-only update naming a package that does not hold the set is 409, nothing stored; CONTROL: a holder is kept', async () => { + const engine = await stamped(); + await expect( + engine.insert(SUGGESTIONS.object, { ...suggestion('n1', P, D_ONLY), [SUGGESTIONS.packageColumn]: U }, { context: SYS_ORG }), + ).rejects.toMatchObject({ code: 'RESOURCE_CONFLICT', refusal: { reason: 'not-held-by-qualifier', callerPackageId: U } }); + expect(await packagesById(engine, SUGGESTIONS.object)).toEqual({}); + + await engine.insert(SUGGESTIONS.object, suggestion('n2', P, D_ONLY), { context: SYS_ORG }); + await expect( + engine.update(SUGGESTIONS.object, { id: 'n2', [SUGGESTIONS.packageColumn]: U }, { context: SYS_ORG }), + ).rejects.toMatchObject({ code: 'RESOURCE_CONFLICT', refusal: { reason: 'not-held-by-qualifier', callerPackageId: U } }); + expect(await packagesById(engine, SUGGESTIONS.object)).toEqual({ n2: D }); + + // CONTROL: a holder, named on the insert, is kept (one of two in the closure, which the rule alone leaves null). + await engine.insert(SUGGESTIONS.object, { ...suggestion('n3', P, D_AND_D2), [SUGGESTIONS.packageColumn]: D }, { context: SYS_ORG }); + expect((await packagesById(engine, SUGGESTIONS.object)).n3).toBe(D); + }); + + // [#32164, contract review 6813617327 should-fix 3] A suggestion is read from + // the package that made it (R3), so a holder named in its package column + // must be one that package's closure reaches. BASE: any holder of the name + // was kept, so a suggestion could be bound to a set the suggester cannot + // reach, which the rule alone never binds. + it('R3: a holder named outside the suggesting package\'s closure is 409 outside-closure, nothing stored; CONTROL: its own and a dependency\'s are kept', async () => { + const engine = await stamped(); + for (const [id, name] of [['o1', U_ONLY], ['o2', P_AND_U]] as const) { + await expect( + engine.insert(SUGGESTIONS.object, { ...suggestion(id, P, name), [SUGGESTIONS.packageColumn]: U }, { context: SYS_ORG }), + ).rejects.toMatchObject({ + code: 'RESOURCE_CONFLICT', + refusal: { reason: 'outside-closure', callerPackageId: P, candidates: [{ kind: 'package', packageId: U }] }, + }); + } + await engine.insert(SUGGESTIONS.object, suggestion('o3', P, P_AND_U), { context: SYS_ORG }); + await expect( + engine.update(SUGGESTIONS.object, { id: 'o3', [SUGGESTIONS.packageColumn]: U }, { context: SYS_ORG }), + ).rejects.toMatchObject({ code: 'RESOURCE_CONFLICT', refusal: { reason: 'outside-closure', callerPackageId: P } }); + expect(await packagesById(engine, SUGGESTIONS.object)).toEqual({ o3: P }); + + // CONTROL: the suggester's own set named on an update, and a dependency's on an insert. + await engine.update(SUGGESTIONS.object, { id: 'o3', [SUGGESTIONS.packageColumn]: P }, { context: SYS_ORG }); + await engine.insert(SUGGESTIONS.object, { ...suggestion('o5', P, D_ONLY), [SUGGESTIONS.packageColumn]: D }, { context: SYS_ORG }); + expect(await packagesById(engine, SUGGESTIONS.object)).toEqual({ o3: P, o5: D }); + }); + + /** + * [#32164, red-line review E2] One grant of a set per user and organization: + * the key before #32164, `(user_id, permission_set, organization_id)`, + * refused every second row of those three; the wider key and the + * package-less guard do not see a pair where one row names no package, or a + * package that does not hold the name. The seam refuses such a write as the + * old key's database did (the engine's duplicate-record refusal, `409 UNIQUE_VIOLATION` on the wire), and admits a pair only + * when the two rows name two different packages that each hold the name. + */ + describe('[E2] R1: one grant of a set per user and organization, but two holders\' sets', () => { + const asUniqueViolation = { name: 'DuplicateRecordError', code: 'DUPLICATE_RECORD', status: 409 }; + + it('one holder: beside a grant naming no package, a second grant is refused 409 as a duplicate record; nothing stored (BASE: the three-column key refused it)', async () => { + const engine = await stamped(); + await rawGrant(engine, { id: 'd0', user_id: 'u_d', permission_set: ONE_HOLDER }); + await expect(engine.insert(GRANTS.object, grant('d1', ONE_HOLDER, { user_id: 'u_d' }), { context: SYS_ORG })) + .rejects.toMatchObject(asUniqueViolation); + await expect(engine.insert(GRANTS.object, grant('d2', ONE_HOLDER, { user_id: 'u_d', permission_set_package: CRM }), { context: SYS_ORG })) + .rejects.toMatchObject(asUniqueViolation); + expect(await packagesById(engine, GRANTS.object)).toEqual({ d0: null }); + }); + + it('one holder: beside a grant naming a package that no longer serves the name, a second grant is refused the same way', async () => { + const engine = await stamped(); + await rawGrant(engine, { id: 'e0', user_id: 'u_e', permission_set: ONE_HOLDER, permission_set_package: 'com.acme.gone' }); + await expect(engine.insert(GRANTS.object, grant('e1', ONE_HOLDER, { user_id: 'u_e' }), { context: SYS_ORG })) + .rejects.toMatchObject(asUniqueViolation); + expect(await packagesById(engine, GRANTS.object)).toEqual({ e0: 'com.acme.gone' }); + }); + + it('two holders: each package\'s set once is admitted (the widening); the same package twice, or a grant naming no package beside one naming a package, is refused', async () => { + const engine = await stamped(); + await engine.insert(GRANTS.object, grant('t1', TWO_HOLDERS, { user_id: 'u_t', permission_set_package: CRM }), { context: SYS_ORG }); + await engine.insert(GRANTS.object, grant('t2', TWO_HOLDERS, { user_id: 'u_t', permission_set_package: HR }), { context: SYS_ORG }); + await expect(engine.insert(GRANTS.object, grant('t3', TWO_HOLDERS, { user_id: 'u_t', permission_set_package: HR }), { context: SYS_ORG })) + .rejects.toMatchObject(asUniqueViolation); + await expect(engine.insert(GRANTS.object, grant('t4', TWO_HOLDERS, { user_id: 'u_t' }), { context: SYS_ORG })) + .rejects.toMatchObject(asUniqueViolation); + // A grant naming no package first: a packaged one beside it is refused. + await engine.insert(GRANTS.object, grant('v1', TWO_HOLDERS, { user_id: 'u_v' }), { context: SYS_ORG }); + await expect(engine.insert(GRANTS.object, grant('v2', TWO_HOLDERS, { user_id: 'u_v', permission_set_package: HR }), { context: SYS_ORG })) + .rejects.toMatchObject(asUniqueViolation); + expect(await packagesById(engine, GRANTS.object)).toEqual({ t1: CRM, t2: HR, v1: null }); + }); + + it('an update that would make such a pair is refused and the row is untouched: a column-only bind, and moving a grant to another user', async () => { + const engine = await stamped(); + await engine.insert(GRANTS.object, grant('x1', ONE_HOLDER, { user_id: 'u_x' }), { context: SYS_ORG }); + await rawGrant(engine, { id: 'x0', user_id: 'u_x', permission_set: ONE_HOLDER }); + await expect(engine.update(GRANTS.object, { id: 'x0', permission_set_package: CRM }, { context: SYS_ORG })) + .rejects.toMatchObject(asUniqueViolation); + await engine.insert(GRANTS.object, grant('y1', ONE_HOLDER, { user_id: 'u_y' }), { context: SYS_ORG }); + await expect(engine.update(GRANTS.object, { id: 'y1', user_id: 'u_x' }, { context: SYS_ORG })) + .rejects.toMatchObject(asUniqueViolation); + expect(await packagesById(engine, GRANTS.object)).toEqual({ x0: null, x1: CRM, y1: CRM }); + const y1 = (await engine.find(GRANTS.object, { where: { id: 'y1' }, context: SYSTEM_CTX })) as Array>; + expect(y1[0].user_id).toBe('u_y'); + }); + + it('CONTROL: another user, another organization, another set — and an update that keeps the key — are not judged against each other', async () => { + const engine = await stamped(); + await engine.insert(GRANTS.object, grant('c1', ONE_HOLDER, { user_id: 'u_c' }), { context: SYS_ORG }); + await engine.insert(GRANTS.object, grant('c2', ONE_HOLDER, { user_id: 'u_c2' }), { context: SYS_ORG }); + await engine.insert(GRANTS.object, grant('c3', ONE_HOLDER, { user_id: 'u_c', organization_id: 'org_b' }), { context: { isSystem: true, tenantId: 'org_b' } }); + await engine.insert(GRANTS.object, grant('c4', TWO_HOLDERS, { user_id: 'u_c' }), { context: SYS_ORG }); + await engine.update(GRANTS.object, { id: 'c1', valid_until: '2099-01-01T00:00:00.000Z' }, { context: SYS_ORG }); + expect(await packagesById(engine, GRANTS.object)).toEqual({ c1: CRM, c2: CRM, c3: CRM, c4: null }); + }); + }); + it('before the holders are sealed nothing is stamped: the boot backfill binds the row', async () => { const engine = await stamped(false); await engine.insert(GRANTS.object, grant('b1', ONE_HOLDER), { context: SYS_ORG }); expect((await packagesById(engine, GRANTS.object)).b1).toBeNull(); }); + + // [#32164] BASE: a named package was replaced by null before the seal. + it('before the holders are sealed a named package is kept unjudged: a stale one reads as no package', async () => { + const engine = await stamped(false); + await engine.insert(GRANTS.object, grant('b2', ONE_HOLDER, { permission_set_package: HR }), { context: SYS_ORG }); + expect((await packagesById(engine, GRANTS.object)).b2).toBe(HR); + }); }); diff --git a/packages/plugins/plugin-security/src/stored-permission-set-package-backfill.ts b/packages/plugins/plugin-security/src/stored-permission-set-package-backfill.ts index 2a21cecaeba..3ac28f1b535 100644 --- a/packages/plugins/plugin-security/src/stored-permission-set-package-backfill.ts +++ b/packages/plugins/plugin-security/src/stored-permission-set-package-backfill.ts @@ -67,6 +67,15 @@ * differs from its `package_id`: with the suggesting package as the caller, * that is a set one of its declared dependencies holds. Every row reads equal * today; one that does not is reported, never rewritten. + * + * A bind the database or the write seam refuses as a unique violation — the + * row would be a second row of one key, a grant beside another of the same + * user, set and organization that already names the holder (#32164) — is + * reported by id (`duplicated`, at `warn`) and the row is left naming no + * package; the walk goes on, so one such row never stops every later row + * from being bound. Any other failed write still ends the run. A dry run asks + * the one-grant check's own predicate of each grant row it would bind, and + * reports a row the write would refuse as `duplicated`, not `bound`. */ import { @@ -76,7 +85,7 @@ import { type PackageScopedResolution, } from '@objectstack/core'; import { packageResolutionClosure, type PackageClosureRegistry } from '@objectstack/metadata-core'; -import { keysetWalk } from '@objectstack/types'; +import { isUniqueViolationError, keysetWalk } from '@objectstack/types'; /** One stored reference to a permission set (ADR-0150 D8). */ export interface StoredPermissionSetReference { @@ -113,6 +122,51 @@ export const STORED_PERMISSION_SET_REFERENCES: readonly StoredPermissionSetRefer /** The suggestion table, whose `package_id` the backfilled column is compared with. */ const SUGGESTION_OBJECT = 'sys_audience_binding_suggestion'; +/** [#32164] The grant table (R1), and the columns its one-grant check reads. */ +export const GRANT_OBJECT = 'sys_user_permission_set'; +export const GRANT_HOLDER_COLUMN = 'user_id'; +export const GRANT_ORGANIZATION_COLUMN = 'organization_id'; + +/** A non-blank string, trimmed, or a finite number as a string; anything else names nothing. */ +export const grantKeyOf = (value: unknown): string | null => { + if (typeof value === 'number' && Number.isFinite(value)) return String(value); + return typeof value === 'string' && value.trim() !== '' ? value.trim() : null; +}; + +/** [#32164] The package holders of `name` the one-grant check reads: the registry's once sealed, none before. */ +export function sealedPackageHoldersOf(registry: unknown, name: string): readonly string[] { + if (!isPermissionSetHolderRegistry(registry) || (registry as { bareNameHoldersAreSealed?: unknown }).bareNameHoldersAreSealed !== true) return []; + return registry.packageScopedHoldersOf('permission', name, null) ?? []; +} + +/** [#32164] The other grants (all but row `id`) of one user, set and organization, read as the system in `transaction`. */ +export async function otherGrantsOf( + engine: { find?: (object: string, query?: any) => Promise }, + reference: StoredPermissionSetReference, + grant: { user: string; name: string; organization: string; id: string | null }, + transaction?: unknown, +): Promise { + if (typeof engine.find !== 'function') return []; + const found = await engine.find(reference.object, { + where: { [GRANT_HOLDER_COLUMN]: grant.user, [reference.nameColumn]: grant.name, [GRANT_ORGANIZATION_COLUMN]: grant.organization }, + fields: ['id', reference.packageColumn], + context: transaction === undefined ? SYSTEM_CTX : { ...SYSTEM_CTX, transaction }, + }); + return (Array.isArray(found) ? (found as Row[]) : []).filter((row) => grant.id === null || grantKeyOf(row.id) !== grant.id); +} + +/** + * [#32164] Is a grant storing package `mine` beside `others` (the other grants of its user, set and organization) a + * second grant of one set, which the key before #32164 refused? Yes, unless the two name two DIFFERENT holders. + */ +export function isSecondGrant(others: readonly Row[], packageColumn: string, mine: unknown, holders: readonly string[]): boolean { + const own = grantKeyOf(mine); + return others.some((row) => { + const theirs = grantKeyOf(row[packageColumn]); + return !(own !== null && theirs !== null && own !== theirs && holders.includes(own) && holders.includes(theirs)); + }); +} + /** * [ADR-0150 D10] The operator's fix for a stored reference the rule refuses: * the reviewed one-row bind of `os migrate stored-references`, named in every @@ -210,6 +264,13 @@ export interface StoredReferenceBackfillReport { readonly unpackaged: ReadonlyArray; /** Suggestion rows whose `permission_set_package` is not their `package_id` (R3 only); never rewritten. */ readonly differs: ReadonlyArray<{ readonly id: string; readonly name: string; readonly packageId: string; readonly permissionSetPackage: string }>; + /** + * [#32164] Rows the bind would make a second row of one key (a grant of the + * same user, set and organization already names the holder): the write was + * refused as a unique violation, the row is left naming no package, and the + * walk goes on. Each is named by id, so an operator can review the pair. + */ + readonly duplicated: ReadonlyArray<{ readonly id: string; readonly name: string; readonly packageId: string; readonly callerPackageId?: string | null }>; } /** The engine slice the backfill reads and writes through. */ @@ -241,6 +302,21 @@ const callerOf = (row: Row, callerColumn: string | undefined): string | null => return typeof v === 'string' && v !== '' ? v : null; }; +/** [#32164] A dry run's reading of the write: would the one-grant check refuse binding grant `row` to `packageId`? */ +async function wouldBeSecondGrant( + engine: StoredReferenceBackfillEngine, + reference: StoredPermissionSetReference, + row: Row, + name: string, + packageId: string, +): Promise { + const user = grantKeyOf(row[GRANT_HOLDER_COLUMN]); + const organization = grantKeyOf(row[GRANT_ORGANIZATION_COLUMN]); + if (user === null || organization === null) return false; + const others = await otherGrantsOf(engine, reference, { user, name, organization, id: grantKeyOf(row.id) }); + return isSecondGrant(others, reference.packageColumn, packageId, sealedPackageHoldersOf((engine as { registry?: unknown }).registry, name)); +} + /** * Bind every row of `reference` whose package column is null to the one * package that holds its name (module doc). Reads by keyset page; writes only @@ -256,9 +332,15 @@ export async function backfillStoredPermissionSetPackages( const ambiguous = new Map(); const unheld = new Map(); const unpackaged = new Map(); + const duplicated: Array<{ id: string; name: string; packageId: string; callerPackageId?: string | null }> = []; const answers = new Map(); const { object, nameColumn, packageColumn, callerColumn } = reference; - const fields = ['id', nameColumn, packageColumn, ...(callerColumn ? [callerColumn] : [])]; + // A dry run of the grant table asks the one-grant check the write would meet (module doc). + const predictsSecondGrants = options?.dryRun === true && object === GRANT_OBJECT; + const fields = [ + 'id', nameColumn, packageColumn, ...(callerColumn ? [callerColumn] : []), + ...(predictsSecondGrants ? [GRANT_HOLDER_COLUMN, GRANT_ORGANIZATION_COLUMN] : []), + ]; /** Who wrote the reference, as the report names it: absent for an environment row (R1). */ const writer = (caller: string | null) => (callerColumn ? { callerPackageId: caller } : {}); @@ -288,10 +370,23 @@ export async function backfillStoredPermissionSetPackages( } switch (holder.kind) { case 'package': { + const packageId = holder.packageId; + if (predictsSecondGrants && (await wouldBeSecondGrant(engine, reference, row, name, packageId))) { + duplicated.push({ id: String(id), name, packageId, ...writer(caller) }); + break; + } if (!options?.dryRun) { - await engine.update(object, { id, [packageColumn]: holder.packageId }, { context: SYSTEM_CTX }); + try { + await engine.update(object, { id, [packageColumn]: packageId }, { context: SYSTEM_CTX }); + } catch (e: unknown) { + // [#32164] One row whose bind is a unique violation is reported + // and left as it stands; the walk goes on, so every other row is + // still bound (`duplicated`). + if (!isUniqueViolationError(e)) throw e; + duplicated.push({ id: String(id), name, packageId, ...writer(caller) }); + break; + } } - const packageId = holder.packageId; tally(bound, key, () => ({ name, ...writer(caller), rows: 0, packageId })); break; } @@ -320,6 +415,7 @@ export async function backfillStoredPermissionSetPackages( unheld: [...unheld.values()], unpackaged: [...unpackaged.values()], differs, + duplicated, }; } @@ -457,4 +553,13 @@ export function logStoredReferenceBackfill(report: StoredReferenceBackfillReport { differs: report.differs }, ); } + if (report.duplicated.length > 0) { + logger.warn( + `[security] ${at}: these rows were left naming no package, because binding each would make it a second row of one ` + + 'key: another row already names the same holder for the same reference (for a grant: the same user, permission ' + + 'set and organization). Review each pair and delete the row that should not stand — ' + + report.duplicated.map((d) => `row ${d.id}: '${d.name}'${typeof d.callerPackageId === 'string' ? ` as written by ${d.callerPackageId}` : ''} → ${d.packageId}`).join(', ') + '.', + { duplicated: report.duplicated }, + ); + } } diff --git a/packages/plugins/plugin-security/src/stored-permission-set-package-stamp.ts b/packages/plugins/plugin-security/src/stored-permission-set-package-stamp.ts index a7eefaddf59..c8473a55eb4 100644 --- a/packages/plugins/plugin-security/src/stored-permission-set-package-stamp.ts +++ b/packages/plugins/plugin-security/src/stored-permission-set-package-stamp.ts @@ -47,22 +47,103 @@ * then on. A null answer writes the key only to replace a value the writer * sent; otherwise the column is left to its default. * - * ## What a write keeps + * ## What a write keeps (ADR-0150 D3/D8, #32164) * - * - **An insert** is stamped from its name, whoever writes it: a value the - * writer sent is replaced — the column is `readonly`, and what it names is - * what the authorization resolver reads. No writer today knows more than the - * name; binding a refused name is the operator's reviewed bind, an update. + * A writer that NAMES a package (a non-blank `permission_set_package` in its + * payload) has said which set it means, so the seam never picks for it: + * + * - **the package holds the name** (a registry holder of `(permission, name)` + * for the reference's writer) ⇒ kept as written — even where the bare name + * is refused (two holders), which is how a grant of either package's set is + * written at all; + * - **it does not** ⇒ refused, `409 RESOURCE_CONFLICT`, core's + * `PackageScopedNameRefusedError`, reason `not-held-by-qualifier`, naming + * every holder — at ANY holder count, never re-stamped to the holder it + * did not name (epic red line 1). One holder included: before #32164 such a + * write was re-stamped to the one holder without a word; + * - **nothing holds the name** ⇒ kept unjudged: there is no holder to name and + * nothing to contradict it, and the reader reads a column naming a package + * that does not serve the set as no package (`storedPermissionSetScope`), so + * it confers nothing. A system writer may write a grant before the set it + * names is registered — the stand-down the grant-name hook takes. + * + * A writer that names none is stamped by the rule: + * + * - **An insert** is stamped from its name, whoever writes it. No first-party + * writer names a package (measured on #32164: the stamp, the boot backfill + * and the reviewed bind are the column's only writers). * - **An update** is stamped only when it changes what the reference names: * the set's name, or (R3) the package that wrote it. A rename never keeps the - * old package. An update that touches neither — the backfill's and the - * reviewed bind's, which write the column alone — is left as it is. + * old package. An update that touches neither is left as it is. + * + * An update that writes the column itself — the backfill's and the reviewed + * bind's, which write it alone, or a rename that names its package — is judged + * as above when a SYSTEM writer sends it. A value equal to the one the row + * already stores is an echo (a whole-row write), not a choice, and is not + * judged. A non-system caller's value of the + * `readonly` column is stripped by the engine after the before-phase, so the + * seam neither judges nor keeps it: a non-system update is stamped by the rule. + * + * Before the holders are sealed nothing is judged: a named package is kept as + * written (a stale one reads as no package), and a name with none is left null. + * + * A suggestion (R3) names a package for the package that suggested it, so the + * package it names must be in that package's reach: itself, or a package of its + * declared dependency closure (ADR-0141, the closure the rule reads the + * suggestion's name in). A holder outside that reach is refused, + * `outside-closure`, naming the holder (epic review 6735731423: such a + * suggestion is never bound). + * + * ## One grant of a set per user and organization (#32164) + * + * The grant's declared key is `(user_id, permission_set, + * permission_set_package, organization_id)`, so one user may hold two + * packages' sets of one name, and the package-less guard keeps grants that + * name no package to one per `(user_id, permission_set, organization_id)`. + * Neither index sees a grant beside another of the same user, set and + * organization when one of the two names no package, or names a package that + * does not hold the name: the key the grant had before #32164, + * `(user_id, permission_set, organization_id)`, refused every such second row. + * So this seam refuses it, once the column is stamped: a grant write that + * leaves a row of the same `(user_id, permission_set, organization_id)` beside + * another is refused unless the two rows name two DIFFERENT packages that each + * hold the name (the one pair the wider key exists to admit). The refusal is + * the one the old key's database answered through the engine: the engine's + * duplicate-record envelope (`DuplicateRecordError`, `code` + * `DUPLICATE_RECORD`, `status` `409`, the same user-facing sentence naming the + * object by its declared label), which every HTTP door reports as `409` + * `UNIQUE_VIOLATION`, "A record with this value already exists". It is built + * here in that shape, the seam's own diagnosis on `cause`, because this + * package does not depend on the engine at runtime. + * Read under the system context, in the writer's transaction. A write with no + * organization on the row and none in its session is not judged here (the + * driver fills the organization after this phase), and a write made below the + * engine, two writes racing, or two rows of one batch insert, are held by the + * two indexes alone. + * + * The check runs at priority 50, after every refusal of the grant table's + * hooks (30, 35, 40, 45), which keep their answer as while the store's key + * answered last; and it steps aside, as they do, on a holder a non-system + * write NAMES that the caller's own read door does not return, which the + * engine's reference check answers as a user that does not exist (#29029, + * `holderLeftToReferenceCheck`). Record validation runs after every hook, so a + * second grant it would also refuse is answered here (declared). */ +import { PackageScopedNameRefusedError, packageScopedRefusalMessage, type PackageScopedHolder } from '@objectstack/core'; +import { packageResolutionClosure } from '@objectstack/metadata-core'; import { isPlainRecord } from '@objectstack/spec/data'; +import { holderLeftToReferenceCheck } from './grant-holder-membership-refusal.js'; import { + GRANT_HOLDER_COLUMN as GRANT_HOLDER, + GRANT_OBJECT, + GRANT_ORGANIZATION_COLUMN as GRANT_ORGANIZATION, + grantKeyOf as keyOf, isPermissionSetHolderRegistry, + isSecondGrant, + otherGrantsOf, permissionSetHolderOf, + sealedPackageHoldersOf, STORED_PERMISSION_SET_REFERENCES, type StoredPermissionSetReference, } from './stored-permission-set-package-backfill.js'; @@ -73,6 +154,9 @@ export const PERMISSION_SET_PACKAGE_STAMP_HOOK_PACKAGE = 'plugin-security:permis /** After the grant-name refusals (priority 30): a refused write is never stamped. */ const HOOK_PRIORITY = 40; +/** The one-grant check: after the agent-account refusal (45), before the default-priority hooks (module doc). */ +const ONE_GRANT_HOOK_PRIORITY = 50; + interface StampEngine { registry?: unknown; getSchema?: (object: string) => unknown; @@ -82,6 +166,7 @@ interface StampEngine { options?: { object?: string | string[]; priority?: number; packageId?: string }, ) => void; unregisterHooksByPackage?: (packageId: string) => number; + find?: (object: string, query?: any) => Promise; } const hasOwn = (o: object, k: string): boolean => Object.prototype.hasOwnProperty.call(o, k); @@ -93,19 +178,63 @@ const named = (value: unknown): string | null => { return v === '' ? null : v; }; +/** The registry's holder reads, once its bare-name holders are sealed; `undefined` before that, or without them. */ +function sealedHolderRegistry(engine: StampEngine) { + const registry = engine.registry; + if (!isPermissionSetHolderRegistry(registry)) return undefined; + if ((registry as { bareNameHoldersAreSealed?: unknown }).bareNameHoldersAreSealed !== true) return undefined; + return registry; +} + /** * The package to stamp for `name` written by `caller` (`null`: no package), or * `null`: no package holds it for that caller, or the holders are not sealed * yet (module doc). */ function stampFor(engine: StampEngine, name: string, caller: string | null): string | null { - const registry = engine.registry; - if (!isPermissionSetHolderRegistry(registry)) return null; - if ((registry as { bareNameHoldersAreSealed?: unknown }).bareNameHoldersAreSealed !== true) return null; + const registry = sealedHolderRegistry(engine); + if (!registry) return null; const holder = permissionSetHolderOf(registry)(name, caller); return holder.kind === 'package' ? holder.packageId : null; } +/** + * [#32164] Judge a package a writer named beside `name` (module doc, "What a + * write keeps"): returns when it is kept, throws the `not-held-by-qualifier` + * refusal naming every holder when it is not. + */ +function assertNamedPackageHolds(engine: StampEngine, name: string, named: string, caller: string | null): void { + const registry = sealedHolderRegistry(engine); + if (!registry) return; + const packageHolders = registry.packageScopedHoldersOf('permission', name, caller) ?? []; + if (packageHolders.includes(named)) { + // A suggestion's package names the set for the package that suggested it: + // a holder outside that package's reach is never bound (module doc). + if (caller === null || named === caller || packageResolutionClosure(registry, caller).has(named)) return; + const outside = { + status: 'refused' as const, + reason: 'outside-closure' as const, + type: 'permission' as const, + name, + callerPackageId: caller, + candidates: [{ kind: 'package' as const, packageId: named }], + }; + throw new PackageScopedNameRefusedError({ ...outside, message: packageScopedRefusalMessage(outside) }); + } + const candidates: PackageScopedHolder[] = packageHolders.map((packageId) => ({ kind: 'package' as const, packageId })); + if (registry.getEnvironmentScopedItem('permission', name) !== undefined) candidates.push({ kind: 'environment' }); + if (candidates.length === 0) return; + const refusal = { + status: 'refused' as const, + reason: 'not-held-by-qualifier' as const, + type: 'permission' as const, + name, + callerPackageId: named, + candidates, + }; + throw new PackageScopedNameRefusedError({ ...refusal, message: packageScopedRefusalMessage(refusal) }); +} + /** Whether the object as registered declares the package column (module doc, "Where the column is not declared"). */ function declaresColumn(engine: StampEngine, reference: StoredPermissionSetReference): boolean { if (typeof engine.getSchema !== 'function') return false; @@ -130,6 +259,113 @@ function writerOf(reference: StoredPermissionSetReference, row: Record, + id: string | null, +): Promise { + const user = keyOf(image[GRANT_HOLDER]); + const name = named(image[reference.nameColumn]); + const organization = keyOf(image[GRANT_ORGANIZATION]) ?? keyOf(ctx?.session?.organizationId); + if (user === null || name === null || organization === null) return; + const others = await otherGrantsOf(engine, reference, { user, name, organization, id }, ctx?.transaction); + if (!isSecondGrant(others, reference.packageColumn, image[reference.packageColumn], sealedPackageHoldersOf(engine.registry, name))) return; + throw secondGrantRefusal(reference.object, labelOf(engine, reference.object)); +} + +/** A holder a non-system write names that the caller cannot read: the engine's reference check answers it (module doc). */ +async function holderLeftToEngine(engine: StampEngine, ctx: any, holder: unknown): Promise { + if (ctx?.session?.isSystem === true) return false; + // The holder's id as written: the reading the grant table's other hooks share. + return keyOf(holder) !== null && (await holderLeftToReferenceCheck(engine, ctx, holder, String(holder))); +} + +/** The one-grant check of an insert (module doc, "One grant of a set per user and organization"). */ +async function oneGrantOnInsert(engine: StampEngine, reference: StoredPermissionSetReference, ctx: any): Promise { + if (ctx?.object !== GRANT_OBJECT || reference.object !== GRANT_OBJECT) return; + const data = ctx?.input?.data; + if (!isPlainRecord(data) || !declaresColumn(engine, reference)) return; + if (await holderLeftToEngine(engine, ctx, data[GRANT_HOLDER])) return; + // A row whose own id the store already holds is the store's own refusal, not a second grant. + await assertOneGrantPerSet(engine, reference, ctx, data, keyOf(data.id)); +} + +/** The one-grant check of an update (module doc). */ +async function oneGrantOnUpdate(engine: StampEngine, reference: StoredPermissionSetReference, ctx: any): Promise { + if (ctx?.object !== GRANT_OBJECT || reference.object !== GRANT_OBJECT) return; + const data = ctx?.input?.data; + if (!isPlainRecord(data) || !declaresColumn(engine, reference)) return; + const previous = isPlainRecord(ctx?.previous) ? ctx.previous : {}; + const system = ctx?.session?.isSystem === true; + // Only a holder the payload NAMES anew: the reference check forgives one the row already stores. + if (hasOwn(data, GRANT_HOLDER) && keyOf(data[GRANT_HOLDER]) !== keyOf(previous[GRANT_HOLDER]) + && (await holderLeftToEngine(engine, ctx, data[GRANT_HOLDER]))) return; + const renamed = hasOwn(data, reference.nameColumn) + && named(data[reference.nameColumn]) !== named(previous[reference.nameColumn]); + // The package the row stores after the write: a system writer's value; a + // re-name's stamp; otherwise the stored one (a non-system caller's value of + // the readonly column is stripped after the before-phase). + const pkg = (system || renamed) && hasOwn(data, reference.packageColumn) + ? data[reference.packageColumn] + : previous[reference.packageColumn]; + const image: Record = { ...previous, ...data, [reference.packageColumn]: pkg }; + const moved = [GRANT_HOLDER, reference.nameColumn, GRANT_ORGANIZATION] + .some((column) => keyOf(image[column]) !== keyOf(previous[column])) + || named(pkg) !== named(previous[reference.packageColumn]); + if (!moved) return; + await assertOneGrantPerSet(engine, reference, ctx, image, keyOf(previous.id) ?? keyOf(ctx?.input?.id)); +} + /** `beforeInsert`: one dispatch per row (module doc, "What a write keeps"). */ function onInsert(engine: StampEngine, reference: StoredPermissionSetReference, ctx: any): void { if (ctx?.object !== reference.object) return; @@ -137,7 +373,16 @@ function onInsert(engine: StampEngine, reference: StoredPermissionSetReference, if (!isPlainRecord(data)) return; const name = named(data[reference.nameColumn]); if (name === null || !declaresColumn(engine, reference)) return; - stamp(data, reference.packageColumn, stampFor(engine, name, writerOf(reference, data))); + const writer = writerOf(reference, data); + const chosen = named(data[reference.packageColumn]); + if (chosen !== null) { + // [#32164] The writer named its package: kept when it holds the name, + // refused when it does not — never re-stamped (module doc). + assertNamedPackageHolds(engine, name, chosen, writer); + data[reference.packageColumn] = chosen; + return; + } + stamp(data, reference.packageColumn, stampFor(engine, name, writer)); } /** `beforeUpdate`: one dispatch per matched row, `previous` bound (module doc). */ @@ -146,13 +391,27 @@ function onUpdate(engine: StampEngine, reference: StoredPermissionSetReference, const data = ctx?.input?.data; if (!isPlainRecord(data)) return; const previous = isPlainRecord(ctx?.previous) ? ctx.previous : {}; + // [#32164] Only a system writer's value of the readonly column is stored; + // a non-system caller's is stripped after this phase (module doc). An echo + // of the stored value (a whole-row write) chooses nothing new. + const sent = ctx?.session?.isSystem === true && hasOwn(data, reference.packageColumn) + ? named(data[reference.packageColumn]) + : null; + const chosen = sent !== null && sent !== named(previous[reference.packageColumn]) ? sent : null; const touchesName = hasOwn(data, reference.nameColumn) && named(data[reference.nameColumn]) !== named(previous[reference.nameColumn]); const touchesWriter = reference.callerColumn !== undefined && hasOwn(data, reference.callerColumn) && named(data[reference.callerColumn]) !== named(previous[reference.callerColumn]); - if ((!touchesName && !touchesWriter) || !declaresColumn(engine, reference)) return; + if ((chosen === null && !touchesName && !touchesWriter) || !declaresColumn(engine, reference)) return; const after = { ...previous, ...data }; const name = named(after[reference.nameColumn]); + if (chosen !== null) { + // A system writer naming the package — the reviewed bind, the backfill, + // a rename that says which set it means — is judged, never re-stamped. + if (name !== null) assertNamedPackageHolds(engine, name, chosen, writerOf(reference, after)); + return; + } + if (!touchesName && !touchesWriter) return; // A rename always writes the key: the old package must not survive it. data[reference.packageColumn] = name === null ? null : stampFor(engine, name, writerOf(reference, after)); } @@ -167,6 +426,11 @@ export function registerPermissionSetPackageStamp(engine: StampEngine | null | u const options = { object: reference.object, priority: HOOK_PRIORITY, packageId: PERMISSION_SET_PACKAGE_STAMP_HOOK_PACKAGE }; engine.registerHook('beforeInsert', (ctx: any) => onInsert(engine, reference, ctx), options); engine.registerHook('beforeUpdate', (ctx: any) => onUpdate(engine, reference, ctx), options); + if (reference.object !== GRANT_OBJECT) continue; + // [#32164] The one-grant check, after the grant table's refusals (module doc). + const oneGrant = { ...options, priority: ONE_GRANT_HOOK_PRIORITY }; + engine.registerHook('beforeInsert', (ctx: any) => oneGrantOnInsert(engine, reference, ctx), oneGrant); + engine.registerHook('beforeUpdate', (ctx: any) => oneGrantOnUpdate(engine, reference, ctx), oneGrant); } return true; } diff --git a/packages/plugins/plugin-security/src/translations/ar.objects.generated.ts b/packages/plugins/plugin-security/src/translations/ar.objects.generated.ts index 77899f1508e..c5077546fd4 100644 --- a/packages/plugins/plugin-security/src/translations/ar.objects.generated.ts +++ b/packages/plugins/plugin-security/src/translations/ar.objects.generated.ts @@ -42,7 +42,7 @@ export const arObjects: NonNullable = { }, permission_set_package: { label: "Permission Set Package", - help: "The app the permission set comes from. Filled in by the platform; empty when the set was created here, or when more than one app provides a set of that name." + help: "The app the permission set comes from. A grant names it to choose between apps that provide a set of the same name; otherwise the platform fills it in. Empty when the set was created here, or when more than one app provides a set of that name and the grant names none." }, granted_by: { label: "مَن منحه", diff --git a/packages/plugins/plugin-security/src/translations/ar.source-hashes.generated.ts b/packages/plugins/plugin-security/src/translations/ar.source-hashes.generated.ts index 6d7aa1be637..b79907deb35 100644 --- a/packages/plugins/plugin-security/src/translations/ar.source-hashes.generated.ts +++ b/packages/plugins/plugin-security/src/translations/ar.source-hashes.generated.ts @@ -18,6 +18,6 @@ */ export const arGeneratedSourceHashes: Readonly> = { - "objects.sys_user_permission_set.fields.permission_set_package.help": "4113fdb4710cddea", + "objects.sys_user_permission_set.fields.permission_set_package.help": "f82676b45357ad48", "objects.sys_user_permission_set.fields.permission_set_package.label": "4b0224196e5cc035", }; diff --git a/packages/plugins/plugin-security/src/translations/de.objects.generated.ts b/packages/plugins/plugin-security/src/translations/de.objects.generated.ts index 0932b8a662e..637028cfbfe 100644 --- a/packages/plugins/plugin-security/src/translations/de.objects.generated.ts +++ b/packages/plugins/plugin-security/src/translations/de.objects.generated.ts @@ -42,7 +42,7 @@ export const deObjects: NonNullable = { }, permission_set_package: { label: "Permission Set Package", - help: "The app the permission set comes from. Filled in by the platform; empty when the set was created here, or when more than one app provides a set of that name." + help: "The app the permission set comes from. A grant names it to choose between apps that provide a set of the same name; otherwise the platform fills it in. Empty when the set was created here, or when more than one app provides a set of that name and the grant names none." }, granted_by: { label: "Gewährt von", diff --git a/packages/plugins/plugin-security/src/translations/de.source-hashes.generated.ts b/packages/plugins/plugin-security/src/translations/de.source-hashes.generated.ts index d31bdd63157..87cb8e50b49 100644 --- a/packages/plugins/plugin-security/src/translations/de.source-hashes.generated.ts +++ b/packages/plugins/plugin-security/src/translations/de.source-hashes.generated.ts @@ -18,7 +18,7 @@ */ export const deGeneratedSourceHashes: Readonly> = { - "objects.sys_user_permission_set.fields.permission_set_package.help": "4113fdb4710cddea", + "objects.sys_user_permission_set.fields.permission_set_package.help": "f82676b45357ad48", "objects.sys_user_permission_set.fields.permission_set_package.label": "4b0224196e5cc035", "objects.sys_user_position.fields.position.label": "9a24c02e441eb0b4", }; diff --git a/packages/plugins/plugin-security/src/translations/en.objects.generated.ts b/packages/plugins/plugin-security/src/translations/en.objects.generated.ts index 705fdfb6a0d..86c6dec08e3 100644 --- a/packages/plugins/plugin-security/src/translations/en.objects.generated.ts +++ b/packages/plugins/plugin-security/src/translations/en.objects.generated.ts @@ -42,7 +42,7 @@ export const enObjects: NonNullable = { }, permission_set_package: { label: "Permission Set Package", - help: "The app the permission set comes from. Filled in by the platform; empty when the set was created here, or when more than one app provides a set of that name." + help: "The app the permission set comes from. A grant names it to choose between apps that provide a set of the same name; otherwise the platform fills it in. Empty when the set was created here, or when more than one app provides a set of that name and the grant names none." }, granted_by: { label: "Granted By", diff --git a/packages/plugins/plugin-security/src/translations/es-ES.objects.generated.ts b/packages/plugins/plugin-security/src/translations/es-ES.objects.generated.ts index 66eec923698..5e7d0d3290e 100644 --- a/packages/plugins/plugin-security/src/translations/es-ES.objects.generated.ts +++ b/packages/plugins/plugin-security/src/translations/es-ES.objects.generated.ts @@ -42,7 +42,7 @@ export const esESObjects: NonNullable = { }, permission_set_package: { label: "Permission Set Package", - help: "The app the permission set comes from. Filled in by the platform; empty when the set was created here, or when more than one app provides a set of that name." + help: "The app the permission set comes from. A grant names it to choose between apps that provide a set of the same name; otherwise the platform fills it in. Empty when the set was created here, or when more than one app provides a set of that name and the grant names none." }, granted_by: { label: "Concedido por", diff --git a/packages/plugins/plugin-security/src/translations/es-ES.source-hashes.generated.ts b/packages/plugins/plugin-security/src/translations/es-ES.source-hashes.generated.ts index b12583cb89e..cd8c3333451 100644 --- a/packages/plugins/plugin-security/src/translations/es-ES.source-hashes.generated.ts +++ b/packages/plugins/plugin-security/src/translations/es-ES.source-hashes.generated.ts @@ -21,7 +21,7 @@ export const esESGeneratedSourceHashes: Readonly> = { "objects.sys_user_permission_set._validations.validity_window_order.message": "b2216aacc3b6f97b", "objects.sys_user_permission_set.fields.display_title.help": "ee7ef063488cd6c3", "objects.sys_user_permission_set.fields.display_title.label": "70f7aadecce647a5", - "objects.sys_user_permission_set.fields.permission_set_package.help": "4113fdb4710cddea", + "objects.sys_user_permission_set.fields.permission_set_package.help": "f82676b45357ad48", "objects.sys_user_permission_set.fields.permission_set_package.label": "4b0224196e5cc035", "objects.sys_user_position._validations.reserved_identity_position.message": "1ab6d3060fc7e20a", "objects.sys_user_position.fields.display_title.help": "39b5571b48e7d800", diff --git a/packages/plugins/plugin-security/src/translations/fr.objects.generated.ts b/packages/plugins/plugin-security/src/translations/fr.objects.generated.ts index 10075bded3c..de3cc50e5bb 100644 --- a/packages/plugins/plugin-security/src/translations/fr.objects.generated.ts +++ b/packages/plugins/plugin-security/src/translations/fr.objects.generated.ts @@ -42,7 +42,7 @@ export const frObjects: NonNullable = { }, permission_set_package: { label: "Permission Set Package", - help: "The app the permission set comes from. Filled in by the platform; empty when the set was created here, or when more than one app provides a set of that name." + help: "The app the permission set comes from. A grant names it to choose between apps that provide a set of the same name; otherwise the platform fills it in. Empty when the set was created here, or when more than one app provides a set of that name and the grant names none." }, granted_by: { label: "Accordé par", diff --git a/packages/plugins/plugin-security/src/translations/fr.source-hashes.generated.ts b/packages/plugins/plugin-security/src/translations/fr.source-hashes.generated.ts index cbb70cdb0a8..f677293a372 100644 --- a/packages/plugins/plugin-security/src/translations/fr.source-hashes.generated.ts +++ b/packages/plugins/plugin-security/src/translations/fr.source-hashes.generated.ts @@ -18,6 +18,6 @@ */ export const frGeneratedSourceHashes: Readonly> = { - "objects.sys_user_permission_set.fields.permission_set_package.help": "4113fdb4710cddea", + "objects.sys_user_permission_set.fields.permission_set_package.help": "f82676b45357ad48", "objects.sys_user_permission_set.fields.permission_set_package.label": "4b0224196e5cc035", }; diff --git a/packages/plugins/plugin-security/src/translations/ja-JP.objects.generated.ts b/packages/plugins/plugin-security/src/translations/ja-JP.objects.generated.ts index cd87608e51a..3130c9116d5 100644 --- a/packages/plugins/plugin-security/src/translations/ja-JP.objects.generated.ts +++ b/packages/plugins/plugin-security/src/translations/ja-JP.objects.generated.ts @@ -42,7 +42,7 @@ export const jaJPObjects: NonNullable = { }, permission_set_package: { label: "Permission Set Package", - help: "The app the permission set comes from. Filled in by the platform; empty when the set was created here, or when more than one app provides a set of that name." + help: "The app the permission set comes from. A grant names it to choose between apps that provide a set of the same name; otherwise the platform fills it in. Empty when the set was created here, or when more than one app provides a set of that name and the grant names none." }, granted_by: { label: "付与者", diff --git a/packages/plugins/plugin-security/src/translations/ja-JP.source-hashes.generated.ts b/packages/plugins/plugin-security/src/translations/ja-JP.source-hashes.generated.ts index 527d7f09342..44e038e9cc0 100644 --- a/packages/plugins/plugin-security/src/translations/ja-JP.source-hashes.generated.ts +++ b/packages/plugins/plugin-security/src/translations/ja-JP.source-hashes.generated.ts @@ -21,7 +21,7 @@ export const jaJPGeneratedSourceHashes: Readonly> = { "objects.sys_user_permission_set._validations.validity_window_order.message": "b2216aacc3b6f97b", "objects.sys_user_permission_set.fields.display_title.help": "ee7ef063488cd6c3", "objects.sys_user_permission_set.fields.display_title.label": "70f7aadecce647a5", - "objects.sys_user_permission_set.fields.permission_set_package.help": "4113fdb4710cddea", + "objects.sys_user_permission_set.fields.permission_set_package.help": "f82676b45357ad48", "objects.sys_user_permission_set.fields.permission_set_package.label": "4b0224196e5cc035", "objects.sys_user_position._validations.reserved_identity_position.message": "1ab6d3060fc7e20a", "objects.sys_user_position.fields.display_title.help": "39b5571b48e7d800", diff --git a/packages/plugins/plugin-security/src/translations/ko.objects.generated.ts b/packages/plugins/plugin-security/src/translations/ko.objects.generated.ts index 31b111f960e..b62b19ced08 100644 --- a/packages/plugins/plugin-security/src/translations/ko.objects.generated.ts +++ b/packages/plugins/plugin-security/src/translations/ko.objects.generated.ts @@ -42,7 +42,7 @@ export const koObjects: NonNullable = { }, permission_set_package: { label: "Permission Set Package", - help: "The app the permission set comes from. Filled in by the platform; empty when the set was created here, or when more than one app provides a set of that name." + help: "The app the permission set comes from. A grant names it to choose between apps that provide a set of the same name; otherwise the platform fills it in. Empty when the set was created here, or when more than one app provides a set of that name and the grant names none." }, granted_by: { label: "부여자", diff --git a/packages/plugins/plugin-security/src/translations/ko.source-hashes.generated.ts b/packages/plugins/plugin-security/src/translations/ko.source-hashes.generated.ts index f739e8a47d6..e79fb5dec73 100644 --- a/packages/plugins/plugin-security/src/translations/ko.source-hashes.generated.ts +++ b/packages/plugins/plugin-security/src/translations/ko.source-hashes.generated.ts @@ -18,6 +18,6 @@ */ export const koGeneratedSourceHashes: Readonly> = { - "objects.sys_user_permission_set.fields.permission_set_package.help": "4113fdb4710cddea", + "objects.sys_user_permission_set.fields.permission_set_package.help": "f82676b45357ad48", "objects.sys_user_permission_set.fields.permission_set_package.label": "4b0224196e5cc035", }; diff --git a/packages/plugins/plugin-security/src/translations/pt-BR.objects.generated.ts b/packages/plugins/plugin-security/src/translations/pt-BR.objects.generated.ts index 471e9a3ad6b..3e472aae485 100644 --- a/packages/plugins/plugin-security/src/translations/pt-BR.objects.generated.ts +++ b/packages/plugins/plugin-security/src/translations/pt-BR.objects.generated.ts @@ -42,7 +42,7 @@ export const ptBRObjects: NonNullable = { }, permission_set_package: { label: "Permission Set Package", - help: "The app the permission set comes from. Filled in by the platform; empty when the set was created here, or when more than one app provides a set of that name." + help: "The app the permission set comes from. A grant names it to choose between apps that provide a set of the same name; otherwise the platform fills it in. Empty when the set was created here, or when more than one app provides a set of that name and the grant names none." }, granted_by: { label: "Concedido por", diff --git a/packages/plugins/plugin-security/src/translations/pt-BR.source-hashes.generated.ts b/packages/plugins/plugin-security/src/translations/pt-BR.source-hashes.generated.ts index 1c3024a9a19..c437f91bfc4 100644 --- a/packages/plugins/plugin-security/src/translations/pt-BR.source-hashes.generated.ts +++ b/packages/plugins/plugin-security/src/translations/pt-BR.source-hashes.generated.ts @@ -18,6 +18,6 @@ */ export const ptBRGeneratedSourceHashes: Readonly> = { - "objects.sys_user_permission_set.fields.permission_set_package.help": "4113fdb4710cddea", + "objects.sys_user_permission_set.fields.permission_set_package.help": "f82676b45357ad48", "objects.sys_user_permission_set.fields.permission_set_package.label": "4b0224196e5cc035", }; diff --git a/packages/plugins/plugin-security/src/translations/ru.objects.generated.ts b/packages/plugins/plugin-security/src/translations/ru.objects.generated.ts index 4d3780cf1a1..daf146033ad 100644 --- a/packages/plugins/plugin-security/src/translations/ru.objects.generated.ts +++ b/packages/plugins/plugin-security/src/translations/ru.objects.generated.ts @@ -42,7 +42,7 @@ export const ruObjects: NonNullable = { }, permission_set_package: { label: "Permission Set Package", - help: "The app the permission set comes from. Filled in by the platform; empty when the set was created here, or when more than one app provides a set of that name." + help: "The app the permission set comes from. A grant names it to choose between apps that provide a set of the same name; otherwise the platform fills it in. Empty when the set was created here, or when more than one app provides a set of that name and the grant names none." }, granted_by: { label: "Кем выдано", diff --git a/packages/plugins/plugin-security/src/translations/ru.source-hashes.generated.ts b/packages/plugins/plugin-security/src/translations/ru.source-hashes.generated.ts index 5310e2fabf0..420553251d8 100644 --- a/packages/plugins/plugin-security/src/translations/ru.source-hashes.generated.ts +++ b/packages/plugins/plugin-security/src/translations/ru.source-hashes.generated.ts @@ -18,6 +18,6 @@ */ export const ruGeneratedSourceHashes: Readonly> = { - "objects.sys_user_permission_set.fields.permission_set_package.help": "4113fdb4710cddea", + "objects.sys_user_permission_set.fields.permission_set_package.help": "f82676b45357ad48", "objects.sys_user_permission_set.fields.permission_set_package.label": "4b0224196e5cc035", }; diff --git a/packages/plugins/plugin-security/src/translations/zh-CN.objects.generated.ts b/packages/plugins/plugin-security/src/translations/zh-CN.objects.generated.ts index 4ef441dfb67..481ae0c3819 100644 --- a/packages/plugins/plugin-security/src/translations/zh-CN.objects.generated.ts +++ b/packages/plugins/plugin-security/src/translations/zh-CN.objects.generated.ts @@ -42,7 +42,7 @@ export const zhCNObjects: NonNullable = { }, permission_set_package: { label: "权限集所属应用", - help: "该权限集来自哪个应用。由平台填写;权限集是在这里创建的,或有多个应用提供同名权限集时为空。" + help: "该权限集来自哪个应用。有多个应用提供同名权限集时,授权用它指明是哪个应用的;否则由平台填写。权限集是在这里创建的,或有多个应用提供同名权限集而授权未指明时为空。" }, granted_by: { label: "授权人", diff --git a/packages/plugins/plugin-security/src/translations/zh-Hant.objects.generated.ts b/packages/plugins/plugin-security/src/translations/zh-Hant.objects.generated.ts index a10268dbd41..f56ff3e179c 100644 --- a/packages/plugins/plugin-security/src/translations/zh-Hant.objects.generated.ts +++ b/packages/plugins/plugin-security/src/translations/zh-Hant.objects.generated.ts @@ -42,7 +42,7 @@ export const zhHantObjects: NonNullable = { }, permission_set_package: { label: "權限集所屬應用", - help: "該權限集來自哪個應用。由平台填寫;權限集是在這裡建立的,或有多個應用提供同名權限集時為空。" + help: "該權限集來自哪個應用。有多個應用提供同名權限集時,授權用它指明是哪個應用的;否則由平台填寫。權限集是在這裡建立的,或有多個應用提供同名權限集而授權未指明時為空。" }, granted_by: { label: "授予者", diff --git a/packages/qa/dogfood/test/stored-reference-package-column.dogfood.test.ts b/packages/qa/dogfood/test/stored-reference-package-column.dogfood.test.ts index 7d86a1e4125..7cb2766d9e7 100644 --- a/packages/qa/dogfood/test/stored-reference-package-column.dogfood.test.ts +++ b/packages/qa/dogfood/test/stored-reference-package-column.dogfood.test.ts @@ -21,7 +21,10 @@ // nothing a package holds stay null; // - CONTROL: the administrator's resolved permissions answer byte-identically // with the column null, filled, and forged to a package that holds nothing -// — no reader reads it; +// — no reader reads it. Since #32164 (F3) the engine refuses to write that +// forged value for every writer, a system column-only bind included, so the +// forge is asserted refused there and then written below the engine, as a +// raw write or an earlier release could leave it; // - a further boot moves no row it bound (a forged value stays forged: a row // that names a package is never a candidate) and rewrites nothing. @@ -54,8 +57,12 @@ interface Engine { find(object: string, options?: unknown): Promise>>; insert(object: string, data: unknown, options?: unknown): Promise>; update(object: string, data: unknown, options?: unknown): Promise; + getDriverForObject(object: string): unknown; } +/** The SQL driver's own query builder, for a write that must not pass the engine's hooks. */ +type Knex = (table: string) => { whereIn(column: string, values: unknown[]): { update(data: Record): Promise } }; + describe('security and sharing references name the package that holds them (SQL driver, one database file)', () => { let stack: VerifyStack | undefined; let prevCwd: string; @@ -154,10 +161,26 @@ describe('security and sharing references name the package that holds them (SQL it('CONTROL: forged to a package that holds nothing, the column changes no answer, and a further boot neither moves it nor rewrites a bound row', async () => { const ql = await engine(); const before = (await rowsOf('sys_user_permission_set', { permission_set: SHOWCASE_SET }))[0]; - for (const g of await rowsOf('sys_user_permission_set', { user_id: admin.userId })) { - if (g.permission_set === SHOWCASE_SET) continue; - await ql.update('sys_user_permission_set', { id: g.id, permission_set_package: FORGED }, { context: SYSTEM_CTX }); + const others = (await rowsOf('sys_user_permission_set', { user_id: admin.userId })) + .filter((g) => g.permission_set !== SHOWCASE_SET); + expect(others.length).toBeGreaterThan(0); + // [#32164 F3] The engine refuses the forge: a named package that does not + // hold the set is `409 RESOURCE_CONFLICT`, `not-held-by-qualifier`, for a + // system column-only bind too, and the row is left as it was. + for (const g of others) { + const refused = await ql + .update('sys_user_permission_set', { id: g.id, permission_set_package: FORGED }, { context: SYSTEM_CTX }) + .then(() => undefined, (e: unknown) => e as { code?: string; refusal?: { status?: string; reason?: string } }); + expect([refused?.code, refused?.refusal?.status, refused?.refusal?.reason], String(g.permission_set)) + .toEqual(['RESOURCE_CONFLICT', 'refused', 'not-held-by-qualifier']); } + const unchanged = (await rowsOf('sys_user_permission_set', { user_id: admin.userId })) + .filter((g) => g.permission_set !== SHOWCASE_SET); + expect(unchanged.map((g) => g.permission_set_package)).toEqual(others.map((g) => g.permission_set_package)); + // So the forged value is written below the engine, straight through the driver. + const knex = (ql.getDriverForObject('sys_user_permission_set') as { knex: Knex }).knex; + expect(await knex('sys_user_permission_set').whereIn('id', others.map((g) => g.id)).update({ permission_set_package: FORGED })) + .toBe(others.length); await restart(); expect(await adminPermissions()).toBe(permissionsAtFirstBoot); diff --git a/packages/qa/dogfood/test/upgrade-18x-index-equivalence.dogfood.test.ts b/packages/qa/dogfood/test/upgrade-18x-index-equivalence.dogfood.test.ts index b777f7e67c2..9351b650c69 100644 --- a/packages/qa/dogfood/test/upgrade-18x-index-equivalence.dogfood.test.ts +++ b/packages/qa/dogfood/test/upgrade-18x-index-equivalence.dogfood.test.ts @@ -177,12 +177,25 @@ describe('[18.x step 7b] the organization key part across the 18.0 → HEAD upgr expectNoDestructiveIndexDrift(await managedDrift(stack!)); }); - it('the 11 declared organization composites survive the HEAD boot byte for byte', () => { + it('[#32164] the grant key that gained its package column: its 18.0 narrower is offered for retirement as ONE safe replace, the guard standing', async () => { + // `sys_user_permission_set`'s `(user_id, permission_set, organization_id)` + // became `(user_id, permission_set, permission_set_package, + // organization_id)`; the boot's schema-sync migration built the + // package-less guard, so on this certified store the differ's widening arm + // offers the 18.0 COALESCE index's retirement — never an orphan drop. + const grant = (await managedDrift(stack!)).filter((d) => d.table === 'sys_user_permission_set'); + expect(grant.map((d) => [d.op.type, d.category])).toEqual([['replace_unique_index', 'safe']]); + expect((grant[0]!.op as { dropIndexNames?: string[] }).dropIndexNames).toEqual(['uniq_sys_user_permission_set_ac248331']); + }); + + it('the 11 organization composites 18.0 declared survive the HEAD boot byte for byte', () => { // The other two are runtime-managed: the metadata protocol's own // migrations rebuild them on every boot over the plain organization key — // `sys_setting`'s identity index, and `sys_notification_preference`'s // one-global-default-per-key index, NULL-safe on its `user_id` (an empty - // User is the admin-global default, ADR-0118 D1). + // User is the admin-global default, ADR-0118 D1). One of the 11, + // `sys_user_permission_set`'s, is no longer declared (#32164): the boot + // keeps it too, and the leg above is its retirement. const declared = COALESCE_INDEXES_18_0.filter((i) => !RUNTIME_MANAGED_INDEX.test(i.name)); expect(declared).toHaveLength(11); const after = new Map(organizationUniqueIndexes(restored).map((i) => [i.name, i.sql])); diff --git a/packages/runtime/src/domains/catalog-activation.ts b/packages/runtime/src/domains/catalog-activation.ts index 443322dc4aa..7b5372d399a 100644 --- a/packages/runtime/src/domains/catalog-activation.ts +++ b/packages/runtime/src/domains/catalog-activation.ts @@ -53,6 +53,44 @@ * Who may call it is exactly who may call the flow and action doors: the * caller's `manage_metadata`, then the ADR-0126 §5 posture rule (inert under * `single`, the platform operator under a wall). ⛔ No new authority. + * + * ## A permission set two packages hold — `?package=` (ADR-0150 D3/D5, #32164) + * + * A permission set is identified by `(package, name)` (ADR-0150 D4), and the + * ledger keys its row the same way (`(metadata_type, package_id, name)`). A + * name two packages hold is the D3 refusal when the request names no package: + * `409 RESOURCE_CONFLICT`, the resolver's sentence, and every candidate + * structured in the envelope (`candidates: [{ kind: 'package', packageId }]`), + * nothing written — never the "nothing to switch off" `404` a miss answers. + * `?package=PKG`, the exact qualifier `/meta` reads (ADR-0150 D2 ruling), + * addresses exactly PKG's set and writes its ledger row naming PKG; a PKG that + * does not hold the name is refused `409` naming the holders + * (`not-held-by-qualifier`). With one holder, a request that names no package + * answers as before. + * + * ## One ledger row per holder (ADR-0150 D4/D8 R4, epic ruling MF1 on #32164) + * + * The permission type's ledger store is addressed by `(package, name)` + * ({@link PERMISSION_LEDGER_ADDRESSING}), as the flow store is: every reader of + * a permission set's row is package-aware (core's `readDisabledCatalogNames` + * and `ledgerRowSwitchesOff` read a row's `package_id` as its holder), so two + * packages each keep their own row of one name, and switching one never + * re-addresses the other's. Every other type keeps the name-addressed store. + * A row naming no package, or naming a package that no longer serves the name, + * is a holder's switch only while the name has that one holder (D8), so only + * then does a write take it over (`adoptPackageless`, or the stale row's + * re-address the name-addressed store always wrote); + * under two holders it is neither's, and the core readers keep every holder + * off by it. {@link planPermissionSetLedgerWrite} refuses `409` a write the + * readers would not follow: one that would re-address a switched-off row + * another holder reads as its own (a legacy row), and an enable that another + * row (one naming no package under two holders, or a package that no longer + * serves the name) would still keep off. Nothing is written then. + * + * The door's query set is closed (AGENTS route rule 5): `package` for + * `permission`, nothing for every other type — a name outside it is refused + * `400 VALIDATION_ERROR` before any lookup, where it used to be dropped + * without a word ({@link catalogActivationQueryParams}). */ import { AUDIENCE_ANCHOR_POSITIONS, GUEST_POSITION } from '@objectstack/spec/identity'; @@ -61,12 +99,17 @@ import { METADATA_ACTIVATION_TABLE, ObjectStoreMetadataActivationStore, PackageScopedNameRefusedError, + catalogEntryAddress, + ledgerRowSwitchesOff, packageScopedRefusalMessage, + resolveCatalogReference, securityCatalogReaderOf, type PackageScopedHolder, type PackageScopedRefusal, type SecurityCatalogEntry, + type SecurityCatalogReader, } from '@objectstack/core'; +import { repeatedQueryParamMessage, unknownQueryParamRefusalMessage } from '@objectstack/rest'; import { refuseUngrantedActivationWrite, refuseUngrantedActivationAuthoring, @@ -236,15 +279,302 @@ function packageScopedRefusalOf(err: unknown): PackageScopedRefusal | undefined /** * The door's answer to a refused name: `409 RESOURCE_CONFLICT`, the * resolver's sentence, and every candidate in the envelope — the shape the - * `/actions` door answers its own refusal with. Nothing is written. + * `/actions` door answers its own refusal with. Nothing is written. The + * permission-set clone door answers its refusals with it too. */ -function refusedNameAnswer(deps: DomainHandlerDeps, refusal: PackageScopedRefusal): HttpDispatcherResult { +export function refusedNameAnswer(deps: DomainHandlerDeps, refusal: PackageScopedRefusal): HttpDispatcherResult { return { handled: true, response: deps.error(refusal.message, 409, { code: 'RESOURCE_CONFLICT', candidates: refusal.candidates }), }; } +/** + * [ADR-0150 D5, #32164; AGENTS route rule 5] The closed query set of a door + * that addresses a permission set — `POST /security/_activation/permission/:name` + * and `POST /security/permission-sets/:name/clone`. **Measured**: `package` + * alone, the exact qualifier ({@link readPermissionSetPackageQuery}); neither + * door nor any helper it calls reads another query parameter. + */ +export const PERMISSION_SET_DOOR_QUERY_PARAMS: readonly string[] = Object.freeze(['package']); + +/** + * [AGENTS route rule 5] The closed query set of this door for every type but + * `permission`. **Measured**: EMPTY — a position, a declared sharing rule, + * webhook, queue or assignment rule is addressed by its path alone. + */ +const CATALOG_ACTIVATION_NO_QUERY_PARAMS: readonly string[] = Object.freeze([]); + +/** The closed query set of `POST /security/_activation/:type/:name`, per type. */ +export function catalogActivationQueryParams(type: string): readonly string[] { + return type === 'permission' ? PERMISSION_SET_DOOR_QUERY_PARAMS : CATALOG_ACTIVATION_NO_QUERY_PARAMS; +} + +/** + * [ADR-0150 D5, #32164] Read a permission-set door's query: refuse a name + * outside `declared` (`400 VALIDATION_ERROR`, the recognition sentence every + * closed-query door answers), then read `?package=` — one non-empty package id, + * or absent. A repeat is refused with the multiplicity sentence and an empty + * value as malformed: omission is spelled by leaving the parameter out. + */ +export function readPermissionSetPackageQuery( + deps: DomainHandlerDeps, + query: unknown, + declared: readonly string[], +): { packageId?: string; refusal?: HttpDispatcherResult } { + const unknownMessage = unknownQueryParamRefusalMessage(query, declared); + if (unknownMessage !== undefined) { + return { refusal: { handled: true, response: deps.error(unknownMessage, 400, { code: 'VALIDATION_ERROR' }) } }; + } + if (!declared.includes('package') || !query || typeof query !== 'object' + || !Object.prototype.hasOwnProperty.call(query, 'package')) { + return {}; + } + let raw = (query as Record).package; + if (Array.isArray(raw)) { + if (raw.length > 1) { + return { + refusal: { + handled: true, + response: deps.error(repeatedQueryParamMessage('package', raw.length), 400, { code: 'VALIDATION_ERROR' }), + }, + }; + } + raw = raw[0]; + } + if (typeof raw !== 'string' || raw.trim() === '') { + return { + refusal: { + handled: true, + response: deps.error( + '`package` names the package whose permission set this request addresses — a non-empty package id. ' + + 'Leave it out to address the set by its name alone.', + 400, + { code: 'VALIDATION_ERROR' }, + ), + }, + }; + } + return { packageId: raw.trim() }; +} + +/** + * [ADR-0150 D3/D5, #32164] The permission set a door addresses: by its name + * alone, or — `packageId` given — exactly that package's set. + * + * - `resolved`: the set. + * - `not-found`: no holder of the name anywhere (the door's `404`). + * - `refused`: the D3 refusal of the bare name (two holders), or a package + * that does not hold it (`not-held-by-qualifier`, naming the holders). Every + * candidate is structured. + * + * The named package is matched against the catalog's own per-holder entries + * (`list`, one per `(package, name)`) — never through the stored-column scope, + * whose stale-column arm reads a package that does not hold the name as no + * package and would pick the other holder. The twin of plugin-security's + * `judgeGrantSet`, which judges a grant's `permission_set_package` the same + * way; the two are pinned with the same cases. + */ +export async function resolvePermissionSetAddress( + reader: SecurityCatalogReader, + name: string, + packageId?: string, +): Promise< + | { readonly status: 'resolved'; readonly entry: SecurityCatalogEntry } + | { readonly status: 'not-found' } + | { readonly status: 'refused'; readonly refusal: PackageScopedRefusal } +> { + if (packageId === undefined) { + const answer = await resolveCatalogReference(reader, 'permission', name); + if (answer.status !== 'refused') return answer; + return { + status: 'refused', + refusal: { + status: 'refused', + reason: answer.reason as PackageScopedRefusal['reason'], + type: 'permission', + name, + callerPackageId: null, + candidates: answer.holders ?? [], + message: answer.message, + }, + }; + } + // [SF7] A holder's package is read as core's `catalogEntryAddress` reads it: + // the overlay provenance sentinel is no package, so `?package=` naming it + // holds nothing and a refusal names the environment, never the sentinel. + const holders = (await reader.list('permission')).filter((e) => e.name === name); + const exact = holders.find((e) => catalogEntryAddress(e).packageId === packageId); + if (exact) return { status: 'resolved', entry: exact }; + if (holders.length === 0) return { status: 'not-found' }; + const candidates: PackageScopedHolder[] = holders.map((e) => { + const holder = catalogEntryAddress(e).packageId; + return holder !== null ? { kind: 'package' as const, packageId: holder } : { kind: 'environment' as const }; + }); + const base = { + status: 'refused' as const, + reason: 'not-held-by-qualifier' as const, + type: 'permission' as const, + name, + callerPackageId: packageId, + candidates, + }; + return { status: 'refused', refusal: { ...base, message: packageScopedRefusalMessage(base) } }; +} + +/** + * [ADR-0150 D4, epic ruling MF1 on #32164] The permission type's ledger rows are + * addressed by `(package, name)` (core's `MetadataActivationRowAddressing`), as + * flows' are (`flow-activation-store.ts`): its readers are package-aware. Only + * this type: every other type's store stays name-addressed. + */ +export const PERMISSION_LEDGER_ADDRESSING = { addressing: 'package-and-name' } as const; + +/** The ledger row a permission write reads, as stored. */ +type PermissionLedgerRow = { id?: unknown; metadata_type?: unknown; name?: unknown; package_id?: unknown; active?: unknown }; + +/** A stored `package_id`, as the store compares it: empty and absent are no package. */ +const storedPackageOf = (row: PermissionLedgerRow): string | null => + (typeof row.package_id === 'string' && row.package_id !== '' ? row.package_id : null); + +/** + * A stored `package_id` as the readers read it (core's `catalogEntryAddress`): + * the overlay provenance sentinel names no package. How a refusal names a row. + */ +const readPackageOf = (row: PermissionLedgerRow, name: string): string | null => { + const stored = storedPackageOf(row); + return stored === null ? null : catalogEntryAddress({ name, packageId: stored }).packageId; +}; + +const holderPhrase = (packageId: string | null): string => + (packageId === null ? 'the environment\'s set' : `package "${packageId}"'s set`); + +/** + * [ADR-0150 D4/D8 R4, epic ruling MF1 on #32164] Plan a permission set's ledger + * write under {@link PERMISSION_LEDGER_ADDRESSING}: whether it takes a row naming + * no package over (`adoptPackageless`, only while the name has this one holder, + * D8), or a `409` with nothing written when the readers would not follow it. + * + * - The row the store would write is switched off and read by core's readers + * as another holder's switch (a legacy row): writing it would re-arm that + * holder without a word (epic red line 1). Refused, naming that holder. + * - An enable while another row keeps this holder off: a row naming no + * package under two holders, which keeps every holder off, or a row naming a + * package that no longer serves the name, read by the D3 rule. This holder's + * own row cannot outvote it, so a `200` would report a switch that did not + * happen. Refused, naming that row. + * + * Both are read with core's `ledgerRowSwitchesOff`, the reader's own rule, so + * the door refuses exactly what the resolver would not follow. + */ +async function planPermissionSetLedgerWrite( + deps: DomainHandlerDeps, + ql: any, + reader: SecurityCatalogReader, + entry: { name: string; packageId?: string }, + enabled: boolean, + context: HttpProtocolContext, +): Promise<{ refusal?: HttpDispatcherResult; adoptPackageless: boolean; bindStale?: boolean; rebindRowId?: unknown }> { + const name = entry.name; + const target = catalogEntryAddress(entry).packageId; + // The holders the readers count: every holder the catalog serves, and every + // holder the D3 rule counts when it refuses the bare name — a disabled + // package's set included, which the catalog does not serve but the rule + // still counts (contract review 6813617327, should-fix 2): a row naming no + // package is every holder's switch while the rule refuses the name, so it + // is never taken over by one of them. + const holders = (await reader.list('permission')) + .filter((e) => e.name === name) + .map((e) => catalogEntryAddress(e).packageId); + const ruled = await resolveCatalogReference(reader, 'permission', name); + if (ruled.status === 'refused') { + for (const holder of ruled.holders ?? []) { + const packageId = holder.kind === 'package' ? holder.packageId : null; + if (!holders.includes(packageId)) holders.push(packageId); + } + } + // Whether `target` is the name's one holder, a package's set or the + // environment's alike (red-line review E1 on #32306: an environment holder + // is a one-holder answer too). + const soleHolder = holders.length === 1 && holders[0] === target; + // A package holder's row naming no package is its own (D8); an environment + // holder's own row names no package already, so it adopts nothing. + const adoptPackageless = target !== null && soleHolder; + const found = await ql.find(METADATA_ACTIVATION_TABLE, { + where: { metadata_type: 'permission', name }, + context: activationWriteContext(context), + }); + const rows: PermissionLedgerRow[] = Array.isArray(found) ? found : []; + // [D8] The name's one holder also takes over its one row when that row names + // a package that no longer serves the name: the readers read it by the name + // alone, so it is this holder's switch, and the name-addressed store wrote + // exactly this re-address before (every one-holder answer unchanged). That + // holds for the environment's set as for a package's, and for a row stamped + // with the overlay provenance sentinel, which the name-addressed store wrote + // for an environment-authored set before #32164 and every reader reads as + // no package. + const bindStale = soleHolder && rows.length === 1 && storedPackageOf(rows[0]) !== null + && storedPackageOf(rows[0]) !== target; + // A row is this holder's own when the readers read its package as this holder: for the environment's set, one + // stamped with the overlay sentinel too (epic read 6817314015, S1), which the write re-addresses by id. + const own = rows.find((r) => storedPackageOf(r) === target) + ?? rows.find((r) => readPackageOf(r, name) === target) + ?? (adoptPackageless ? rows.find((r) => storedPackageOf(r) === null) : undefined) + ?? (bindStale ? rows[0] : undefined); + const rebindRowId = own && !bindStale && storedPackageOf(own) !== target && readPackageOf(own, name) === target + ? own.id + : undefined; + + if (own) { + for (const other of holders) { + if (other === target || !(await ledgerRowSwitchesOff(ql, own, other, name))) continue; + return { + adoptPackageless, + bindStale, + refusal: { + handled: true, + response: deps.error( + `Permission set '${name}': the activation ledger row this switch would write ` + + `(${readPackageOf(own, name) === null ? 'naming no package' : `naming package "${readPackageOf(own, name)}"`}) ` + + `switches off ${holderPhrase(other)} too, so writing it for ${holderPhrase(target)} would switch ` + + `that one back on without a word (ADR-0150). Nothing was written. Delete that row from ` + + `${METADATA_ACTIVATION_TABLE} and switch each holder through its own row.`, + 409, + { code: 'RESOURCE_CONFLICT' }, + ), + }, + }; + } + } + if (enabled) { + for (const row of rows) { + if (row === own || !(await ledgerRowSwitchesOff(ql, row, target, name))) continue; + const named = readPackageOf(row, name); + return { + adoptPackageless, + bindStale, + refusal: { + handled: true, + response: deps.error( + `Permission set '${name}' of ${target === null ? 'the environment' : `package "${target}"`} ` + + `stays switched off by another activation ledger row, ` + + (named === null + ? (ruled.status === 'refused' + ? 'one naming no package, which switches off every holder of the name while the name alone is refused (ADR-0150 D3: more than one package holds it, and the environment does not)' + : 'one naming no package, which is read by the name alone (ADR-0150 D3)') + : `one naming package "${named}", which no longer serves the name, so it is read by the name alone (ADR-0150 D3)`) + + `, so switching it on here would not take effect. Nothing was written. Delete that row from ` + + `${METADATA_ACTIVATION_TABLE}, then switch each holder through its own row (ADR-0150).`, + 409, + { code: 'RESOURCE_CONFLICT' }, + ), + }, + }; + } + } + return { adoptPackageless, bindStale, rebindRowId }; +} + /** * The declaration-backed types — declarations a plugin or the engine owns, not * catalog entries — each with how its declaration is looked up and how it is @@ -331,12 +661,17 @@ function ledgerUnregistered(ql: any): boolean { * caller could not read off the route ledger. * 2. **Shape**: `['_activation', type, name]`, `type` a catalog type, and * not an audience anchor (`everyone` / `guest`), which this door refuses. + * Then the **query**: the type's closed set + * ({@link catalogActivationQueryParams}), and `?package=` for a + * permission set ({@link readPermissionSetPackageQuery}). * 3. **Body**: {@link readActivationBody}. * 4. **Declaration**, through the catalog reader the security plugin binds to * the engine — the one `resolveUserAuthzGrants` reads, so this door and * the resolver cannot disagree about which names exist. No reader bound, * or a reader that cannot answer ⇒ 503 (an outage is not a verdict); - * unknown ⇒ 404. + * unknown ⇒ 404; a permission set the rule refuses, or a `?package=` that + * does not hold it ⇒ 409 naming every candidate + * ({@link resolvePermissionSetAddress}). * 5. **The durable write**, through the engine. A packaged item's row names * its package; an environment-authored item's row names none. */ @@ -345,6 +680,7 @@ export async function handleCatalogActivationWrite( parts: readonly string[], body: unknown, context: HttpProtocolContext, + query?: unknown, ): Promise { const requestedType = parts[1] ?? ''; const subject = isCatalogActivationType(requestedType) @@ -391,6 +727,13 @@ export async function handleCatalogActivationWrite( }; } + // ── 2c. query ─────────────────────────────────────────────────────────── + // [AGENTS route rule 5, ADR-0150 D5, #32164] The type's closed set, read + // before the body and before any lookup, so a refused request reads + // nothing and writes nothing. + const queryReading = readPermissionSetPackageQuery(deps, query, catalogActivationQueryParams(type)); + if (queryReading.refusal) return queryReading.refusal; + // ── 3. body ───────────────────────────────────────────────────────────── const bodyReading = readActivationBody(deps, body); if (bodyReading.refusal) return bodyReading.refusal; @@ -470,7 +813,15 @@ export async function handleCatalogActivationWrite( }; } try { - if (reader) entry = (await reader.resolve(type as 'position' | 'permission', name)) as SecurityCatalogEntry | undefined; + if (reader && type === 'permission') { + // [ADR-0150 D3/D5, #32164] By name, or exactly `?package=`'s set: a + // refusal is an answer about the name, never a miss. + const address = await resolvePermissionSetAddress(reader, name, queryReading.packageId); + if (address.status === 'refused') return refusedNameAnswer(deps, address.refusal); + entry = address.status === 'resolved' ? address.entry : undefined; + } else if (reader) { + entry = (await reader.resolve(type as 'position', name)) as SecurityCatalogEntry | undefined; + } } catch (err: any) { const refusal = packageScopedRefusalOf(err); if (refusal) return refusedNameAnswer(deps, refusal); @@ -514,17 +865,45 @@ export async function handleCatalogActivationWrite( // [#22621 → A] The row carries the definition's package when it names // one, and NO package when it does not — a position or permission set // the environment authored through the metadata door. That item is - // switched exactly like a packaged one: the resolver keys the row by - // type and name, never by package. The write runs for the caller, + // switched exactly like a packaged one. The write runs for the caller, // elevated, so the row and its audit row name the administrator who // switched the item (`activationWriteContext`). - await new ObjectStoreMetadataActivationStore(ql, type).setActive( + // + // [ADR-0150 D4, MF1 on #32164] A permission set's row is its holder's + // own, addressed by `(package, name)` ({@link planPermissionSetLedgerWrite}); + // every other type's row is addressed by `(type, name)`, as before. + let adoptPackageless = false; + let bindStale = false; + let rebindRowId: unknown; + if (type === 'permission' && reader) { + const plan = await planPermissionSetLedgerWrite(deps, ql, reader, entry, enabled, context); + if (plan.refusal) return plan.refusal; + adoptPackageless = plan.adoptPackageless; + bindStale = plan.bindStale === true; + rebindRowId = plan.rebindRowId; + } + const packageId = type === 'permission' ? catalogEntryAddress(entry).packageId ?? undefined : entry.packageId; + if (rebindRowId !== undefined) { + // The environment's sentinel-stamped row, re-addressed to name no package ({@link planPermissionSetLedgerWrite}). + await ql.update( + METADATA_ACTIVATION_TABLE, + { id: rebindRowId, active: enabled, package_id: null }, + { context: activationWriteContext(context) }, + ); + return { handled: true, response: deps.success({ type, name: entry.name, enabled }) }; + } + // A stale row the one holder takes over is the name's only row, which the + // name-addressed store writes (`bindStale`, {@link planPermissionSetLedgerWrite}). + const store = type === 'permission' && !bindStale + ? new ObjectStoreMetadataActivationStore(ql, type, PERMISSION_LEDGER_ADDRESSING) + : new ObjectStoreMetadataActivationStore(ql, type); + await store.setActive( { name: entry.name, - ...(entry.packageId !== undefined ? { packageId: entry.packageId } : {}), + ...(packageId !== undefined ? { packageId } : {}), active: enabled, }, - { context: activationWriteContext(context) }, + { context: activationWriteContext(context), ...(adoptPackageless ? { adoptPackageless: true } : {}) }, ); } catch (err: unknown) { // A failed write must never read as a successful flip, and its code and diff --git a/packages/runtime/src/domains/permission-set-clone.ts b/packages/runtime/src/domains/permission-set-clone.ts index 317f89a46fb..a54f70c1edd 100644 --- a/packages/runtime/src/domains/permission-set-clone.ts +++ b/packages/runtime/src/domains/permission-set-clone.ts @@ -110,13 +110,35 @@ * catalog is shared by every organization, so the clone is the platform * operator's. That is D3's own refusal ("the server refuses anyway"), not a new * gate; under `single` it is inert. + * + * ## A source two packages hold — `?package=` (ADR-0150 D3/D5, #32164) + * + * A permission set is identified by `(package, name)` (ADR-0150 D4). A source + * name two packages hold is the D3 refusal when the request names no package: + * `409 RESOURCE_CONFLICT`, the resolver's sentence and every candidate + * structured (`candidates: [{ kind: 'package', packageId }]`, the activation + * door's shape), nothing saved — never the "nothing to clone" `404` a miss + * answers. `?package=PKG`, the exact qualifier `/meta` reads, clones exactly + * PKG's set; a PKG that does not hold the name is refused `409` naming the + * holders. The query names the SOURCE's package because the body's `package` + * already names where the copy LANDS. A target name the rule refuses is a name + * the catalog holds, so it is taken (`409`), as a resolved one is. The query + * set is closed (AGENTS route rule 5): `package` alone, refused `400 + * VALIDATION_ERROR` otherwise. With one holder, a request that names no + * package answers as before. */ import { METADATA_READ_DECORATIONS, MetadataProtectionFields } from '@objectstack/spec/kernel'; import { SnakeCaseIdentifierSchema } from '@objectstack/spec/shared'; import { metaWriteCapabilityVerdict, walledCatalogWriteVerdict } from '@objectstack/metadata-core'; import { readEffectiveTenancyPosture } from './activation-gate.js'; -import { securityCatalogReaderOf, type SecurityCatalogEntry } from '@objectstack/core'; +import { resolveCatalogReference, securityCatalogReaderOf, type SecurityCatalogEntry } from '@objectstack/core'; +import { + PERMISSION_SET_DOOR_QUERY_PARAMS, + readPermissionSetPackageQuery, + refusedNameAnswer, + resolvePermissionSetAddress, +} from './catalog-activation.js'; import { isWritablePackage, kernelPackageScope, type ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { newSimilarTargetRefusal, newSimilarTargetRefusalAnswer } from './new-similar-target.js'; import { validationFailure } from '../validation-failure.js'; @@ -417,14 +439,19 @@ function readCloneBody(body: unknown): { name: string; label: string; package?: * 1. **Authority, first** — ahead of the path and body checks and of any * lookup, so a refused caller learns nothing: neither the body contract nor * whether the source exists. - * 2. **Shape**: `['permission-sets', source, 'clone']`. + * 2. **Shape**: `['permission-sets', source, 'clone']`; then the closed + * query set, `?package=` naming the source's package + * ({@link readPermissionSetPackageQuery}). * 3. **Body**: closed `{ name, label, package? }`, the name meeting the * metadata name rule — refused before the catalog is consulted. * 4. **Source**, through the catalog reader the security plugin binds to the * engine — the read `resolveUserAuthzGrants` uses, registry first. ⛔ No * `sys_permission_set` row is read. No reader bound, or one that cannot - * answer ⇒ 503; unknown ⇒ 404. - * 5. **Target**: a name the catalog holds ⇒ 409. + * answer ⇒ 503; unknown ⇒ 404; refused by the rule, or a `?package=` that + * does not hold it ⇒ 409 naming every candidate + * ({@link resolvePermissionSetAddress}). + * 5. **Target**: a name the catalog holds — or one the rule refuses, which it + * holds more than once — ⇒ 409. * 6. **Landing**: the package the copy is saved in: a given target is judged * by the shared rule (refused with nothing written), an omitted one * ({@link resolveDefaultCloneLanding}) @@ -444,6 +471,7 @@ export async function handlePermissionSetCloneWrite( parts: readonly string[], body: unknown, context: HttpProtocolContext, + query?: unknown, ): Promise { // ── 1. authority ──────────────────────────────────────────────────────── const ec: any = context.executionContext; @@ -480,6 +508,10 @@ export async function handlePermissionSetCloneWrite( }; } const sourceName = decodeURIComponent(parts[1]); + // [AGENTS route rule 5, ADR-0150 D5, #32164] The closed query set, read + // before the body and before any lookup. + const queryReading = readPermissionSetPackageQuery(deps, query, PERMISSION_SET_DOOR_QUERY_PARAMS); + if (queryReading.refusal) return queryReading.refusal; // ── 3. body ───────────────────────────────────────────────────────── const target = readCloneBody(body); @@ -503,11 +535,16 @@ export async function handlePermissionSetCloneWrite( }; } let source: SecurityCatalogEntry | undefined; - let taken: SecurityCatalogEntry | undefined; + let taken = false; try { - source = await reader.resolve(PERMISSION_METADATA_TYPE, sourceName); + // [ADR-0150 D3/D5, #32164] By name, or exactly `?package=`'s set: + // a refusal is an answer about the name, never a miss. + const address = await resolvePermissionSetAddress(reader, sourceName, queryReading.packageId); + if (address.status === 'refused') return refusedNameAnswer(deps, address.refusal); + source = address.status === 'resolved' ? address.entry : undefined; // ── 5. target (asked of the same read) ────────────────────────── - if (source) taken = await reader.resolve(PERMISSION_METADATA_TYPE, target.name); + // A name the rule refuses is held — more than once — so it is taken. + if (source) taken = (await resolveCatalogReference(reader, PERMISSION_METADATA_TYPE, target.name)).status !== 'not-found'; } catch (err: any) { return { handled: true, diff --git a/packages/runtime/src/domains/permission-set-package-doors.test.ts b/packages/runtime/src/domains/permission-set-package-doors.test.ts new file mode 100644 index 00000000000..ca07d52f4df --- /dev/null +++ b/packages/runtime/src/domains/permission-set-package-doors.test.ts @@ -0,0 +1,515 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D3/D5, #32164] The two doors that address a permission set by name + * — the activation door (`POST /security/_activation/permission/:name`) and the + * clone door (`POST /security/permission-sets/:name/clone`) — over a set two + * packages hold, and `?package=`, the exact qualifier both now take. + * + * The catalog is the real reader (`createSecurityCatalogReader`) over a + * stand-in registry carrying the package-scoped reads, because a name two + * packages hold cannot be registered on a real registry before the narrowing + * (#31698 PR-2). The one-holder CONTROLs are what a real environment answers. + * + * BASE (main e40f2df2, measured in step 0 on a booted showcase over a stand-in + * holder pair — comment 6769973229 on #32164): + * - two holders, no package: both doors answered `404 RESOURCE_NOT_FOUND` + * ("has no definition — there is nothing to switch off / to clone"); + * - `?package=` was dropped without a word, so the same `404`; + * - the activation body's `package` key is refused as an unknown field (still); + * - a clone TARGET name two packages hold was not taken (the reader's + * by-name read answers nothing for a refused name), so the copy was saved. + */ + +import '@objectstack/metadata'; +import { describe, it, expect } from 'vitest'; +import { bindSecurityCatalogReader, createSecurityCatalogReader } from '@objectstack/core'; +import { assertEngineUpdateDispatch } from '@objectstack/objectql'; + +import { HttpDispatcher } from '../http-dispatcher.js'; +import { resolvePermissionSetAddress } from './catalog-activation.js'; +import type { HttpProtocolContext } from '../http-dispatcher.js'; + +const LEDGER = 'sys_metadata_activation'; +const CRM = 'com.acme.crm'; +const HR = 'com.acme.hr'; +const OTHER = 'com.acme.other'; +/** Held by CRM and HR. */ +const TWO = 'shared_reader'; +/** Held by CRM alone. */ +const ONE = 'crm_sales_rep'; +/** A position CRM holds: the type whose ledger store stays name-addressed. */ +const POSITION = 'crm_rep'; + +type Row = Record; +const setOf = (name: string, packageId: string) => ({ + name, + label: `${name} (${packageId})`, + objects: { account: { allowRead: true } }, + _packageId: packageId, +}); +const holders: Record = { [TWO]: [CRM, HR], [ONE]: [CRM] }; +/** The overlay provenance sentinel: the `_packageId` of a set rehydrated from `sys_metadata`, which names no package. */ +const SENTINEL = 'sys_metadata'; +/** A set the environment authored: no package, or (`overlay`) the sentinel. */ +const envSetOf = (name: string, spelling: 'plain' | 'overlay') => ({ + name, + label: `${name} (environment)`, + objects: { account: { allowRead: true } }, + ...(spelling === 'overlay' ? { _packageId: SENTINEL } : {}), +}); + +/** + * `environment`: names the environment holds alone, and how its set is spelled; + * `disabled`: holders whose package is disabled (the catalog does not serve + * their set; the D3 rule still counts them). + */ +function boot(opts: { environment?: Record; disabled?: readonly string[] } = {}) { + const environment = opts.environment ?? {}; + const disabled = new Set(opts.disabled ?? []); + const packages: Record = { + [CRM]: { manifest: { id: CRM, namespace: 'crm', version: '1.0.0' } }, + [HR]: { manifest: { id: HR, namespace: 'hr', version: '1.0.0' } }, + [OTHER]: { manifest: { id: OTHER, namespace: 'other', version: '1.0.0' } }, + }; + const tables: Record = { [LEDGER]: [] }; + const writes: Row[] = []; + let nextId = 1; + const engine: any = { + // Both packages are booted code packages: read-only, so a clone lands in the pair. + manifests: new Set([CRM, HR]), + registry: { + getObject: (name: string) => (name === LEDGER ? { name: LEDGER } : name === 'account' ? { name: 'account' } : undefined), + getObjectOwner: (name: string) => (name === 'account' ? { packageId: CRM } : undefined), + getPackage: (id: string) => packages[id], + getAllPackages: () => Object.values(packages), + }, + async find(object: string, options: any) { + const rows = (tables[object] ?? []).filter((r) => + Object.entries(options?.where ?? {}).every(([k, v]) => { + if (k.startsWith('$') || (v !== null && typeof v === 'object')) throw new Error(`engine double: ${k} is not modelled`); + return (r[k] ?? null) === v; + })); + return typeof options?.limit === 'number' ? rows.slice(0, options.limit) : rows; + }, + async insert(object: string, data: Row) { + writes.push(data); + const row = { id: `act_${nextId++}`, ...data }; + (tables[object] ??= []).push(row); + return row; + }, + async update(object: string, data: Row, options?: any) { + const dispatch = assertEngineUpdateDispatch(data, options); + if (dispatch.kind !== 'by-id') throw new Error('engine double: only by-id updates are modelled'); + writes.push(data); + const row = (tables[object] ?? []).find((r) => r.id === dispatch.id); + if (row) Object.assign(row, data); + return row; + }, + }; + const manifests = Object.values(packages); + bindSecurityCatalogReader(engine, createSecurityCatalogReader({ + registry: { + getItem: (type: string, name: string) => (type === 'permission' && holders[name] + ? setOf(name, holders[name][0]) + : type === 'permission' && environment[name] ? envSetOf(name, environment[name]) + : type === 'position' && name === POSITION ? { name, label: name, _packageId: CRM } : undefined), + listItems: (type: string) => (type === 'permission' + ? [ + ...Object.entries(holders).flatMap(([name, held]) => held.map((p) => setOf(name, p))), + ...Object.entries(environment).map(([name, spelling]) => envSetOf(name, spelling)), + ] + : type === 'position' ? [{ name: POSITION, label: POSITION, _packageId: CRM }] : []), + isPackageDisabled: (packageId: string) => disabled.has(packageId), + packageScopedHoldersOf: (type: string, name: string) => (type === 'permission' ? holders[name] ?? [] : []), + getPackageScopedItem: (type: string, name: string, packageId: string) => + (type === 'permission' && (holders[name] ?? []).includes(packageId) ? setOf(name, packageId) : undefined), + getEnvironmentScopedItem: (type: string, name: string) => + (type === 'permission' && environment[name] ? envSetOf(name, environment[name]) : undefined), + getArtifactItem: () => undefined, + getPackage: (id: string) => packages[id], + getAllPackages: () => manifests, + } as never, + metadata: { get: () => undefined, list: () => [] }, + })); + + const saves: Array<{ name: string; item: Row; packageId?: string }> = []; + const protocol = { + async saveMetaItem(request: { name: string; item: Row; packageId?: string }) { + saves.push(structuredClone(request)); + return { success: true }; + }, + async ensureCustomizationPackage({ basePackageId }: { basePackageId: string }) { + const packageId = `${basePackageId}.custom`; + const created = packages[packageId] === undefined; + if (created) packages[packageId] = { manifest: { id: packageId, dependencies: { [basePackageId]: '^1' } } }; + return { basePackageId, packageId, namespace: `${basePackageId.split('.').pop()}_custom`, dependencyRange: '^1', created, writable: true }; + }, + }; + const services: Record = { objectql: engine, data: engine, protocol }; + const resolve = (name: string): unknown => services[name] ?? null; + const kernel = { getService: resolve, getServiceAsync: async (name: string) => resolve(name), context: { getService: resolve } }; + return { dispatcher: new HttpDispatcher(kernel as never), tables, writes, saves }; +} + +const OPERATOR = (): HttpProtocolContext => ({ + request: {}, + environmentId: 'platform', + executionContext: { userId: 'u_admin', positions: [], systemPermissions: ['manage_metadata'] }, +} as unknown as HttpProtocolContext); + +type Harness = ReturnType; +const flip = (h: Harness, name: string, query: Row = {}, body: unknown = { enabled: false }) => + h.dispatcher.handleSecurity(`/_activation/permission/${name}`, 'POST', body, query, OPERATOR()) as Promise; +const clone = (h: Harness, source: string, query: Row = {}, body: unknown = { name: 'my_reader', label: 'My Reader' }) => + h.dispatcher.handleSecurity(`/permission-sets/${source}/clone`, 'POST', body, query, OPERATOR()) as Promise; +const answer = (res: any) => ({ + status: res?.response?.status, + code: res?.response?.body?.error?.code, + message: String(res?.response?.body?.error?.message ?? ''), + candidates: res?.response?.body?.error?.details?.candidates, +}); +const BOTH = [{ kind: 'package', packageId: CRM }, { kind: 'package', packageId: HR }]; + +describe('the activation door — a permission set two packages hold', () => { + it('no package named: 409 RESOURCE_CONFLICT naming both holders, structured; nothing written (BASE: 404)', async () => { + const h = boot(); + const res = answer(await flip(h, TWO)); + expect(res).toMatchObject({ status: 409, code: 'RESOURCE_CONFLICT', candidates: BOTH }); + expect(res.message).toContain(`package "${CRM}"`); + expect(res.message).toContain(`package "${HR}"`); + expect(h.writes).toEqual([]); + }); + + it('?package= a holder: switches exactly that package\'s set and writes that package\'s ledger row', async () => { + const h = boot(); + expect(answer(await flip(h, TWO, { package: HR })).status).toBe(200); + expect(h.tables[LEDGER]).toEqual([expect.objectContaining({ metadata_type: 'permission', name: TWO, package_id: HR, active: false })]); + // Back on for HR updates that one row. + expect(answer(await flip(h, TWO, { package: HR }, { enabled: true })).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.package_id, r.active])).toEqual([[HR, true]]); + }); + + /** + * [MF1, epic ruling on #32164] The permission ledger store is addressed by + * `(package, name)` (`PERMISSION_LEDGER_ADDRESSING`): each holder keeps its + * own row. BASE (this branch before the ruling, the name-addressed store): + * the CRM flip re-addressed HR's row, `[[CRM, false]]`, and HR's set + * granted again with both calls answering 200. + */ + it('each holder keeps its own row: flipping CRM leaves HR\'s switched-off row untouched, and both stay independently switchable', async () => { + const h = boot(); + expect(answer(await flip(h, TWO, { package: HR })).status).toBe(200); + expect(answer(await flip(h, TWO, { package: CRM })).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.package_id, r.active])).toEqual([[HR, false], [CRM, false]]); + // CRM back on: HR's row is not touched. + expect(answer(await flip(h, TWO, { package: CRM }, { enabled: true })).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.package_id, r.active])).toEqual([[HR, false], [CRM, true]]); + // HR back on, then off again: CRM's row is not touched. + expect(answer(await flip(h, TWO, { package: HR }, { enabled: true })).status).toBe(200); + expect(answer(await flip(h, TWO, { package: CRM })).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.package_id, r.active])).toEqual([[HR, true], [CRM, false]]); + }); + + it('a row naming no package keeps both holders off, so switching one on is 409 naming that row; nothing written (red line 1)', async () => { + const h = boot(); + h.tables[LEDGER].push({ id: 'legacy', metadata_type: 'permission', name: TWO, package_id: null, active: false }); + const res = answer(await flip(h, TWO, { package: CRM }, { enabled: true })); + expect(res).toMatchObject({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect(res.message).toContain(`package "${CRM}"`); + expect(res.message).toContain('naming no package'); + expect(h.writes).toEqual([]); + // Switching it off writes CRM's own row; the package-less row is neither's and stays. + expect(answer(await flip(h, TWO, { package: CRM })).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.package_id, r.active])).toEqual([[null, false], [CRM, false]]); + }); + + it('a row naming a package that no longer serves the name keeps both holders off too: switching one on is 409; nothing written', async () => { + const h = boot(); + h.tables[LEDGER].push({ id: 'stale', metadata_type: 'permission', name: TWO, package_id: OTHER, active: false }); + const res = answer(await flip(h, TWO, { package: HR }, { enabled: true })); + expect(res).toMatchObject({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect(res.message).toContain(`naming package "${OTHER}"`); + expect(h.writes).toEqual([]); + }); + + it('?package= a package that does not hold it: 409 not-held-by-qualifier naming the holders; nothing written', async () => { + const h = boot(); + const res = answer(await flip(h, TWO, { package: OTHER })); + expect(res).toMatchObject({ status: 409, code: 'RESOURCE_CONFLICT', candidates: BOTH }); + expect(res.message).toContain(OTHER); + expect(h.writes).toEqual([]); + }); + + it('the query set is closed: an unknown name, a repeat and a blank value are 400 VALIDATION_ERROR, before any lookup', async () => { + const h = boot(); + for (const query of [{ pkg: HR }, { package: [HR, CRM] }, { package: ' ' }]) { + expect(answer(await flip(h, TWO, query)), JSON.stringify(query)).toMatchObject({ status: 400, code: 'VALIDATION_ERROR' }); + } + expect(answer(await flip(h, TWO, { pkg: HR })).message).toContain('pkg'); + // Every other type takes no query at all. + expect(answer(await h.dispatcher.handleSecurity('/_activation/position/p', 'POST', { enabled: false }, { package: CRM }, OPERATOR()))) + .toMatchObject({ status: 400, code: 'VALIDATION_ERROR' }); + expect(h.writes).toEqual([]); + }); +}); + +describe('the activation door — CONTROL, one holder', () => { + it('no package named: 200, the holder\'s ledger row, as before', async () => { + const h = boot(); + expect(answer(await flip(h, ONE)).status).toBe(200); + expect(h.tables[LEDGER]).toEqual([expect.objectContaining({ name: ONE, package_id: CRM, active: false })]); + }); + + it('[MF1, D8] a row naming no package is the one holder\'s switch: the flip takes it over, never a second row', async () => { + const h = boot(); + h.tables[LEDGER].push({ id: 'legacy', metadata_type: 'permission', name: ONE, package_id: null, active: false }); + expect(answer(await flip(h, ONE, {}, { enabled: true })).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.id, r.package_id, r.active])).toEqual([['legacy', CRM, true]]); + }); + + it('[MF1, D8] a row naming a package that no longer serves the name is the one holder\'s switch too: re-addressed, as before', async () => { + const h = boot(); + h.tables[LEDGER].push({ id: 'stale', metadata_type: 'permission', name: ONE, package_id: OTHER, active: false }); + expect(answer(await flip(h, ONE, {}, { enabled: true })).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.id, r.package_id, r.active])).toEqual([['stale', CRM, true]]); + }); + + // BASE (the name-addressed store): the first row found was re-addressed and + // the other row stayed, so the answer hung on the order the rows came back. + it('[MF1] beside the holder\'s own row, a row naming no package keeps it off: switching it on is 409 naming that row; nothing written', async () => { + const h = boot(); + h.tables[LEDGER].push( + { id: 'own', metadata_type: 'permission', name: ONE, package_id: CRM, active: false }, + { id: 'legacy', metadata_type: 'permission', name: ONE, package_id: null, active: false }, + ); + const res = answer(await flip(h, ONE, {}, { enabled: true })); + expect(res).toMatchObject({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect(res.message).toContain('naming no package, which is read by the name alone'); + expect(h.writes).toEqual([]); + }); + + it('[MF1] every other type keeps the name-addressed store: a position row is re-attributed by name, as before', async () => { + const h = boot(); + h.tables[LEDGER].push({ id: 'pos', metadata_type: 'position', name: POSITION, package_id: OTHER, active: true }); + expect(answer(await h.dispatcher.handleSecurity(`/_activation/position/${POSITION}`, 'POST', { enabled: false }, {}, OPERATOR())).status) + .toBe(200); + expect(h.tables[LEDGER].map((r) => [r.id, r.metadata_type, r.package_id, r.active])).toEqual([['pos', 'position', CRM, false]]); + }); + + it('?package= the holder answers the same; another package is 409; a name nothing holds stays 404', async () => { + const h = boot(); + expect(answer(await flip(h, ONE, { package: CRM })).status).toBe(200); + expect(answer(await flip(h, ONE, { package: HR }))).toMatchObject({ status: 409, candidates: [{ kind: 'package', packageId: CRM }] }); + expect(answer(await flip(h, 'nobody_holds_this')).status).toBe(404); + expect(answer(await flip(h, 'nobody_holds_this', { package: CRM })).status).toBe(404); + }); +}); + +/** + * [#32306 red-line review E1, contract review 6813617327 must-fix 1] A set the + * ENVIRONMENT holds alone is a one-holder answer too: its only ledger row is + * its switch, whatever package that row names — one that no longer serves the + * name, or the overlay provenance sentinel `main`'s name-addressed store wrote + * for a set rehydrated from `sys_metadata`. The flip takes that row over. + * + * BASE (`main`, the name-addressed store): `200`, the one row re-addressed by + * name to the entry's `_packageId` as stored (the sentinel for an overlay + * entry, none for a plain one). Before this fix, this branch answered the + * enable `409` ("Delete that row") and wrote a second row on a disable. + */ +describe('[E1] the activation door — CONTROL, the environment is the one holder', () => { + const ENV = 'env_auditor'; + describe.each(['plain', 'overlay'] as const)('the environment\'s set spelled %s', (spelling) => { + const h0 = () => boot({ environment: { [ENV]: spelling } }); + + it('a row naming a package that no longer serves the name is its switch: switching on takes it over, 200', async () => { + const h = h0(); + h.tables[LEDGER].push({ id: 'stale', metadata_type: 'permission', name: ENV, package_id: OTHER, active: false }); + expect(answer(await flip(h, ENV, {}, { enabled: true })).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.id, r.package_id, r.active])).toEqual([['stale', null, true]]); + }); + + it('a row stamped with the overlay provenance sentinel is its switch: switching on takes it over, 200', async () => { + const h = h0(); + h.tables[LEDGER].push({ id: 'sentinel', metadata_type: 'permission', name: ENV, package_id: SENTINEL, active: false }); + expect(answer(await flip(h, ENV, {}, { enabled: true })).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.id, r.package_id, r.active])).toEqual([['sentinel', null, true]]); + }); + + it('switching off over such a row re-addresses that one row, never a second', async () => { + const h = h0(); + h.tables[LEDGER].push({ id: 'stale', metadata_type: 'permission', name: ENV, package_id: OTHER, active: true }); + expect(answer(await flip(h, ENV)).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.id, r.package_id, r.active])).toEqual([['stale', null, false]]); + }); + + it('CONTROL: no row: the flip writes the environment\'s own row, naming no package', async () => { + const h = h0(); + expect(answer(await flip(h, ENV)).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.package_id ?? null, r.active])).toEqual([[null, false]]); + }); + }); +}); + +/** + * [Epic read 6817314015, S1] A package and the ENVIRONMENT hold one name: the name alone is the environment's set + * (D3, a caller with no package), so a row stamped with the overlay sentinel is the environment's own switch. + * BASE (ec39bd8e5): matched on its raw `package_id`, it was not; switching on answered 409 ("switches off every + * holder", false), and switching off wrote a second row. + */ +describe('[S1] the activation door — a package and the environment hold one name', () => { + describe.each(['plain', 'overlay'] as const)('the environment\'s set spelled %s', (spelling) => { + const h0 = () => boot({ environment: { [ONE]: spelling } }); + + it('a sentinel row is the environment\'s switch: switching the environment\'s set on takes it over, 200; the package\'s set is untouched', async () => { + const h = h0(); + h.tables[LEDGER].push({ id: 'sentinel', metadata_type: 'permission', name: ONE, package_id: SENTINEL, active: false }); + expect(answer(await flip(h, ONE, {}, { enabled: true })).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.id, r.package_id, r.active])).toEqual([['sentinel', null, true]]); + }); + + it('switching it off over a sentinel row re-addresses that one row, never a second; the package\'s own row stays as it was', async () => { + const h = h0(); + h.tables[LEDGER].push( + { id: 'sentinel', metadata_type: 'permission', name: ONE, package_id: SENTINEL, active: true }, + { id: 'crm', metadata_type: 'permission', name: ONE, package_id: CRM, active: false }, + ); + expect(answer(await flip(h, ONE)).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.id, r.package_id, r.active])).toEqual([['sentinel', null, false], ['crm', CRM, false]]); + }); + + it('CONTROL: ?package= the package switches its own row; the environment\'s sentinel row is untouched', async () => { + const h = h0(); + h.tables[LEDGER].push({ id: 'sentinel', metadata_type: 'permission', name: ONE, package_id: SENTINEL, active: false }); + expect(answer(await flip(h, ONE, { package: CRM }, { enabled: true })).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.id, r.package_id ?? null, r.active])).toEqual([ + ['sentinel', SENTINEL, false], + [expect.any(String), CRM, true], + ]); + }); + + it('[S3] beside the environment\'s own row, a switched-off sentinel row keeps it off: 409 reading that row by the name alone, never "every holder"; nothing written', async () => { + const h = h0(); + h.tables[LEDGER].push( + { id: 'env', metadata_type: 'permission', name: ONE, package_id: null, active: false }, + { id: 'sentinel', metadata_type: 'permission', name: ONE, package_id: SENTINEL, active: false }, + ); + const res = answer(await flip(h, ONE, {}, { enabled: true })); + expect(res).toMatchObject({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect(res.message).toContain('one naming no package, which is read by the name alone (ADR-0150 D3)'); + expect(h.writes).toEqual([]); + }); + }); +}); + +/** + * [Contract review 6813617327, should-fix 2] A package that holds the name but + * is DISABLED: the catalog does not serve its set, and the D3 rule still counts + * it as a holder. So the activation door counts it too: a row naming no + * package is every holder's switch while the rule refuses the bare name, and + * switching the served holder on beside it is `409`, never a take-over that + * would leave the disabled holder's set on once its package is enabled again. + * Before this fix the door counted the served holder alone and took the row + * over (`200`). + */ +describe('[should-fix 2] a disabled package still holds the name, at the activation door', () => { + it('a row naming no package keeps the served holder off: switching it on is 409 naming that row; nothing written', async () => { + const h = boot({ disabled: [HR] }); + h.tables[LEDGER].push({ id: 'legacy', metadata_type: 'permission', name: TWO, package_id: null, active: false }); + const res = answer(await flip(h, TWO, { package: CRM }, { enabled: true })); + expect(res).toMatchObject({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect(res.message).toContain('one naming no package, which switches off every holder of the name while the name alone is refused (ADR-0150 D3: more than one package holds it, and the environment does not)'); + expect(h.writes).toEqual([]); + }); + + it('the bare name is refused naming both holders; ?package= the disabled one holds nothing the door can switch: 409 naming the served holder', async () => { + const h = boot({ disabled: [HR] }); + expect(answer(await flip(h, TWO))).toMatchObject({ status: 409, candidates: BOTH }); + expect(answer(await flip(h, TWO, { package: HR }))).toMatchObject({ status: 409, candidates: [{ kind: 'package', packageId: CRM }] }); + expect(h.writes).toEqual([]); + }); + + it('CONTROL: the served holder\'s own flip with no other row is 200, its own row', async () => { + const h = boot({ disabled: [HR] }); + expect(answer(await flip(h, TWO, { package: CRM })).status).toBe(200); + expect(h.tables[LEDGER].map((r) => [r.package_id, r.active])).toEqual([[CRM, false]]); + }); +}); + +describe('the clone door — a source two packages hold', () => { + it('no package named: 409 RESOURCE_CONFLICT naming both holders; nothing saved (BASE: 404)', async () => { + const h = boot(); + expect(answer(await clone(h, TWO))).toMatchObject({ status: 409, code: 'RESOURCE_CONFLICT', candidates: BOTH }); + expect(h.saves).toEqual([]); + }); + + it('?package= names the SOURCE\'s package: exactly HR\'s set is copied, and lands in HR\'s pair', async () => { + const h = boot(); + const res = await clone(h, TWO, { package: HR }); + expect(res?.response?.status, JSON.stringify(res?.response?.body)).toBe(200); + expect(h.saves).toHaveLength(1); + expect(h.saves[0]).toMatchObject({ name: 'my_reader', packageId: `${HR}.custom` }); + expect(h.saves[0].item).toMatchObject({ name: 'my_reader', label: 'My Reader', objects: { account: { allowRead: true } } }); + }); + + it('?package= a non-holder: 409 naming the holders; nothing saved', async () => { + const h = boot(); + expect(answer(await clone(h, TWO, { package: OTHER }))).toMatchObject({ status: 409, code: 'RESOURCE_CONFLICT', candidates: BOTH }); + expect(h.saves).toEqual([]); + }); + + it('a TARGET name two packages hold is taken: 409, nothing saved (BASE: saved)', async () => { + const h = boot(); + const res = answer(await clone(h, ONE, {}, { name: TWO, label: 'Copy' })); + expect([res.status, res.code]).toEqual([409, 'RESOURCE_CONFLICT']); + expect(h.saves).toEqual([]); + }); + + it('the query set is closed: an unknown name is 400 VALIDATION_ERROR, before the body and any lookup', async () => { + const h = boot(); + expect(answer(await clone(h, TWO, { source: HR }))).toMatchObject({ status: 400, code: 'VALIDATION_ERROR' }); + expect(answer(await clone(h, TWO, { package: [CRM, HR] }))).toMatchObject({ status: 400, code: 'VALIDATION_ERROR' }); + expect(h.saves).toEqual([]); + }); +}); + +describe('the clone door — CONTROL, one holder', () => { + it('no package named: copied, landing in the holder\'s pair, as before', async () => { + const h = boot(); + const res = await clone(h, ONE); + expect(res?.response?.status, JSON.stringify(res?.response?.body)).toBe(200); + expect(h.saves[0]).toMatchObject({ name: 'my_reader', packageId: `${CRM}.custom` }); + }); + + it('a target name one package holds is taken, as before', async () => { + const h = boot(); + expect(answer(await clone(h, ONE, {}, { name: ONE, label: 'Copy' })).status).toBe(409); + expect(h.saves).toEqual([]); + }); +}); + +describe('[SF7] the overlay provenance sentinel is no package, at both doors\' address read', () => { + const OVERLAID = 'overlaid_auditor'; + const SENTINEL = 'sys_metadata'; + const reader = () => createSecurityCatalogReader({ + registry: { + getItem: (type: string, name: string) => (type === 'permission' && name === OVERLAID ? setOf(OVERLAID, SENTINEL) : undefined), + listItems: (type: string) => (type === 'permission' ? [setOf(OVERLAID, SENTINEL)] : []), + isPackageDisabled: () => false, + getPackage: () => undefined, + getAllPackages: () => [], + } as never, + metadata: { get: () => undefined, list: () => [] }, + }); + + it('?package= the sentinel holds nothing: refused not-held-by-qualifier, the holder named as the environment; CONTROL: the bare name resolves', async () => { + expect(await resolvePermissionSetAddress(reader(), OVERLAID, SENTINEL)).toMatchObject({ + status: 'refused', + refusal: { reason: 'not-held-by-qualifier', candidates: [{ kind: 'environment' }] }, + }); + expect(await resolvePermissionSetAddress(reader(), OVERLAID, OTHER)) + .toMatchObject({ status: 'refused', refusal: { candidates: [{ kind: 'environment' }] } }); + expect(await resolvePermissionSetAddress(reader(), OVERLAID)).toMatchObject({ status: 'resolved', entry: { name: OVERLAID } }); + }); +}); diff --git a/packages/runtime/src/domains/security.ts b/packages/runtime/src/domains/security.ts index 4e2e09d3721..6289a54f928 100644 --- a/packages/runtime/src/domains/security.ts +++ b/packages/runtime/src/domains/security.ts @@ -24,9 +24,11 @@ * permission set (`permission`), a declared * sharing rule (`sharing_rule`) or a declared * webhook (`webhook`) on/off - * for this deployment (`./catalog-activation.ts`) + * for this deployment (`./catalog-activation.ts`); + * `?package=` names a permission set's package * POST /security/permission-sets/:name/clone → copy a permission set's whole definition - * under a new name (`./permission-set-clone.ts`) + * under a new name (`./permission-set-clone.ts`); + * `?package=` names the source set's package */ import { @@ -108,7 +110,7 @@ export async function handleSecurityRequest( // split+filter, as below, so no regex runs over request-controlled input. const activationParts = path.split('/').filter(Boolean); if (isCatalogActivationWrite(activationParts, method.toUpperCase())) { - return handleCatalogActivationWrite(deps, activationParts, _body, context); + return handleCatalogActivationWrite(deps, activationParts, _body, context, query); } // [ADR-0126 §7.1] THE PERMISSION-SET CLONE DOOR — copy a set's whole @@ -117,7 +119,7 @@ export async function handleSecurityRequest( // reads the security catalog and saves through the metadata protocol, // behind the metadata door's own authority (`./permission-set-clone.ts`). if (isPermissionSetCloneWrite(activationParts, method.toUpperCase())) { - return handlePermissionSetCloneWrite(deps, activationParts, _body, context); + return handlePermissionSetCloneWrite(deps, activationParts, _body, context, query); } // [#4127 batch 3] The `as any` was the only thing between this call and diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index ca4c9bdcb6c..774f74e7834 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -5166,6 +5166,11 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/runtime/src/domains/permission-set-package-doors.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/runtime/src/domains/share-links-enforcement-context.test.ts", "verb": "delete",