Skip to content

access

access

The score-facing access: grammar and the named GrantRecord type.

access := "inherit" | "grant:" name ["@" version] — permissions never appear in score YAML; a grant reference names a conductor-side record. This module only parses the grammar and defines the record shape. There is no grant store yet (it is administered by mzt memory access, not built in this wave), so nothing here resolves a reference.

:class:GrantStore (gateway wave) is the on-disk store: one JSON file per grant name holding every version, written atomically. It resolves a (principal, scope, permission) question to a :class:GrantRecord or raises E2 / E3 / E8.

Classes

AccessRef dataclass

AccessRef(kind, name=None, version=None)

A parsed access: value: inherit or a (possibly pinned) grant.

GrantRecord dataclass

GrantRecord(name, version, principal, scope, permissions, revocation_state, created_at, revoked_at=None, parent_version=None)

One version of a named grant (grant-record/1).

Updating a grant writes version n+1 and marks n superseded with parent_version linking the lineage. A pinned reference to a superseded version keeps that version's permissions; a revoked version never confers authority.

GrantStore

GrantStore(root)

Versioned grants under root, one <name>.json per lineage.

Revocation is per lineage: it marks every version revoked. A pinned reference to a superseded version keeps that version's permissions.

Source code in src/marianne/memory/access.py
def __init__(self, root: Path | str) -> None:
    self._root = Path(root)
    self._lock = threading.RLock()
Methods:
versions
versions(name)

Every version of name, oldest first (empty when unknown).

Source code in src/marianne/memory/access.py
def versions(self, name: str) -> list[GrantRecord]:
    """Every version of ``name``, oldest first (empty when unknown)."""
    with self._lock:
        return self._load(name)
update
update(name, *, permissions=None, scope=None)

Write version n+1 and mark n superseded (parent link kept).

Source code in src/marianne/memory/access.py
def update(
    self, name: str, *, permissions: Iterable[str] | None = None,
    scope: str | None = None,
) -> GrantRecord:
    """Write version n+1 and mark n superseded (parent link kept)."""
    with self._lock:
        history = self._load(name)
        if not history:
            raise NotFound(f"no grant {name!r}", subtype="grant_not_found")
        head = history[-1]
        if not head.is_active():
            raise AuthorityRevoked(
                f"grant {name!r} is {head.revocation_state}", subtype="grant_revoked"
            )
        new_scope = head.scope
        if scope is not None:
            base, path = _split_scope(scope)
            new_scope = "/".join([base, *path])
        new = GrantRecord(
            name=name, version=head.version + 1, principal=head.principal,
            scope=new_scope,
            permissions=_check_permissions(
                head.permissions if permissions is None else permissions
            ),
            revocation_state="active", created_at=time.time(),
            parent_version=head.version,
        )
        history[-1] = _replace_state(head, "superseded")
        self._save(name, [*history, new])
        return new
revoke
revoke(name)

Revoke the whole lineage; no version confers authority afterwards.

Source code in src/marianne/memory/access.py
def revoke(self, name: str) -> None:
    """Revoke the whole lineage; no version confers authority afterwards."""
    with self._lock:
        history = self._load(name)
        if not history:
            raise NotFound(f"no grant {name!r}", subtype="grant_not_found")
        now = time.time()
        self._save(name, [_replace_state(r, "revoked", now) for r in history])
resolve_ref
resolve_ref(ref)

Float grant:<n> -> highest active; pin @v -> that version.

Source code in src/marianne/memory/access.py
def resolve_ref(self, ref: AccessRef) -> GrantRecord:
    """Float ``grant:<n>`` -> highest active; pin ``@v`` -> that version."""
    if ref.kind != "grant" or ref.name is None:
        raise SchemaViolation("`inherit` names no grant", subtype="access_invalid")
    with self._lock:
        history = self._load(ref.name)
    if not history:
        raise NotFound(f"no grant {ref.name!r}", subtype="grant_not_found")
    if any(r.revocation_state == "revoked" for r in history):
        raise AuthorityRevoked(f"grant {ref.name!r} is revoked", subtype="grant_revoked")
    if ref.version is not None:
        for rec in history:
            if rec.version == ref.version:
                return rec
        raise NotFound(
            f"grant {ref.name!r} has no version {ref.version}",
            subtype="grant_version_not_found",
        )
    return history[-1]
resolve
resolve(principal, scope, permission)

Answer one (principal, scope, permission) question or refuse.

Only active grants held by principal that cover scope count. E8 when the only candidates are revoked; E3 when no grant of the principal covers the scope; E2 when one covers it without permission.

Source code in src/marianne/memory/access.py
def resolve(self, principal: str, scope: str, permission: str) -> GrantRecord:
    """Answer one (principal, scope, permission) question or refuse.

    Only active grants held by ``principal`` that cover ``scope`` count.
    E8 when the only candidates are revoked; E3 when no grant of the
    principal covers the scope; E2 when one covers it without ``permission``.
    """
    if permission not in PERMISSION_VALUES:
        raise SchemaViolation(
            f"unknown permission {permission!r}", subtype="permission_invalid"
        )
    _split_scope(scope)
    covering: list[GrantRecord] = []
    revoked_hit = False
    with self._lock:
        for name in self.names():
            history = self._load(name)
            head = history[-1]
            if head.principal != principal or not scope_covers(head.scope, scope):
                continue
            if head.revocation_state == "revoked":
                revoked_hit = True
            elif head.is_active():
                covering.append(head)
    for rec in covering:
        if permission in rec.permissions:
            return rec
    if covering:
        raise PermissionDenied(
            f"{principal} holds no `{permission}` on {scope}", subtype="permission_denied",
        )
    if revoked_hit:
        raise AuthorityRevoked(
            f"every grant of {principal} covering {scope} is revoked", subtype="grant_revoked"
        )
    raise ScopeRefused(f"{principal} has no grant covering {scope}", subtype="scope_refused")

Functions:

parse_access

parse_access(raw)

Parse an access: expression or raise E7 schema_violation.

Source code in src/marianne/memory/access.py
def parse_access(raw: str) -> AccessRef:
    """Parse an ``access:`` expression or raise E7 ``schema_violation``."""
    if raw == "inherit":
        return INHERIT
    match = _ACCESS_RE.match(raw) if isinstance(raw, str) else None
    if match is None:
        raise SchemaViolation(
            f"access {raw!r} is neither `inherit` nor `grant:<name>[@<version>]` "
            "(name: a-z 0-9 _ -; version: a positive integer)",
            subtype="access_invalid",
            remedy="write `access: inherit` or `access: grant:<name>` / `grant:<name>@<n>`",
        )
    version = int(match.group(2)) if match.group(2) else None
    return AccessRef(kind="grant", name=match.group(1), version=version)

scope_covers

scope_covers(grant_scope, target_scope)

True when target_scope equals grant_scope or descends from it.

Source code in src/marianne/memory/access.py
def scope_covers(grant_scope: str, target_scope: str) -> bool:
    """True when ``target_scope`` equals ``grant_scope`` or descends from it."""
    g_base, g_path = _split_scope(grant_scope)
    t_base, t_path = _split_scope(target_scope)
    return g_base == t_base and t_path[: len(g_path)] == g_path