Repository navigation
fix(#486): service-bridge last-admin + self-raise guard; page-restriction self-dealing guards (wiki-v2#486) - #52
Merged
Merged
Conversation
…ions changeMemberRole, removeMember and the addMember upsert (which re-roles an existing live row) now run in ONE transaction that locks the space row FOR NO KEY UPDATE and refuses (409) a write that would leave the space with no live admin. The count is upstream validateLastAdmin parity (user AND group rows) plus a deleted_at filter: the outbox projects a soft-deleted row as removed, so it is no admin in the PDP. The guard keys on "the target is a live admin and no other remains", so a space that already has no admin never becomes unmanageable. FOR NO KEY UPDATE serializes this space's bridge member mutations (and archive/unarchive) without blocking the FOR KEY SHARE that FK checks take, so content writes into the space are never held up. The workspace and both shadow users are resolved before the transaction opens. Removing a member from an archived space stays allowed and is still guarded (a direct admin row is the only administer path left there). The new pg spec proves the lock on the engine (a waiter observed in pg_stat_activity, not by wall-clock), that an FK insert is not blocked, and that a concurrent demote pair leaves exactly one admin. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Inside the member-mutation transaction (under the space lock), a write that
sets a role on a membership row covering the actor — their own user row,
or a group row they belong to (group_users) — is refused with 403
{code:'self_grant'} when the new role outranks the row's current live role
(reader < writer < admin; a missing or soft-deleted row ranks as none,
since the upsert revives it). Narrowing stays allowed: self-demote and
removing yourself or your group, subject to the last-admin 409.
addMember compares the member's shadow id with the addedBy shadow id.
changeMemberRole loads the row by id AND space_id FOR UPDATE (a miss is a
404, never judged "not self") and takes its actor from the now-REQUIRED
UpdateSpaceMemberDto.actorExternalId, so a caller that omits it gets a 400
instead of an unchecked write. The actor is resolved with a new lookup-only
ServiceBridgeService.findShadowUserId (the lower-cased shadow email, as
mint/deactivate use): an identity is only compared here, and one with no
shadow user cannot be covered by any row, so nothing is provisioned.
Every comparison is between Docmost user ids read from this database, so
case variants of the externalId or memberId cannot slip past; the pg spec
pins that, and the wire spec pins the 403 body the platform maps.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…x → 409 Unarchiving a personal space whose owner already has a live one violates spaces_personal_creator_unique (partial on deleted_at IS NULL) and surfaced as a 500. It is now a 409 the platform maps to `conflict`; the message names no owner. Only that index can fire on this UPDATE — the slug index is not partial, so an archived space still holds its slug. Any other error is rethrown unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ant; one subject; grantee cap
updatePermission relied on upstream updatePagePermissionRole, which returns
void, so a role change for a subject with no grant on the page answered
success (and the platform's /v1 PATCH reported {updated:true}). The service
now locks the grant row itself (SELECT ... FOR UPDATE in one transaction)
and updates it by id, answering 404 when there is none; the upstream repo
is not edited.
It also requires exactly one of userId/groupId (400 before any read — both
used to silently update only the user grant), and caps every add/remove
id list at MAX_PAGE_GRANTEES = 256, the platform relay's own limit, so the
native path is bounded the same way.
Kysely is injected from the @global connection, so the module still
imports nothing.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Restriction management must never become a way to reach content the actor
could not already see. Enforced in PageRestrictionService, which both the
native UI and the platform relay land in:
- A1: addPermission/updatePermission refuse (403 {code:'self_grant'}) when
the grantees include the actor (compared lower-cased) or a group the
actor belongs to (group_users). Revoking your own grant stays allowed.
- A2: restrict's auto-grant keeps only the access the actor already had,
decided BEFORE any write. Remote mode: under a restricted ancestor
(upstream's read-only hasRestrictedAncestor, local tables) nothing;
otherwise a strict tryCheckBulk of space view/edit — view+edit → writer,
view → reader, neither → no grant, no answer → 503 with nothing written.
Native mode keeps upstream's writer self-grant.
- A3: new RemoveRestrictionDto.requireActorCoverage (strict boolean; the
platform relay always sends it). With it, unrestrict needs the actor to
hold page#edit (remote: strict tryCheckBulk, no answer → 503, false →
403; native: upstream's own page-edit rule) and refuses with 409 while a
direct sub-page (trashed included) has no page_access row — such a child
is locked only through its parent and cannot carry grants, so lifting the
parent would expose a subtree nobody can see. Without the flag unrestrict
is unchanged: the native break-glass for an orphaned page.
The PDP is asked space view/edit and page edit only, never `locked`
(issue 499). AUTHZ_MODE comes from the @global AuthzModeModule; the PDP
client is provided by PageRestrictionModule itself because AuthzModule
imports this module (a cycle otherwise) — HttpAuthzClient is stateless and
env-configured. A new module spec compiles the wiring against @global
stand-ins for what the app provides.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… and the re-role actor service-bridge.openapi.json now declares what the fork answers since the last-admin invariant and rule M landed: - 409 (new LastAdmin response) on member add, re-role and remove, and 409 (Conflict) on unarchive for the personal-space index; - 403 on member add and re-role is MemberWriteForbidden: the scope denial OR a SelfGrantError whose code `self_grant` is contractual (the platform maps it to its own problem code); - UpdateSpaceMemberRequest requires actorExternalId, with an example. The provider contract spec pins the new responses and ties the request key set to UpdateSpaceMemberDto, so a field added on either side fails from both directions. (The platform's consumer contract spec passes unchanged against this document.) Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A minor bump for the additive member-mutation responses (409 LastAdmin / restore Conflict, 403 self_grant) and the newly required actorExternalId on the member re-role body. Kept in its own commit so a rebase over another contract bump only conflicts here. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The rank lookup used `role in ROLE_RANK`, which is also true for Object prototype keys (`toString`, `constructor`), so an unexpected stored role string would have produced a function instead of a rank and silently disabled the comparison. Rank against SPACE_ROLES instead: anything else is none, the fail-closed reading (any raise of it by a covered actor is refused). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ealing SQL The A3 dark-sub-page check, the A1 group-membership lookup and the updatePermission lock-then-update were pinned only through a Kysely spy, which cannot tell a correct correlated subquery from a wrong one: comparing against c.parentPageId instead of c.id passed every test and would never fire. They now run against real tables with the real upstream PagePermissionRepo: an unrestricted or trashed direct child refuses the agent-path unrestrict (409), restricted children allow it whatever lies deeper, other pages' children are ignored, the native path is unchanged; a grant or re-role to the actor's own group is refused; a restrict under a restricted ancestor keeps nothing and asks the PDP nothing; a missing grant is a 404. The mutation above now fails two cases. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…m's ACL revoke A /v1 page-permission revoke skipped every grantee the platform had no cached Docmost mapping for, assuming no mapping meant no grant, and still answered revoked. The mapping can be missing while the shadow user and its grants exist: a member add's actor is provisioned fork-side, a stale cache is cleared by the self-heal path, a grant is made in the native UI. POST /api/service/users/lookup (scope users:resolve, read-only) resolves a batch of identity ids to shadow user ids, null when none exists. It never provisions: the provision upsert would revive a soft-deleted shadow. Same lower-cased shadow-email derivation as mint and deactivate, soft-deleted rows included, one query, 1..256 ids with the externalId charset guard on each. Pinned in the OpenAPI contract, the scope-coverage map, the DTO spec and a real-Postgres case. Found in PR 516 review. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
TL;DR
This is the fork half of wiki-v2 issue 486, which gives MCP agents admin tools. It hardens the two CCC fork seams the new admin tools write through. The first is the service-bridge space-membership mutations: they get a last-admin invariant and rule M, which refuses any write that raises a membership row covering the actor (their own row, or a group they belong to). The second is
PageRestrictionService, which gets:Everything is CCC code (
service-bridge/,authz/page-restriction/,docs/integrations/). No upstream-owned file is touched.Context
The /v1 admin routes already existed. wiki-v2 issue 486 exposes them to MCP agents on behalf of admin users. The super-repo design is in ADR 0025, and plan and progress are on the tracking issue.
An adversarial verification showed that self-dealing was a practical way around the intended agent-admin boundaries, using the new tools or raw /v1 with the agent's token:
manage_membersrole binding, or a workspace admin whose authority comes only from the cascade, could add themselves as a direct space admin. That persists past revocation and archive (+ adminsits outside- archived), and it brings content access the binding never gave.The fork is the right place to enforce this. The member row and
group_usersare read under the same lock, and comparisons use canonical DB ids, which avoids races and id-case variants.PageRestrictionServicealso serves the native UI and the relay, so one change covers both.The service-bridge also had no last-admin guard. Upstream
SpaceMemberService.validateLastAdminis bypassed by the bridge's raw SQL.Related issues
tryCheckBulk), which is already merged./api/spaces/members/*,/admin/bindings), issue 504 (native restriction policy), issue 512 (page-restriction race safety: restrict/grant are still not transactional).What changed
service-bridge/service-space.service.ts:changeMemberRole,removeMember, and anaddMemberupsert that would demote an admin now run in one transaction.FOR NO KEY UPDATE. This serializes bridge member mutations per space without blocking FKKEY SHAREfrom content writes.role='admin'rows, user and group,deleted_at IS NULL, excluding the target. This matches upstream parity plus the soft-delete filter.{code:'self_grant', message}.UpdateSpaceMemberDto.actorExternalIdis now required, so a missing actor is a 400 and the check fails closed.findShadowUserIdresolves the actor without provisioning a user.role in ROLE_RANKwould also have matched prototype keys.unarchivemaps a23505onspaces_personal_creator_uniqueto 409 instead of 500.authz/page-restriction/:updatePermissionreturns 404 when no grant matches. It selectsFOR UPDATEand then updates by row id, and the upstream repo is not edited.userId/groupIdmust be set.@ArrayMaxSize(256)on add/remove.self_grant). Self-revoke is allowed.writer, as before;tryCheckBulkspace view/edit gives writer / reader / none, and an unknown result is a 503 with nothing written.requireActorCoverageon remove-restriction, which the platform relay always sends. It requires strict PDPpage#edit(otherwise 403) and no unrestricted direct child page (otherwise 409), so no dark subtree is exposed. Without the flag, native behavior is unchanged; it stays the human break-glass.HttpAuthzClientis provided locally inPageRestrictionModule. It is stateless, and importingAuthzModulewould create a cycle.POST /api/service/users/lookup(scopeusers:resolve)./v1page-permission revoke and re-role use it for a grantee with no cached mapping. Before this, such a grantee was skipped and the revoke was still reported as done.docs/integrations/authorization/service-bridge.openapi.json: documents the 409s, 403self_grantand the requiredactorExternalId. Bumped to 1.3.0 in its own commit.How this was tested
jest src/authz src/service-bridge src/editor-compat(the CIdocmost-authzlane): 83 suites, 826 passed, 93 skipped. The skips are pg specs without a DB.AUTHZ_REQUIRE_PG=1 jest --runInBand 'src/(service-bridge|authz)/.*\.pg\.spec\.ts$'againstpostgres:18: 11 suites, 104 passed. The newauthz/page-restriction/page-restriction.pg.spec.ts(16 cases) proves A3 (unrestricted/trashed direct child → 409; restricted children allowed whatever lies deeper; correlation; flag-less native path unchanged), A1 viagroup_users, A2 under a restricted ancestor andupdatePermission's 404/re-role with the real upstreamPagePermissionRepo. Mutating A3's subquery toc.parentPageIdnow fails 2 cases. The wiki-v2 CI job collectssrc/authzpg specs too (PR 516). That includes the newservice-space-mutations.pg.spec.ts(21 tests, run 3× with no flakes). It covers:memberIdreturns 404;memberId, missing actor, self-removal;pg_stat_activitywait polling, not wall-clock. It also shows an FK insert is not blocked, and that a concurrent demote pair ends with exactly one admin. The lock tests fail if the lock is removed.{code:'self_grant', message}.actorExternalIdreturns 400.PageRestrictionModuleDI wiring.tsc -p tsconfig.build.jsonis clean.scripts/check-upstream-boundary.shpasses against this branch.docmost-service.contract.spec.ts(33 tests) passes against the updated document.AWS / infra apply
N/A. This is fork code only. It ships with the next release after the super repo re-pins the gitlink.
Checklist
Scope
Tests
Docs & contracts
README/docs// an ADR), or N/A.Safety (this is a security-first, deny-by-default platform)
UPSTREAM_MODIFICATIONS.md); proprietary/authz logic stays out-of-process.Housekeeping
Known limitations / follow-ups
actorExternalIdis now required, so an older platform gets a 400 on member PATCH. The reverse is also true: an older fork silently stripsrequireActorCoverage, which loses A3. Ship both from the same super-repo gitlink (PR 516)./api/spaces/members/*path takes no space lock and has no self-dealing rule (issue 503).🤖 Generated with Claude Code