§22 S3: scope-role enforcement + collection-grain visibility (@S3) — v0.42.0
Implement slice S3 of the §22 three-tier refactor: the four-layer
most-permissive scope-role resolver (§B.2) over {owner, contributor}
grants at {global, project, collection}, with the §22.5 visibility gate
enforced at the collection grain.
- migration 030: memberships.scope_type += 'global' (the global RFC
Contributor tier; sentinel scope_id '*').
- auth.effective_scope_role folds global → project → collection,
most-permissive, no negative override; can_read_collection /
can_contribute_in_collection / is_collection_superuser /
can_create_collection gate reads, writes, admin, and create.
- collection-grain visibility: a gated collection is hidden from the
public (404, omitted from the directory) yet visible+listed for a
scope-role holder; a collection may be set only as strict or stricter
than its project (public < unlisted < gated), validated at create and
clamped at the mirror.
- entry-scoped authority (mark-reviewed, graduate, branch read/contribute,
PR/discussion/contribution moderation) re-pointed from the project grain
to the entry's collection.
- create-collection authority widened to a project/global-scope grant
holder (§B.1), not only a deployment owner/admin.
Keystone reconciliation (session 0076): a plain granted account is a
granted *account*, not a write-everywhere global role; the implicit-public
write baseline is grandfathered onto the migration-seeded `default`
collection only, so the N=1 deployment loses no capability. Reinterprets
§B.1/§B.3 literally — flagged for the SPEC merge (S6).
Completes @S3 (C1.1–C1.8). Tests: test_s3_scope_roles_vertical.py (8 C.1
scenarios + visibility/strictness), test_migration_030_global_scope.py.
Full backend suite 493 passed.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
+265
-51
@@ -16,6 +16,7 @@ from typing import Any
|
||||
import httpx
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from . import collections as collections_mod
|
||||
from . import db
|
||||
from .bot import Actor
|
||||
from .config import Config
|
||||
@@ -336,26 +337,37 @@ def project_visibility(project_id: str) -> str:
|
||||
return row["visibility"] or "gated"
|
||||
|
||||
|
||||
def project_member_role(user: SessionUser | None, project_id: str) -> str | None:
|
||||
"""The user's *explicit* §22.6 membership role at this project, or None.
|
||||
def _is_default_project(project_id: str) -> bool:
|
||||
"""True iff `project_id` owns the migration-seeded `default` collection — the
|
||||
deployment's primary project (§22.13), whatever its configured id. Only there
|
||||
do M2's role rows (which migrated to collection scope `default`) stand in for
|
||||
project-level authority."""
|
||||
return collections_mod.project_of_collection(collections_mod.DEFAULT_COLLECTION_ID) == project_id
|
||||
|
||||
§22 three-tier (S1): M2's `project_members` rows migrated into the unified
|
||||
`memberships` table at the project's default collection (and the project
|
||||
tier is freshly grantable). The unified `{owner, contributor}` roles are
|
||||
mapped back to the legacy `project_admin`/`project_contributor` strings the
|
||||
S1 project-grain authz still speaks; the four-layer scope resolver lands in
|
||||
S3. Reads the stored grant only (project OR default-collection scope) — it
|
||||
does not fold in the deployment tier or the implicit-on-public baseline."""
|
||||
|
||||
def project_member_role(user: SessionUser | None, project_id: str) -> str | None:
|
||||
"""The user's *project-grain* §22.6 role at this project, or None — the
|
||||
most-permissive of a **global** grant (inherits down to every project) and a
|
||||
**project**-scope grant. Mapped back to the legacy
|
||||
`project_admin`/`project_contributor` strings the project-grain authz speaks.
|
||||
|
||||
Back-compat: on the deployment's *default* project only, M2's rows live at
|
||||
collection scope `default` (§B.3 migration), so a `default` collection-scope
|
||||
grant there is read as project-level too. A collection grant on any other
|
||||
project is NOT project authority — that is the four-layer collection resolver
|
||||
(`effective_scope_role`). Does not fold in the deployment tier
|
||||
(`is_project_superuser` adds it) or the implicit-on-public baseline."""
|
||||
if user is None:
|
||||
return None
|
||||
from . import collections as collections_mod
|
||||
cid = collections_mod.default_collection_id(project_id)
|
||||
clauses = ["scope_type = 'global'", "(scope_type = 'project' AND scope_id = ?)"]
|
||||
params: list = [user.user_id, project_id]
|
||||
if _is_default_project(project_id):
|
||||
clauses.append("(scope_type = 'collection' AND scope_id = ?)")
|
||||
params.append(collections_mod.DEFAULT_COLLECTION_ID)
|
||||
row = db.conn().execute(
|
||||
"SELECT role FROM memberships "
|
||||
"WHERE user_id = ? AND ((scope_type = 'project' AND scope_id = ?) "
|
||||
" OR (scope_type = 'collection' AND scope_id = ?)) "
|
||||
"SELECT role FROM memberships WHERE user_id = ? AND (" + " OR ".join(clauses) + ") "
|
||||
"ORDER BY CASE role WHEN 'owner' THEN 0 ELSE 1 END LIMIT 1",
|
||||
(user.user_id, project_id, cid),
|
||||
params,
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
@@ -378,6 +390,20 @@ def project_of_rfc(rfc_slug: str) -> str:
|
||||
return row["project_id"] or DEFAULT_PROJECT_ID
|
||||
|
||||
|
||||
def collection_of_rfc(rfc_slug: str) -> str:
|
||||
"""The collection an RFC belongs to (`cached_rfcs.collection_id`). Falls back
|
||||
to the default collection when the slug isn't cached. Mirrors
|
||||
`project_of_rfc`'s first-match semantics; a slug shared across collections is
|
||||
a known routing ambiguity (the RFC-grain helpers take a bare slug) resolved
|
||||
by the collection-qualified routes in later slices."""
|
||||
row = db.conn().execute(
|
||||
"SELECT collection_id FROM cached_rfcs WHERE slug = ?", (rfc_slug,)
|
||||
).fetchone()
|
||||
if row is None or not row["collection_id"]:
|
||||
return collections_mod.DEFAULT_COLLECTION_ID
|
||||
return row["collection_id"]
|
||||
|
||||
|
||||
def is_project_superuser(user: SessionUser | None, project_id: str) -> bool:
|
||||
"""Maximal authority within a project: a deployment owner/admin (superuser
|
||||
in every project, §22.7) or an explicit `project_admin` (§22.6). Both
|
||||
@@ -390,20 +416,30 @@ def is_project_superuser(user: SessionUser | None, project_id: str) -> bool:
|
||||
|
||||
|
||||
def can_read_project(user: SessionUser | None, project_id: str) -> bool:
|
||||
"""The §22.5 visibility gate. `public`/`unlisted` are readable by anyone
|
||||
(anonymous included — `unlisted` is link-only but the link still reads);
|
||||
`gated` is readable only by a deployment owner/admin or a granted project
|
||||
member of any role. Used as the subtractive read gate (a gated project's
|
||||
entries 404 to non-members)."""
|
||||
"""The §22.5 visibility gate at the project grain. `public`/`unlisted` are
|
||||
readable by anyone (anonymous included — `unlisted` is link-only but the link
|
||||
still reads); `gated` is readable only by a deployment owner/admin or a
|
||||
holder of any scope grant reaching the project — a global grant, a project
|
||||
grant, or membership at *any* collection within it (seeing a collection
|
||||
implies seeing its project). Used as the subtractive read gate (a gated
|
||||
project's entries 404 to non-members)."""
|
||||
vis = project_visibility(project_id)
|
||||
if vis in ("public", "unlisted"):
|
||||
return True
|
||||
# gated — members + superusers only, subject to the §6 admission floor.
|
||||
# gated — scope-role holders + superusers only, subject to the §6 floor.
|
||||
if user is None or user.permission_state != "granted":
|
||||
return False
|
||||
if user.role in _DEPLOYMENT_SUPERUSER_ROLES:
|
||||
return True
|
||||
return project_member_role(user, project_id) is not None
|
||||
row = db.conn().execute(
|
||||
"SELECT 1 FROM memberships m WHERE m.user_id = ? AND ("
|
||||
" m.scope_type = 'global'"
|
||||
" OR (m.scope_type = 'project' AND m.scope_id = ?)"
|
||||
" OR (m.scope_type = 'collection' AND m.scope_id IN "
|
||||
" (SELECT id FROM collections WHERE project_id = ?))) LIMIT 1",
|
||||
(user.user_id, project_id, project_id),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def require_project_readable(user: SessionUser | None, project_id: str) -> None:
|
||||
@@ -465,6 +501,187 @@ def visible_project_ids(user: SessionUser | None) -> list[str]:
|
||||
return [r["id"] for r in rows if can_read_project(user, r["id"])]
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# §22 three-tier — S3. The four-layer scope-role resolver (§B.2) and the
|
||||
# collection-grain visibility gate.
|
||||
#
|
||||
# A grant attaches the unified role {owner, contributor} at a scope: global,
|
||||
# project, or collection (§B.1). Grants inherit downward, are additive, and
|
||||
# admit no negative override (§B.2). Effective authority over a *collection* is
|
||||
# the most-permissive union of the layers reaching it:
|
||||
#
|
||||
# global (users.role owner/admin ∪ memberships scope_type='global')
|
||||
# ∪ project (memberships scope_type='project' at the collection's project)
|
||||
# ∪ collection (memberships scope_type='collection' at the collection)
|
||||
#
|
||||
# minus the §22.5 visibility gate and §6.2 write-mute (subtractive, as today).
|
||||
# Per-entry authority (owners / arbiters / rfc_collaborators) is a distinct,
|
||||
# finer layer the RFC-grain helpers union in beneath collection.
|
||||
#
|
||||
# OPERATOR DECISIONS (S3, session 0076):
|
||||
# * scope-role-primary — a plain granted account (users.role 'contributor', no
|
||||
# membership) is a granted *account*, not a write-everywhere global role.
|
||||
# Write standing comes from an explicit scope grant; the lone exception is the
|
||||
# grandfathered implicit-public baseline below.
|
||||
# * grandfathered baseline — the migration-seeded `default` collection keeps the
|
||||
# pre-three-tier implicit-on-public write baseline (a granted deployment
|
||||
# contributor may propose while it is public), so the N=1 deployment (§22.13)
|
||||
# loses no capability. Every *explicitly-created* collection requires an
|
||||
# explicit scope grant to write.
|
||||
# * hidden-from-public — a `gated` collection is invisible to the public (404,
|
||||
# omitted from the directory) yet visible to any scope-role holder reaching it
|
||||
# (collection/project/global). A collection's visibility may be set only as
|
||||
# strict or stricter than its project's (the rank ordering below).
|
||||
# ===========================================================================
|
||||
|
||||
# The global scope is a single tier per deployment; its grant rows use this
|
||||
# sentinel scope_id (migration 030).
|
||||
GLOBAL_SCOPE_ID = "*"
|
||||
|
||||
# §22.5 visibility strictness on the public-exposure axis: `public` is least
|
||||
# strict, `gated` most strict. A collection may narrow its project's visibility
|
||||
# but never widen it (`rank(collection) >= rank(project)`).
|
||||
_VISIBILITY_RANK = {"public": 0, "unlisted": 1, "gated": 2}
|
||||
|
||||
|
||||
def visibility_rank(visibility: str | None) -> int:
|
||||
"""The strictness rank of a §22.5 visibility (higher = stricter). An unknown
|
||||
value reads as the strictest (`gated`) — the safe default."""
|
||||
return _VISIBILITY_RANK.get(visibility or "", _VISIBILITY_RANK["gated"])
|
||||
|
||||
|
||||
def effective_scope_role(user: SessionUser | None, collection_id: str) -> str | None:
|
||||
"""The most-permissive unified role ({'owner','contributor'}) the user holds
|
||||
over `collection_id`, folding §B.2's global → project → collection layers.
|
||||
Returns None when no scope grant reaches the collection. 'owner' outranks
|
||||
'contributor'; there is no negative override (a parent grant is never
|
||||
subtracted by a child). Subject to the §6 admission floor."""
|
||||
if user is None or user.permission_state != "granted":
|
||||
return None
|
||||
# Global tier — a deployment owner/admin is a global Owner (§B.1).
|
||||
if user.role in _DEPLOYMENT_SUPERUSER_ROLES:
|
||||
return "owner"
|
||||
pid = collections_mod.project_of_collection(collection_id)
|
||||
row = db.conn().execute(
|
||||
"SELECT role FROM memberships "
|
||||
"WHERE user_id = ? AND ("
|
||||
" scope_type = 'global'"
|
||||
" OR (scope_type = 'project' AND scope_id = ?)"
|
||||
" OR (scope_type = 'collection' AND scope_id = ?)) "
|
||||
"ORDER BY CASE role WHEN 'owner' THEN 0 ELSE 1 END LIMIT 1",
|
||||
(user.user_id, pid, collection_id),
|
||||
).fetchone()
|
||||
return row["role"] if row else None
|
||||
|
||||
|
||||
def collection_visibility(collection_id: str) -> str:
|
||||
"""The collection's own §22.5 visibility. A missing row reads as 'gated' —
|
||||
an unknown collection is invisible rather than open."""
|
||||
row = db.conn().execute(
|
||||
"SELECT visibility FROM collections WHERE id = ?", (collection_id,)
|
||||
).fetchone()
|
||||
if row is None or not row["visibility"]:
|
||||
return "gated"
|
||||
return row["visibility"]
|
||||
|
||||
|
||||
def effective_collection_visibility(collection_id: str) -> str:
|
||||
"""The stricter of the collection's own visibility and its project's (§22.5
|
||||
'both gates'). A collection is constrained to be ≥ its project in strictness,
|
||||
but we max() defensively so a misconfigured looser collection can never widen
|
||||
its project's gate."""
|
||||
cvis = collection_visibility(collection_id)
|
||||
pid = collections_mod.project_of_collection(collection_id)
|
||||
pvis = project_visibility(pid) if pid else "gated"
|
||||
return cvis if visibility_rank(cvis) >= visibility_rank(pvis) else pvis
|
||||
|
||||
|
||||
def can_read_collection(user: SessionUser | None, collection_id: str) -> bool:
|
||||
"""§22.5 read/existence gate at the collection grain. `public`/`unlisted`
|
||||
read by anyone (anonymous included — `unlisted` is link-only but the link
|
||||
reads); `gated` ("hidden from public existence") reads only for a scope-role
|
||||
holder over the collection (collection/project/global) or a deployment
|
||||
owner/admin. The subtractive read gate — a gated collection 404s a
|
||||
non-holder, indistinguishable from absent."""
|
||||
vis = effective_collection_visibility(collection_id)
|
||||
if vis in ("public", "unlisted"):
|
||||
return True
|
||||
if user is None or user.permission_state != "granted":
|
||||
return False
|
||||
return effective_scope_role(user, collection_id) is not None
|
||||
|
||||
|
||||
def require_collection_readable(user: SessionUser | None, collection_id: str) -> None:
|
||||
"""Raise 404 when the collection is not readable by this viewer (§22.5: a
|
||||
hidden/gated collection is invisible to non-holders — the shape matches an
|
||||
unknown collection)."""
|
||||
if not can_read_collection(user, collection_id):
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
|
||||
|
||||
def is_collection_superuser(user: SessionUser | None, collection_id: str) -> bool:
|
||||
"""Maximal authority over a collection: an effective scope role of 'owner'
|
||||
reaching it (a collection Owner, a project Owner of its project, a global
|
||||
Owner, or a deployment owner/admin). Subsumes the per-entry owners/arbiters
|
||||
tier within the collection."""
|
||||
return effective_scope_role(user, collection_id) == "owner"
|
||||
|
||||
|
||||
def _has_collection_write_baseline(user: SessionUser | None, collection_id: str) -> bool:
|
||||
"""The grandfathered implicit-on-public write baseline, narrowed to the
|
||||
migration-seeded `default` collection (§22.13 N=1 case). A granted deployment
|
||||
`contributor` keeps its pre-three-tier write standing on the default
|
||||
collection while its effective visibility is public; every explicitly-created
|
||||
collection requires an explicit scope grant (S3 operator decision)."""
|
||||
if user is None or user.permission_state != "granted":
|
||||
return False
|
||||
if collection_id != collections_mod.DEFAULT_COLLECTION_ID:
|
||||
return False
|
||||
return user.role == "contributor" and effective_collection_visibility(collection_id) == "public"
|
||||
|
||||
|
||||
def can_contribute_in_collection(user: SessionUser | None, collection_id: str) -> bool:
|
||||
"""May the user contribute *new* content to the collection (propose an entry)
|
||||
— the collection-level contribute standing. The union of the scope-role grant
|
||||
(owner/contributor reaching the collection) and the grandfathered default
|
||||
baseline, subject to the visibility read gate."""
|
||||
if user is None or user.permission_state != "granted":
|
||||
return False
|
||||
if not can_read_collection(user, collection_id):
|
||||
return False
|
||||
if effective_scope_role(user, collection_id) is not None:
|
||||
return True
|
||||
return _has_collection_write_baseline(user, collection_id)
|
||||
|
||||
|
||||
def can_discuss_in_collection(user: SessionUser | None, collection_id: str) -> bool:
|
||||
"""May the user participate in discussion in the collection — the
|
||||
collection-level discuss standing. A superset of contribute for this pass
|
||||
(the read-only viewer tier is deferred, §B.3), so it mirrors
|
||||
`can_contribute_in_collection`."""
|
||||
return can_contribute_in_collection(user, collection_id)
|
||||
|
||||
|
||||
def can_create_collection(user: SessionUser | None, project_id: str) -> bool:
|
||||
"""May the user create a new collection in this project (§B.1)? Creating a
|
||||
collection is a *project-level* action: a deployment owner/admin, or any
|
||||
holder of a project-scope or global-scope grant (Owner OR RFC Contributor —
|
||||
'anyone at the project level with permission to create a collection'). A
|
||||
*collection*-scope grant cannot create sibling collections."""
|
||||
if user is None or user.permission_state != "granted":
|
||||
return False
|
||||
if user.role in _DEPLOYMENT_SUPERUSER_ROLES:
|
||||
return True
|
||||
row = db.conn().execute(
|
||||
"SELECT 1 FROM memberships "
|
||||
"WHERE user_id = ? AND ("
|
||||
" scope_type = 'global'"
|
||||
" OR (scope_type = 'project' AND scope_id = ?)) LIMIT 1",
|
||||
(user.user_id, project_id),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
# v0.16.0 (roadmap item #12): per-RFC membership helpers.
|
||||
#
|
||||
# These don't replace `require_contributor` — they layer on top of it for
|
||||
@@ -561,16 +778,14 @@ def can_discuss_rfc(user: SessionUser | None, rfc_slug: str) -> bool:
|
||||
return False
|
||||
if user.permission_state != "granted":
|
||||
return False
|
||||
pid = project_of_rfc(rfc_slug)
|
||||
# §22.5 visibility gate is subtractive (§22.7) — no capability in a project
|
||||
# the viewer cannot even read.
|
||||
if not can_read_project(user, pid):
|
||||
cid = collection_of_rfc(rfc_slug)
|
||||
# §22.5 visibility gate is subtractive (§22.7) — no capability in a
|
||||
# collection the viewer cannot even read.
|
||||
if not can_read_collection(user, cid):
|
||||
return False
|
||||
# §22.7 union, override grants first — these bypass per-RFC curation
|
||||
# (project_viewer ⊇ discussant; project_admin / deployment superuser ⊇ all).
|
||||
if is_project_superuser(user, pid):
|
||||
return True
|
||||
if project_member_role(user, pid) in ("project_viewer", "project_contributor"):
|
||||
# §B.2 union, scope-role grants first — these bypass per-RFC curation (a
|
||||
# collection/project/global Owner or RFC Contributor ⊇ discussant).
|
||||
if effective_scope_role(user, cid) is not None:
|
||||
return True
|
||||
# per-RFC authority (union term).
|
||||
owners = _rfc_owners_set(rfc_slug)
|
||||
@@ -578,11 +793,11 @@ def can_discuss_rfc(user: SessionUser | None, rfc_slug: str) -> bool:
|
||||
return True
|
||||
if is_rfc_collaborator(user, rfc_slug, role_in_rfc=None):
|
||||
return True
|
||||
# implicit-public baseline (curation preserved): a granted deployment
|
||||
# contributor on a public project may discuss only while the RFC is
|
||||
# unclaimed. The first §13.1 claim engages the per-RFC gate, mirroring the
|
||||
# grandfathered implicit-public baseline (curation preserved): on the default
|
||||
# collection a granted deployment contributor may discuss only while the RFC
|
||||
# is unclaimed. The first §13.1 claim engages the per-RFC gate, mirroring the
|
||||
# pre-multi-project v0.16.0 contract.
|
||||
if not owners and _has_write_baseline(user, pid):
|
||||
if not owners and _has_collection_write_baseline(user, cid):
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -606,14 +821,12 @@ def can_contribute_to_rfc(user: SessionUser | None, rfc_slug: str) -> bool:
|
||||
return False
|
||||
if user.permission_state != "granted":
|
||||
return False
|
||||
pid = project_of_rfc(rfc_slug)
|
||||
if not can_read_project(user, pid):
|
||||
cid = collection_of_rfc(rfc_slug)
|
||||
if not can_read_collection(user, cid):
|
||||
return False
|
||||
# §22.7 union, override grants first (project_contributor ⊇
|
||||
# rfc_collaborators(contributor); project_admin / superuser ⊇ all).
|
||||
if is_project_superuser(user, pid):
|
||||
return True
|
||||
if project_member_role(user, pid) == "project_contributor":
|
||||
# §B.2 union, scope-role grants first (a collection/project/global RFC
|
||||
# Contributor ⊇ rfc_collaborators(contributor); an Owner ⊇ all).
|
||||
if effective_scope_role(user, cid) is not None:
|
||||
return True
|
||||
# per-RFC authority (union term). A 'discussant' row is NOT sufficient —
|
||||
# PRs are the higher-privilege surface.
|
||||
@@ -622,9 +835,10 @@ def can_contribute_to_rfc(user: SessionUser | None, rfc_slug: str) -> bool:
|
||||
return True
|
||||
if is_rfc_collaborator(user, rfc_slug, role_in_rfc="contributor"):
|
||||
return True
|
||||
# implicit-public baseline (curation preserved): until an owner exists, a
|
||||
# granted deployment contributor on a public project may contribute.
|
||||
if not owners and _has_write_baseline(user, pid):
|
||||
# grandfathered implicit-public baseline (curation preserved): until an owner
|
||||
# exists, a granted deployment contributor on the public default collection
|
||||
# may contribute.
|
||||
if not owners and _has_collection_write_baseline(user, cid):
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -637,13 +851,13 @@ def can_invite_to_rfc(user: SessionUser | None, rfc_slug: str) -> bool:
|
||||
return False
|
||||
if user.permission_state != "granted":
|
||||
return False
|
||||
pid = project_of_rfc(rfc_slug)
|
||||
if not can_read_project(user, pid):
|
||||
cid = collection_of_rfc(rfc_slug)
|
||||
if not can_read_collection(user, cid):
|
||||
return False
|
||||
# Deployment owner/admin or project_admin (§22.6) may invite; otherwise
|
||||
# only the RFC's frontmatter owner. Per-RFC collaborators and the
|
||||
# implicit-public baseline do not get the invite-others power.
|
||||
if is_project_superuser(user, pid):
|
||||
# An Owner reaching the collection (collection/project/global Owner, or a
|
||||
# deployment owner/admin) may invite; otherwise only the RFC's frontmatter
|
||||
# owner. Per-RFC collaborators and the baseline do not get the invite power.
|
||||
if is_collection_superuser(user, cid):
|
||||
return True
|
||||
return is_rfc_owner(user, rfc_slug)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user