Skip to content

fix(#486): service-bridge last-admin + self-raise guard; page-restriction self-dealing guards (wiki-v2#486) - #52

Merged
PMQ9 merged 10 commits into
wiki-v2from
feat/486-admin-tools
Sep 22, 2026
Merged

PMQ9 merged 10 commits into
wiki-v2from
feat/486-admin-tools

Conversation

@PMQ9

@PMQ9 PMQ9 commented Sep 22, 2026 •

Copy link
Copy Markdown

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:

  • a refusal of self page-grants;
  • a restrict auto-grant that only keeps access the actor already had;
  • an unrestrict on the agent path that requires the actor to be able to edit the page, and refuses if it would expose unrestricted sub-pages.

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:

  • A user whose only authority is a manage_members role 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 (+ admin sits outside - archived), and it brings content access the binding never gave.
  • The same kind of user could raise a group row they belong to.
  • They could grant themselves access to a restricted page.
  • They could restrict a child page to get writer inside a hidden subtree.
  • They could unrestrict content nobody could see, then read it.

The fork is the right place to enforce this. The member row and group_users are read under the same lock, and comparisons use canonical DB ids, which avoids races and id-case variants. PageRestrictionService also serves the native UI and the relay, so one change covers both.

The service-bridge also had no last-admin guard. Upstream SpaceMemberService.validateLastAdmin is bypassed by the bridge's raw SQL.

Related issues

  • Part of cccvu/wiki-v2#486. The issue closes when super-repo PR 516 merges.
  • Builds on PR 51 (issue 492, tryCheckBulk), which is already merged.
  • Follow-ups are filed in wiki-v2: issue 503 (human-only self-dealing paths: native /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 an addMember upsert that would demote an admin now run in one transaction.
    • The space row is locked FOR NO KEY UPDATE. This serializes bridge member mutations per space without blocking FK KEY SHARE from content writes.
    • The transaction counts live role='admin' rows, user and group, deleted_at IS NULL, excluding the target. This matches upstream parity plus the soft-delete filter.
    • If none would remain, it returns 409. Removal from an archived space stays allowed, but is guarded.
  • Rule M, in the same transaction: a write whose target row covers the actor, and whose new role outranks the row's live role (none < reader < writer < admin; soft-deleted counts as none), is refused with 403 {code:'self_grant', message}.
    • Narrowing, self-removal and removing your own group are allowed.
    • UpdateSpaceMemberDto.actorExternalId is now required, so a missing actor is a 400 and the check fails closed.
    • A new lookup-only findShadowUserId resolves the actor without provisioning a user.
    • The rank table only ranks known roles. role in ROLE_RANK would also have matched prototype keys.
  • Restore: unarchive maps a 23505 on spaces_personal_creator_unique to 409 instead of 500.
  • authz/page-restriction/:
    • updatePermission returns 404 when no grant matches. It selects FOR UPDATE and then updates by row id, and the upstream repo is not edited.
    • Exactly one of userId/groupId must be set.
    • @ArrayMaxSize(256) on add/remove.
    • A1: add/update refuse the actor, or a group containing the actor (self_grant). Self-revoke is allowed.
    • A2: the restrict auto-grant role is computed before any write:
      • native mode gives writer, as before;
      • a restricted ancestor gives none;
      • otherwise strict tryCheckBulk space view/edit gives writer / reader / none, and an unknown result is a 503 with nothing written.
    • A3: a new optional requireActorCoverage on remove-restriction, which the platform relay always sends. It requires strict PDP page#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.
    • HttpAuthzClient is provided locally in PageRestrictionModule. It is stateless, and importing AuthzModule would create a cycle.
  • Lookup-only shadow-user resolution (review round 1): a new POST /api/service/users/lookup (scope users:resolve).
    • It maps 1..256 platform identity ids to shadow user ids, or null when none exists, in one query.
    • It never provisions and never revives a user.
    • The platform's /v1 page-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, 403 self_grant and the required actorExternalId. Bumped to 1.3.0 in its own commit.

How this was tested

  • Unit: jest src/authz src/service-bridge src/editor-compat (the CI docmost-authz lane): 83 suites, 826 passed, 93 skipped. The skips are pg specs without a DB.
  • pg lane: AUTHZ_REQUIRE_PG=1 jest --runInBand 'src/(service-bridge|authz)/.*\.pg\.spec\.ts$' against postgres:18: 11 suites, 104 passed. The new authz/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 via group_users, A2 under a restricted ancestor and updatePermission's 404/re-role with the real upstream PagePermissionRepo. Mutating A3's subquery to c.parentPageId now fails 2 cases. The wiki-v2 CI job collects src/authz pg specs too (PR 516). That includes the new service-space-mutations.pg.spec.ts (21 tests, run 3× with no flakes). It covers:
    • a sole admin cannot be demoted, removed or upsert-demoted;
    • a group admin counts toward the admin total;
    • a soft-deleted admin does not count;
    • an archived-space removal is guarded;
    • a cross-space memberId returns 404;
    • personal-space restore returns 409;
    • the full rule-M matrix: self-add, uppercase id, raise vs demote, soft-deleted own row, a group row the actor is or isn't in, uppercase memberId, missing actor, self-removal;
    • a lock proof: pg_stat_activity wait 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.
  • Wire and module specs:
    • The 403 body is exactly {code:'self_grant', message}.
    • A PATCH without actorExternalId returns 400.
    • PageRestrictionModule DI wiring.
  • A1–A3 unit matrix: view+edit gives writer, view gives reader, none gives no grant; a restricted ancestor makes no PDP call; a PDP error returns 503 with no insert; the flag's edit-false, dark-child and only-restricted-children cases.
  • Typecheck: tsc -p tsconfig.build.json is clean.
  • Boundary: super-repo scripts/check-upstream-boundary.sh passes against this branch.
  • Consumer: the platform consumer contract 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

  • Complete and scoped to one logical concern — no unrelated drive-by changes (or follow-ups noted below).

Tests

  • New/changed behavior has appropriate tests — unit / integration / e2e / security / regression as applicable (or N/A, with why).
  • Existing tests pass, and any new tests pass.

Docs & contracts

  • Docs added/updated where needed (README / docs/ / an ADR), or N/A.
  • Any API/contract, config, migration, permission, or deployment impact is called out in this PR, or N/A.
  • Any AWS/infra apply is described precisely, scoped (no mass-apply), and captured in a reviewable one-time script — see "AWS / infra apply" above, or N/A.

Safety (this is a security-first, deny-by-default platform)

  • Security, authorization, data integrity, failure paths, and backward compatibility considered, or N/A.
  • Upstream boundary respected — no undocumented edits to Docmost-owned files (see UPSTREAM_MODIFICATIONS.md); proprietary/authz logic stays out-of-process.

Housekeeping

  • Related issue(s) linked above.
  • Known limitations, follow-ups, or intentionally deferred work identified below.

Known limitations / follow-ups

  • Ship with the matching platform. actorExternalId is now required, so an older platform gets a 400 on member PATCH. The reverse is also true: an older fork silently strips requireActorCoverage, which loses A3. Ship both from the same super-repo gitlink (PR 516).
  • Races and paths not covered here:
    • A child page created between A3's check and the delete can still be exposed.
    • Restrict and grant are still not transactional (issue 512).
    • The native /api/spaces/members/* path takes no space lock and has no self-dealing rule (issue 503).
  • Native mode A3 edit check uses upstream's page-edit rule, because there is no platform to call. Remote mode is exactly as specified.

🤖 Generated with Claude Code

PMQ9 and others added 10 commits September 22, 2026 14:59
…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]>
@PMQ9
PMQ9 merged commit 4c36032 into wiki-v2 Sep 22, 2026
@PMQ9
PMQ9 deleted the feat/486-admin-tools branch September 22, 2026 22:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant