Files
pages/docs/design/authorization-groups.md
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

22 KiB

Endpoint Authorization and Groups

Scope

2026-09-14 extension: locality access and publication adds restrictive named user/group layers over existing grants and a separate explicitly approved anonymous semantic/raw path. For Objects, all local restrictive alias caps apply before the original positive-grant/any-readable- alias rule below. Existing group profiles and administrative roles are unchanged.

This document completes the backend design between authentication and the existing capability graph. It specifies route-level enforcement, target resolution, groups, and the /g/ namespace. Authentication providers prove a Principal; neither an OIDC/LDAP group nor an HTTP route grants authority by itself.

Request authorization pipeline

Every registered route has a static RoutePolicy. Authorization must not infer authority from arbitrary URL substring matching.

type RoutePolicy struct {
    Name           string
    Methods        map[string]MethodPolicy
    Authentication AuthenticationPolicy // public, optional, principal, service
    CSRF           bool
}

type MethodPolicy struct {
    Capability string // read, write, rename, delete, link, manage, delegate
    Resolve    TargetResolver
}

type AuthorizationTarget struct {
    DomainUUID string
    Type       string // domain, quartier, street, spot, path, object, group
    ID         string // canonical UUID where one exists
}

The request sequence is fixed:

  1. Normalize the request and attach a request ID.
  2. Resolve the local Domain from the effective host. Reject remote placement.
  3. Match a registered route and method. An unregistered method returns 405.
  4. Resolve credentials into an optional Principal or a service/delegation context. Domain browser sessions and Bearer tokens use the same stored session record; adapter, federation, and future share tokens are distinct credential types and are never promoted to Principal sessions.
  5. Guard browser mutations with same-origin Fetch Metadata/Origin before any authorization bypass. Cookie requests missing that evidence require a matching Referer; otherwise deny. Explicit Bearer/service clients may omit browser metadata, but actual cross-origin requests are still rejected. See browser request boundaries.
  6. Resolve the target without performing the operation. Path input is normalized and resolved in the current Domain; Object and Revision routes resolve back to their owning Object and all currently relevant bindings.
  7. Evaluate Principal state, Domain membership, direct Role bindings, group Role bindings, and positive grants. No match means deny.
  8. Invoke the handler only after authorization. Record sensitive allows, administrative mutations, and all denies in auth_audit_log.

Target resolvers return 404 only after the caller has enough read authority to distinguish absence. Otherwise they return 403, preventing private-object enumeration. Authentication failures are 401 JSON for APIs and a login redirect for browser navigation. Authorization failures are 403 in both.

For a path, candidate grants are the exact Object/Path exceptional grant, its Spot/Street/Quartier ancestry once ZoneTree exists, and finally the Domain. Evaluation stops at no artificial path segment: only stored topology records participate. Until those locality records exist, the safe fallback is the Domain grant plus exact Object/Path grants, not string-prefix inheritance.

An Object with several semantic bindings is readable through its UUID when an exact Object grant applies or at least one live binding is readable. Responses then include only bindings separately readable by the caller. A Revision and its raw/derived projections inherit this Object decision; knowing a Revision UUID never supplies authority. Broad Domain grants require a live local binding or recorded creation provenance while the Object has no bindings anywhere. Other unbound/foreign-only Objects require an exact Object grant, never a broad Domain or Object-wildcard grant. See Object authority scope.

Route policy inventory

The first implementation slice uses the following policies. A more specific locality target replaces domain as Quartier, Street, and Spot records become available.

Surface Methods Authentication Capability and target
/health, static theme/CSS needed by login GET/HEAD public none; health exposes no internals
/_/auth/login, setup, OIDC callback, magic-link request/verify declared flow methods public challenge rate-limited, challenge-bound
/_/auth/logout GET/HEAD confirmation; POST revocation principal revoke the supplied session only; browser origin guard
/u/{username}, /g/{group} and semantic Viewer paths GET/HEAD optional in legacy, principal in enforcing read resolved path/domain
/e/-/..., /:/new, upload and compile write surfaces GET plus declared writes principal write resolved path/locality
/o/uuid:*, /o/path:*, /r/view/*, /r/history/*, /r/diff/* GET/HEAD policy-dependent principal read owning object/path; immutable IDs do not bypass policy
/v/raw/*, previews, archive/email/PDF children GET/HEAD policy-dependent principal read source object/revision; cached derivations inherit source policy
/v/search, tree, browser and children GET/HEAD optional/principal filter every result by read; never reveal hidden counts or ancestors
/l/uuid:* GET principal read; POST/DELETE require link on object and affected paths
object/revision/tag APIs exact route method principal list/read=read, create/save/tag=write, restore=write, purge=delete
path bind/copy/rename/remove APIs POST principal link, write, rename, or delete on both source and destination as applicable
GC zombie list/purge GET/POST principal Domain manage
/-/sys/config*, auth administration GET/POST principal Domain manage; provider secrets never returned
event scheduler and queue APIs GET or mutation method principal GET Domain manage; mutation Domain manage
adapter registry/open-with GET/POST principal read source plus Domain manage for registry mutation
adapter session exchange/read/write declared ticket service ticket scope, object UUID, base Revision, method, expiry, one use
federation enrollment POST service Campus enrollment token, rate limit, controller mode; not Domain RBAC
future /s/* GET/HEAD delegated macaroon caveats and underlying still-valid delegated grant

Handlers must declare supported methods; a mutating operation is never exposed through GET. Search indexes, recent-object lists, children projection caches, preview caches, archive entries, and adapter workspaces are derived data and must apply the source object's current authorization on every read.

The server keeps these declarations in a central typed endpoint policy classifier. Exact API routes are method-closed, unknown mutations below a reserved namespace fail closed, and semantic Page mutations use a Path target. Handler-local checks remain authoritative where the target is carried in JSON, multipart data, or an adapter ticket; those checks must be replaced only by a typed target resolver with equivalent source and destination coverage.

For immutable addresses, authorization resolves back to mutable authority: a Revision is authorized through its Object, and an Object is readable through an exact Object grant or at least one readable live Path binding in the current Domain. Raw bytes, bounded text, generated PDF pages, cached thumbnails, print, history, and diff projections all reuse that decision. Their responses use private caches varying on credentials even when the underlying Revision is content-addressed. Directory/search projections authorize their requested scope and filter every returned Path; hidden entries are excluded from displayed counts.

Recursive namespace mutations expand the complete stored source set before the transaction. Rename requires rename on every source and create on every mapped destination; copy requires read and create respectively; recursive delete requires delete on every affected Path. Link management additionally requires link authority on the Object and affected Path, and only readable bindings are returned by its UI.

Content permission profiles

The group UI exposes profiles rather than ambiguous collections of checkboxes:

Profile Effective capabilities Explicit exclusions
read read every mutation
read_write_once read, create, upload for a previously absent target overwrite, later Revision save, rename, unlink, delete
read_write read, create, upload, write, rename, link delete
upload_only upload for a previously absent target list/read, overwrite, rename, unlink, delete

write implies create and upload for canonical direct Role grants, while a group profile stores its exact set above. create means create a new semantic binding/Object and its first Revision. upload is checked only after the final filename and destination path are normalized. Both fail closed if the target already exists unless write is also granted. Deletion is never inferred from write and requires an explicit delete grant outside these four profiles.

group admin and group user are membership administration roles, not content profiles. Owner and manager are presented as group-admin variants; member is presented as group user. Their Wiki access still comes only from a content permission profile or another Role binding.

Group model

A Pages group is a Domain-scoped collection of Domain memberships. It is not an authentication provider group, a Role, a Capability, a Campus object, or a semantic path. The group UUID is stable while its name and Wiki binding may change.

CREATE TABLE groups (
  uuid TEXT PRIMARY KEY,
  domain_uuid TEXT NOT NULL,
  name TEXT NOT NULL,
  display_name TEXT NOT NULL DEFAULT '',
  description TEXT NOT NULL DEFAULT '',
  visibility TEXT NOT NULL DEFAULT 'members', -- public, domain, members
  state TEXT NOT NULL DEFAULT 'active',       -- active, readonly, archived
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  UNIQUE(domain_uuid, name)
);

CREATE TABLE group_members (
  group_uuid TEXT NOT NULL,
  membership_uuid TEXT NOT NULL,
  member_role TEXT NOT NULL DEFAULT 'member', -- owner, manager, member
  source TEXT NOT NULL DEFAULT 'local',       -- local or mapping UUID
  created_at_ms INTEGER NOT NULL,
  PRIMARY KEY(group_uuid, membership_uuid)
);

CREATE TABLE auth_group_role_bindings (
  group_uuid TEXT NOT NULL,
  role_uuid TEXT NOT NULL,
  created_at_ms INTEGER NOT NULL,
  PRIMARY KEY(group_uuid, role_uuid)
);

CREATE TABLE auth_group_mappings (
  uuid TEXT PRIMARY KEY,
  domain_uuid TEXT NOT NULL,
  provider_type TEXT NOT NULL,
  provider_uuid TEXT NOT NULL,
  external_group TEXT NOT NULL,
  group_uuid TEXT NOT NULL,
  mode TEXT NOT NULL DEFAULT 'additive', -- additive or authoritative
  enabled INTEGER NOT NULL DEFAULT 1,
  UNIQUE(domain_uuid, provider_type, provider_uuid, external_group)
);

Names use ^[a-z0-9][a-z0-9_-]{1,63}$; dots and the reserved names _, new, and sys are rejected. Display names are unrestricted presentation metadata. Initial implementation permits direct Principal membership only. Nested groups are deliberately deferred to avoid membership cycles and unclear ownership.

Deleting a group is a soft archive followed by explicit purge. Archive removes effective group Role bindings immediately but retains audit history and its Wiki objects. Purge requires Domain manage, fails while bindings/mappings remain, and never deletes Wiki Objects or Revisions implicitly.

Effective capabilities

The evaluator unions positive grants from:

Domain membership -> direct Role bindings -> grants
Domain membership -> group membership -> group Role bindings -> grants

Then it applies Principal, Domain membership, group, and Role lifecycle state. There are no negative group grants. A Principal who belongs to the same Role both directly and through groups receives one effective grant. Cache keys include domain_uuid, principal_uuid, and a monotonically increasing policy version; membership, binding, role, grant, or state mutation increments that version.

owner, manager, and member in group_members.member_role govern group administration only:

  • owner: metadata, managers/members, Role bindings, external mappings, archive;
  • manager: metadata and member list, but not owners, Role bindings, or mappings;
  • member: view the group according to visibility and use granted Roles.

Domain manage bypasses group-administration roles. Group ownership itself does not imply Wiki read or write; those remain capabilities. At least one local owner must remain while a group is active.

Group visibility controls only profile metadata and discoverability. public does not make the group Wiki public, domain does not grant Wiki read, and members does not make every member a Wiki editor. The normal capability decision always protects the Wiki subtree.

/g/ user interface namespace

/g/ is reserved before the semantic Viewer catch-all, parallel to /u/:

Route Purpose Required authority
/g/{groupname} Group profile followed by the group Wiki root document visibility plus Wiki read
/g/{groupname}/_/edit Metadata, owners/managers/members, Role bindings and mappings group manager/owner or Domain manage
/g/{groupname}/_/avatar Mutable non-revision group image GET by visibility; PUT/POST owner/manager
/g/{groupname}/... Ordinary group Wiki semantic subtree normal path capability
/e/-/g/{groupname}/... Canonical editor route for group Wiki documents normal write capability

The reserved /_/ segment is intercepted only immediately below the group name. It never creates semantic children named _. /g/ is excluded from the normal root children projection just as /u/ is; group discovery is provided by an explicit group directory UI subject to group visibility.

The profile shell and Wiki document are separate projections. Absence of a Wiki root document does not make the group absent. Renaming a group changes its /g/{name} binding transactionally, preserves the group UUID and Objects, and leaves an optional time-bounded redirect alias. It must check destination path conflicts before mutation.

Group API

HTML forms call versioned JSON endpoints; handlers may render errors for normal browser submission but share the same service layer.

Endpoint Methods Operation
/_/api/v1/groups GET, POST visible group list; create group
/_/api/v1/groups/{uuid} GET, PATCH, DELETE detail; metadata/state; archive
/_/api/v1/groups/{uuid}/members GET, POST list; add Domain membership
/_/api/v1/groups/{uuid}/members/{membership_uuid} PATCH, DELETE change administrative role; remove
/_/api/v1/groups/{uuid}/roles GET, PUT, DELETE effective Role bindings
/_/api/v1/groups/{uuid}/mappings GET, POST, DELETE external group mappings

All mutations require CSRF for cookie sessions, use optimistic updated_at_ms or an ETag, and append actor, request ID, old/new values, and outcome to the audit log. Bulk membership updates are transactional and bounded. List APIs use cursor pagination and do not disclose invisible groups.

Implementation boundaries

Route policies live beside route registration in internal/server/routes so a new handler cannot silently inherit a broad default. Startup validates that every non-catch-all route has policies for every accepted method. Typed target resolvers live in internal/server/authorization_targets.go; they perform only bounded reads. internal/store/authorization.go owns the effective direct and group grant query, while internal/store/groups.go owns transactional group mutations. HTTP handlers do not issue authorization SQL directly.

The semantic Viewer catch-all has one explicit policy whose resolver uses the normalized semantic path. Reserved /u/ and /g/ handlers are registered before it and delegate their Wiki descendants back to that same semantic service after resolving the profile shell.

Minimum audit events are auth.login.*, authz.denied, role.binding.*, grant.*, group.created, group.updated, group.member.*, group.role_binding.*, group.mapping.*, and group.archived. Details contain stable UUIDs and changed field names, but never passwords, provider secrets, TOTP seeds, session/challenge tokens, email magic links, or raw OIDC tokens.

Required integration tests enumerate every registered route/method in the policy registry and cover anonymous, authenticated-but-ungranted, direct Role, group Role, readonly, suspended, cross-Domain, cookie-without-CSRF, Bearer, service-ticket, renamed-path, multiple-binding, and derived-cache access.

External group synchronization

OIDC/LDAP claims are normalized attributes, then matched only against explicit auth_group_mappings. No mapping means no change. additive adds mapped memberships but never removes local membership. authoritative may remove only memberships previously created by that same mapping UUID; it cannot remove a local owner or membership from another source. Every synchronization is audited.

OIDC synchronization occurs after successful subject verification and before session issuance. Existing sessions observe policy-version changes on their next request. Controller-managed Campus manifests may distribute provider metadata and mapping definitions, but client/bind/SMTP secrets and live group membership are not federated unless a future signed policy explicitly says so.

Built-in administrator groups

Every Domain has reserved campus_admin and domain_admin groups. They cannot be created, renamed, archived, or repurposed as ordinary groups. Existing owner or Domain-manage bindings seed both groups during migration to avoid lockout.

  • campus_admin controls Campus records and tokens, Domain creation, placement, update, and deletion for that Campus. It has an owner-controlled option to project its membership into every Domain belonging to the Campus.
  • domain_admin controls Domain-local configuration, accounts, sessions, groups, Roles, and grants. Only a domain_admin may create an ordinary group. It is never inherited merely because two Domains share a Campus.
  • ordinary group admins control only their own group and cannot grant themselves either built-in administrative membership.

Campus projection records each independent origin in campus_admin_grants; group_members is its strongest-role projection. Disabling inheritance or removing a source revokes derived grants transactionally, without promoting inherited entries into new roots. New projection-owned Domain memberships are removed, and their sessions revoked, after the last source disappears unless an independent group/role grant has adopted that membership. Local and other inherited sources are preserved. Legacy memberships with unknown provenance remain inert rather than being guessed to be safe to delete. See Campus administrator revocation for the migration boundary, transaction hooks, regression coverage, and remaining protocol work.

Cross-Domain identity inheritance

Cross-instance inheritance uses a Domain-pair PSK, not a browser session or a Campus enrollment token. The source stores only the PSK hash; the receiver stores the PSK encrypted by its instance authentication key. A peer record pins source/target Domain UUIDs, source FQDN, instance fingerprint, enabled datasets, and last successful sequence. TLS remains mandatory except for an explicitly named development-only HTTP setup path.

The signed snapshot/delta contains Principal UUID plus non-secret profile metadata, stable external identities, groups, administrative membership role, and content permission profiles. It never contains password verifiers, TOTP seeds, recovery codes, sessions, challenges, provider client secrets, SMTP credentials, avatars unless separately enabled, or audit-log secrets.

Imported rows retain (source_instance_fingerprint, source_domain_uuid, source_uuid) as their stable key. Local UUIDs remain local. Each imported membership records its peer UUID as source, so disabling a peer removes only that peer's effective membership. Groups with the same display/name but a different source identity are not merged implicitly.

The receiver pulls monotonically sequenced deltas and applies each sequence in one transaction. Replay is idempotent; gaps trigger a full snapshot. A changed source fingerprint stops synchronization and emits a warning until a Campus administrator approves the replacement. campus_admin may opt into fan-out to all Domains in its Campus; domain_admin and ordinary groups are inherited only when explicitly selected by the peer policy.

Migration and implementation slices

  1. Replace requestedCapability with route policy registration, exact methods, typed target resolvers, and deny/audit tests. Preserve legacy only for semantic read routes; administration and mutation are never anonymous.
  2. Add CSRF for cookie mutations and separate Principal, adapter, federation, and future delegation credential resolvers.
  3. Add group schema/service, /g/ routing, profile/edit UI, and i18n. Migrate no existing Role binding destructively; group Role bindings use a new table.
  4. Extend effective authorization with group bindings and policy-version cache; add direct/group union and state-invalidation tests.
  5. Add external group mapping and audited OIDC/LDAP group synchronization. LDAP authentication is implemented; directory-group lookup and explicit mapping reconciliation remain separate authorization work and must not be inferred from the successful login attributes.
  6. Switch new Domains to enforcing after owner bootstrap; retire the broad legacy bypass only after the endpoint matrix has integration coverage.

Rollback disables group-derived evaluation and route-policy enforcement behind separate migration flags; additive tables remain readable. It never drops Principals, sessions, existing direct Role bindings, Objects, or Revisions.