From e636103bd1ab7413ba842e3024f57bb49ca110cf Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Sun, 6 Dec 2026 00:47:18 +0100 Subject: [PATCH 01/15] =?UTF-8?q?test(ctx=5Fcheckpoint):=20S1=20contract?= =?UTF-8?q?=20for=20access-group=20bindings=20=E2=80=94=20inert=20stubs,?= =?UTF-8?q?=20fakes=20of=20ctx=20and=20the=20Hermes=20host,=20and=20the=20?= =?UTF-8?q?red=20tests=20of=20P-A=20to=20P-G=20behind=20a=20per-cluster=20?= =?UTF-8?q?shield?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The plugin side of per-group ctx bindings is split into clusters P-A to P-G that are built in parallel; this commit fixes what they build against. New modules hold the final data forms and inert stubs: memory/access.py (field schema, detection, decision table, markers), memory/narrowing.py (client narrowing, whoami proof), memory/base_blocks.py (the access_group_fields hook), memory/access_cli.py (operator tools); CtxClient takes a narrowing and gains get_blocks, status.py gains record_access/read_access, checkpoint.py gains window_writes. Nothing calls them yet, so the plugin behaves as before (both suites unchanged: 763 passed + 2 skipped, 655 passed). tests/fakes holds a ctx server with the target narrowing semantics and the Hermes surface of the access-group core change (aligned to its code, not to the draft). Each cluster's red tests carry a marker; while the cluster is listed in tests/fakes/s1_pending.py they are strict xfails that only an assertion about the missing behaviour satisfies. Co-Authored-By: Claude Opus 5.5 --- .../plugin/ctx_checkpoint/memory/access.py | 299 +++++++++++ .../ctx_checkpoint/memory/access_cli.py | 51 ++ .../ctx_checkpoint/memory/base_blocks.py | 82 +++ .../ctx_checkpoint/memory/checkpoint.py | 14 + .../plugin/ctx_checkpoint/memory/client.py | 14 + .../plugin/ctx_checkpoint/memory/narrowing.py | 130 +++++ .../plugin/ctx_checkpoint/memory/status.py | 21 +- .../plugin/ctx_checkpoint/tests/conftest.py | 47 ++ .../ctx_checkpoint/tests/fakes/__init__.py | 3 + .../ctx_checkpoint/tests/fakes/access_host.py | 363 ++++++++++++++ .../ctx_checkpoint/tests/fakes/ctx_server.py | 474 ++++++++++++++++++ .../ctx_checkpoint/tests/fakes/s1_pending.py | 15 + .../tests/test_access_pa_client.py | 256 ++++++++++ .../tests/test_access_pb_decide.py | 291 +++++++++++ .../tests/test_access_pc_binding.py | 176 +++++++ .../tests/test_access_pd_base_blocks.py | 235 +++++++++ .../tests/test_access_pe_tools.py | 111 ++++ .../tests/test_access_pf_docs.py | 30 ++ .../tests/test_access_pg_window.py | 29 ++ 19 files changed, 2640 insertions(+), 1 deletion(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/memory/access.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/__init__.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/access_host.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_decide.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pf_docs.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py new file mode 100644 index 000000000..11654f786 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py @@ -0,0 +1,299 @@ +"""Access groups: the fields ctx_checkpoint adds to them and the binding decision (contract, S1). + +Hermes' access groups (``gateway.access_groups``) run each sender of a governed server in the +profile of the first group that matches. A plugin adds fields to those groups +(``PluginContext.register_access_fields``) and is told, per agent build, which group the turn serves +(``initialize(scope_id=, access_group=, access_group_restricted=, access_fields=, +restricted_profile=)``) and, inside a turn, through ``gateway.access_groups.current_access()``. + +This module holds the schema of ctx_checkpoint's twelve fields, the detection of that host surface +and the pure decision which connection a session gets (``off``, the profile's own, or a group +binding). S1 state: the data forms are final, the functions are inert stubs; nothing in the plugin +calls them yet, so the plugin behaves as 0.19.1. The decision cluster (P-B) fills them in. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, field +from types import MappingProxyType +from typing import Any, Literal + +# The namespace is the plugin id ``memory.provider`` selects the provider by. +NAMESPACE = "ctx_checkpoint" +# The hook the core fires before a governed server's turn (gateway/access_prompt.py). +HOOK_NAME = "access_group_fields" + +# Platforms of a local, interactive session (``ungoverned: local`` admits them; forks only when +# their parent session was local). +# The profile's markers (``read_markers``, ``raise_markers``, ``reset_markers``), under the home. +MARKERS_FILE = "ctx_state/access-mode.json" + +LOCAL_PLATFORMS = frozenset({"cli", "tui", "desktop", "local", "codex", "acp", "gui"}) + +# ``memory.ctx_checkpoint.*`` keys of config.yaml this axis reads (never from ctx.json), with defaults. +SETTINGS_DEFAULTS: Mapping[str, Any] = MappingProxyType( + { + "ungoverned": "auto", # auto | profile | local | off + "governed_unbound": "off", # profile | off + "restricted_allow": (), # subset of ("recall", "capture") + "base_cache_s": 900, # 60 .. 86400 + "base_cache_entries": 2048, # 64 .. 65536 + "base_timeout_s": 4, # 1 .. 10 + "base_workers": 4, # 1 .. 32 + "verify_timeout_s": 3, # 1 .. 10 + } +) + + +def _spec(kind: str, description: str) -> Mapping[str, str]: + return MappingProxyType({"type": kind, "description": description}) + + +# The twelve fields (registered without ``default``: the values that apply when a field is not set +# depend on whether the group is restricted, and the core's profile check must judge set values). +# The list only grows: no field changes its type or meaning, none is renamed (the core's registry is +# process-wide, profiles may carry different plugin versions). +SCHEMA: Mapping[str, Mapping[str, str]] = MappingProxyType( + { + "key": _spec( + "env_name", + "Variable in the serving profile's .env holding the ctx key: CTX_KEY, CTX_API_KEY or CTX_KEY_<...>;" + " restricted groups only CTX_KEY__<...>. Not set: restricted groups get no ctx," + " others follow memory.ctx_checkpoint.governed_unbound.", + ), + "base_url": _spec( + "env_name", + "Variable holding the https URL of this group's ctx server: CTX_BASE_URL or CTX_BASE_URL_<...>." + " Not set: the profile's ctx URL.", + ), + "tenant": _spec( + "str", + "Expected tenant slug of the key; the group binds only when the key belongs to it." + " Not set: not checked (restricted groups need it).", + ), + "read": _spec( + "list", + "ctx scopes (:, 1 to 8) recall, read tools and base blocks read." + " Not set: the key's read set without 'write' (restricted groups need it).", + ), + "write": _spec( + "str", + "ctx scope the chain, facts, digests and mirror write to; must be the key's home scope." + " Not set: the key's home scope (restricted groups need it).", + ), + "store": _spec( + "str", + "ctx scope the ctx_store tool writes to; unrestricted groups only, within the key's write set." + " Not set: 'write'.", + ), + "recall": _spec( + "bool", + "Recall before each turn. Not set: on for unrestricted groups, off for restricted ones;" + " restricted groups need memory.ctx_checkpoint.restricted_allow to list recall.", + ), + "capture": _spec( + "bool", + "Chain, facts, digests and mirror are written. Not set: on for unrestricted groups, off for" + " restricted ones; restricted groups need memory.ctx_checkpoint.restricted_allow to list capture.", + ), + "base_blocks": _spec( + "list", + "ctx block ids (up to 16) whose content joins the group's prompt. Not set: no base blocks.", + ), + "base_max_chars": _spec( + "int", + "Most characters the base blocks add to the group's prompt (256 to 8000). Not set: 4000.", + ), + "base_rev": _spec( + "int", + "Raise it to reload the base blocks in every session of the group. Not set: 0.", + ), + "enabled": _spec( + "bool", + "false: this group gets no ctx (counts as set for the core's profile check). Not set: true.", + ), + } +) + + +@dataclass(frozen=True) +class AccessContext: + """The access group a session serves, in ctx_checkpoint's terms: from ``initialize``'s access + kwargs or from ``gateway.access_groups.current_access()``. ``restricted``: the group's (``None`` + = unknown, which counts as restricted). ``fields``: this plugin's namespace only.""" + + platform: str + scope_id: str + group: str + profile: str | None + restricted: bool | None + admin: bool = False + fields: Mapping[str, Any] = field(default_factory=lambda: MappingProxyType({}), compare=False) + + +@dataclass(frozen=True) +class GroupFields: + """The group's fields, parsed and with their forms checked (``parse_fields``); defaults applied + for the group's strictness.""" + + key: str + base_url: str + tenant: str + read: tuple[str, ...] + write: str + store: str + recall: bool | None + capture: bool | None + base_blocks: tuple[str, ...] + base_max_chars: int + base_rev: int + enabled: bool + + +@dataclass(frozen=True) +class FieldError: + """Why the fields do not bind: the field and the rule it breaks, never its value.""" + + field: str + reason: str + + +@dataclass(frozen=True) +class Markers: + """The profile's monotone markers (``/ctx_state/access-mode.json``).""" + + restricted_seen: bool = False + governed_seen: bool = False + + +@dataclass(frozen=True) +class Decision: + """What ``initialize`` binds: ``off`` (no ctx at all), ``profile`` (the profile's own connection, + as 0.19.1) or ``group`` (a group binding from ``fields``). ``reason`` names the row of the + decision table and the cause; ``strict``: the group counts as restricted.""" + + kind: Literal["off", "profile", "group"] + reason: str + context: AccessContext | None = None + fields: GroupFields | None = None + strict: bool = False + + +def access_supported() -> bool: + """V8b: the host has the core's access-group fields and hook, read on the public class + ``hermes_cli.plugins.PluginContext`` (a memory provider's ``ctx`` answers every ``register_*``). + S1 stub: ``False``.""" + return False + + +def current_access() -> AccessContext | None: + """V8a/V6a: the access group serving the current turn, through the published + ``gateway.access_groups.current_access`` (imported at call time; ``None`` when the host lacks it, + outside a turn, or for a server that is not governed), with this plugin's namespace only. + S1 stub: ``None``.""" + return None + + +def session_parent_platform() -> str | None: + """The platform of the session a fork was built in: ``HERMES_SESSION_PLATFORM`` through the + published ``gateway.session_context.get_session_env``, and only when the name is not in + ``os.environ`` (else ``get_session_env`` answers with the process value, which says nothing about + the session); ``None`` when unknown. The ``parent_platform`` of ``decide``. S1 stub: ``None``.""" + return None + + +def context_from_init(init_kwargs: Mapping[str, Any]) -> AccessContext | None: + """The access group ``initialize`` was told about (``platform``, ``scope_id``, ``access_group``, + ``access_group_restricted``, ``access_fields``, ``agent_identity``); ``None`` without + ``access_group``. S1 stub: ``None``.""" + return None + + +def is_strict(context: AccessContext | None, *, restricted_profile: bool | None, markers: Markers) -> bool: + """The one definition of "restricted" (design 02 §3.3): the group's ``restricted``; unknown counts + as restricted when the profile is restricted or the marker ``restricted_seen`` is set; in the hook + (no profile knowledge) unknown counts as restricted. S1 stub: ``True``.""" + return True + + +def parse_fields(raw: Mapping[str, Any], *, scope_id: str, strict: bool) -> GroupFields | FieldError: + """The group's fields with their forms checked before any secret is read or request sent: ``key`` + and ``base_url`` name ctx variables (restricted: ``CTX_KEY__...``), scopes match the ctx + scope pattern, bounds hold; with ``strict`` the rules of E1. S1 stub: a ``FieldError``.""" + return FieldError(field="*", reason="access groups are not available") + + +def load_settings(hermes_home: str) -> Mapping[str, Any]: + """``memory.ctx_checkpoint.*`` of this axis from the home's config.yaml only (``ctx.json`` never + sets them), bounded, unknown values replaced by the defaults. S1 stub: the defaults.""" + return SETTINGS_DEFAULTS + + +def read_markers(hermes_home: str) -> Markers: + """The markers of ``/ctx_state/access-mode.json``; a missing file is no marker, an + unreadable one counts as both set. S1 stub: no marker.""" + return Markers() + + +def raise_markers(hermes_home: str, **flags: bool) -> None: + """Set the named markers (``restricted_seen=True``, ``governed_seen=True``), only from false to + true, atomically; ``False`` never lowers one (only ``access reset-marker`` does). S1 stub: no-op.""" + return None + + +def reset_markers(hermes_home: str, *, restricted: bool = False, governed: bool = False) -> None: + """Lower the named markers (``access reset-marker``, the only way down), atomically; the other + marker stays. File: ``MARKERS_FILE`` under the home, JSON ``{"restricted_seen": bool, + "governed_seen": bool, "since": ""}``. S1 stub: no-op.""" + return None + + +def e7_inputs(hermes_home: str, platform: str) -> tuple[tuple[str, ...], tuple[str, ...]] | None: + """What rule E7 judges, read without network from the profile at *hermes_home*: the variable + NAMES in its ``.env`` (never a value) and the toolset list ``platform_toolsets.`` of its + config.yaml, exactly as configured. ``None`` when either cannot be read, which fails E7 (the one + reader P-C, P-D and P-E share). S1 stub: ``None``.""" + return None + + +def decide( + init_kwargs: Mapping[str, Any], + current: AccessContext | None, + parent_platform: str | None, + settings: Mapping[str, Any], + markers: Markers, + v8: bool, +) -> Decision: + """The decision table of design 02 §4.2 (first matching row): pure, no network, no files. + ``current``: ``current_access()`` at the build; ``parent_platform``: the copied session variable + ``HERMES_SESSION_PLATFORM`` of a fork (only when it is not in ``os.environ``). S1 stub: the + profile's own connection, as 0.19.1.""" + return Decision(kind="profile", reason="access groups are not available") + + +__all__ = [ + "HOOK_NAME", + "LOCAL_PLATFORMS", + "MARKERS_FILE", + "NAMESPACE", + "SCHEMA", + "SETTINGS_DEFAULTS", + "AccessContext", + "Decision", + "FieldError", + "GroupFields", + "Markers", + "access_supported", + "context_from_init", + "current_access", + "decide", + "e7_inputs", + "is_strict", + "load_settings", + "parse_fields", + "raise_markers", + "read_markers", + "reset_markers", + "session_parent_platform", +] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py new file mode 100644 index 000000000..9455de6aa --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -0,0 +1,51 @@ +"""``hermes ctx_checkpoint access `` (contract, S1). + +Operator tools for access-group bindings (design 02 §4.7): ``status`` reads the per-binding status +files without network; ``check`` proves a group's fields (E1 to E7) and names every broken rule with +the expected value; ``provision`` computes scope names and the label, calls ctx's +``keyset-provision`` with ``replace_label`` and a tenant-admin key read from a named variable (never +stored), adds the new key to the target profile's ``.env`` and prints the ``/policy field`` lines +(``--emit-yaml``: the whole group entry); ``reset-marker`` lowers the profile's markers. + +Naming (design 02 §3.4): a ctx scope name is 1 to 24 characters of lowercase letters, digits and +inner hyphens (ctx ``scopeNamePattern``). Group names may hold ``_`` and 32 characters: ``_`` becomes +``-``, the edges are cleaned, the text is cut; when the name was changed or cut, its last four +characters are a hash of the original. Collisions are refused. One tenant per operator: +``d-k`` and ``d-``; one tenant +per community: ``k`` and ````. The key variable is ``CTX_KEY__`` (profile +upper-cased, ``-`` as ``_``), at most 64 characters (a hash suffix replaces the rest). + +S1 state: the forms are final, the functions are inert stubs, and ``memory/cli.py`` does not offer +``access`` yet. The tools cluster (P-E) fills them in and wires the subcommand. +""" + +from __future__ import annotations + +import re +from collections.abc import Mapping, Sequence + +# ctx: go/internal/handler/tenant_manage.go scopeNamePattern (name part of :). +SCOPE_NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,22}[a-z0-9])?$") +# Hermes: hermes_cli/access_fields.py ENV_NAME. +ENV_NAME = re.compile(r"^[A-Z][A-Z0-9_]{0,63}$") +KNOWLEDGE = "k" + + +def scope_layout(scope_id: str, groups: Sequence[str], *, per_community: bool = False) -> Mapping[str, str]: + """The ctx scope name (name part, no slug) for the server's knowledge scope (key ``"k"``) and for + each group in *groups*; ``ValueError`` when two map to the same name. S1 stub: ``{}``.""" + return {} + + +def key_env_name(scope_id: str, profile: str) -> str: + """The ``.env`` variable holding a restricted group's key on server *scope_id* served by + *profile*. S1 stub: ``""``.""" + return "" + + +def run_access(argv: Sequence[str], *, hermes_home: str) -> int: + """Run ``access `` for the home; the exit code. S1 stub: 2 (not available).""" + return 2 + + +__all__ = ["ENV_NAME", "KNOWLEDGE", "SCOPE_NAME", "key_env_name", "run_access", "scope_layout"] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py new file mode 100644 index 000000000..865d80d08 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -0,0 +1,82 @@ +"""Base blocks: ctx blocks whose content joins an access group's prompt (contract, S1). + +The core fires the hook ``access_group_fields`` before a governed server's turn, in the serving +profile (its secrets are readable), once per session, group and digest of the group's fields and +prompt; it keeps answers (``None`` too) and asks again after a callback that raised or timed out. +The callback is an ``async def`` (the core awaits it on the gateway loop under +``plugins.hook_callback_timeout``); the blocking work runs on this module's own thread pool, so a +slow ctx server holds neither the loop nor its default executor. Only whole answers: a transient +failure or the end of ``base_timeout_s`` raises ``BaseBlocksUnavailable``, never a partial text. +The callback takes every value from its arguments or ``current_access()``, never from a provider +instance (the active provider's hooks hang on an instance that is never initialized). + +S1 state: the forms are final, the functions are inert stubs, and nothing registers the hook yet. +The base-block cluster (P-D) fills them in. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +# The heading the rendered text starts with (part of the deterministic form). +HEADING = "## Knowledge for this conversation (ctx)" +TRUNCATED_MARK = "…[truncated]" + + +class BaseBlocksUnavailable(Exception): + """A base block could not be fetched now (network, time, 429) or the budget ran out: the hook + gives no partial text, the core keeps the group's prompt and asks again on a later turn.""" + + +@dataclass(frozen=True) +class BaseBlock: + """One fetched base block: its id, title, content and the ctx scope it lives in.""" + + id: str + title: str + content: str + scope: str + + +async def on_access_group_fields( + *, + platform: str, + scope_id: str, + group: str, + restricted: bool | None = None, + profile: str, + fields: Mapping[str, Mapping[str, Any]], + session_key: str, + user_id: str, + **kwargs: Any, +) -> dict | None: + """The hook callback: ``{"prompt": text}`` from the group's base blocks, or ``None``. + ``restricted``: the group's (``None`` = unknown = restricted); ``fields``: every valid namespace + of the group (this plugin reads ``fields["ctx_checkpoint"]``). S1 stub: ``None``.""" + return None + + +def render(blocks: Sequence[BaseBlock], max_chars: int, *, redact: Sequence[str] = ()) -> str: + """The deterministic text of *blocks* (heading, then ``### `` and content per block, in + list order), every value of *redact* removed, filled up to *max_chars*: the block that overflows + is cut with ``…[truncated]``, the rest dropped. S1 stub: ``""``.""" + return "" + + +def reset_state() -> None: + """Drop the render cache, the joined in-flight fetches and the thread pool (tests). S1 stub: + no-op.""" + return None + + +__all__ = [ + "HEADING", + "TRUNCATED_MARK", + "BaseBlock", + "BaseBlocksUnavailable", + "on_access_group_fields", + "render", + "reset_state", +] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py index 07c38b0fb..578378cdb 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py @@ -102,6 +102,17 @@ # would cut recall, the agent's ctx tools and other sessions' checkpoints of the profile off for a # minute. MAX_RATE_REFUSALS = 2 + + +def window_writes(max_parts: int, rate_limit_write: int | None = None) -> int: + """Writes one chain plans inside one rate window: ``max_parts`` parts (at most + ``MAX_PARTS_CEILING``) plus manifest and head. ``rate_limit_write``: the write limit per 60 s the + server reports for the key (``whoami``; ctx with per-request narrowing), which the chain is to + follow (contract, S1: the chain cluster P-G makes it count and wires ``ChainWriter`` to it; + until then the reported limit is ignored).""" + return max(1, min(int(max_parts), MAX_PARTS_CEILING)) + 2 + + # How long (real seconds) a call waits for the answer of another call of the same entry before it # looks at its deadline again (EntryState.admit: the answer in flight decides whether it may go). ENTRY_WAIT_POLL_S = 0.05 @@ -1619,6 +1630,9 @@ class ChainWriter: # The process-wide state of the server entry the client writes to (entry_state; the provider # binds it before each checkpoint). None: every chain keeps a state of its own (before 0.17.0). entry: EntryState | None = field(default=None, repr=False) + # The write limit per 60 s the server reports for the bound key (``whoami.rate_limit_write``; + # the binding sets it, ``window_writes`` follows it). S1 contract: kept, not yet read. + rate_limit_write: int | None = None _tool_evidence_warned: bool = field(default=False, init=False) def _notify(self, message: str) -> None: diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py index 450ef0cdd..d1c08651d 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py @@ -33,8 +33,11 @@ import urllib.error import urllib.parse import urllib.request +from collections.abc import Mapping, Sequence from typing import Any +from .narrowing import Narrowing + logger = logging.getLogger(__name__) @@ -378,6 +381,7 @@ def __init__( api_key: str, timeout: float = 10.0, synthesis_timeout: float = 90.0, + narrowing: Narrowing | None = None, ): parsed = urllib.parse.urlsplit(str(base_url or "").strip()) if parsed.scheme not in ("http", "https") or not parsed.netloc: @@ -393,6 +397,9 @@ def __init__( self._key = api_key self._timeout = timeout self._synthesis_timeout = synthesis_timeout + # Per-request scope narrowing (access groups): sent with every call and checked against the + # server's echo on every answer (CtxApiError code "narrowing_lost"). S1: kept, not yet sent. + self._narrowing = narrowing # The server registry's type names (``query_types``), read once per client. self._type_names: frozenset[str] | None = None @@ -632,3 +639,10 @@ def get_block(self, block_id: str, timeout: float | None = None) -> dict[str, An if left <= 0: raise CtxApiError("connection error: timed out") # what the bound ends a call with return self._request("POST", "/api/manage", {"action": "get", "data": {"id": block_id}}, timeout=left) + + def get_blocks(self, ids: Sequence[str], timeout: float | None = None) -> list[Mapping[str, Any]]: + """The blocks *ids* (1 to 16), in order, with one ``get`` carrying ``ids`` (ctx with the + multi-id get); against a server that answers that with 400, one ``get`` per id within the + same bound. A block that cannot be had is an entry with ``error`` (and ``code``), never an + exception for the whole call; a transient failure raises. S1 stub: no blocks.""" + return [] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py new file mode 100644 index 000000000..cb727351b --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py @@ -0,0 +1,130 @@ +"""Per-request scope narrowing on the client side and the proof of a group binding (contract, S1). + +A narrowed client sends ``X-Context-Read-Scopes`` (and ``X-Context-Write-Scope``) on every call and +expects the server's echo ``X-Context-Narrowed: <read,...>;<write>`` on every answer. A binding is +proven by ``whoami`` answers: one narrowed, and for restricted groups one unnarrowed of the same key. +Only the raw answers are remembered (per base URL, key digest and header set: 60 s after success, +15 s after failure); every binding evaluates the rules E2 to E5 and E7 itself, so a proof for one +group never satisfies another's stricter expectation. + +S1 state: the data forms are final, the functions are inert stubs (nothing calls them yet). The +client cluster (P-A) fills them in. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: # pragma: no cover - typing only + from .client import CtxClient + +HEADER_READ_SCOPES = "X-Context-Read-Scopes" +HEADER_WRITE_SCOPE = "X-Context-Write-Scope" +HEADER_NARROWED = "X-Context-Narrowed" + +# Raw whoami answers are kept this long (seconds) after a success and after a failure. +PROOF_TTL_OK_S = 60.0 +PROOF_TTL_FAILED_S = 15.0 +# The ctx label column is VARCHAR(100); a longer label hashes the profile part. +LABEL_MAX = 100 + + +@dataclass(frozen=True) +class Narrowing: + """The narrowing a client sends: ``read`` = the request's read set, in order (1 to 8 scopes); + ``write`` = its write scope (``None``: the client writes nothing).""" + + read: tuple[str, ...] + write: str | None = None + + def headers(self) -> dict[str, str]: + """The request headers of this narrowing.""" + out = {HEADER_READ_SCOPES: ",".join(self.read)} + if self.write: + out[HEADER_WRITE_SCOPE] = self.write + return out + + def echo(self) -> str: + """The ``X-Context-Narrowed`` value a server answers this narrowing with.""" + return f"{','.join(self.read)};{self.write or ''}" + + +@dataclass(frozen=True) +class Expect: + """What a binding expects of the key (design 02 §3.3). ``strict``: the group is restricted (E2 + to E4 apply in full); ``tenant``/``label``: expected values or ``None``; ``env_names``: the + variable names in the profile's ``.env`` and ``platform_toolsets``: the toolset list of the + platform in the profile (both for E7); ``scope_id``: the server the binding is for; ``write``: + the group's write scope (E3: the key's home scope, its write set exactly ``{write}``, its + unnarrowed read set exactly ``read ∪ {write}``) — the narrowing of a read client carries no write + scope, so it is named here (``None``: the key's home scope, unrestricted groups only).""" + + narrowing: Narrowing + strict: bool + tenant: str | None + label: str | None + env_names: tuple[str, ...] + platform_toolsets: tuple[str, ...] + scope_id: str + write: str | None = None + + +@dataclass(frozen=True) +class VerifyResult: + """The outcome of ``evaluate``: ``ok`` and, when not, the rules broken (``"E2"`` ...) with the + expected value per rule (no key value ever).""" + + ok: bool + failed: tuple[str, ...] = () + detail: Mapping[str, str] = field(default_factory=dict) + + +def key_digest(api_key: str) -> str: + """The first 16 hex characters of SHA-256 of a key: the only form of a key in caches, status + files and logs.""" + return hashlib.sha256(str(api_key or "").encode("utf-8")).hexdigest()[:16] + + +def expected_label(platform: str, scope_id: str, profile: str) -> str: + """The label a restricted group's key carries (E4): ``hermes:<platform>:<scope_id>:<profile>``; + past 100 characters ``#`` and 16 hex characters of SHA-256 of the profile name replace the + profile part. S1 stub: ``""``.""" + return "" + + +def whoami_raw(client: CtxClient, *, narrowed: bool, budget_s: float) -> Mapping[str, Any]: + """The raw ``whoami`` answer of *client* (narrowed: with its headers; else the same key without + them), from the proof store or the server within *budget_s*; a failure is remembered 15 s and + raised as ``CtxApiError``. S1 stub: an empty answer.""" + return {} + + +def evaluate(raw_narrowed: Mapping[str, Any], raw_unnarrowed: Mapping[str, Any] | None, expect: Expect) -> VerifyResult: + """E2 to E5 and E7 over raw answers, pure, without network. S1 stub: not proven.""" + return VerifyResult(ok=False, failed=("E5",), detail={"E5": "narrowing is not available"}) + + +def reset_proofs() -> None: + """Forget every remembered ``whoami`` answer (tests, ``access check``). S1 stub: no-op.""" + return None + + +__all__ = [ + "HEADER_NARROWED", + "HEADER_READ_SCOPES", + "HEADER_WRITE_SCOPE", + "LABEL_MAX", + "PROOF_TTL_FAILED_S", + "PROOF_TTL_OK_S", + "Expect", + "Narrowing", + "VerifyResult", + "evaluate", + "expected_label", + "key_digest", + "reset_proofs", + "whoami_raw", +] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/status.py b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py index 34a7dae22..72569d56b 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/status.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py @@ -17,7 +17,7 @@ import tempfile import threading import time -from collections.abc import Callable, Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator, Mapping from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime, timezone @@ -749,3 +749,22 @@ def mcp_report(hermes_home: str) -> dict[str, Any]: secrets=profile_ctx_keys(name), servers=servers if isinstance(servers, dict) else {}, ) + + +# -- access groups (contract, S1) --------------------------------------------------------------- +# One small file per binding under <home>/ctx_state/access/<platform>-<scope_id>-<profile>.json, +# written atomically and only when the state changes: ``bound`` or ``off: <reason>``, the rules +# checked (E1-E7), the key digest (16 hex), tenant slug, read, write, time, base blocks loaded and +# skipped with reason. Display only (``hermes memory status``, ``access status``): never read to +# bind, never a key value. The binding cluster (P-C) writes through ``record_access``; the tools +# cluster (P-E) owns the rest. + + +def record_access(hermes_home: str, platform: str, scope_id: str, profile: str, result: Mapping[str, Any]) -> None: + """Record the state of one binding (see above). S1 stub: no-op.""" + return None + + +def read_access(hermes_home: str) -> list[Mapping[str, Any]]: + """Every recorded binding of the home, sorted by platform, server and profile. S1 stub: none.""" + return [] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py b/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py index b1728fcd1..9c12acdec 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py @@ -7,9 +7,11 @@ from __future__ import annotations +import os import sys import pytest +from fakes.s1_pending import S1_PENDING @pytest.fixture(autouse=True) @@ -35,3 +37,48 @@ def reset() -> None: reset() yield reset() + + +# -- access groups (S1): cluster shield and shared fakes ----------------------------------------- +# Red S1 tests carry ``pytestmark = pytest.mark.access_cluster("<P-x>")``. While their cluster is +# listed in ``fakes/s1_pending.py`` each test gets a strict xfail that only an assertion about the +# missing behaviour satisfies (a TypeError or an import error stays an error); ``s1_green`` marks a +# guard that already holds on the stubs. ``CTX_S1_UNSHIELD=1`` lifts the shield (the red proof). + + +def pytest_configure(config): + config.addinivalue_line("markers", "access_cluster(name): red S1 test of an access-group plugin cluster") + config.addinivalue_line("markers", "s1_green: S1 guard that already holds on the stubs") + + +def pytest_collection_modifyitems(config, items): + if os.environ.get("CTX_S1_UNSHIELD") == "1": + return + for item in items: + marker = item.get_closest_marker("access_cluster") + if marker is None or item.get_closest_marker("s1_green") is not None: + continue + cluster = marker.args[0] if marker.args else "" + if cluster in S1_PENDING: + item.add_marker( + pytest.mark.xfail( + strict=True, + raises=(AssertionError, pytest.fail.Exception), + reason=f"S1 red: {cluster} not built yet", + ) + ) + + +@pytest.fixture +def fake_ctx(monkeypatch): + """A running fake ctx server (``fakes/ctx_server.py``); requests to it on 127.0.0.1 never go + through a proxy of the environment.""" + from fakes.ctx_server import FakeCtx + + monkeypatch.setenv("no_proxy", "127.0.0.1,localhost") + monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost") + server = FakeCtx().start() + try: + yield server + finally: + server.stop() diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/__init__.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/__init__.py new file mode 100644 index 000000000..441862ecb --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/__init__.py @@ -0,0 +1,3 @@ +"""Test fakes of the access-group surfaces (S1): a local ctx server with per-request narrowing +(``ctx_server``) and the Hermes surface of the access-groups core PR over the pinned Hermes +(``access_host``). They belong to no cluster; every plugin cluster tests against them.""" diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/access_host.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/access_host.py new file mode 100644 index 000000000..2c0999f32 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/access_host.py @@ -0,0 +1,363 @@ +"""The Hermes surface of the access-groups core PR (NousResearch/hermes-agent#164604, head +``0b613f2fdf``) over the pinned Hermes the CI runs (``26cd2e6d83``, without the PR), through +``monkeypatch`` only. Forms as the PR's code has them: + +- V8b: ``register_access_fields`` on the class ``hermes_cli.plugins.PluginContext`` + (``hermes_cli/plugins_context.py:825``); a memory provider's ``ctx`` is the collector, which + answers ``register_access_fields`` itself (``plugins/memory/__init__.py:562-564``) and every other + ``register_*`` through ``__getattr__`` (``FakeCollector``). +- V8a/V6a: a module ``gateway.access_groups`` with ``AccessContext(platform, scope_id, group, + profile, restricted: bool, admin=False, fields)`` and ``fields_for`` (``gateway/access_groups.py:131-148``) + and ``current_access()`` read from a ContextVar, so copied contexts (threads, ``/background``) + see it and a cron run sees ``None`` (``:949-980``). +- V4: ``ainvoke_hook_callback`` (``hermes_cli/plugins_dispatch.py:684-729``): an ``async def`` + callback is awaited on the loop under ``asyncio.wait_for(timeout)`` and cancelled when it passes; + any other runs on a daemon thread of its own; a raise or a timeout is ``(False, None)``. The + kwargs of ``gateway/access_prompt.py:46-60`` (``hook_kwargs``), ``fields`` deep-copied per call. +- Secrets: ``agent.secret_scope.get_secret`` reads a ContextVar mapping and counts reads. +- V5: ``initialize`` always gets ``scope_id``, ``access_group``, ``access_group_restricted``, + ``access_fields`` and ``restricted_profile`` (``agent/agent_init_memory_provider.py:180-201``); + ``truth_filter=True`` simulates a host that passes only true values (VB-2). +""" + +from __future__ import annotations + +import asyncio +import contextvars +import copy +import importlib +import importlib.util +import inspect +import sys +import threading +import types +from collections import Counter +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager +from dataclasses import dataclass, field +from pathlib import Path +from types import MappingProxyType +from typing import Any + +PLUGIN_DIR = Path(__file__).resolve().parents[2] +_EMPTY: Mapping[str, Any] = MappingProxyType({}) +OBSERVER_SCHEMA_VERSION = 1 + + +def load_plugin(name: str) -> types.ModuleType: + """The plugin package under a name of its own (as ``tests/test_provider_contract.py`` does).""" + if name in sys.modules: + return sys.modules[name] + spec = importlib.util.spec_from_file_location( + name, PLUGIN_DIR / "__init__.py", submodule_search_locations=[str(PLUGIN_DIR)] + ) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def plugin_module(package: types.ModuleType, sub: str) -> types.ModuleType: + """A submodule of a loaded plugin copy (``memory.access`` ...).""" + return importlib.import_module(f"{package.__name__}.{sub}") + + +# -- V6a --------------------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class AccessContext: + """The core's form (``gateway/access_groups.py:131-148``).""" + + platform: str + scope_id: str + group: str + profile: str | None + restricted: bool + admin: bool = False + fields: Mapping[str, Mapping[str, Any]] = field(default=_EMPTY, compare=False) + + def fields_for(self, plugin_id: str) -> Mapping[str, Any]: + return self.fields.get(plugin_id) or _EMPTY + + +_CURRENT: contextvars.ContextVar[AccessContext | None] = contextvars.ContextVar("fake_current_access", default=None) + + +def make_access( + *, + platform: str = "discord", + scope_id: str = "111", + group: str = "members", + profile: str | None = "members", + restricted: bool = True, + admin: bool = False, + fields: Mapping[str, Any] | None = None, + namespace: str = "ctx_checkpoint", +) -> AccessContext: + spaces = {namespace: MappingProxyType(copy.deepcopy(dict(fields)))} if fields else {} + return AccessContext(platform, str(scope_id), group, profile, restricted, admin, MappingProxyType(spaces)) + + +@contextmanager +def turn(access: AccessContext | None) -> Iterator[None]: + """Run the block as a gateway turn whose ``current_access()`` is *access*.""" + token = _CURRENT.set(access) + try: + yield + finally: + _CURRENT.reset(token) + + +# -- secrets ----------------------------------------------------------------------------------- + + +class SecretScope: + """``agent.secret_scope.get_secret`` over a ContextVar mapping, with a read counter.""" + + def __init__(self, base: Mapping[str, str] | None = None) -> None: + self.var: contextvars.ContextVar[Mapping[str, str]] = contextvars.ContextVar( + "fake_secret_scope", default=MappingProxyType(dict(base or {})) + ) + self.reads: Counter[str] = Counter() + self._lock = threading.Lock() + + def get_secret(self, name: str, default: str | None = None) -> str | None: + with self._lock: + self.reads[name] += 1 + return self.var.get().get(name, default) + + def set_base(self, values: Mapping[str, str]) -> None: + self.var.set(MappingProxyType(dict(values))) + + @contextmanager + def scoped(self, values: Mapping[str, str]) -> Iterator[None]: + token = self.var.set(MappingProxyType(dict(values))) + try: + yield + finally: + self.var.reset(token) + + def total_reads(self) -> int: + return sum(self.reads.values()) + + +# -- the collector a memory provider's register(ctx) gets --------------------------------------- + + +class FakeCollector: + """What ``register(ctx)`` of a memory plugin is handed: records every ``register_*`` call. + ``register_access_fields`` exists on the instance only when the host has V8 (the real collector + answers it itself, and only forwards it while the provider is active).""" + + def __init__(self, *, v8: bool, active: bool = True) -> None: + self.calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = [] + self.hooks: dict[str, list[Callable[..., Any]]] = {} + self.providers: list[Any] = [] + self.access_fields: list[Mapping[str, Any]] = [] + self._v8 = v8 + self._active = active + + def register_memory_provider(self, provider: Any) -> None: + self.calls.append(("register_memory_provider", (provider,), {})) + self.providers.append(provider) + + def register_hook(self, name: str, callback: Callable[..., Any], **kwargs: Any) -> None: + self.calls.append(("register_hook", (name, callback), kwargs)) + self.hooks.setdefault(name, []).append(callback) + + def register_access_fields(self, schema: Mapping[str, Any]) -> Any: + self.calls.append(("register_access_fields", (schema,), {})) + if not self._v8: + raise AttributeError("register_access_fields") # a pre-PR host's collector forwards nothing + if self._active: + self.access_fields.append(schema) + return None + + def __getattr__(self, name: str) -> Any: + if name.startswith("register_"): + + def record(*args: Any, **kwargs: Any) -> None: + self.calls.append((name, args, kwargs)) + + return record + raise AttributeError(name) + + def called(self, name: str) -> int: + return sum(1 for call in self.calls if call[0] == name) + + +# -- V5 ---------------------------------------------------------------------------------------- + + +def v5_kwargs( + *, + scope_id: str | None = None, + group: str | None = None, + group_restricted: bool = False, + fields: Mapping[str, Any] | None = None, + restricted_profile: bool = False, + truth_filter: bool = False, +) -> dict[str, Any]: + """The five access kwargs of every ``initialize`` (all of them; ``truth_filter``: only true ones).""" + out: dict[str, Any] = { + "scope_id": scope_id, + "access_group": group, + "access_group_restricted": bool(group_restricted) if group else False, + "access_fields": copy.deepcopy(dict(fields or {})), + "restricted_profile": bool(restricted_profile), + } + if truth_filter: + out = {k: v for k, v in out.items() if v} + return out + + +# -- V4 ---------------------------------------------------------------------------------------- + + +def hook_kwargs( + *, + platform: str = "discord", + scope_id: str = "111", + group: str = "members", + restricted: bool = True, + profile: str = "members", + fields: Mapping[str, Mapping[str, Any]] | None = None, + session_key: str = "agent:main:discord:group:111:222", + user_id: str = "333", +) -> dict[str, Any]: + """The hook's kwargs as ``gateway/access_prompt.py:_payload`` builds them.""" + return { + "platform": platform, + "scope_id": str(scope_id), + "group": group, + "restricted": bool(restricted), + "profile": profile, + "fields": copy.deepcopy(dict(fields or {})), + "session_key": session_key, + "user_id": user_id, + "telemetry_schema_version": OBSERVER_SCHEMA_VERSION, + } + + +@dataclass +class HookOutcome: + answered: bool + result: Any + error: BaseException | None = None + + +async def ainvoke_hook_callback(callback: Callable[..., Any], *, timeout: float = 30.0, **kwargs: Any) -> HookOutcome: + """One callback the way the core's dispatcher runs it (see the module text).""" + kwargs = dict(kwargs, fields=copy.deepcopy(kwargs.get("fields") or {})) + kwargs.setdefault("telemetry_schema_version", OBSERVER_SCHEMA_VERSION) + try: + if inspect.iscoroutinefunction(callback): + try: + return HookOutcome(True, await asyncio.wait_for(callback(**kwargs), timeout)) + except TimeoutError as exc: + return HookOutcome(False, None, exc) + loop = asyncio.get_running_loop() + done: asyncio.Future[Any] = loop.create_future() + ctx = contextvars.copy_context() + + def run() -> None: + try: + value = ctx.run(callback, **kwargs) + except BaseException as exc: # reported as the callback's failure + loop.call_soon_threadsafe(_settle, done, None, exc) + else: + loop.call_soon_threadsafe(_settle, done, value, None) + + threading.Thread(target=run, name="hermes-hook-access_group_fields", daemon=True).start() + return HookOutcome(True, await done) + except asyncio.CancelledError as exc: + task = asyncio.current_task() + if task is not None and task.cancelling(): + raise + return HookOutcome(False, None, exc) + except BaseException as exc: + return HookOutcome(False, None, exc) + + +def _settle(future: asyncio.Future[Any], value: Any, exc: BaseException | None) -> None: + if future.done(): + return + if exc is not None: + future.set_exception(exc) + else: + future.set_result(value) + + +# -- installation ------------------------------------------------------------------------------ + + +@dataclass +class Host: + """The installed surface; ``v8`` says whether the class carries ``register_access_fields``.""" + + v8: bool + secrets: SecretScope + module: types.ModuleType + + def collector(self, *, active: bool = True) -> FakeCollector: + return FakeCollector(v8=self.v8, active=active) + + +def install(monkeypatch: Any, *, v8: bool = True, secrets: Mapping[str, str] | None = None) -> Host: + """Patch the pinned Hermes with the PR's surface (``v8=False``: the pinned Hermes as it is, but + with the fake secret scope).""" + import agent.secret_scope as secret_scope + import hermes_cli.plugins as plugins + + scope = SecretScope(secrets) + monkeypatch.setattr(secret_scope, "get_secret", scope.get_secret) + module = types.ModuleType("gateway.access_groups") + module.AccessContext = AccessContext # type: ignore[attr-defined] + module.current_access = _CURRENT.get # type: ignore[attr-defined] + if v8: + + def register_access_fields(self: Any, schema: Mapping[str, Any]) -> None: + return None + + monkeypatch.setattr(plugins.PluginContext, "register_access_fields", register_access_fields, raising=False) + monkeypatch.setitem(sys.modules, "gateway.access_groups", module) + import gateway + + monkeypatch.setattr(gateway, "access_groups", module, raising=False) + else: + monkeypatch.delattr(plugins.PluginContext, "register_access_fields", raising=False) + monkeypatch.delitem(sys.modules, "gateway.access_groups", raising=False) + return Host(v8=v8, secrets=scope, module=module) + + +# -- the core's field schema rules (hermes_cli/access_fields.py), for schema checks -------------- + +FIELD_TYPES = frozenset({"str", "int", "float", "bool", "list", "env_name"}) +SPEC_KEYS = frozenset({"type", "description", "default"}) +MAX_FIELDS = 16 +FIELD_NAME = r"^[a-z][a-z0-9_]{0,63}$" +ENV_NAME = r"^[A-Z][A-Z0-9_]{0,63}$" + + +__all__ = [ + "ENV_NAME", + "FIELD_NAME", + "FIELD_TYPES", + "MAX_FIELDS", + "SPEC_KEYS", + "AccessContext", + "FakeCollector", + "HookOutcome", + "Host", + "SecretScope", + "ainvoke_hook_callback", + "hook_kwargs", + "install", + "load_plugin", + "make_access", + "plugin_module", + "turn", + "v5_kwargs", +] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py new file mode 100644 index 000000000..b702a7cce --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py @@ -0,0 +1,474 @@ +"""A local ctx server with the target semantics of per-request narrowing (design 02 §3.5 C-1 to +C-4), stdlib only: one thread, ``127.0.0.1``, port 0. + +Keys carry tenant (slug), home, ``allowed_scopes``, tenant grants, ``write_scopes``, +``scope_narrowing``, label, role, admin and ``confirm_writes``. Narrowing headers follow C-1 +(subset rule, write scope rules, closed route list, ``get``/``type-list`` only on ``/api/manage``), +C-2 (``required`` keys refuse every unnarrowed request but ``whoami``), C-3 (``keyset-provision``) +and C-4 (``get`` with ``ids``). Every request is counted per route and header set. Faults are +switches on the server object: echo missing or wrong, latency per route, 429 per route, a server +without C-1 (headers ignored, ``whoami`` without the new fields) and without C-4 (``ids`` refused). + +Answer forms follow what ``memory/client.py`` and ``memory/provider.py`` read today: +``/api/query`` ``{"success", "answer", "sources"}``, ``/api/search`` ``{"success", "results"}``, +``/api/store`` ``{"block": {...}}``, ``/api/manage`` ``get`` as ctx answers it today +(``{"action": "get", "success": true, "block": {...}}``; a miss is 200 with ``{"success": false, +"error": "Block not found"}``). The multi-id form (C-4) is the S1 contract, the same the Go test of +C-4 pins: ``{"success": true, "blocks": [block | {"id", "error", "code": "not_found"}]}``. +""" + +from __future__ import annotations + +import hashlib +import json +import threading +import time +import uuid +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any + +HEADER_READ = "X-Context-Read-Scopes" +HEADER_WRITE = "X-Context-Write-Scope" +HEADER_NARROWED = "X-Context-Narrowed" +# C-1: the closed list of routes a narrowed request may take. +NARROWED_ROUTES = frozenset( + { + ("POST", "/api/query"), + ("POST", "/api/search"), + ("POST", "/api/store"), + ("GET", "/api/whoami"), + ("POST", "/api/manage"), + } +) +NARROWED_ACTIONS = frozenset({"get", "type-list"}) +MAX_READ_SCOPES = 8 +MAX_IDS = 16 +TYPE_NAMES = ("knowledge", "checkpoint", "session-digest", "fact") + + +@dataclass +class FakeKey: + """One API key of the fake (the secret is what ``X-Context-Key`` carries).""" + + secret: str + tenant: str + home: str + allowed: tuple[str, ...] = () + grants: tuple[str, ...] = () # tenant grants: readable, never writable + write_scopes: tuple[str, ...] = () + scope_narrowing: str = "optional" + label: str = "" + role: str = "member" + admin: bool = False + confirm_writes: bool = False + active: bool = True + + @property + def read_scopes(self) -> list[str]: + out: list[str] = [] + for scope in (self.home, *self.allowed, *self.grants): + if scope not in out: + out.append(scope) + return out + + @property + def writable(self) -> list[str]: + return [self.home, *[s for s in self.write_scopes if s != self.home]] + + +@dataclass +class Seen: + """One request as the fake saw it.""" + + method: str + path: str + action: str + key_digest: str + read_header: str | None + write_header: str | None + status: int + body: Mapping[str, Any] = field(default_factory=dict) + + +def digest(secret: str) -> str: + return hashlib.sha256(secret.encode("utf-8")).hexdigest()[:16] + + +class FakeCtx: + """The fake server: keys, blocks per scope, counters and fault switches.""" + + def __init__(self) -> None: + self.keys: dict[str, FakeKey] = {} + self.blocks: dict[str, dict[str, Any]] = {} + self.scopes: set[str] = set() # scopes keyset-provision created or found (C-3) + self.seen: list[Seen] = [] + self.lock = threading.Lock() + # Fault switches. + self.echo_missing = False + self.echo_wrong = False + self.without_c1 = False + self.without_c4 = False + self.leak_on_get = False # get answers blocks outside the request's read set (E6 is the client's too) + self.latency: dict[str, float] = {} # route key ("/api/whoami", "manage:get", ...) -> seconds + self.throttle: dict[str, int] = {} # route key -> number of 429 answers still to give + self.rate_limit_write = 97 + self.max_keys = 50 + self._server: ThreadingHTTPServer | None = None + self._thread: threading.Thread | None = None + + # -- set-up ------------------------------------------------------------------------------ + + def add_key(self, **kwargs: Any) -> FakeKey: + key = FakeKey(**kwargs) + self.keys[key.secret] = key + return key + + def add_block(self, scope: str, title: str, content: str, *, block_id: str = "", **extra: Any) -> str: + block_id = block_id or str(uuid.uuid4()) + self.blocks[block_id] = { + "id": block_id, + "title": title, + "content": content, + "category": extra.pop("category", "reference"), + "type": extra.pop("type", "knowledge"), + "scope": scope, + "tags": list(extra.pop("tags", [])), + "metadata": dict(extra.pop("metadata", {})), + "archived": bool(extra.pop("archived", False)), + } + return block_id + + # -- counters ---------------------------------------------------------------------------- + + def count(self, path: str | None = None, action: str | None = None, *, narrowed: bool | None = None) -> int: + with self.lock: + rows = list(self.seen) + return sum( + 1 + for row in rows + if (path is None or row.path == path) + and (action is None or row.action == action) + and (narrowed is None or (row.read_header is not None) == narrowed) + ) + + def requests(self, path: str | None = None) -> list[Seen]: + with self.lock: + return [row for row in self.seen if path is None or row.path == path] + + def reset_counters(self) -> None: + with self.lock: + self.seen.clear() + + # -- life cycle -------------------------------------------------------------------------- + + @property + def url(self) -> str: + assert self._server is not None + return f"http://127.0.0.1:{self._server.server_port}" + + def start(self) -> FakeCtx: + fake = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args: Any) -> None: + return None + + def do_GET(self) -> None: + fake._handle(self, "GET") + + def do_POST(self) -> None: + fake._handle(self, "POST") + + self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self._server.daemon_threads = True + self._thread = threading.Thread(target=self._server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True) + self._thread.start() + return self + + def stop(self) -> None: + if self._server is not None: + self._server.shutdown() + self._server.server_close() + self._server = None + + # -- request handling -------------------------------------------------------------------- + + def _handle(self, h: BaseHTTPRequestHandler, method: str) -> None: + path = h.path.split("?", 1)[0] + length = int(h.headers.get("Content-Length") or 0) + raw = h.rfile.read(length) if length else b"" + try: + body = json.loads(raw.decode("utf-8")) if raw else {} + except ValueError: + body = {} + if not isinstance(body, dict): + body = {} + action = str(body.get("action") or "") if path == "/api/manage" else "" + secret = h.headers.get("X-Context-Key") or "" + read_values = h.headers.get_all(HEADER_READ) or [] + write_values = h.headers.get_all(HEADER_WRITE) or [] + route = f"manage:{action}" if action else path + status, payload, echo = self._answer(method, path, action, body, secret, read_values, write_values) + with self.lock: + self.seen.append( + Seen( + method=method, + path=path, + action=action, + key_digest=digest(secret), + read_header=",".join(read_values) if read_values else None, + write_header=",".join(write_values) if write_values else None, + status=status, + body=body, + ) + ) + delay = self.latency.get(route, self.latency.get(path, 0.0)) + if delay: + time.sleep(delay) + data = json.dumps(payload).encode("utf-8") + try: + h.send_response(status) + h.send_header("Content-Type", "application/json") + h.send_header("Content-Length", str(len(data))) + if echo is not None and not self.echo_missing: + h.send_header(HEADER_NARROWED, "x;y" if self.echo_wrong else echo) + h.end_headers() + h.wfile.write(data) + except OSError: + pass # the client gave up (its deadline); nothing to answer + + def _answer( + self, + method: str, + path: str, + action: str, + body: Mapping[str, Any], + secret: str, + read_values: list[str], + write_values: list[str], + ) -> tuple[int, dict[str, Any], str | None]: + key = self.keys.get(secret) + if key is None or not key.active: + return 401, {"success": False, "error": "unauthorized", "code": "unauthorized"}, None + route = f"manage:{action}" if action else path + with self.lock: + left = self.throttle.get(route, self.throttle.get(path, 0)) + if left > 0: + self.throttle[route if route in self.throttle else path] = left - 1 + return 429, {"success": False, "error": "rate limited", "code": "rate_limit"}, None + narrowed: tuple[list[str], str] | None = None + if not self.without_c1 and (read_values or write_values): + if not read_values: + return 400, _err("write scope without read scopes", "scope_narrowing_invalid"), None + if len(read_values) > 1 or len(write_values) > 1: + return 400, _err("narrowing header repeated", "scope_narrowing_invalid"), None + read = [s.strip() for s in read_values[0].split(",")] + if not read_values[0].strip() or any(not s for s in read) or len(read) != len(set(read)): + return 400, _err("empty or doubled narrowing", "scope_narrowing_invalid"), None + if len(read) > MAX_READ_SCOPES: + return 400, _err("too many read scopes", "scope_narrowing_invalid"), None + write = write_values[0].strip() if write_values else "" + if write_values and not write: + return 400, _err("empty write scope", "scope_narrowing_invalid"), None + if any(s not in key.read_scopes for s in read): + return 403, _err("scope outside the key", "scope_denied"), None + if write and (write not in key.writable or write not in read): + return 403, _err("write scope outside the key", "scope_denied"), None + if (method, path) not in NARROWED_ROUTES: + return 403, _err("route not open to narrowing", "scope_narrowing_route"), None + narrowed = (read, write) + elif not self.without_c1 and key.scope_narrowing == "required" and (method, path) != ("GET", "/api/whoami"): + return 403, _err("this key requires narrowing", "scope_narrowing_required"), None + echo = f"{','.join(narrowed[0])};{narrowed[1]}" if narrowed else None + read_set = narrowed[0] if narrowed else key.read_scopes + if (method, path) == ("GET", "/api/whoami"): + return 200, self._whoami(key, narrowed), echo + if (method, path) == ("POST", "/api/query"): + hits = self._visible(read_set, body.get("types_exclude")) + return 200, {"success": True, "answer": "", "sources": hits}, echo + if (method, path) == ("POST", "/api/search"): + hits = self._visible(read_set, body.get("types_exclude")) + return 200, {"success": True, "results": hits}, echo + if (method, path) == ("POST", "/api/store"): + if narrowed is not None: + if not narrowed[1]: + return 403, _err("no write scope on a narrowed request", "scope_denied"), echo + scope = narrowed[1] + else: + scope = key.home + block_id = self.add_block( + scope, + str(body.get("title") or ""), + str(body.get("content") or ""), + category=str(body.get("category") or "reference"), + type=str(body.get("type") or "knowledge"), + tags=list(body.get("tags") or []), + metadata=dict(body.get("metadata") or {}), + ) + now = "2026-12-06T00:00:00Z" + block = dict(self.blocks[block_id], created_at=now, updated_at=now) + return 200, {"block": block}, echo + if (method, path) == ("POST", "/api/manage"): + if narrowed is not None and (action not in NARROWED_ACTIONS or _shadowed_action(body)): + return 403, _err("action not open to narrowing", "scope_narrowing_route"), echo + return self._manage(key, action, body, read_set, echo) + if narrowed is not None: # unreachable: other routes were refused above + return 403, _err("route not open to narrowing", "scope_narrowing_route"), echo + return 200, {"success": True}, echo + + def whoami_answer(self, secret: str, read: Iterable[str] | None = None, write: str = "") -> dict[str, Any]: + """The ``whoami`` body this server gives *secret* (narrowed to *read*/*write* when given), + without a request: raw answers for the pure rule checks.""" + return self._whoami(self.keys[secret], (list(read), write) if read is not None else None) + + def _whoami(self, key: FakeKey, narrowed: tuple[list[str], str] | None) -> dict[str, Any]: + out: dict[str, Any] = { + "success": True, + "home_scope": key.home, + "read_scopes": list(key.read_scopes), + "tenant_slug": key.tenant, + "label": key.label, + "role": key.role, + "admin": key.admin, + } + if self.without_c1: + return out + out.update( + { + "write_scopes": [narrowed[1]] if narrowed and narrowed[1] else ([] if narrowed else key.writable), + "confirm_writes": key.confirm_writes, + "narrowed": {"read": list(narrowed[0]), "write": narrowed[1]} if narrowed else None, + "scope_narrowing": key.scope_narrowing, + "rate_limit_write": self.rate_limit_write, + } + ) + if narrowed: + out["read_scopes"] = list(narrowed[0]) + out["admin"] = False + out["role"] = "member" + return out + + def _visible(self, read_set: Iterable[str], types_exclude: Any) -> list[dict[str, Any]]: + excluded = {str(t) for t in types_exclude} if isinstance(types_exclude, list) else set() + scopes = set(read_set) + return [ + {k: v for k, v in block.items() if k != "archived"} + for block in self.blocks.values() + if block["scope"] in scopes and not block["archived"] and block["type"] not in excluded + ] + + def _manage( + self, key: FakeKey, action: str, body: Mapping[str, Any], read_set: list[str], echo: str | None + ) -> tuple[int, dict[str, Any], str | None]: + if action == "type-list": + return 200, {"success": True, "types": [{"name": name} for name in TYPE_NAMES]}, echo + if action == "get": + if "ids" in body: + ids = body.get("ids") + if self.without_c4: + return 400, _err("Missing required field: id", "missing_fields"), echo + if not isinstance(ids, list) or not 1 <= len(ids) <= MAX_IDS: + return 400, _err("ids: 1 to 16", "invalid_body"), echo + return 200, {"success": True, "blocks": [self._get_one(str(i), read_set) for i in ids]}, echo + block_id = str(body.get("id") or "") + if not block_id: + return 400, _err("Missing required field: id", "missing_fields"), echo + # The single get answers as ctx does today (go/internal/handler/context_manage.go handleGet): + # 200 with {"action": "get", "success": true, "block": ...}; a miss is 200 with + # {"success": false, "error": "Block not found"}. + one = self._get_one(block_id, read_set) + if "error" in one: + return 200, {"success": False, "error": "Block not found"}, echo + return 200, {"action": "get", "success": True, "block": one}, echo + if action == "keyset-provision": + return self._keyset_provision(key, body, echo) + return 200, {"success": True}, echo + + def _get_one(self, block_id: str, read_set: list[str]) -> dict[str, Any]: + block = self.blocks.get(block_id) + if block is None or block["archived"] or (block["scope"] not in read_set and not self.leak_on_get): + return {"id": block_id, "error": "block not found", "code": "not_found"} + return {k: v for k, v in block.items() if k != "archived"} + + def _keyset_provision( + self, admin: FakeKey, body: Mapping[str, Any], echo: str | None + ) -> tuple[int, dict[str, Any], str | None]: + # Wire form of the S1 contract, the same the Go test of C-3 pins + # (go/cmd/ctxd/keyset_provision_c3_integration_test.go): tenant owner or admin (or a ctx server + # admin); data.scopes = bare scope names, created when missing; the answer lists the scopes as + # {"scope", "created"} and the keys as {"id", "label", "home_scope", "allowed_scopes", + # "write_scopes", "scope_narrowing", "api_key"}, both in request order. + if admin.role not in ("owner", "admin") and not admin.admin: + return 403, _err("tenant admin required", "scope_denied"), echo + data = body.get("data") if isinstance(body.get("data"), dict) else {} + keys = data.get("keys") if isinstance(data.get("keys"), list) else [] + names = data.get("scopes") if isinstance(data.get("scopes"), list) else [] + if len(names) > 64: + return 400, _err("at most 64 scopes", "invalid_body"), echo + if len(keys) > 64: + return 400, _err("at most 64 keys", "invalid_body"), echo + active = [k for k in self.keys.values() if k.tenant == admin.tenant and k.active] + replaced = {str(spec.get("label")) for spec in keys if isinstance(spec, dict) and spec.get("replace_label")} + after = len([k for k in active if k.label not in replaced]) + len(keys) + if after > self.max_keys: + return ( + 429, + { + "success": False, + "error": "max_keys", + "code": "rate_limit", + "limit": self.max_keys, + "count": len(active), + }, + echo, + ) + scopes_out = [] + for name in names: + full = f"{admin.tenant}:{name}" + created = full not in self.scopes + self.scopes.add(full) + scopes_out.append({"scope": full, "created": created}) + out = [] + for spec in keys: + label = str(spec.get("label") or "") + if spec.get("replace_label"): + for other in active: + if other.label == label: + other.active = False + secret = "ctx_" + uuid.uuid4().hex + scope = lambda name: name if ":" in name else f"{admin.tenant}:{name}" # noqa: E731 + made = self.add_key( + secret=secret, + tenant=admin.tenant, + home=scope(str(spec.get("home_scope") or "")), + allowed=tuple(scope(str(s)) for s in spec.get("allowed_scopes") or ()), + write_scopes=tuple(scope(str(s)) for s in spec.get("write_scopes") or ()), + scope_narrowing=str(spec.get("scope_narrowing") or "optional"), + label=label, + ) + out.append( + { + "id": str(uuid.uuid4()), + "label": label, + "home_scope": made.home, + "allowed_scopes": list(made.allowed), + "write_scopes": list(made.write_scopes), + "scope_narrowing": made.scope_narrowing, + "api_key": secret, + } + ) + return 200, {"success": True, "scopes": scopes_out, "keys": out}, echo + + +def _shadowed_action(body: Mapping[str, Any]) -> bool: + """A second spelling of ``action`` (``{"action":"get","ACTION":"purge"}``) counts as another action.""" + return any(k.lower() == "action" and k != "action" for k in body) + + +def _err(text: str, code: str) -> dict[str, Any]: + return {"success": False, "error": text, "code": code} + + +__all__ = ["HEADER_NARROWED", "HEADER_READ", "HEADER_WRITE", "FakeCtx", "FakeKey", "Seen", "digest"] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py new file mode 100644 index 000000000..fc032c8d1 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py @@ -0,0 +1,15 @@ +"""Clusters whose red S1 tests are still shielded (``tests/conftest.py`` gives each test marked +``access_cluster(<c>)`` with ``c`` listed here a strict xfail). Switching a cluster on = deleting +its line. ``CTX_S1_UNSHIELD=1`` lifts the shield for every cluster (the red proof).""" + +S1_PENDING = frozenset( + { + "P-A", + "P-B", + "P-C", + "P-D", + "P-E", + "P-F", + "P-G", + } +) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py new file mode 100644 index 000000000..3f7d2a70f --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py @@ -0,0 +1,256 @@ +"""P-A (design 02 §4.5, §7.3): the client narrows every call, checks the server's echo, proves a +binding by raw ``whoami`` answers and fetches base blocks with one multi-id ``get``. Red on S1: +``CtxClient`` keeps the narrowing but sends nothing, ``whoami_raw``/``evaluate``/``get_blocks`` are +stubs. Real ``CtxClient`` against the fake ctx server (``fakes/ctx_server.py``).""" + +from __future__ import annotations + +import time + +import pytest +from fakes.access_host import load_plugin, plugin_module + +pytestmark = pytest.mark.access_cluster("P-A") + +_PKG = load_plugin("ctx_checkpoint_access_pa") +_client = plugin_module(_PKG, "memory.client") +_nar = plugin_module(_PKG, "memory.narrowing") +CtxClient, CtxApiError = _client.CtxClient, _client.CtxApiError +Narrowing, Expect = _nar.Narrowing, _nar.Expect + +K, M, B = "t:d111-k", "t:d111-members", "t:d222-k" +LABEL = "hermes:discord:111:members" +MEMBER_KEY = "ctx_member_111" +OPS_KEY = "ctx_ops" + + +@pytest.fixture(autouse=True) +def _fresh_proofs(): + _nar.reset_proofs() + yield + _nar.reset_proofs() + + +def _keys(fake, *, narrowing="optional"): + fake.add_key( + secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing=narrowing, label=LABEL, role="member" + ) + fake.add_key(secret=OPS_KEY, tenant="t", home="t:d111-ops", allowed=(K, M, B), write_scopes=(K,), role="admin") + + +def _expect(**overrides): + values = { + "narrowing": Narrowing(read=(K,)), + "strict": True, + "tenant": "t", + "label": LABEL, + "env_names": ("CTX_KEY_111_MEMBERS",), + "platform_toolsets": ("web",), + "scope_id": "111", + "write": M, + } + values.update(overrides) + return Expect(**values) + + +def _raws(fake, secret=MEMBER_KEY, read=(K,), write=""): + return fake.whoami_answer(secret, read, write), fake.whoami_answer(secret) + + +def _baseline_ok(fake): + narrowed, unnarrowed = _raws(fake) + result = _nar.evaluate(narrowed, unnarrowed, _expect()) + assert result.ok, f"a key that fits the restricted layout proves the binding: {result}" + return narrowed, unnarrowed + + +# -- headers and echo --------------------------------------------------------------------------- + + +def test_narrowed_client_sends_read_scopes_on_search_store_get_and_type_list(fake_ctx): + _keys(fake_ctx) + block = fake_ctx.add_block(K, "rules", "be kind") + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K, M), write=M)) + client.search("rules") + client.store("reference", "note", "text") + client.get_block(block) + client.query_types("rules", ["knowledge"], limit=3) + seen = fake_ctx.requests() + assert {(r.path, r.action) for r in seen} >= { + ("/api/search", ""), + ("/api/store", ""), + ("/api/manage", "get"), + ("/api/manage", "type-list"), + } + assert all(r.read_header == f"{K},{M}" for r in seen), [(r.path, r.read_header) for r in seen] + assert all(r.write_header == M for r in seen), [(r.path, r.write_header) for r in seen] + + +@pytest.mark.parametrize("fault", ["echo_missing", "echo_wrong"]) +def test_answer_without_the_right_echo_is_narrowing_lost(fake_ctx, fault): + _keys(fake_ctx) + setattr(fake_ctx, fault, True) + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + with pytest.raises(CtxApiError) as caught: + client.search("rules") + assert caught.value.code == "narrowing_lost" + + +@pytest.mark.s1_green +def test_client_without_narrowing_sends_no_narrowing_header(fake_ctx): + """Guard: a client built without ``narrowing`` stays as 0.19.1 (no header, no echo check).""" + _keys(fake_ctx) + fake_ctx.echo_missing = True + CtxClient(fake_ctx.url, OPS_KEY, timeout=5).search("rules") + assert [r.read_header for r in fake_ctx.requests()] == [None] + + +# -- proof: raw whoami answers, rules evaluated per binding -------------------------------------- + + +def test_whoami_raw_returns_the_narrowed_and_the_unnarrowed_answer(fake_ctx): + _keys(fake_ctx, narrowing="required") + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + narrowed = _nar.whoami_raw(client, narrowed=True, budget_s=3) + unnarrowed = _nar.whoami_raw(client, narrowed=False, budget_s=3) + assert narrowed.get("narrowed") == {"read": [K], "write": ""} + assert unnarrowed.get("narrowed") is None + assert unnarrowed.get("home_scope") == M + assert fake_ctx.count("/api/whoami", narrowed=True) == 1 + assert fake_ctx.count("/api/whoami", narrowed=False) == 1 + + +def test_server_without_narrowed_in_whoami_fails_e5(fake_ctx): + _keys(fake_ctx, narrowing="required") + _baseline_ok(fake_ctx) + fake_ctx.without_c1 = True + narrowed, unnarrowed = _raws(fake_ctx) + result = _nar.evaluate(narrowed, unnarrowed, _expect()) + assert not result.ok and "E5" in result.failed + + +def test_other_narrowed_list_fails_e5(fake_ctx): + _keys(fake_ctx, narrowing="required") + _baseline_ok(fake_ctx) + narrowed, unnarrowed = _raws(fake_ctx, read=(K, M)) + result = _nar.evaluate(narrowed, unnarrowed, _expect()) + assert not result.ok and "E5" in result.failed + + +@pytest.mark.parametrize( + ("change", "rule"), + [ + ("grant", "E3"), + ("write_not_home", "E3"), + ("admin", "E2"), + ("role", "E2"), + ("optional", "E2"), + ("tenant", "E2"), + ("label", "E4"), + ("toolset", "E7"), + ], +) +def test_strict_expectation_names_the_broken_rule(fake_ctx, change, rule): + _keys(fake_ctx, narrowing="required") + narrowed, unnarrowed = _baseline_ok(fake_ctx) + unnarrowed = dict(unnarrowed) + expect = _expect() + if change == "grant": + unnarrowed["read_scopes"] = [*unnarrowed["read_scopes"], "u:shared"] + elif change == "write_not_home": + expect = _expect(write="t:d111-mods") + elif change == "admin": + unnarrowed["admin"] = True + elif change == "role": + unnarrowed["role"] = "admin" + elif change == "optional": + unnarrowed["scope_narrowing"] = "optional" + elif change == "tenant": + expect = _expect(tenant="other") + elif change == "label": + expect = _expect(label="hermes:discord:111:mods") + elif change == "toolset": + expect = _expect(env_names=("CTX_KEY_111_MEMBERS", "CTX_KEY_222_MEMBERS"), platform_toolsets=("web", "file")) + result = _nar.evaluate(narrowed, unnarrowed, expect) + assert not result.ok + assert rule in result.failed, result + assert rule in result.detail and MEMBER_KEY not in str(result.detail) + + +def test_other_label_within_the_proof_ttl_is_off(fake_ctx): + """BP-21: the remembered answers are raw; a second binding with the same key and scopes but + another label is evaluated anew and fails E4.""" + _keys(fake_ctx, narrowing="required") + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + first = _nar.evaluate( + _nar.whoami_raw(client, narrowed=True, budget_s=3), + _nar.whoami_raw(client, narrowed=False, budget_s=3), + _expect(), + ) + assert first.ok, first + second = _nar.evaluate( + _nar.whoami_raw(client, narrowed=True, budget_s=3), + _nar.whoami_raw(client, narrowed=False, budget_s=3), + _expect(label="hermes:discord:111:other-profile"), + ) + assert fake_ctx.count("/api/whoami") == 2, "the second binding reads the remembered answers" + assert not second.ok and "E4" in second.failed + + +def test_failed_proof_is_remembered_15_s_then_asked_again(fake_ctx, monkeypatch): + _keys(fake_ctx, narrowing="required") + fake_ctx.throttle["/api/whoami"] = 2 # the first answer and its one retry are 429 + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + clock = [time.monotonic()] + monkeypatch.setattr(time, "monotonic", lambda: clock[0]) + with pytest.raises(CtxApiError): + _nar.whoami_raw(client, narrowed=True, budget_s=3) + asked = fake_ctx.count("/api/whoami") + with pytest.raises(CtxApiError): + _nar.whoami_raw(client, narrowed=True, budget_s=3) + assert fake_ctx.count("/api/whoami") == asked, "a failure is remembered" + clock[0] += _nar.PROOF_TTL_FAILED_S + 1 + assert _nar.whoami_raw(client, narrowed=True, budget_s=3).get("narrowed") == {"read": [K], "write": ""} + assert fake_ctx.count("/api/whoami") == asked + 1 + + +def test_proof_holds_its_budget(fake_ctx): + _keys(fake_ctx, narrowing="required") + fake_ctx.latency["/api/whoami"] = 4.0 + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=10, narrowing=Narrowing(read=(K,))) + started = time.monotonic() + with pytest.raises(CtxApiError): + _nar.whoami_raw(client, narrowed=True, budget_s=1.0) + assert time.monotonic() - started < 2.0 + + +def test_expected_label_and_its_hash_past_100_characters(): + assert _nar.expected_label("discord", "111", "members") == LABEL + long_profile = "p" * 120 + label = _nar.expected_label("discord", "111", long_profile) + assert len(label) <= _nar.LABEL_MAX + assert label.startswith("hermes:discord:111:#") and len(label.rsplit("#", 1)[1]) == 16 + + +# -- multi-id get (C-4) and its fallback --------------------------------------------------------- + + +def test_get_blocks_is_one_request_with_ids(fake_ctx): + _keys(fake_ctx) + first = fake_ctx.add_block(K, "one", "1") + second = fake_ctx.add_block(K, "two", "2") + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + blocks = client.get_blocks([second, "missing-id", first]) + assert [b.get("id") for b in blocks] == [second, "missing-id", first] + assert blocks[1].get("code") == "not_found" and "error" in blocks[1] + assert fake_ctx.count("/api/manage", "get") == 1 + + +def test_get_blocks_falls_back_to_one_get_per_id_on_400(fake_ctx): + _keys(fake_ctx) + fake_ctx.without_c4 = True + ids = [fake_ctx.add_block(K, f"b{i}", str(i)) for i in range(3)] + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + blocks = client.get_blocks(ids) + assert [b.get("title") for b in blocks] == ["b0", "b1", "b2"] + assert fake_ctx.count("/api/manage", "get") == 1 + len(ids) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_decide.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_decide.py new file mode 100644 index 000000000..0336898b8 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_decide.py @@ -0,0 +1,291 @@ +"""P-B (design 02 §3.1, §3.2, §3.6, §4.1 steps 1-2, §4.2 table): detection, the field schema, the +decision table and the markers. Red on S1: ``access_supported``/``decide``/``parse_fields``/markers +are stubs and ``register`` registers no fields. Aligned to the core PR's code: ``initialize`` always +gets the five access kwargs, ``access_group_restricted`` is the group's (the draft had no +restriction in V5, VB-11).""" + +from __future__ import annotations + +import json +import logging +import re + +import pytest +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-B") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pb") +acc = ah.plugin_module(_PKG, "memory.access") + +K, M = "t:d111-k", "t:d111-members" +RESTRICTED_FIELDS = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [K], "write": M, "base_blocks": ["b1"]} +OPS_FIELDS = {"key": "CTX_KEY_OPS", "read": [K], "write": "t:d111-ops"} + + +def _settings(**overrides): + return {**dict(acc.SETTINGS_DEFAULTS), **overrides} + + +def _init(platform="discord", agent_context="primary", **v5): + return {"platform": platform, "agent_context": agent_context, "hermes_home": "/h/profiles/members", **v5} + + +def _decide(init, *, current=None, parent=None, markers=None, v8=True, **settings): + return acc.decide(init, current, parent, _settings(**settings), markers or acc.Markers(), v8) + + +def _group_init(fields, *, restricted=True, truth_filter=False): + return _init( + **ah.v5_kwargs( + scope_id="111", group="members", group_restricted=restricted, fields=fields, truth_filter=truth_filter + ) + ) + + +# -- register(ctx): detection (V8b), fields (V3) ------------------------------------------------- + + +def test_register_on_a_host_with_v8_registers_the_schema(monkeypatch): + host = ah.install(monkeypatch, v8=True) + collector = host.collector() + _PKG.register(collector) + assert collector.access_fields == [acc.SCHEMA] + assert collector.called("register_memory_provider") == 1 + + +@pytest.mark.s1_green +def test_register_on_a_host_without_v8_calls_nothing_new_and_warns_nothing(monkeypatch, caplog): + """Guard: the collector answers every ``register_*``; detection reads the class, so a pre-PR + host sees no call and no WARNING.""" + host = ah.install(monkeypatch, v8=False) + collector = host.collector() + with caplog.at_level(logging.WARNING): + _PKG.register(collector) + assert collector.called("register_access_fields") == 0 + assert collector.called("register_hook") == 0 + assert collector.called("register_memory_provider") == 1 + assert not [r for r in caplog.records if r.levelno >= logging.WARNING] + + +def test_access_supported_reads_the_public_class(monkeypatch): + ah.install(monkeypatch, v8=True) + assert acc.access_supported() is True + ah.install(monkeypatch, v8=False) + assert acc.access_supported() is False + + +@pytest.mark.s1_green +def test_schema_fits_the_core_rules(): + assert 0 < len(acc.SCHEMA) <= ah.MAX_FIELDS + for name, spec in acc.SCHEMA.items(): + assert re.match(ah.FIELD_NAME, name), name + assert set(spec) <= ah.SPEC_KEYS - {"default"}, (name, spec) + assert spec["type"] in ah.FIELD_TYPES, (name, spec) + assert "Not set" in spec.get("description", ""), name + + +# -- current_access (V6a) and the init kwargs (V5) ----------------------------------------------- + + +def test_current_access_gives_this_plugins_namespace(monkeypatch): + ah.install(monkeypatch, v8=True) + access = ah.make_access(fields=RESTRICTED_FIELDS) + with ah.turn(access): + got = acc.current_access() + assert got is not None + assert (got.platform, got.scope_id, got.group, got.profile, got.restricted) == ( + "discord", + "111", + "members", + "members", + True, + ) + assert dict(got.fields) == RESTRICTED_FIELDS + + +@pytest.mark.s1_green +def test_current_access_is_none_outside_a_turn_and_without_the_core(monkeypatch): + ah.install(monkeypatch, v8=True) + assert acc.current_access() is None + ah.install(monkeypatch, v8=False) + assert acc.current_access() is None + + +def test_context_from_init_takes_the_groups_restriction(): + ctx = acc.context_from_init(_group_init(RESTRICTED_FIELDS, restricted=False)) + assert ctx is not None + assert (ctx.scope_id, ctx.group, ctx.restricted) == ("111", "members", False) + assert dict(ctx.fields) == RESTRICTED_FIELDS + assert acc.context_from_init(_init(**ah.v5_kwargs())) is None + + +def test_is_strict_follows_the_group_then_profile_then_marker(): + open_group = acc.AccessContext("discord", "111", "ops", "ops", False) + unknown = acc.AccessContext("discord", "111", "ops", "ops", None) + assert acc.is_strict(open_group, restricted_profile=False, markers=acc.Markers()) is False + assert acc.is_strict(unknown, restricted_profile=True, markers=acc.Markers()) is True + assert acc.is_strict(unknown, restricted_profile=False, markers=acc.Markers(restricted_seen=True)) is True + + +# -- the decision table (§4.2), one case per row -------------------------------------------------- + + +def test_row1_v8_false_with_restricted_seen_is_off(): + decision = _decide(_init(platform="cli"), v8=False, markers=acc.Markers(restricted_seen=True)) + assert decision.kind == "off" + + +@pytest.mark.s1_green +def test_row1_v8_false_without_marker_is_the_profile_connection(): + assert _decide(_init(platform="cli"), v8=False).kind == "profile" + + +def test_row2_group_with_fields_binds_the_group(): + decision = _decide(_group_init(RESTRICTED_FIELDS)) + assert decision.kind == "group" + assert decision.strict is True + assert decision.fields is not None + assert (decision.fields.read, decision.fields.write, decision.fields.tenant) == ((K,), M, "t") + + +def test_row2_enabled_false_is_off(): + assert _decide(_group_init({**RESTRICTED_FIELDS, "enabled": False})).kind == "off" + + +def test_row2_without_key_restricted_off_unrestricted_governed_unbound(): + no_key = {k: v for k, v in OPS_FIELDS.items() if k != "key"} + restricted_no_key = {k: v for k, v in RESTRICTED_FIELDS.items() if k != "key"} + assert _decide(_group_init(restricted_no_key, restricted=True)).kind == "off" + assert _decide(_group_init(no_key, restricted=False)).kind == "off" + assert _decide(_group_init(no_key, restricted=False), governed_unbound="profile").kind == "profile" + + +def test_row3_group_without_fields_restricted_off_unrestricted_governed_unbound(): + assert _decide(_group_init({}, restricted=True)).kind == "off" + assert _decide(_group_init({}, restricted=False)).kind == "off" + assert _decide(_group_init({}, restricted=False), governed_unbound="profile").kind == "profile" + + +@pytest.mark.parametrize("profile", ["members", None]) +def test_row4_background_with_a_turn_context_binds_its_group(profile): + current = acc.AccessContext("discord", "111", "members", profile, True, fields=RESTRICTED_FIELDS) + decision = _decide(_init(platform="discord", agent_context="primary", **ah.v5_kwargs()), current=current) + assert decision.kind == "group" and decision.strict is True + + +def test_row5_restricted_profile_is_off(): + assert _decide(_init(platform="cli", **ah.v5_kwargs(restricted_profile=True))).kind == "off" + + +def test_row6_restricted_seen_is_off_even_when_the_host_drops_false_values(): + init = _init(platform="cli", **ah.v5_kwargs(restricted_profile=False, truth_filter=True)) + assert "restricted_profile" not in init + assert _decide(init, markers=acc.Markers(restricted_seen=True)).kind == "off" + + +def test_row7_messaging_session_without_context_after_governed_seen_is_off(): + init = _init(platform="discord", **ah.v5_kwargs()) + assert _decide(init, markers=acc.Markers(governed_seen=True), ungoverned="profile").kind == "off" + + +def test_parent_platform_comes_from_the_session_never_from_the_process_env(monkeypatch): + """Row 7 and ``ungoverned: local`` for forks read the copied ``HERMES_SESSION_PLATFORM`` only + through ``get_session_env`` and only while the name is not in ``os.environ`` (where + ``get_session_env`` would answer with the process value).""" + import gateway.session_context as session_context + + def session_env(name, default=""): + return "discord" if name == "HERMES_SESSION_PLATFORM" else default + + monkeypatch.setattr(session_context, "get_session_env", session_env) + monkeypatch.delenv("HERMES_SESSION_PLATFORM", raising=False) + assert acc.session_parent_platform() == "discord" + monkeypatch.setenv("HERMES_SESSION_PLATFORM", "discord") + assert acc.session_parent_platform() is None + + +def test_row8_auto_is_profile_before_and_local_after_governed_seen(): + discord = _init(platform="discord", **ah.v5_kwargs()) + cli = _init(platform="cli", **ah.v5_kwargs()) + assert _decide(discord).kind == "profile" + assert _decide(discord, markers=acc.Markers(governed_seen=True)).kind == "off" + assert _decide(cli, markers=acc.Markers(governed_seen=True)).kind == "profile" + + +@pytest.mark.parametrize( + ("platform", "agent_context", "parent", "kind"), + [ + ("cli", "primary", None, "profile"), + ("tui", "primary", None, "profile"), + ("cron", "cron", None, "off"), + ("api_server", "primary", None, "off"), + ("discord", "primary", None, "off"), + ("cli", "subagent", "cli", "profile"), + ("discord", "subagent", "discord", "off"), + ], +) +def test_ungoverned_local_admits_local_sessions_only(platform, agent_context, parent, kind): + init = _init(platform=platform, agent_context=agent_context, **ah.v5_kwargs()) + assert _decide(init, parent=parent, ungoverned="local").kind == kind + assert _decide(init, parent=parent, ungoverned="off").kind == "off" + + +# -- fields: forms before any secret -------------------------------------------------------------- + + +def test_parse_fields_accepts_the_restricted_layout(): + parsed = acc.parse_fields(RESTRICTED_FIELDS, scope_id="111", strict=True) + assert isinstance(parsed, acc.GroupFields), parsed + assert parsed.recall is None or parsed.recall is False + assert parsed.base_blocks == ("b1",) and parsed.base_max_chars == 4000 and parsed.enabled is True + + +@pytest.mark.parametrize( + ("change", "field", "strict"), + [ + ({"key": "OPENAI_API_KEY"}, "key", False), + ({"key": "CTX_KEY_222_MEMBERS"}, "key", True), + ({"base_url": "HOME_URL"}, "base_url", False), + ({"read": ["no scope"]}, "read", False), + ({"read": [f"t:s{i}" for i in range(9)]}, "read", False), + ({"write": "t:d111-k"}, "write", True), + ({"tenant": "Bad_Slug"}, "tenant", False), + ({"base_blocks": [f"b{i}" for i in range(17)]}, "base_blocks", False), + ({"base_max_chars": 100}, "base_max_chars", False), + ], +) +def test_parse_fields_names_the_broken_field(change, field, strict): + assert isinstance(acc.parse_fields(RESTRICTED_FIELDS, scope_id="111", strict=True), acc.GroupFields) + parsed = acc.parse_fields({**RESTRICTED_FIELDS, **change}, scope_id="111", strict=strict) + assert isinstance(parsed, acc.FieldError) and parsed.field == field, parsed + assert str(change[field]) not in parsed.reason + + +# -- settings and markers (§3.2, §3.6) ------------------------------------------------------------ + + +def test_settings_come_from_config_yaml_never_from_ctx_json(tmp_path): + (tmp_path / "config.yaml").write_text( + "memory:\n ctx_checkpoint:\n governed_unbound: profile\n base_timeout_s: 99\n", encoding="utf-8" + ) + (tmp_path / "ctx.json").write_text(json.dumps({"ungoverned": "off"}), encoding="utf-8") + settings = acc.load_settings(str(tmp_path)) + assert settings["governed_unbound"] == "profile" + assert settings["ungoverned"] == "auto" + assert settings["base_timeout_s"] == 10 + + +def test_markers_only_rise(tmp_path): + home = str(tmp_path) + acc.raise_markers(home, restricted_seen=True) + assert acc.read_markers(home).restricted_seen is True + acc.raise_markers(home, restricted_seen=False, governed_seen=True) + assert acc.read_markers(home) == acc.Markers(restricted_seen=True, governed_seen=True) + + +def test_unreadable_marker_file_counts_as_both_set(tmp_path): + state = tmp_path / "ctx_state" + state.mkdir() + (state / "access-mode.json").write_text("{not json", encoding="utf-8") + assert acc.read_markers(str(tmp_path)) == acc.Markers(restricted_seen=True, governed_seen=True) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py new file mode 100644 index 000000000..05fc79e9d --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py @@ -0,0 +1,176 @@ +"""P-C (design 02 §4.2 steps 0, 3-9, §4.6): the provider binds a group, or nothing, from the access +kwargs every ``initialize`` gets (V5) and drops a binding whose group changed under it (V6a). Red on +S1: the provider ignores the access kwargs and connects as 0.19.1 with the profile's key. Real +``CtxCheckpointMemoryProvider`` over REST against the fake ctx server, secrets from the fake +secret scope.""" + +from __future__ import annotations + +import pytest +from fakes import access_host as ah +from fakes.ctx_server import digest + +pytestmark = pytest.mark.access_cluster("P-C") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pc") +_cfg = ah.plugin_module(_PKG, "memory.config") +Provider = _PKG.CtxCheckpointMemoryProvider + +A_K, A_OPS, B_K = "t:d111-k", "t:d111-ops", "t:d222-k" +A_MEMBERS = "t:d111-members" +PROFILE_KEY = "ctx_profile_operator" +OPS_A_KEY = "ctx_ops_a" +MEMBER_KEY = "ctx_member_111" +MEMBER_LABEL = "hermes:discord:111:members" +OPS_FIELDS = {"key": "CTX_KEY_111_OPS", "read": [A_K], "write": A_OPS} +MEMBER_FIELDS = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [A_K], "write": A_MEMBERS} + + +@pytest.fixture +def world(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=PROFILE_KEY, tenant="t", home="t:main", allowed=(A_K, B_K, A_OPS, A_MEMBERS)) + fake_ctx.add_key(secret=OPS_A_KEY, tenant="t", home=A_OPS, allowed=(A_K,), write_scopes=(A_K,)) + fake_ctx.add_key( + secret=MEMBER_KEY, tenant="t", home=A_MEMBERS, allowed=(A_K,), scope_narrowing="required", label=MEMBER_LABEL + ) + fake_ctx.add_block(A_K, "Server A rules", "alpha knowledge") + fake_ctx.add_block(B_K, "Server B secret plans", "bravo knowledge") + fake_ctx.add_block(A_MEMBERS, "member transcript", "what another member said") + host = ah.install( + monkeypatch, + v8=True, + secrets={ + "CTX_KEY": PROFILE_KEY, + "CTX_BASE_URL": fake_ctx.url, + "CTX_KEY_111_OPS": OPS_A_KEY, + "CTX_KEY_111_MEMBERS": MEMBER_KEY, + }, + ) + home = tmp_path / "profiles" / "members" + home.mkdir(parents=True) + return fake_ctx, host, home + + +def _write_settings(home, text): + (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n" + text, encoding="utf-8") + + +def _provider(home, *, platform="discord", **v5): + provider = Provider(config={"transport": "rest", "memory": True}) + provider.initialize("s-1", hermes_home=str(home), platform=platform, agent_context="primary", **v5) + return provider + + +def test_restricted_profile_group_without_fields_sends_nothing(world): + fake, _host, home = world + provider = _provider( + home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, restricted_profile=True) + ) + text = provider.prefetch("what are the plans?") + assert fake.count() == 0, [(r.path, r.action) for r in fake.requests()] + assert text == "" and provider.get_tool_schemas() == [] and provider.system_prompt_block() == "" + + +def test_session_in_server_a_never_reads_server_b(world): + fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + text = provider.prefetch("what are the plans?") + assert "bravo knowledge" not in text + assert "alpha knowledge" in text + assert all(r.read_header == A_K for r in fake.requests() if r.path != "/api/whoami") + assert {r.key_digest for r in fake.requests()} == {digest(OPS_A_KEY)} + + +def test_changed_fields_under_a_cached_agent_turn_the_binding_off(world): + fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + changed = ah.make_access(group="ops", profile="members", restricted=False, fields={**OPS_FIELDS, "read": [B_K]}) + fake.reset_counters() + with ah.turn(changed): + text = provider.prefetch("what are the plans?") + assert text == "" and fake.count() == 0 + with ah.turn(None): + assert provider.prefetch("what are the plans?") == "", "the trip wire turns the instance off for good" + + +def test_member_layout_binds_and_recall_never_reads_the_write_scope(world): + _fake, _host, home = world + _write_settings(home, " restricted_allow: [recall]\n") + fields = {**MEMBER_FIELDS, "recall": True} + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields)) + text = provider.prefetch("rules?") + assert "alpha knowledge" in text + assert "what another member said" not in text + names = [s.get("name") for s in provider.get_tool_schemas()] + assert "ctx_store" not in names and "ctx_query" in names + + +def test_swapped_fields_are_off_e3(world): + fake, _host, home = world + swapped = {**MEMBER_FIELDS, "read": [A_MEMBERS], "write": A_K, "recall": True} + _write_settings(home, " restricted_allow: [recall]\n") + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=swapped)) + assert fake.count("/api/whoami") >= 1, "the proof asked the server" + fake.reset_counters() + assert provider.prefetch("rules?") == "" and fake.count() == 0 + + +def test_restricted_recall_without_restricted_allow_stays_off(world): + fake, _host, home = world + fields = {**MEMBER_FIELDS, "recall": True} + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields)) + assert fake.count("/api/whoami", narrowed=True) == 1, "the group is proven" + fake.reset_counters() + assert provider.prefetch("rules?") == "" and fake.count() == 0 + + +def test_foreign_key_in_env_with_file_toolset_is_off_e7(world): + fake, _host, home = world + _write_settings(home, " restricted_allow: [recall]\n") + (home / ".env").write_text("CTX_KEY_111_MEMBERS=x\nCTX_KEY_222_MEMBERS=y\n", encoding="utf-8") + (home / "config.yaml").write_text( + "platform_toolsets:\n discord: [web, file]\nmemory:\n ctx_checkpoint:\n restricted_allow: [recall]\n", + encoding="utf-8", + ) + fields = {**MEMBER_FIELDS, "recall": True} + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields)) + assert fake.count("/api/whoami") >= 1, "E7 is evaluated with the proof" + fake.reset_counters() + assert provider.prefetch("rules?") == "" and fake.count() == 0 + + +def test_invalid_key_name_reads_no_secret_and_sends_nothing(world): + fake, host, home = world + bad = {**OPS_FIELDS, "key": "OPENAI_API_KEY"} + host.secrets.reads.clear() + _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=bad)) + assert host.secrets.reads["OPENAI_API_KEY"] == 0 + assert fake.count() == 0 + + +def test_reinit_that_fails_validation_reads_nothing_after(world): + fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + assert "alpha knowledge" in provider.prefetch("plans?") + provider.initialize( + "s-2", + hermes_home=str(home), + platform="discord", + **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields={**OPS_FIELDS, "read": ["bad"]}), + ) + fake.reset_counters() + assert provider.prefetch("plans?") == "" and fake.count() == 0 + + +def test_profile_without_default_key_is_available_with_ungoverned_local(world, monkeypatch): + fake, host, home = world + host.secrets.set_base({"CTX_BASE_URL": fake.url}) + _write_settings(home, " ungoverned: local\n") + monkeypatch.setenv("HERMES_HOME", str(home)) + assert Provider(config={"transport": "rest"}).is_available() is True + + +def test_group_and_server_tags_are_reserved_for_the_plugin(): + tags = _cfg.merge_tags(["server:discord:999", "group:admins", "topic"], "members", "tool") + assert "topic" in tags + assert not [t for t in tags if t.startswith(("server:", "group:"))] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py new file mode 100644 index 000000000..6c66188bc --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py @@ -0,0 +1,235 @@ +"""P-D (design 02 §4.1 step 3, §4.4): the hook ``access_group_fields`` puts the group's base blocks +into its prompt, whole or not at all, without holding the gateway loop. Red on S1: ``register`` +registers no hook and the callback returns ``None``. Driven through the core's dispatcher form +(``fakes.access_host.ainvoke_hook_callback``) against the fake ctx server. + +Aligned to the core PR's code, not the draft: the core passes ``restricted`` (the group's) to the +hook, so "unknown" is only the absence of that kwarg (an older core); a plain callback would run on a +daemon thread of its own, not inline on the loop (the draft's reason for ``async def`` is now the +bounded ``wait_for`` and the cancellation, not a blocked loop).""" + +from __future__ import annotations + +import asyncio +import inspect +import time + +import pytest +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-D") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pd") +bb = ah.plugin_module(_PKG, "memory.base_blocks") +_nar = ah.plugin_module(_PKG, "memory.narrowing") + +K, M, B = "t:d111-k", "t:d111-members", "t:d222-k" +MEMBER_KEY = "ctx_member_111_secret_value" +LABEL = "hermes:discord:111:members" + + +@pytest.fixture +def world(fake_ctx, monkeypatch, _isolated_hermes_home): + bb.reset_state() + _nar.reset_proofs() + fake_ctx.add_key( + secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=LABEL, role="member" + ) + ids = { + "one": fake_ctx.add_block(K, "House rules", "Be kind to each other."), + "two": fake_ctx.add_block(K, "FAQ", "Ask in #help."), + "other_server": fake_ctx.add_block(B, "Server B notes", "bravo"), + "own_write": fake_ctx.add_block(M, "Member chatter", "said by a member"), + } + host = ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) + yield fake_ctx, host, ids, _isolated_hermes_home + bb.reset_state() + _nar.reset_proofs() + + +def _fields(ids, *names, **extra): + own = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [K], "write": M} + own["base_blocks"] = [ids.get(n, n) for n in names] + own.update(extra) + return {"ctx_checkpoint": own} + + +def _call(fields, **overrides): + kwargs = ah.hook_kwargs(fields=fields, **overrides) + return asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs)) + + +def _prompt(outcome): + assert outcome.answered, f"the hook failed: {outcome.error!r}" + assert isinstance(outcome.result, dict) and isinstance(outcome.result.get("prompt"), str), outcome.result + return outcome.result["prompt"] + + +def test_hook_gives_the_prompt_of_two_base_blocks(world): + _fake, _host, ids, _home = world + text = _prompt(_call(_fields(ids, "one", "two"))) + assert text.startswith(bb.HEADING) + assert text.index("### House rules") < text.index("### FAQ") + assert "Be kind to each other." in text and "Ask in #help." in text + + +def test_register_on_v8_registers_the_async_hook(monkeypatch): + host = ah.install(monkeypatch, v8=True) + collector = host.collector() + _PKG.register(collector) + callbacks = collector.hooks.get("access_group_fields") or [] + assert len(callbacks) == 1 and inspect.iscoroutinefunction(callbacks[0]) + + +@pytest.mark.s1_green +def test_restricted_group_without_fields_is_none_with_no_request_and_no_secret(world): + fake, host, _ids, _home = world + host.secrets.reads.clear() + outcome = _call({}) + assert outcome.answered and outcome.result is None + assert fake.count() == 0 and host.secrets.total_reads() == 0 + + +@pytest.mark.s1_green +def test_enabled_false_is_none_with_no_request_and_no_secret(world): + fake, host, ids, _home = world + host.secrets.reads.clear() + outcome = _call(_fields(ids, "one", enabled=False)) + assert outcome.answered and outcome.result is None + assert fake.count() == 0 and host.secrets.total_reads() == 0 + + +def test_unknown_strictness_counts_as_restricted(world): + fake, _host, ids, _home = world + no_tenant = _fields(ids, "one") + del no_tenant["ctx_checkpoint"]["tenant"] + kwargs = ah.hook_kwargs(fields=no_tenant) + del kwargs["restricted"] # an older core: the group's restriction is not told + outcome = asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs)) + assert outcome.answered and outcome.result is None and fake.count() == 0 + assert "House rules" in _prompt(_call(no_tenant, restricted=False)) + + +def test_swapped_fields_are_none_without_get(world): + fake, _host, ids, _home = world + assert "House rules" in _prompt(_call(_fields(ids, "one"))) + bb.reset_state() + fake.reset_counters() + swapped = _fields(ids, "one", read=[M], write=K) + outcome = _call(swapped) + assert outcome.answered and outcome.result is None + assert fake.count("/api/manage", "get") == 0 + + +def test_block_outside_read_is_skipped(world): + _fake, _host, ids, _home = world + text = _prompt(_call(_fields(ids, "one", "other_server"))) + assert "House rules" in text and "bravo" not in text + + +def test_block_of_the_write_scope_is_refused_e6(world): + fake, _host, ids, _home = world + fake.leak_on_get = True # a server that answers outside the narrowing: E6 holds on the client too + text = _prompt(_call(_fields(ids, "one", "own_write"))) + assert "House rules" in text and "said by a member" not in text + + +def test_render_is_deterministic_and_cut_with_a_marker(): + blocks = [bb.BaseBlock("1", "First", "a" * 300, K), bb.BaseBlock("2", "Second", "b" * 300, K)] + once, twice = bb.render(blocks, 4000), bb.render(blocks, 4000) + assert once == twice and once.startswith(bb.HEADING) and "### First" in once and "### Second" in once + short = bb.render(blocks, 200) + assert len(short) <= 200 and short.endswith(bb.TRUNCATED_MARK) and "### Second" not in short + + +def test_key_value_in_a_block_is_redacted(world): + fake, _host, ids, _home = world + leaked = fake.add_block(K, "Leaky", f"the key is {MEMBER_KEY} here") + text = _prompt(_call(_fields(ids, leaked))) + assert "Leaky" in text and MEMBER_KEY not in text + + +def test_base_rev_changes_the_cache_key(world): + fake, _host, ids, _home = world + _prompt(_call(_fields(ids, "one"))) + _prompt(_call(_fields(ids, "one"))) + assert fake.count("/api/manage", "get") == 1, "the second call is a cache hit" + _prompt(_call(_fields(ids, "one", base_rev=1))) + assert fake.count("/api/manage", "get") == 2 + + +def test_loop_stays_free_while_a_fetch_hangs(world): + fake, _host, ids, _home = world + fake.latency["manage:get"] = 3.0 + kwargs = ah.hook_kwargs(fields=_fields(ids, "one")) + ticks = [] + + async def ticker(stop): + while not stop.is_set(): + ticks.append(time.monotonic()) + await asyncio.sleep(0.1) + + async def main(): + stop = asyncio.Event() + tick = asyncio.create_task(ticker(stop)) + outcome = await ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs) + stop.set() + await tick + return outcome + + text = _prompt(asyncio.run(main())) + assert "House rules" in text + assert len(ticks) >= 15, f"the loop ran only {len(ticks)} ticks during a 3 s fetch" + + +def test_budget_ends_in_unavailable_never_a_partial_text(world): + fake, _host, ids, home = world + (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n base_timeout_s: 1\n", encoding="utf-8") + fake.latency["manage:get"] = 5.0 + started = time.monotonic() + outcome = _call(_fields(ids, "one", "two")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + assert time.monotonic() - started < 1.5 + + +def test_transient_failure_of_one_block_is_unavailable(world): + fake, _host, ids, _home = world + fake.without_c4 = True + fake.throttle["manage:get"] = 4 # the multi-id get is refused (400 without C-4); per-id gets meet 429s + outcome = _call(_fields(ids, "one", "two")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + + +def test_one_request_with_c4_one_per_id_without(world): + fake, _host, ids, _home = world + _prompt(_call(_fields(ids, "one", "two"))) + assert fake.count("/api/manage", "get") == 1 + bb.reset_state() + fake.reset_counters() + fake.without_c4 = True + _prompt(_call(_fields(ids, "one", "two"))) + assert fake.count("/api/manage", "get") == 3 + + +def test_concurrent_calls_with_the_same_key_fetch_once(world): + fake, _host, ids, _home = world + fake.latency["manage:get"] = 0.5 + kwargs = ah.hook_kwargs(fields=_fields(ids, "one")) + + async def main(): + return await asyncio.gather( + ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs), + ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs), + ) + + first, second = asyncio.run(main()) + assert _prompt(first) == _prompt(second) + assert fake.count("/api/manage", "get") == 1 + + +def test_secret_of_the_turn_scope_is_read_in_the_hook(world): + fake, host, ids, _home = world + host.secrets.set_base({"CTX_BASE_URL": fake.url}) + with host.secrets.scoped({"CTX_BASE_URL": fake.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}): + text = _prompt(_call(_fields(ids, "one"))) + assert "House rules" in text and host.secrets.reads["CTX_KEY_111_MEMBERS"] >= 1 diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py new file mode 100644 index 000000000..f374805d6 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py @@ -0,0 +1,111 @@ +"""P-E (design 02 §3.6, §4.7): per-binding status files and ``hermes ctx_checkpoint access ...``. +Red on S1: ``record_access``/``read_access`` and ``access_cli`` are stubs. ``provision`` runs against +the fake ctx server's ``keyset-provision`` (C-3).""" + +from __future__ import annotations + +import re + +import pytest +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-E") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pe") +st = ah.plugin_module(_PKG, "memory.status") +cli = ah.plugin_module(_PKG, "memory.access_cli") +acc = ah.plugin_module(_PKG, "memory.access") + +ADMIN_KEY = "ctx_admin_MARKED_FAKE_KEY_do_not_store" +OFF_RESULT = { + "state": "off: E4", + "rules": {"E4": "label hermes:discord:111:members"}, + "key_digest": "0123456789abcdef", + "tenant_slug": "t", + "read": ["t:d111-k"], + "write": "t:d111-members", +} + + +def _files_text(root): + return "\n".join(p.read_text(encoding="utf-8", errors="replace") for p in root.rglob("*") if p.is_file()) + + +def test_record_access_is_read_back_without_a_key_value(tmp_path): + st.record_access(str(tmp_path), "discord", "111", "members", {**OFF_RESULT, "key": "ctx_secret_value"}) + rows = st.read_access(str(tmp_path)) + assert len(rows) == 1 and rows[0].get("state") == "off: E4" + assert (tmp_path / "ctx_state" / "access" / "discord-111-members.json").is_file() + assert "ctx_secret_value" not in _files_text(tmp_path) + + +def test_access_status_names_an_off_binding(tmp_path, capsys): + st.record_access(str(tmp_path), "discord", "111", "members", OFF_RESULT) + assert cli.run_access(["status"], hermes_home=str(tmp_path)) == 0 + out = capsys.readouterr().out + assert "111" in out and "off: E4" in out and "api-key-update" in out + + +def test_reset_marker_lowers_the_markers(tmp_path): + home = str(tmp_path) + acc.raise_markers(home, restricted_seen=True, governed_seen=True) + assert acc.read_markers(home) == acc.Markers(True, True) + assert cli.run_access(["reset-marker", "--profile", "members", "--restricted"], hermes_home=home) == 0 + assert acc.read_markers(home) == acc.Markers(False, True) + + +def test_scope_names_fit_the_ctx_pattern_and_refuse_collisions(): + layout = cli.scope_layout("1234567890123456789", ["members", "Mod_Team_With_A_Long_Name"]) + assert layout.get(cli.KNOWLEDGE, "").endswith("-k") + assert set(layout) == {cli.KNOWLEDGE, "members", "Mod_Team_With_A_Long_Name"} + for name in layout.values(): + assert cli.SCOPE_NAME.match(name) and "_" not in name, name + assert layout["members"].startswith("d") and len(layout["members"]) <= 24 + with pytest.raises(ValueError): + cli.scope_layout("111", ["a_b", "a-b"]) + + +def test_key_variable_name_is_bounded(): + name = cli.key_env_name("1234567890123456789", "members-eu") + assert name == "CTX_KEY_1234567890123456789_MEMBERS_EU" + long_name = cli.key_env_name("1234567890123456789", "p" * 80) + assert ( + len(long_name) <= 64 and cli.ENV_NAME.match(long_name) and long_name.startswith("CTX_KEY_1234567890123456789_") + ) + + +def _provision_world(fake_ctx, monkeypatch, home): + fake_ctx.add_key(secret=ADMIN_KEY, tenant="t", home="t:main", role="admin") + host = ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_ADMIN": ADMIN_KEY}) + monkeypatch.setenv("CTX_ADMIN", ADMIN_KEY) + monkeypatch.setenv("CTX_BASE_URL", fake_ctx.url) + return host + + +def _provision(home, *extra): + argv = ["provision", "--server", "discord:111", "--profile", "members", "--group", "members"] + return cli.run_access([*argv, "--admin-key-env", "CTX_ADMIN", *extra], hermes_home=str(home)) + + +def test_provision_at_the_key_limit_writes_no_env_line(fake_ctx, monkeypatch, tmp_path, caplog, capsys): + _provision_world(fake_ctx, monkeypatch, tmp_path) + fake_ctx.max_keys = 1 + assert _provision(tmp_path) != 0 + assert fake_ctx.count("/api/manage", "keyset-provision") == 1 + env = tmp_path / ".env" + assert not env.exists() or "CTX_KEY_111" not in env.read_text(encoding="utf-8") + assert ADMIN_KEY not in caplog.text + capsys.readouterr().out + _files_text(tmp_path) + + +def test_provision_twice_leaves_one_active_key_per_label(fake_ctx, monkeypatch, tmp_path, capsys): + _provision_world(fake_ctx, monkeypatch, tmp_path) + assert _provision(tmp_path, "--emit-yaml") == 0 + assert _provision(tmp_path) == 0 + calls = [r.body for r in fake_ctx.requests("/api/manage") if r.action == "keyset-provision"] + assert len(calls) == 2 and all(k.get("replace_label") for c in calls for k in c["data"]["keys"]) + labels = [k.label for k in fake_ctx.keys.values() if k.active and k.label.startswith("hermes:")] + assert labels == ["hermes:discord:111:members"] + out = capsys.readouterr().out + assert "members" in out and "ctx_checkpoint" in out + assert ADMIN_KEY not in out + _files_text(tmp_path) + assert re.search(r"^CTX_KEY_111_MEMBERS=", (tmp_path / ".env").read_text(encoding="utf-8"), re.M) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pf_docs.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pf_docs.py new file mode 100644 index 000000000..efb6f86cc --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pf_docs.py @@ -0,0 +1,30 @@ +"""P-F (design 02 §7.3): the README names every access-group field and every setting of this axis. +Red on S1: the README predates both.""" + +from __future__ import annotations + +import pytest +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-F") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pf") +acc = ah.plugin_module(_PKG, "memory.access") +README = (ah.PLUGIN_DIR / "README.md").read_text(encoding="utf-8") + + +@pytest.mark.parametrize("name", sorted(acc.SCHEMA)) +def test_readme_names_every_field(name): + assert f"`{name}`" in README and "Access groups" in README + + +@pytest.mark.parametrize("name", sorted(acc.SETTINGS_DEFAULTS)) +def test_readme_names_every_setting(name): + assert f"`{name}`" in README and "Access groups" in README + + +@pytest.mark.parametrize( + "heading", ["Access groups", "Base blocks", "Recipe for restricted profiles", "What this does not promise"] +) +def test_readme_has_the_sections(heading): + assert heading in README diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py new file mode 100644 index 000000000..8e99e7c79 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py @@ -0,0 +1,29 @@ +"""P-G (design 02 §7.3, CC-7): the chain's writes per rate window follow the write limit the +server reports for the key (``whoami.rate_limit_write``). Red on S1: ``window_writes`` ignores it.""" + +from __future__ import annotations + +import pytest +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-G") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pg") +cp = ah.plugin_module(_PKG, "memory.checkpoint") + + +def test_reported_limit_bounds_the_window(): + assert cp.window_writes(cp.MAX_PARTS_CEILING, 40) <= 40 + assert cp.window_writes(10, 40) == 12 + + +@pytest.mark.s1_green +def test_server_without_the_field_keeps_todays_window(): + assert cp.window_writes(cp.MAX_PARTS_CEILING, None) == cp.MAX_PARTS_CEILING + 2 + assert cp.window_writes(10) == 12 + + +@pytest.mark.s1_green +def test_reported_limit_over_100_never_raises_the_window(): + assert cp.window_writes(500, 1000) == min(500, cp.MAX_PARTS_CEILING) + 2 + assert cp.window_writes(cp.MAX_PARTS_CEILING, 101) == cp.MAX_PARTS_CEILING + 2 From e8df54f750db42aadc538e0b51adb05f56b838fd Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 01:12:54 +0100 Subject: [PATCH 02/15] =?UTF-8?q?test(auth):=20S1=20contract=20for=20per-r?= =?UTF-8?q?equest=20scope=20narrowing=20=E2=80=94=20inert=20stubs=20and=20?= =?UTF-8?q?call=20sites,=20the=20red=20tests=20of=20C-1=20to=20C-4=20behin?= =?UTF-8?q?d=20per-cluster=20build=20tags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The contract the four server clusters of the access-group binding build against, with behaviour unchanged: auth.Narrowing and the AuthResult fields Narrowed and ScopeNarrowing, the scope_narrowing values, narrowAuth (headers ignored) in the Auth middleware between the validity check and the context value, fed only to the handlers while store.WithRequestKey keeps the unnarrowed key, the action check of a narrowed /api/manage request on the one decoded action, and insertApiKeyTx's scopeNarrowing parameter (every caller passes optional; the column is migration 198's). The red tests drive the production router and stay out of every gate behind `integration && s1red_cN`; a cluster enables its file by shortening that line to `//go:build integration`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../keyset_provision_c3_integration_test.go | 494 +++++++++++ .../manage_get_ids_c4_integration_test.go | 261 ++++++ go/cmd/ctxd/narrowing_c1_integration_test.go | 806 ++++++++++++++++++ ..._narrowing_required_c2_integration_test.go | 385 +++++++++ go/internal/auth/auth.go | 28 + go/internal/handler/manage_table.go | 9 + go/internal/handler/middleware.go | 15 +- go/internal/handler/narrowing.go | 65 ++ go/internal/store/api_keys.go | 16 +- go/internal/store/api_keys_insert_test.go | 4 +- .../store/api_keys_write_scopes_test.go | 4 +- go/internal/store/provision.go | 3 +- 12 files changed, 2081 insertions(+), 9 deletions(-) create mode 100644 go/cmd/ctxd/keyset_provision_c3_integration_test.go create mode 100644 go/cmd/ctxd/manage_get_ids_c4_integration_test.go create mode 100644 go/cmd/ctxd/narrowing_c1_integration_test.go create mode 100644 go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go create mode 100644 go/internal/handler/narrowing.go diff --git a/go/cmd/ctxd/keyset_provision_c3_integration_test.go b/go/cmd/ctxd/keyset_provision_c3_integration_test.go new file mode 100644 index 000000000..f1074158f --- /dev/null +++ b/go/cmd/ctxd/keyset_provision_c3_integration_test.go @@ -0,0 +1,494 @@ +//go:build integration && s1red_c3 + +// Achse 02, cluster C-3 (design2/02-ctx-checkpoint.md §3.5 C-3, §7.3, BP-26): +// the manage action keyset-provision creates, for a tenant-admin in its own +// tenant, the missing scopes and then the keys of one set in ONE transaction +// under the tenant row's lock, with the checks of scope-create and +// api-key-create (name rules, max_scopes, max_keys, write_scopes ⊆ +// allowed ∪ {home}), at most 64 scopes and 64 keys per call, each key its own +// principal; replace_label deactivates the active keys of the same label in +// the same transaction. Written in S1, where the action does not exist; the +// second build tag keeps the file out of every gate until C-3 lands. To +// enable, shorten the constraint line to `//go:build integration`. The +// required keys need C-2 (integration order C-1, C-2, C-4, C-3). +// +// Wire form fixed by these tests (S1 contract, design §3.5 plus the lead's +// reading where the design is silent): +// +// request: {"action":"keyset-provision","data":{"scopes":[<name>…], +// "keys":[{"label","home_scope","allowed_scopes","write_scopes", +// "scope_narrowing","replace_label"}…]}} +// names in "scopes" are bare scope names (scope-create's rule); +// a key's scopes are bare names (the tenant's "<slug>:" is put in +// front) or full scope names, which must be the tenant's own (403). +// answer: {"success":true,"scopes":[{"scope":"<slug>:<name>","created":bool}…], +// "keys":[{"id","label","home_scope","allowed_scopes","write_scopes", +// "scope_narrowing","api_key"}…]} — both in request order, the +// plaintext (api_key) only here. +// +// Every refusal test ends with a valid call of the same caller (its control): +// on a tree without the action the refusals would pass for the wrong reason +// (an unknown action is a 400 that creates nothing too). +// +// go test -tags=integration,s1red_c3 -p 1 -count=1 -run '^TestC3' ./cmd/ctxd/ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/blocktype" + "github.com/GottZ/ctx/internal/config" + "github.com/GottZ/ctx/internal/dispatch" + "github.com/GottZ/ctx/internal/events" + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" +) + +// c3AdminKey is the bootstrap server-admin key (default tenant, owner). +const c3AdminKey = "c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0" + +type c3Resp struct { + status int + body map[string]any + raw string +} + +// c3World: tenant c3t with its owner key; the server-admin key. +type c3World struct { + pool *pgxpool.Pool + router http.Handler + owner string // owner key of c3t + tenantID string // id of c3t +} + +func c3Setup(t *testing.T) *c3World { + t.Helper() + pool := testdb.SetupTestDB(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + applyEnv(t, map[string]string{}) + cc, issues := loadFromEnv() + if config.HasErrors(issues) { + t.Fatalf("env fixture invalid: %v", issues) + } + cfgStore := config.NewStore(cc) + backendPool := backends.NewPool(pool, nil) + scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) + projectHub := events.NewProjectHub(ctx, pool, cfgStore) + d := dispatch.New(nil, dispatch.DefaultSettings()) + t.Cleanup(d.Close) + scheduler.SetDispatcher(d) + if created, _, err := store.BootstrapAdminKey(ctx, pool, c3AdminKey, "c3-admin"); err != nil || !created { + t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) + } + w := &c3World{pool: pool, router: NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d)} + r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3t", "display_name": "C3"}}).must(t, "tenant-create") + w.owner, _ = r.body["owner_key"].(string) + tn, _ := r.body["tenant"].(map[string]any) + w.tenantID, _ = tn["id"].(string) + if w.owner == "" || w.tenantID == "" { + t.Fatalf("fixture tenant-create: %s", r.raw) + } + return w +} + +func (w *c3World) do(t *testing.T, method, path, key string, body any) c3Resp { + t.Helper() + var rd io.Reader = http.NoBody + if body != nil { + b, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + rd = bytes.NewReader(b) + } + req := httptest.NewRequest(method, path, rd) + req.Header.Set("X-Context-Key", key) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + rec := httptest.NewRecorder() + w.router.ServeHTTP(rec, req) + var out map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &out) + return c3Resp{status: rec.Code, body: out, raw: rec.Body.String()} +} + +func (w *c3World) manage(t *testing.T, key string, body map[string]any) c3Resp { + t.Helper() + return w.do(t, http.MethodPost, "/api/manage", key, body) +} + +func (r c3Resp) must(t *testing.T, what string) c3Resp { + t.Helper() + if r.status != http.StatusOK || r.body["success"] != true { + t.Fatalf("%s: HTTP %d %s", what, r.status, r.raw) + } + return r +} + +// provision posts one keyset-provision as key. +func (w *c3World) provision(t *testing.T, key string, scopes []string, keys ...map[string]any) c3Resp { + t.Helper() + if scopes == nil { + scopes = []string{} + } + return w.manage(t, key, map[string]any{"action": "keyset-provision", "data": map[string]any{"scopes": scopes, "keys": keys}}) +} + +// c3Key is one key spec. +func c3Key(label, home string, allowed, write []string, narrowing string) map[string]any { + if allowed == nil { + allowed = []string{} + } + if write == nil { + write = []string{} + } + return map[string]any{"label": label, "home_scope": home, "allowed_scopes": allowed, "write_scopes": write, "scope_narrowing": narrowing} +} + +// state is the tenant's scopes and active key labels, sorted. +func (w *c3World) state(t *testing.T) (scopes, labels []string) { + t.Helper() + ctx := context.Background() + rows, err := w.pool.Query(ctx, `SELECT scope FROM context_tenant_scopes WHERE tenant_id = $1::uuid ORDER BY scope`, w.tenantID) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var s string + if err := rows.Scan(&s); err != nil { + t.Fatal(err) + } + scopes = append(scopes, s) + } + rows.Close() + rows, err = w.pool.Query(ctx, `SELECT label FROM context_api_keys WHERE tenant_id = $1::uuid AND active ORDER BY label`, w.tenantID) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var s string + if err := rows.Scan(&s); err != nil { + t.Fatal(err) + } + labels = append(labels, s) + } + rows.Close() + return scopes, labels +} + +// wantUnchanged fails unless the tenant's scopes and active keys are exactly +// the ones before. +func (w *c3World) wantUnchanged(t *testing.T, what string, scopes, labels []string) { + t.Helper() + s, l := w.state(t) + if !slices.Equal(s, scopes) || !slices.Equal(l, labels) { + t.Errorf("%s: scopes %v keys %v, want unchanged %v %v (nothing created)", what, s, l, scopes, labels) + } +} + +// keysOf reads the answer's keys: label → (id, plaintext). +func c3KeysOf(r c3Resp) (labels []string, ids, plains map[string]string) { + ids, plains = map[string]string{}, map[string]string{} + list, _ := r.body["keys"].([]any) + for _, e := range list { + m, _ := e.(map[string]any) + l, _ := m["label"].(string) + labels = append(labels, l) + ids[l], _ = m["id"].(string) + plains[l], _ = m["api_key"].(string) + } + return labels, ids, plains +} + +func (w *c3World) whoami(t *testing.T, key string) map[string]any { + t.Helper() + r := w.do(t, http.MethodGet, "/api/whoami", key, nil) + if r.status != http.StatusOK { + t.Fatalf("whoami: HTTP %d %s", r.status, r.raw) + } + return r.body +} + +// TestC3KeysetProvisionCreatesScopesAndKeys: missing scopes are created, an +// existing own scope is reused, the keys carry label, scopes and +// scope_narrowing as asked, and their plaintexts appear in this answer only. +func TestC3KeysetProvisionCreatesScopesAndKeys(t *testing.T) { + w := c3Setup(t) + w.manage(t, w.owner, map[string]any{"action": "scope-create", "data": map[string]any{"name": "k"}}).must(t, "scope-create k") + + r := w.provision(t, w.owner, []string{"k", "members", "mods"}, + c3Key("hermes:discord:111:members", "members", []string{"k"}, nil, "required"), + c3Key("hermes:discord:111:mods", "mods", []string{"k", "members"}, nil, "required")) + r.must(t, "keyset-provision") + + sc, _ := r.body["scopes"].([]any) + var got []string + for _, e := range sc { + m, _ := e.(map[string]any) + got = append(got, fmt.Sprintf("%v=%v", m["scope"], m["created"])) + } + if want := []string{"c3t:k=false", "c3t:members=true", "c3t:mods=true"}; !slices.Equal(got, want) { + t.Errorf("answer scopes %v, want %v (in request order, k reused)", got, want) + } + scopes, _ := w.state(t) + if want := []string{"c3t:k", "c3t:main", "c3t:members", "c3t:mods"}; !slices.Equal(scopes, want) { + t.Errorf("tenant scopes %v, want %v", scopes, want) + } + + labels, ids, plains := c3KeysOf(r) + if want := []string{"hermes:discord:111:members", "hermes:discord:111:mods"}; !slices.Equal(labels, want) { + t.Fatalf("answer keys %v, want %v in request order", labels, want) + } + for l, wantHome := range map[string]string{"hermes:discord:111:members": "c3t:members", "hermes:discord:111:mods": "c3t:mods"} { + if plains[l] == "" || ids[l] == "" { + t.Errorf("%s: no id or plaintext in the answer", l) + continue + } + b := w.whoami(t, plains[l]) + if b["label"] != l || b["home_scope"] != wantHome || b["scope_narrowing"] != "required" || b["role"] != "member" || b["admin"] != false || b["api_key_id"] != ids[l] { + t.Errorf("%s: whoami label %v home %v scope_narrowing %v role %v admin %v id %v, want %s %s required member false %s", + l, b["label"], b["home_scope"], b["scope_narrowing"], b["role"], b["admin"], b["api_key_id"], l, wantHome, ids[l]) + } + } + b := w.whoami(t, plains["hermes:discord:111:mods"]) + rs, _ := b["read_scopes"].([]any) + if fmt.Sprint(rs) != "[c3t:mods c3t:k c3t:members]" { + t.Errorf("mods key reads %v, want [c3t:mods c3t:k c3t:members]", rs) + } + + // The plaintexts are in no later answer. + list := w.manage(t, w.owner, map[string]any{"action": "api-key-list"}).must(t, "api-key-list") + for l, p := range plains { + if strings.Contains(list.raw, p) { + t.Errorf("api-key-list carries the plaintext of %s", l) + } + } +} + +// TestC3QuotaRefusesTheWholeSet: a set that would pass max_scopes after its +// second new scope, or max_keys, is a 429 and creates nothing — not the +// scopes before the limit, not a key. +func TestC3QuotaRefusesTheWholeSet(t *testing.T) { + w := c3Setup(t) + w.manage(t, c3AdminKey, map[string]any{"action": "tenant-limit-set", "id": w.tenantID, "data": map[string]any{"max_scopes": 3, "max_keys": 3}}).must(t, "tenant-limit-set") + scopes, labels := w.state(t) + + r := w.provision(t, w.owner, []string{"a", "b", "c"}, c3Key("c3-q", "a", nil, nil, "required")) + if r.status != http.StatusTooManyRequests { + t.Errorf("third new scope over max_scopes 3 (main counts): HTTP %d %s, want 429", r.status, r.raw) + } + if r.body["limit"] != float64(3) || r.body["count"] == nil { + t.Errorf("the 429 names limit %v and count %v, want the limit 3 and the tenant's count", r.body["limit"], r.body["count"]) + } + w.wantUnchanged(t, "after the scope refusal", scopes, labels) + + r = w.provision(t, w.owner, []string{"a"}, c3Key("c3-q1", "a", nil, nil, "required"), c3Key("c3-q2", "a", nil, nil, "required"), c3Key("c3-q3", "a", nil, nil, "required")) + if r.status != http.StatusTooManyRequests { + t.Errorf("three keys over max_keys 3 (the owner key counts): HTTP %d %s, want 429", r.status, r.raw) + } + w.wantUnchanged(t, "after the key refusal", scopes, labels) + + w.provision(t, w.owner, []string{"a", "b"}, c3Key("c3-q1", "a", nil, nil, "required"), c3Key("c3-q2", "b", nil, nil, "required")).must(t, "control: within both limits") +} + +// TestC3MemberIsRefused: keyset-provision is a tenant-admin action. +func TestC3MemberIsRefused(t *testing.T) { + w := c3Setup(t) + r := w.manage(t, w.owner, map[string]any{"action": "api-key-create", "data": map[string]any{"label": "c3-member", "home_scope": "c3t:main"}}).must(t, "member key") + member, _ := r.body["api_key"].(string) + scopes, labels := w.state(t) + if r := w.provision(t, member, []string{"members"}, c3Key("c3-by-member", "members", nil, nil, "required")); r.status != http.StatusForbidden { + t.Errorf("member: HTTP %d %s, want 403", r.status, r.raw) + } + w.wantUnchanged(t, "after the member's call", scopes, labels) + w.provision(t, w.owner, []string{"members"}, c3Key("c3-by-owner", "members", nil, nil, "required")).must(t, "control: the owner") +} + +// TestC3ForeignScopeIsRefused: a key that names another tenant's scope is a +// 403, and nothing of the set is created. +func TestC3ForeignScopeIsRefused(t *testing.T) { + w := c3Setup(t) + r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3u", "display_name": "C3 other"}}).must(t, "second tenant") + foreign, _ := r.body["scope"].(string) + scopes, labels := w.state(t) + for _, k := range []map[string]any{ + c3Key("c3-foreign-read", "members", []string{foreign}, nil, "required"), + c3Key("c3-foreign-home", foreign, nil, nil, "required"), + } { + if r := w.provision(t, w.owner, []string{"members"}, k); r.status != http.StatusForbidden { + t.Errorf("%s: HTTP %d %s, want 403", k["label"], r.status, r.raw) + } + w.wantUnchanged(t, fmt.Sprint(k["label"]), scopes, labels) + } + w.provision(t, w.owner, []string{"members"}, c3Key("c3-own", "members", []string{"c3t:main"}, nil, "required")).must(t, "control: own scopes, bare and full") +} + +// TestC3WriteScopesOutsideTheReadSetAreRefused: write_scopes ⊄ allowed ∪ +// {home} is a 400, and nothing is created. +func TestC3WriteScopesOutsideTheReadSetAreRefused(t *testing.T) { + w := c3Setup(t) + scopes, labels := w.state(t) + r := w.provision(t, w.owner, []string{"k", "members", "mods"}, + c3Key("c3-ok", "members", []string{"k"}, nil, "required"), + c3Key("c3-blind", "members", []string{"k"}, []string{"mods"}, "required")) + if e, _ := r.body["error"].(string); r.status != http.StatusBadRequest || !strings.Contains(e, "write_scope") { + t.Errorf("write scope outside the read set: HTTP %d %s, want 400 naming the write_scope", r.status, r.raw) + } + w.wantUnchanged(t, "after the refusal", scopes, labels) + w.provision(t, w.owner, []string{"k", "members"}, c3Key("c3-ok", "members", []string{"k"}, []string{"k"}, "required")).must(t, "control: write scope inside the read set") +} + +// TestC3SizeOfASetIsCapped: 65 keys or 65 scopes in one call are a 400 before +// anything is created, also when the tenant's limits would allow them; 64 +// keys pass. +func TestC3SizeOfASetIsCapped(t *testing.T) { + w := c3Setup(t) + w.manage(t, c3AdminKey, map[string]any{"action": "tenant-limit-set", "id": w.tenantID, "data": map[string]any{"max_scopes": 1000, "max_keys": 1000}}).must(t, "tenant-limit-set") + scopes, labels := w.state(t) + keys := func(n int) []map[string]any { + out := make([]map[string]any, n) + for i := range out { + out[i] = c3Key(fmt.Sprintf("c3-many-%02d", i), "many", nil, nil, "required") + } + return out + } + if r := w.provision(t, w.owner, []string{"many"}, keys(65)...); r.status != http.StatusBadRequest || !strings.Contains(r.raw, "64") { + t.Errorf("65 keys: HTTP %d %s, want 400 naming the cap 64", r.status, r.raw) + } + w.wantUnchanged(t, "after 65 keys", scopes, labels) + names := make([]string, 65) + for i := range names { + names[i] = fmt.Sprintf("s%02d", i) + } + if r := w.provision(t, w.owner, names, c3Key("c3-many-scopes", "s00", nil, nil, "required")); r.status != http.StatusBadRequest || !strings.Contains(r.raw, "64") { + t.Errorf("65 scopes: HTTP %d %s, want 400 naming the cap 64", r.status, r.raw) + } + w.wantUnchanged(t, "after 65 scopes", scopes, labels) + r := w.provision(t, w.owner, []string{"many"}, keys(64)...).must(t, "control: 64 keys") + if l, _, _ := c3KeysOf(r); len(l) != 64 { + t.Errorf("64 keys asked, %d answered", len(l)) + } +} + +// TestC3ReplaceLabelDeactivatesThePreviousKey: replace_label deactivates the +// active keys of the tenant with the same label, in the same call, so a +// repeated provision leaves one active key per label. +func TestC3ReplaceLabelDeactivatesThePreviousKey(t *testing.T) { + w := c3Setup(t) + const label = "hermes:discord:222:members" + + // The same label in another tenant: labels are predictable, so the + // replacement must stay inside the caller's tenant. + r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3v", "display_name": "C3 same label"}}).must(t, "second tenant") + otherOwner, _ := r.body["owner_key"].(string) + r = w.provision(t, otherOwner, []string{"members"}, c3Key(label, "members", nil, nil, "required")).must(t, "the other tenant's key") + _, _, other := c3KeysOf(r) + + r = w.provision(t, w.owner, []string{"members"}, c3Key(label, "members", nil, nil, "required")).must(t, "first provision") + _, _, first := c3KeysOf(r) + // At the key limit (owner key and the first key): the replacement does not + // count the key it deactivates. + w.manage(t, c3AdminKey, map[string]any{"action": "tenant-limit-set", "id": w.tenantID, "data": map[string]any{"max_scopes": 25, "max_keys": 2}}).must(t, "tenant-limit-set") + k := c3Key(label, "members", nil, nil, "required") + k["replace_label"] = true + r = w.provision(t, w.owner, []string{"members"}, k).must(t, "second provision with replace_label, at max_keys") + _, _, second := c3KeysOf(r) + if s := w.do(t, http.MethodGet, "/api/whoami", first[label], nil); s.status != http.StatusUnauthorized { + t.Errorf("the replaced key still authenticates: HTTP %d", s.status) + } + if s := w.do(t, http.MethodGet, "/api/whoami", second[label], nil); s.status != http.StatusOK { + t.Errorf("the new key does not authenticate: HTTP %d %s", s.status, s.raw) + } + if s := w.do(t, http.MethodGet, "/api/whoami", other[label], nil); s.status != http.StatusOK { + t.Errorf("the other tenant's key with the same label was deactivated: HTTP %d %s", s.status, s.raw) + } + var n int + if err := w.pool.QueryRow(context.Background(), `SELECT count(*) FROM context_api_keys WHERE label = $1 AND active AND tenant_id = $2::uuid`, label, w.tenantID).Scan(&n); err != nil || n != 1 { + t.Errorf("%d active key(s) with the label in the tenant (err %v), want 1", n, err) + } +} + +// TestC3TenantIDIsServerAdminOnly: like api-key-create, only a server-admin +// may name tenant_id; a tenant-admin naming another tenant is a 403 and +// nothing is created in either tenant. +func TestC3TenantIDIsServerAdminOnly(t *testing.T) { + w := c3Setup(t) + r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3w", "display_name": "C3 target"}}).must(t, "target tenant") + tn, _ := r.body["tenant"].(map[string]any) + target, _ := tn["id"].(string) + scopes, labels := w.state(t) + data := map[string]any{"tenant_id": target, "scopes": []string{"members"}, "keys": []map[string]any{c3Key("c3-cross", "members", nil, nil, "required")}} + + r = w.manage(t, w.owner, map[string]any{"action": "keyset-provision", "data": data}) + if r.status != http.StatusForbidden { + t.Errorf("tenant-admin naming another tenant: HTTP %d %s, want 403", r.status, r.raw) + } + w.wantUnchanged(t, "the caller's tenant", scopes, labels) + var n int + if err := w.pool.QueryRow(context.Background(), `SELECT (SELECT count(*) FROM context_api_keys WHERE label = 'c3-cross') + (SELECT count(*) FROM context_tenant_scopes WHERE scope = 'c3w:members')`).Scan(&n); err != nil || n != 0 { + t.Errorf("the refused call created %d key(s) or scope(s) (err %v)", n, err) + } + + r = w.manage(t, c3AdminKey, map[string]any{"action": "keyset-provision", "data": data}).must(t, "server-admin naming the tenant") + _, _, plains := c3KeysOf(r) + if b := w.whoami(t, plains["c3-cross"]); b["tenant_slug"] != "c3w" || b["home_scope"] != "c3w:members" { + t.Errorf("server-admin provision: key in tenant %v home %v, want c3w c3w:members", b["tenant_slug"], b["home_scope"]) + } + w.wantUnchanged(t, "the caller's tenant after the server-admin call", scopes, labels) +} + +// TestC3EveryKeyIsItsOwnPrincipal (BP-26): the keys of one set never share a +// principal — signed in with one of them, /api/session/keys lists that one +// key and no other, so a leaked key cannot select its way to the others. +func TestC3EveryKeyIsItsOwnPrincipal(t *testing.T) { + w := c3Setup(t) + r := w.provision(t, w.owner, []string{"a", "b"}, + c3Key("c3-p-a", "a", nil, nil, "optional"), + c3Key("c3-p-b", "b", nil, nil, "optional"), + c3Key("c3-p-c", "b", []string{"a"}, nil, "required")).must(t, "keyset-provision") + _, ids, plains := c3KeysOf(r) + principals := map[string]string{} + for l, p := range plains { + b := w.whoami(t, p) + pid, _ := b["principal_id"].(string) + if pid == "" { + t.Errorf("%s: no principal_id", l) + } + if other, dup := principals[pid]; dup { + t.Errorf("%s and %s share the principal %s", l, other, pid) + } + principals[pid] = l + } + if ob := w.whoami(t, w.owner); principals[fmt.Sprint(ob["principal_id"])] != "" { + t.Errorf("a provisioned key shares the owner's principal") + } + for _, l := range []string{"c3-p-a", "c3-p-b"} { + s := w.do(t, http.MethodGet, "/api/session/keys", plains[l], nil) + if s.status != http.StatusOK { + t.Errorf("%s: session keys: HTTP %d %s", l, s.status, s.raw) + continue + } + list, _ := s.body["keys"].([]any) + if len(list) != 1 { + t.Errorf("%s: /api/session/keys lists %d key(s), want exactly its own (%s)", l, len(list), s.raw) + continue + } + if m, _ := list[0].(map[string]any); m["api_key_id"] != ids[l] { + t.Errorf("%s: /api/session/keys lists %v, want %s", l, m["api_key_id"], ids[l]) + } + } +} diff --git a/go/cmd/ctxd/manage_get_ids_c4_integration_test.go b/go/cmd/ctxd/manage_get_ids_c4_integration_test.go new file mode 100644 index 000000000..22384951f --- /dev/null +++ b/go/cmd/ctxd/manage_get_ids_c4_integration_test.go @@ -0,0 +1,261 @@ +//go:build integration && s1red_c4 + +// Achse 02, cluster C-4 (design2/02-ctx-checkpoint.md §3.5 C-4, §7.3): +// POST /api/manage {"action":"get","ids":[…]} with 1 to 16 ids answers the +// blocks in request order, each id through the resolution of today's get +// (store.ResolveBlockID over the read scopes and the block grants); an id +// that resolves to no visible block is an entry with a code, never a failure +// of the whole request. "id" alone stays as it is. Written in S1, where "ids" +// is ignored; the second build tag keeps the file out of every gate until C-4 +// lands. To enable, shorten the constraint line to `//go:build integration`. +// The narrowed cases need C-1 as well (integration order C-1, C-2, C-4). +// +// Wire form fixed by these tests (S1 contract; the reading of the plugin fake +// tests/fakes/ctx_server.py where the design is silent): +// +// {"success":true,"blocks":[ +// {…the block a single get answers under "block"…}, +// {"id":"<as asked>","code":"not_found","error":"…"}, …]} +// +// one entry per asked id, in request order; an entry with "code" is a miss. +// An id the caller may not see answers exactly like an id that does not exist +// (no existence oracle). +// +// go test -tags=integration,s1red_c4 -p 1 -count=1 -run '^TestC4' ./cmd/ctxd/ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/blocktype" + "github.com/GottZ/ctx/internal/config" + "github.com/GottZ/ctx/internal/dispatch" + "github.com/GottZ/ctx/internal/events" + "github.com/GottZ/ctx/internal/handler" + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" +) + +// c4AdminKey is the bootstrap server-admin key (default tenant, owner). +const c4AdminKey = "c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0" + +// c4Missing is a well-formed id no block has. +const c4Missing = "00000000-0000-7000-8000-00000000c4c4" + +type c4Resp struct { + status int + body map[string]any + header http.Header + raw string +} + +// c4World: default tenant with scope default:k; key w (home work, allowed +// shared and default:k); blocks in private (granted to the default tenant as +// a single block), private (not granted), shared, work (two), default:k. +type c4World struct { + router http.Handler + w string + blocks map[string]string +} + +func (c *c4World) do(t *testing.T, key string, extra http.Header, body any) c4Resp { + t.Helper() + return c.req(t, http.MethodPost, "/api/manage", key, extra, body) +} + +func (c *c4World) req(t *testing.T, method, path, key string, extra http.Header, body any) c4Resp { + t.Helper() + var rd io.Reader = http.NoBody + if body != nil { + b, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + rd = bytes.NewReader(b) + } + req := httptest.NewRequest(method, path, rd) + req.Header.Set("X-Context-Key", key) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + for k, vs := range extra { + for _, v := range vs { + req.Header.Add(k, v) + } + } + rec := httptest.NewRecorder() + c.router.ServeHTTP(rec, req) + var out map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &out) + return c4Resp{status: rec.Code, body: out, header: rec.Header(), raw: rec.Body.String()} +} + +func (r c4Resp) must(t *testing.T, what string) c4Resp { + t.Helper() + if r.status != http.StatusOK || r.body["success"] != true { + t.Fatalf("%s: HTTP %d %s", what, r.status, r.raw) + } + return r +} + +func c4Setup(t *testing.T) *c4World { + t.Helper() + pool := testdb.SetupTestDB(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + applyEnv(t, map[string]string{}) + cc, issues := loadFromEnv() + if config.HasErrors(issues) { + t.Fatalf("env fixture invalid: %v", issues) + } + cfgStore := config.NewStore(cc) + backendPool := backends.NewPool(pool, nil) + scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) + projectHub := events.NewProjectHub(ctx, pool, cfgStore) + d := dispatch.New(nil, dispatch.DefaultSettings()) + t.Cleanup(d.Close) + scheduler.SetDispatcher(d) + if created, _, err := store.BootstrapAdminKey(ctx, pool, c4AdminKey, "c4-admin"); err != nil || !created { + t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) + } + c := &c4World{router: NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d), blocks: map[string]string{}} + + c.do(t, c4AdminKey, nil, map[string]any{"action": "scope-create", "data": map[string]any{"name": "k"}}).must(t, "scope-create k") + mint := func(data map[string]any) string { + r := c.do(t, c4AdminKey, nil, map[string]any{"action": "api-key-create", "data": data}).must(t, "api-key-create") + k, _ := r.body["api_key"].(string) + return k + } + c.w = mint(map[string]any{"label": "c4-w", "home_scope": "work", "allowed_scopes": []string{"shared", "default:k"}}) + kw := mint(map[string]any{"label": "c4-kw", "home_scope": "default:k"}) + put := func(name, key, scope string) { + body := map[string]any{"category": "learnings", "title": "c4 " + name, "content": "c4 " + name + " content"} + if scope != "" { + body["scope"] = scope + } + r := c.req(t, http.MethodPost, "/api/store", key, nil, body).must(t, "store "+name) + blk, _ := r.body["block"].(map[string]any) + c.blocks[name], _ = blk["id"].(string) + } + put("granted", c4AdminKey, "") + put("private", c4AdminKey, "") + put("shared", c4AdminKey, "shared") + put("work1", c.w, "") + put("work2", c.w, "") + put("k", kw, "") + c.do(t, c4AdminKey, nil, map[string]any{"action": "block-grant-create", + "data": map[string]any{"block_id": c.blocks["granted"], "grantee_tenant": store.DefaultTenantID}}).must(t, "block-grant-create") + return c +} + +// c4Entry is one entry of a multi-get answer: its "id" (the block's id when +// found, the asked id when missed) and its code ("" when found). +type c4Entry struct{ id, code, err string } + +func c4Entries(t *testing.T, r c4Resp) []c4Entry { + t.Helper() + list, ok := r.body["blocks"].([]any) + if !ok { + t.Errorf("answer has no blocks list: HTTP %d %s", r.status, r.raw) + return nil + } + out := make([]c4Entry, 0, len(list)) + for _, e := range list { + m, _ := e.(map[string]any) + var en c4Entry + en.id, _ = m["id"].(string) + en.code, _ = m["code"].(string) + en.err, _ = m["error"].(string) + out = append(out, en) + } + return out +} + +// wantEntries checks the answer entry by entry: name "" means "not found". +func (c *c4World) wantEntries(t *testing.T, what string, r c4Resp, asked []string, found []string) { + t.Helper() + if r.status != http.StatusOK || r.body["success"] != true { + t.Errorf("%s: HTTP %d %s, want 200 success", what, r.status, r.raw) + return + } + got := c4Entries(t, r) + if len(got) != len(asked) { + t.Errorf("%s: %d entries, want %d (one per id, in order)", what, len(got), len(asked)) + return + } + for i, e := range got { + switch want := found[i]; { + case want == "" && (e.id != asked[i] || e.code != "not_found"): + t.Errorf("%s: entry %d (%s): id %q code %q, want a not_found entry for the asked id", what, i, asked[i], e.id, e.code) + case want != "" && (e.id != c.blocks[want] || e.code != ""): + t.Errorf("%s: entry %d: id %q code %q, want block %s (%s), request order", what, i, e.id, e.code, want, c.blocks[want]) + } + } +} + +// TestC4GetIdsAnswersInOrder: found blocks and misses in the order asked; an +// id the key may not read answers like one that does not exist; a block read +// through a block grant is found unnarrowed. +func TestC4GetIdsAnswersInOrder(t *testing.T) { + c := c4Setup(t) + asked := []string{c.blocks["work2"], c.blocks["shared"], c4Missing, c.blocks["work1"], c.blocks["private"], c.blocks["k"], c.blocks["granted"]} + r := c.do(t, c.w, nil, map[string]any{"action": "get", "ids": asked}) + c.wantEntries(t, "seven ids", r, asked, []string{"work2", "shared", "", "work1", "", "k", "granted"}) + // No existence oracle: the miss of a block the key may not read and the + // miss of an id no block has differ in nothing but the id. + if e := c4Entries(t, r); len(e) == len(asked) && (e[2].code != e[4].code || e[2].err != e[4].err || e[2].err == "") { + t.Errorf("the invisible block's entry %+v differs from the missing id's %+v", e[4], e[2]) + } + // "id" alone is unchanged: one block under "block". + one := c.do(t, c.w, nil, map[string]any{"action": "get", "id": c.blocks["work1"]}).must(t, "single get") + if b, _ := one.body["block"].(map[string]any); b["id"] != c.blocks["work1"] { + t.Errorf("single get answers %v", one.raw) + } +} + +// TestC4GetIdsCountIsCapped: 17 ids are a 400; 16 are answered (control). +func TestC4GetIdsCountIsCapped(t *testing.T) { + c := c4Setup(t) + ids := func(n int) []string { + out := make([]string, n) + for i := range out { + out[i] = fmt.Sprintf("00000000-0000-7000-8000-%012d", i) + } + out[0] = c.blocks["work1"] + return out + } + if r := c.do(t, c.w, nil, map[string]any{"action": "get", "ids": ids(17)}); r.status != http.StatusBadRequest || !strings.Contains(r.raw, "16") { + t.Errorf("17 ids: HTTP %d %s, want 400 naming the cap 16", r.status, r.raw) + } + r := c.do(t, c.w, nil, map[string]any{"action": "get", "ids": ids(16)}) + want := make([]string, 16) + want[0] = "work1" + c.wantEntries(t, "16 ids", r, ids(16), want) +} + +// TestC4NarrowedGetIdsReadsOnlyTheNamedScopes: under a narrowing the multi-get +// finds blocks of the named scopes only; a block-grant block is not found. +func TestC4NarrowedGetIdsReadsOnlyTheNamedScopes(t *testing.T) { + c := c4Setup(t) + h := http.Header{} + h.Set(handler.HeaderReadScopes, "work") + asked := []string{c.blocks["work1"], c.blocks["shared"], c.blocks["k"], c.blocks["granted"]} + r := c.do(t, c.w, h, map[string]any{"action": "get", "ids": asked}) + c.wantEntries(t, "narrowed to work", r, asked, []string{"work1", "", "", ""}) + if got := r.header.Get(handler.HeaderNarrowed); got != "work;" { + t.Errorf("narrowed multi-get: echo %q, want \"work;\"", got) + } + + h.Set(handler.HeaderReadScopes, "work,shared,default:k") + r = c.do(t, c.w, h, map[string]any{"action": "get", "ids": asked}) + c.wantEntries(t, "narrowed to all own scopes", r, asked, []string{"work1", "shared", "k", ""}) +} diff --git a/go/cmd/ctxd/narrowing_c1_integration_test.go b/go/cmd/ctxd/narrowing_c1_integration_test.go new file mode 100644 index 000000000..2066593d8 --- /dev/null +++ b/go/cmd/ctxd/narrowing_c1_integration_test.go @@ -0,0 +1,806 @@ +//go:build integration && s1red_c1 + +// Achse 02, cluster C-1 (design2/02-ctx-checkpoint.md §3.5 C-1, §7.3): a +// request narrows its key's rights to the scopes it names — X-Context-Read- +// Scopes (1 to 8, in order) and X-Context-Write-Scope (one, inside the read +// set, writable for the key) — on a closed list of routes and /api/manage +// actions, echoed in X-Context-Narrowed. Written in S1 against the inert stubs +// of internal/handler/narrowing.go; the second build tag keeps the file out of +// every gate until C-1 lands. To enable, shorten the constraint line to +// `//go:build integration`. +// +// The tests drive the PRODUCTION router (NewRouter): the route rule sits in the +// Auth middleware and means something only against the mounts production +// serves. Every fixture goes through a write path — tenant-create, +// scope-create, api-key-create, /api/store, delete, tenant-grant-create, +// block-grant-create, PUT /api/settings — except confirm_writes, which has none +// and is set in SQL. TestC1Pin* are green on the stubs on purpose: they pin +// what a narrowing must leave alone (the mutant "HomeScope rewritten") and +// carry no red reason of their own. +// +// go test -tags=integration,s1red_c1 -p 1 -count=1 -run '^TestC1' ./cmd/ctxd/ +package main + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/blocktype" + "github.com/GottZ/ctx/internal/config" + "github.com/GottZ/ctx/internal/dispatch" + "github.com/GottZ/ctx/internal/events" + "github.com/GottZ/ctx/internal/handler" + "github.com/GottZ/ctx/internal/settings" + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" +) + +// c1AdminKey is the bootstrap server-admin key (default tenant, owner). +const c1AdminKey = "c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0" + +// c1Probe is the word every fixture block carries, so one search finds them all. +const c1Probe = "narrowprobe" + +// c1Resp is one answer of the router. +type c1Resp struct { + status int + body map[string]any + header http.Header + raw string +} + +// c1World is the fixture: the router, the keys and the blocks. +// +// Default tenant: scopes private, work, shared (baseline) plus default:k and +// default:m. Key w: home work, allowed shared and default:k (writable: work, +// shared; default:k read-only). Key x: home default:m, allowed and write +// default:k. Key kw: home default:k. Tenant c1two: owner key, home c1two:main, +// granted to the default tenant (a grant scope in every default key's read +// set). Block "private" is granted to the default tenant as a single block. +type c1World struct { + pool *pgxpool.Pool + router http.Handler + keys map[string]string + blocks map[string]string + two string // c1two:main, the grant scope +} + +// c1EmbedHost serves the embed and translate halves of an Ollama backend: one +// fixed vector per input. +func c1EmbedHost(t *testing.T) string { + t.Helper() + vec := make([]float64, 1024) + for i := range vec { + vec[i] = float64((i % 2) * 2) + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/api/embed": + var req struct { + Input any `json:"input"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + n := 1 + if in, ok := req.Input.([]any); ok { + n = len(in) + } + out := make([][]float64, n) + for i := range out { + out[i] = vec + } + _ = json.NewEncoder(w).Encode(map[string]any{"embeddings": out}) + case "/api/chat": + _, _ = io.Copy(io.Discard, r.Body) + _ = json.NewEncoder(w).Encode(map[string]any{ + "message": map[string]any{"role": "assistant", "content": c1Probe}, + "eval_count": 1, "prompt_eval_count": 1, + }) + default: + _, _ = io.Copy(io.Discard, r.Body) + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(srv.Close) + return srv.URL +} + +// c1Router builds the production router on a fresh database, with an embed +// backend, and the bootstrap admin key. +func c1Router(t *testing.T) (*pgxpool.Pool, http.Handler) { + t.Helper() + pool := testdb.SetupTestDB(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + applyEnv(t, map[string]string{}) + cc, issues := loadFromEnv() + if config.HasErrors(issues) { + t.Fatalf("env fixture invalid: %v", issues) + } + cfgStore := config.NewStore(cc) + // The tenant overlay, as the boot wires it (main.go): the settings a + // tenant-admin writes reach that tenant's requests. + cfgStore.SetOverlay(settings.TenantOverlay(pool)) + backendPool := backends.NewPool(pool, nil) + host := c1EmbedHost(t) + backendPool.SeedSnapshotForTest([]backends.Backend{ + {ID: "c1-embed", Name: "c1-embed", Scope: "_global", Host: host, Protocol: backends.ProtocolOllama, + Model: "test-embed", Trust: backends.TrustFull, Enabled: true, Priority: 1, Roles: []string{backends.RoleEmbed}}, + {ID: "c1-chat", Name: "c1-chat", Scope: "_global", Host: host, Protocol: backends.ProtocolOllama, + Model: "test-chat", Trust: backends.TrustFull, Enabled: true, Priority: 1, Roles: []string{backends.RoleTranslate}}, + }) + scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) + projectHub := events.NewProjectHub(ctx, pool, cfgStore) + d := dispatch.New(nil, dispatch.DefaultSettings()) + t.Cleanup(d.Close) + scheduler.SetDispatcher(d) + if created, _, err := store.BootstrapAdminKey(ctx, pool, c1AdminKey, "c1-admin"); err != nil || !created { + t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) + } + return pool, NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d) +} + +// c1Narrow is the header set of a narrowing: read scopes, optionally the +// write scope. +func c1Narrow(read string, write ...string) http.Header { + h := http.Header{} + h.Set(handler.HeaderReadScopes, read) + if len(write) > 0 { + h.Set(handler.HeaderWriteScope, write[0]) + } + return h +} + +// do sends one request with the raw key and the extra headers. +func (w *c1World) do(t *testing.T, method, path, key string, extra http.Header, body any) c1Resp { + t.Helper() + var rd io.Reader = http.NoBody + if body != nil { + b, ok := body.([]byte) + if !ok { + var err error + if b, err = json.Marshal(body); err != nil { + t.Fatal(err) + } + } + rd = bytes.NewReader(b) + } + req := httptest.NewRequest(method, path, rd) + req.Header.Set("X-Context-Key", key) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + for k, vs := range extra { + for _, v := range vs { + req.Header.Add(k, v) + } + } + rec := httptest.NewRecorder() + w.router.ServeHTTP(rec, req) + var out map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &out) + return c1Resp{status: rec.Code, body: out, header: rec.Header(), raw: rec.Body.String()} +} + +// manage posts one /api/manage body. +func (w *c1World) manage(t *testing.T, key string, extra http.Header, body map[string]any) c1Resp { + t.Helper() + return w.do(t, http.MethodPost, "/api/manage", key, extra, body) +} + +// must fails the test unless the answer is a 200. +func (r c1Resp) must(t *testing.T, what string) c1Resp { + t.Helper() + if r.status != http.StatusOK { + t.Fatalf("fixture %s: HTTP %d %s", what, r.status, r.raw) + } + return r +} + +// storeBlock writes one block through /api/store and returns its id. +func (w *c1World) storeBlock(t *testing.T, key, scope, title string) string { + t.Helper() + body := map[string]any{"category": "learnings", "title": title, "content": title + " " + c1Probe + " content"} + if scope != "" { + body["scope"] = scope + } + r := w.do(t, http.MethodPost, "/api/store", key, nil, body).must(t, "store "+title) + blk, _ := r.body["block"].(map[string]any) + id, _ := blk["id"].(string) + if id == "" { + t.Fatalf("fixture store %s: no block id in %s", title, r.raw) + } + return id +} + +// mintKey creates one key through api-key-create as the admin. +func (w *c1World) mintKey(t *testing.T, data map[string]any) string { + t.Helper() + r := w.manage(t, c1AdminKey, nil, map[string]any{"action": "api-key-create", "data": data}).must(t, "api-key-create") + k, _ := r.body["api_key"].(string) + if k == "" { + t.Fatalf("fixture api-key-create: no key in %s", r.raw) + } + return k +} + +func c1Setup(t *testing.T) *c1World { + t.Helper() + pool, router := c1Router(t) + w := &c1World{pool: pool, router: router, keys: map[string]string{}, blocks: map[string]string{}} + for _, n := range []string{"k", "m"} { + w.manage(t, c1AdminKey, nil, map[string]any{"action": "scope-create", "data": map[string]any{"name": n}}).must(t, "scope-create "+n) + } + w.keys["w"] = w.mintKey(t, map[string]any{"label": "c1-w", "home_scope": "work", "allowed_scopes": []string{"shared", "default:k"}}) + w.keys["x"] = w.mintKey(t, map[string]any{"label": "c1-x", "home_scope": "default:m", + "allowed_scopes": []string{"default:k"}, "write_scopes": []string{"default:k"}}) + w.keys["kw"] = w.mintKey(t, map[string]any{"label": "c1-kw", "home_scope": "default:k"}) + + w.blocks["private"] = w.storeBlock(t, c1AdminKey, "", "c1 private alpha") + w.blocks["shared"] = w.storeBlock(t, c1AdminKey, "shared", "c1 shared foxtrot") + w.blocks["work"] = w.storeBlock(t, w.keys["w"], "", "c1 work bravo") + w.blocks["k"] = w.storeBlock(t, w.keys["kw"], "", "c1 k charlie") + w.blocks["m"] = w.storeBlock(t, w.keys["x"], "", "c1 m golf") + + r := w.manage(t, c1AdminKey, nil, map[string]any{"action": "tenant-create", + "data": map[string]any{"slug": "c1two", "display_name": "C1 two"}}).must(t, "tenant-create") + w.keys["two"], _ = r.body["owner_key"].(string) + w.two, _ = r.body["scope"].(string) + if w.keys["two"] == "" || w.two == "" { + t.Fatalf("fixture tenant-create: %s", r.raw) + } + w.blocks["two"] = w.storeBlock(t, w.keys["two"], "", "c1 two delta") + w.blocks["twoArchived"] = w.storeBlock(t, w.keys["two"], "", "c1 two archived echo") + w.manage(t, w.keys["two"], nil, map[string]any{"action": "delete", "id": w.blocks["twoArchived"]}).must(t, "delete") + w.manage(t, c1AdminKey, nil, map[string]any{"action": "tenant-grant-create", + "data": map[string]any{"grantee_tenant": store.DefaultTenantID, "granted_scope": w.two}}).must(t, "tenant-grant-create") + w.manage(t, c1AdminKey, nil, map[string]any{"action": "block-grant-create", + "data": map[string]any{"block_id": w.blocks["private"], "grantee_tenant": store.DefaultTenantID}}).must(t, "block-grant-create") + return w +} + +// c1IDs reads the "id" of every element of the list under key. +func c1IDs(body map[string]any, key string) []string { + list, _ := body[key].([]any) + var ids []string + for _, e := range list { + m, _ := e.(map[string]any) + if id, _ := m["id"].(string); id != "" { + ids = append(ids, id) + } + } + return ids +} + +// names maps block ids back to their fixture names, for readable failures. +func (w *c1World) names(ids []string) []string { + out := make([]string, 0, len(ids)) + for _, id := range ids { + name := id + for n, b := range w.blocks { + if b == id { + name = n + } + } + out = append(out, name) + } + slices.Sort(out) + return out +} + +// code is the machine code of an answer. +func (r c1Resp) code() string { + c, _ := r.body["code"].(string) + return c +} + +// wantRefused fails unless the answer is status with code. +func c1WantRefused(t *testing.T, what string, r c1Resp, status int, code string) { + t.Helper() + if r.status != status || r.code() != code { + t.Errorf("%s: HTTP %d code %q, want %d %q (%s)", what, r.status, r.code(), status, code, strings.TrimSpace(r.raw)) + } +} + +// wantEcho fails unless the answer carries the narrowing echo want. +func c1WantEcho(t *testing.T, what string, r c1Resp, want string) { + t.Helper() + if got := r.header.Get(handler.HeaderNarrowed); got != want || len(r.header.Values(handler.HeaderNarrowed)) != 1 { + t.Errorf("%s: %s = %q (%d value(s)), want exactly %q", what, handler.HeaderNarrowed, got, len(r.header.Values(handler.HeaderNarrowed)), want) + } +} + +// TestC1NarrowedSearchReadsOnlyTheNamedScopes: a narrowed /api/search finds +// blocks of the named scopes and nothing else; the unnarrowed request of the +// same key finds the rest (fixture control). +func TestC1NarrowedSearchReadsOnlyTheNamedScopes(t *testing.T) { + w := c1Setup(t) + body := map[string]any{"query": c1Probe, "limit": 50} + all := w.do(t, http.MethodPost, "/api/search", w.keys["w"], nil, body).must(t, "unnarrowed search") + // private: through the block grant; two: through the tenant grant. + if got := w.names(c1IDs(all.body, "results")); !slices.Equal(got, []string{"k", "private", "shared", "two", "work"}) { + t.Fatalf("fixture: the unnarrowed search of key w finds %v, want [k private shared two work] (%s)", got, all.raw) + } + for _, c := range []struct { + read string + want []string + }{ + {"work", []string{"work"}}, + {"default:k", []string{"k"}}, + {w.two, []string{"two"}}, + {"shared,work", []string{"shared", "work"}}, + } { + r := w.do(t, http.MethodPost, "/api/search", w.keys["w"], c1Narrow(c.read), body) + if r.status != http.StatusOK { + t.Errorf("search narrowed to %s: HTTP %d %s", c.read, r.status, r.raw) + continue + } + if got := w.names(c1IDs(r.body, "results")); !slices.Equal(got, c.want) { + t.Errorf("search narrowed to %s finds %v, want %v", c.read, got, c.want) + } + c1WantEcho(t, "search narrowed to "+c.read, r, c.read+";") + } +} + +// TestC1NarrowedQueryReadsOnlyTheNamedScopes: the same for /api/query +// (synthesize off) — the red test the design names first. +func TestC1NarrowedQueryReadsOnlyTheNamedScopes(t *testing.T) { + w := c1Setup(t) + body := map[string]any{"query": c1Probe, "synthesize": false, "limit": 20} + all := w.do(t, http.MethodPost, "/api/query", w.keys["w"], nil, body).must(t, "unnarrowed query") + if got := w.names(c1IDs(all.body, "sources")); len(got) < 2 || !slices.Contains(got, "work") { + t.Fatalf("fixture: the unnarrowed query of key w finds %v, want work and at least one other scope's block (%s)", got, all.raw) + } + for _, c := range []struct { + read string + want []string + }{ + {"work", []string{"work"}}, + {"default:k", []string{"k"}}, + } { + r := w.do(t, http.MethodPost, "/api/query", w.keys["w"], c1Narrow(c.read), body) + if r.status != http.StatusOK { + t.Errorf("query narrowed to %s: HTTP %d %s", c.read, r.status, r.raw) + continue + } + if got := w.names(c1IDs(r.body, "sources")); !slices.Equal(got, c.want) { + t.Errorf("query narrowed to %s finds %v, want %v", c.read, got, c.want) + } + c1WantEcho(t, "query narrowed to "+c.read, r, c.read+";") + } +} + +// TestC1ScopeOutsideTheKeyIsDenied: a read scope the key cannot read is a +// 403 scope_denied, on every route — never a silently smaller read set. +func TestC1ScopeOutsideTheKeyIsDenied(t *testing.T) { + w := c1Setup(t) + h := c1Narrow("work,private") + c1WantRefused(t, "search", w.do(t, http.MethodPost, "/api/search", w.keys["w"], h, map[string]any{"query": c1Probe}), http.StatusForbidden, "scope_denied") + c1WantRefused(t, "query", w.do(t, http.MethodPost, "/api/query", w.keys["w"], h, map[string]any{"query": c1Probe, "synthesize": false}), http.StatusForbidden, "scope_denied") + c1WantRefused(t, "whoami", w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], h, nil), http.StatusForbidden, "scope_denied") +} + +// c1Count counts the blocks with this title, archived included. +func (w *c1World) c1Count(t *testing.T, title string) int { + t.Helper() + var n int + if err := w.pool.QueryRow(context.Background(), `SELECT count(*) FROM context_blocks WHERE title = $1`, title).Scan(&n); err != nil { + t.Fatal(err) + } + return n +} + +// TestC1NarrowedWriteNeedsItsWriteScope: a narrowed write without +// X-Context-Write-Scope writes nothing (403 scope_denied, the answer still +// carries the echo — the narrowing itself was valid). A write scope the key +// can only read, or one outside the read set, makes the narrowing itself +// invalid: 403 scope_denied on every route, whoami included. Nothing lands in +// any scope. +func TestC1NarrowedWriteNeedsItsWriteScope(t *testing.T) { + w := c1Setup(t) + for _, c := range []struct { + name string + h http.Header + scope string + badWrite bool // the write scope itself is refused (in the Auth middleware) + }{ + {"read header only", c1Narrow("work"), "", false}, + {"read header only, scope named in the body", c1Narrow("work"), "work", false}, + {"read-only scope as write scope", c1Narrow("work,default:k", "default:k"), "", true}, + {"write scope outside the read set", c1Narrow("work", "shared"), "", true}, + } { + title := "c1 refused write " + c.name + body := map[string]any{"category": "learnings", "title": title, "content": "x " + c1Probe} + if c.scope != "" { + body["scope"] = c.scope + } + r := w.do(t, http.MethodPost, "/api/store", w.keys["w"], c.h, body) + c1WantRefused(t, c.name, r, http.StatusForbidden, "scope_denied") + if n := w.c1Count(t, title); n != 0 { + t.Errorf("%s: %d block(s) written, want none", c.name, n) + } + if c.badWrite { + c1WantRefused(t, c.name+" (whoami)", w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], c.h, nil), http.StatusForbidden, "scope_denied") + } else { + c1WantEcho(t, c.name, r, "work;") + } + } +} + +// TestC1NarrowingHeaderFormIsChecked: X-Context-Write-Scope alone, an empty +// header, a header that occurs twice, an empty list element and more than +// eight read scopes are 400 scope_narrowing_invalid — before any handler runs. +func TestC1NarrowingHeaderFormIsChecked(t *testing.T) { + w := c1Setup(t) + writeOnly := http.Header{} + writeOnly.Set(handler.HeaderWriteScope, "work") + empty := http.Header{} + empty.Set(handler.HeaderReadScopes, "") + twiceRead := http.Header{} + twiceRead.Add(handler.HeaderReadScopes, "work") + twiceRead.Add(handler.HeaderReadScopes, "shared") + twiceWrite := c1Narrow("work") + twiceWrite.Add(handler.HeaderWriteScope, "work") + twiceWrite.Add(handler.HeaderWriteScope, "work") + emptyElement := c1Narrow("work,,shared") + for _, c := range []struct { + name string + h http.Header + }{ + {"write scope alone", writeOnly}, + {"empty read header", empty}, + {"read header twice", twiceRead}, + {"write header twice", twiceWrite}, + {"empty list element", emptyElement}, + } { + c1WantRefused(t, c.name+" (whoami)", w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], c.h, nil), http.StatusBadRequest, "scope_narrowing_invalid") + title := "c1 invalid header " + c.name + c1WantRefused(t, c.name+" (store)", w.do(t, http.MethodPost, "/api/store", w.keys["w"], c.h, + map[string]any{"category": "learnings", "title": title, "content": "x"}), http.StatusBadRequest, "scope_narrowing_invalid") + if n := w.c1Count(t, title); n != 0 { + t.Errorf("%s: %d block(s) written, want none", c.name, n) + } + } +} + +// TestC1ReadScopesAreCappedAtEight: eight distinct readable scopes narrow a +// request; a ninth is 400 scope_narrowing_invalid, also when the key reads all +// nine. +func TestC1ReadScopesAreCappedAtEight(t *testing.T) { + w := c1Setup(t) + for _, n := range []string{"n1", "n2", "n3"} { + w.manage(t, c1AdminKey, nil, map[string]any{"action": "scope-create", "data": map[string]any{"name": n}}).must(t, "scope-create "+n) + } + key := w.mintKey(t, map[string]any{"label": "c1-nine", "home_scope": "work", + "allowed_scopes": []string{"private", "shared", "default:k", "default:m", "default:n1", "default:n2", "default:n3"}}) + eight := "work,private,shared,default:k,default:m,default:n1,default:n2,default:n3" + r := w.do(t, http.MethodGet, "/api/whoami", key, nil, nil).must(t, "whoami of the nine-scope key") + if rs := c1Strings(r.body["read_scopes"]); len(rs) != 9 || !slices.Contains(rs, w.two) { + t.Fatalf("fixture: the key reads %v, want nine scopes with the grant scope %s", rs, w.two) + } + r = w.do(t, http.MethodGet, "/api/whoami", key, c1Narrow(eight), nil) + if r.status != http.StatusOK { + t.Errorf("eight read scopes: HTTP %d %s, want 200", r.status, r.raw) + } + c1WantEcho(t, "eight read scopes", r, eight+";") + c1WantRefused(t, "nine read scopes", w.do(t, http.MethodGet, "/api/whoami", key, c1Narrow(eight+","+w.two), nil), http.StatusBadRequest, "scope_narrowing_invalid") +} + +// TestC1NarrowedWriteLandsInItsWriteScope: a narrowed write without a scope in +// the body lands in X-Context-Write-Scope — here a write_scope of the key, +// not its home — and passes the write recheck of issue #555 +// (store.WithRequestKey carries the key's own scopes, and default:k is one of +// its write_scopes). The answer carries the echo. +func TestC1NarrowedWriteLandsInItsWriteScope(t *testing.T) { + w := c1Setup(t) + r := w.do(t, http.MethodPost, "/api/store", w.keys["x"], c1Narrow("default:k", "default:k"), + map[string]any{"category": "learnings", "title": "c1 narrowed write hotel", "content": "x " + c1Probe}) + if r.status != http.StatusOK { + t.Fatalf("narrowed write: HTTP %d %s", r.status, r.raw) + } + blk, _ := r.body["block"].(map[string]any) + if got, _ := blk["scope"].(string); got != "default:k" { + t.Errorf("narrowed write answered scope %q, want default:k (the write scope, not the home default:m)", got) + } + var scope string + if err := w.pool.QueryRow(context.Background(), `SELECT scope FROM context_blocks WHERE title = 'c1 narrowed write hotel' AND NOT is_archived`).Scan(&scope); err != nil { + t.Fatalf("narrowed write: row: %v", err) + } + if scope != "default:k" { + t.Errorf("narrowed write stored in %q, want default:k", scope) + } + c1WantEcho(t, "narrowed write", r, "default:k;default:k") + + // The home scope narrowed explicitly, named in the body as well. + r = w.do(t, http.MethodPost, "/api/store", w.keys["x"], c1Narrow("default:m", "default:m"), + map[string]any{"category": "learnings", "title": "c1 narrowed home write india", "content": "x", "scope": "default:m"}) + if r.status != http.StatusOK { + t.Fatalf("narrowed home write: HTTP %d %s", r.status, r.raw) + } + c1WantEcho(t, "narrowed home write", r, "default:m;default:m") +} + +// TestC1BlockGrantIsInvisibleWhenNarrowed: a block the key reads only through +// a block grant is found unnarrowed (fixture control) and not found under any +// narrowing — a narrowed request reads its named scopes and nothing else. +func TestC1BlockGrantIsInvisibleWhenNarrowed(t *testing.T) { + w := c1Setup(t) + get := map[string]any{"action": "get", "id": w.blocks["private"]} + if r := w.manage(t, w.keys["w"], nil, get).must(t, "unnarrowed get of the granted block"); r.body["success"] != true { + t.Fatalf("fixture: key w does not read the granted block unnarrowed: %s", r.raw) + } + r := w.manage(t, w.keys["w"], c1Narrow("work,shared,default:k"), get) + if r.status != http.StatusOK || r.body["success"] != false { + t.Errorf("narrowed get of the granted block: HTTP %d %s, want 200 with success false (not found)", r.status, r.raw) + } + c1WantEcho(t, "narrowed get of the granted block", r, "work,shared,default:k;") + s := w.do(t, http.MethodPost, "/api/search", w.keys["w"], c1Narrow("work,shared,default:k"), map[string]any{"query": "alpha"}) + if slices.Contains(c1IDs(s.body, "results"), w.blocks["private"]) || s.status != http.StatusOK { + t.Errorf("narrowed search: HTTP %d, finds the granted block: %s", s.status, s.raw) + } +} + +// TestC1RoutesOutsideTheListAreRefused: a narrowed request on any route but +// the five of the list is 403 scope_narrowing_route — decided in the Auth +// middleware, by method and path, before the route's handler runs. +func TestC1RoutesOutsideTheListAreRefused(t *testing.T) { + w := c1Setup(t) + h := c1Narrow("work") + mcp := c1Narrow("work") + mcp.Set("Accept", "application/json, text/event-stream") + for _, c := range []struct { + method, path string + body any + }{ + {http.MethodPost, "/mcp", map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}}, + {http.MethodPost, "/api/store/batch", map[string]any{"items": []any{map[string]any{"category": "learnings", "title": "c1 batch kilo", "content": "x"}}}}, + {http.MethodPost, "/api/blob/store", map[string]any{"file": "aGk=", "filename": "f.txt", "category": "files", "title": "c1 blob lima", "mime_type": "text/plain"}}, + {http.MethodPost, "/api/recent", map[string]any{}}, + {http.MethodGet, "/api/session/keys", nil}, + } { + hc := h + if c.path == "/mcp" { + hc = mcp + } + c1WantRefused(t, c.method+" "+c.path, w.do(t, c.method, c.path, w.keys["w"], hc, c.body), http.StatusForbidden, "scope_narrowing_route") + } + if n := w.c1Count(t, "c1 batch kilo"); n != 0 { + t.Errorf("narrowed batch wrote %d block(s)", n) + } +} + +// TestC1ManageActionsOutsideTheListAreRefused: on /api/manage a narrowed +// request runs get and type-list only; update and purge are 403 +// scope_narrowing_route and change nothing. BP-25: Go's decoder matches JSON +// keys case-insensitively and the LAST one wins, so {"action":"get", +// "ACTION":"purge"} decodes to purge — the check must judge that one decoded +// action (a check reading the lowercase key would see get). The other key +// order is left open: refusing it as well is safe. +func TestC1ManageActionsOutsideTheListAreRefused(t *testing.T) { + w := c1Setup(t) + + // The premise, on the decoder the dispatcher uses. + var probe struct { + Action string `json:"action"` + } + if err := json.NewDecoder(strings.NewReader(`{"action":"get","ACTION":"purge"}`)).Decode(&probe); err != nil || probe.Action != "purge" { + t.Fatalf("premise: the decoder reads %q (err %v), want purge — rewrite the BP-25 cases", probe.Action, err) + } + + hw := c1Narrow("work") + r := w.manage(t, w.keys["w"], hw, map[string]any{"action": "update", "id": w.blocks["work"], "data": map[string]any{"content": "c1 overwritten"}}) + c1WantRefused(t, "narrowed update", r, http.StatusForbidden, "scope_narrowing_route") + c1WantEcho(t, "narrowed update", r, "work;") + var content string + if err := w.pool.QueryRow(context.Background(), `SELECT content FROM context_blocks WHERE id = $1`, w.blocks["work"]).Scan(&content); err != nil || content == "c1 overwritten" { + t.Errorf("narrowed update changed the block: %q (err %v)", content, err) + } + + ha := c1Narrow("private") + r = w.manage(t, c1AdminKey, ha, map[string]any{"action": "purge"}) + c1WantRefused(t, "narrowed purge (owner key)", r, http.StatusForbidden, "scope_narrowing_route") + c1WantEcho(t, "narrowed purge", r, "private;") + c1WantRefused(t, "narrowed delete", w.manage(t, w.keys["w"], hw, map[string]any{"action": "delete", "id": w.blocks["work"]}), http.StatusForbidden, "scope_narrowing_route") + + raw := []byte(`{"action":"get","id":"` + w.blocks["private"] + `","ACTION":"purge"}`) + c1WantRefused(t, "BP-25 get then ACTION purge", w.do(t, http.MethodPost, "/api/manage", c1AdminKey, ha, raw), http.StatusForbidden, "scope_narrowing_route") + r = w.manage(t, w.keys["w"], hw, map[string]any{"action": "type-list"}) + if r.status != http.StatusOK { + t.Errorf("narrowed type-list: HTTP %d %s", r.status, r.raw) + } + c1WantEcho(t, "narrowed type-list", r, "work;") +} + +// TestC1EchoOnEveryNarrowedAnswer: every answer to a narrowed request carries +// X-Context-Narrowed: <read scopes as sent>;<write scope> — the client's proof +// that no proxy dropped the narrowing (E5 of the plugin). +func TestC1EchoOnEveryNarrowedAnswer(t *testing.T) { + w := c1Setup(t) + h := c1Narrow("work,shared") + for _, c := range []struct { + method, path string + body any + }{ + {http.MethodGet, "/api/whoami", nil}, + {http.MethodPost, "/api/search", map[string]any{"query": c1Probe}}, + {http.MethodPost, "/api/query", map[string]any{"query": c1Probe, "synthesize": false}}, + {http.MethodPost, "/api/manage", map[string]any{"action": "get", "id": w.blocks["work"]}}, + {http.MethodPost, "/api/manage", map[string]any{"action": "type-list"}}, + } { + r := w.do(t, c.method, c.path, w.keys["w"], h, c.body) + if r.status != http.StatusOK { + t.Errorf("%s %s narrowed: HTTP %d %s", c.method, c.path, r.status, r.raw) + } + c1WantEcho(t, c.method+" "+c.path, r, "work,shared;") + } + r := w.do(t, http.MethodPost, "/api/store", w.keys["w"], c1Narrow("work,shared", "work"), + map[string]any{"category": "learnings", "title": "c1 echo write juliet", "content": "x"}) + if r.status != http.StatusOK { + t.Errorf("narrowed store: HTTP %d %s", r.status, r.raw) + } + c1WantEcho(t, "POST /api/store", r, "work,shared;work") + if r := w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], nil, nil); len(r.header.Values(handler.HeaderNarrowed)) != 0 { + t.Errorf("an unnarrowed answer carries %s: %v", handler.HeaderNarrowed, r.header.Values(handler.HeaderNarrowed)) + } +} + +// c1Strings reads a JSON string list. +func c1Strings(v any) []string { + list, _ := v.([]any) + out := make([]string, 0, len(list)) + for _, e := range list { + s, _ := e.(string) + out = append(out, s) + } + return out +} + +// TestC1WhoamiReportsTheWriteSideAndTheNarrowing: whoami grows write_scopes +// (the effective write set), confirm_writes, narrowed ({read, write} or +// null) and rate_limit_write (the write limit per 60 s that applies to the +// key: query.rate_limit_write after the tenant overlay). +func TestC1WhoamiReportsTheWriteSideAndTheNarrowing(t *testing.T) { + w := c1Setup(t) + whoami := func(key string, h http.Header) map[string]any { + t.Helper() + r := w.do(t, http.MethodGet, "/api/whoami", key, h, nil) + if r.status != http.StatusOK { + t.Fatalf("whoami: HTTP %d %s", r.status, r.raw) + } + return r.body + } + has := func(what string, body map[string]any, field string) bool { + t.Helper() + if _, ok := body[field]; !ok { + t.Errorf("%s: whoami has no %q", what, field) + return false + } + return true + } + + // Unnarrowed: the key's effective write set, home first. + b := whoami(w.keys["x"], nil) + if has("x unnarrowed", b, "write_scopes") && !slices.Equal(c1Strings(b["write_scopes"]), []string{"default:m", "default:k"}) { + t.Errorf("x unnarrowed: write_scopes %v, want [default:m default:k]", b["write_scopes"]) + } + if has("x unnarrowed", b, "confirm_writes") && b["confirm_writes"] != false { + t.Errorf("x unnarrowed: confirm_writes %v, want false", b["confirm_writes"]) + } + if has("x unnarrowed", b, "narrowed") && b["narrowed"] != nil { + t.Errorf("x unnarrowed: narrowed %v, want null", b["narrowed"]) + } + if has("x unnarrowed", b, "rate_limit_write") && b["rate_limit_write"] != float64(100) { + t.Errorf("x unnarrowed: rate_limit_write %v, want 100 (the default of query.rate_limit_write)", b["rate_limit_write"]) + } + + // Narrowed with a write scope: the write set is that scope alone. + b = whoami(w.keys["x"], c1Narrow("default:k", "default:k")) + if has("x narrowed", b, "write_scopes") && !slices.Equal(c1Strings(b["write_scopes"]), []string{"default:k"}) { + t.Errorf("x narrowed: write_scopes %v, want [default:k]", b["write_scopes"]) + } + if n, _ := b["narrowed"].(map[string]any); n == nil || !slices.Equal(c1Strings(n["read"]), []string{"default:k"}) || n["write"] != "default:k" { + t.Errorf("x narrowed: narrowed %v, want {read:[default:k], write:default:k}", b["narrowed"]) + } + + // Narrowed without a write scope: nothing writable, read in header order. + b = whoami(w.keys["w"], c1Narrow("shared,work")) + if has("w narrowed", b, "write_scopes") && len(c1Strings(b["write_scopes"])) != 0 { + t.Errorf("w narrowed read-only: write_scopes %v, want []", b["write_scopes"]) + } + if n, _ := b["narrowed"].(map[string]any); n == nil || !slices.Equal(c1Strings(n["read"]), []string{"shared", "work"}) || n["write"] != "" { + t.Errorf("w narrowed read-only: narrowed %v, want {read:[shared work], write:\"\"}", b["narrowed"]) + } + + // confirm_writes has no write path (it is set out of band). + if _, err := w.pool.Exec(context.Background(), `UPDATE context_api_keys SET confirm_writes = true WHERE label = 'c1-kw'`); err != nil { + t.Fatal(err) + } + if b = whoami(w.keys["kw"], nil); b["confirm_writes"] != true { + t.Errorf("kw with confirm_writes: confirm_writes %v, want true", b["confirm_writes"]) + } + + // The tenant overlay of query.rate_limit_write. + w.do(t, http.MethodPut, "/api/settings/query.rate_limit_write", w.keys["two"], nil, map[string]any{"value": 40}).must(t, "tenant overlay of query.rate_limit_write") + if r := w.do(t, http.MethodGet, "/api/settings/query.rate_limit_write", w.keys["two"], nil, nil).must(t, "read back the overlay"); !strings.Contains(r.raw, `"value":40`) { + t.Fatalf("fixture: tenant c1two reads back %s, want the overlay 40", r.raw) + } + if b = whoami(w.keys["two"], nil); b["rate_limit_write"] != float64(40) { + t.Errorf("tenant c1two with the overlay 40: rate_limit_write %v, want 40", b["rate_limit_write"]) + } + if b = whoami(w.keys["w"], nil); b["rate_limit_write"] != float64(100) { + t.Errorf("default tenant beside c1two's overlay: rate_limit_write %v, want 100", b["rate_limit_write"]) + } +} + +// TestC1NarrowedRequestIsNeverAnAdmin: under a narrowing the request is a +// member without the server-admin tier, whatever the key is — a narrowed +// request is never an administration request. +func TestC1NarrowedRequestIsNeverAnAdmin(t *testing.T) { + w := c1Setup(t) + r := w.do(t, http.MethodGet, "/api/whoami", c1AdminKey, nil, nil).must(t, "unnarrowed admin whoami") + if r.body["admin"] != true || r.body["role"] != "owner" { + t.Fatalf("fixture: the admin key reads admin %v role %v, want true owner", r.body["admin"], r.body["role"]) + } + r = w.do(t, http.MethodGet, "/api/whoami", c1AdminKey, c1Narrow("private"), nil) + if r.status != http.StatusOK || r.body["admin"] != false || r.body["role"] != "member" { + t.Errorf("narrowed admin whoami: HTTP %d admin %v role %v, want 200 false member", r.status, r.body["admin"], r.body["role"]) + } +} + +// TestC1ArchivedBlockOutsideTheNarrowingStaysHidden: the archive read of a +// narrowed request covers the named scopes that are the key's own, not every +// own scope — an archived block of an own scope the request does not name is +// not found. +func TestC1ArchivedBlockOutsideTheNarrowingStaysHidden(t *testing.T) { + w := c1Setup(t) + id := w.storeBlock(t, w.keys["w"], "shared", "c1 shared archived mike") + w.manage(t, w.keys["w"], nil, map[string]any{"action": "delete", "id": id}).must(t, "delete") + get := map[string]any{"action": "get", "id": id, "include_archived": true} + if r := w.manage(t, w.keys["w"], nil, get).must(t, "unnarrowed archive read"); r.body["success"] != true { + t.Fatalf("fixture: key w does not read its own archived block unnarrowed: %s", r.raw) + } + r := w.manage(t, w.keys["w"], c1Narrow("work"), get) + if r.status != http.StatusOK || r.body["success"] != false { + t.Errorf("archive read narrowed to work of a block in shared: HTTP %d %s, want not found", r.status, r.raw) + } + c1WantEcho(t, "narrowed archive read", r, "work;") +} + +// TestC1PinHomeScopeStaysTheKeys (green on the stubs): a narrowing with a +// grant scope first leaves the home scope the key's own — backend chain, +// quota, the archive read and the settings overlay hang on it. +func TestC1PinHomeScopeStaysTheKeys(t *testing.T) { + w := c1Setup(t) + r := w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], c1Narrow(w.two+",work"), nil).must(t, "narrowed whoami") + if r.body["home_scope"] != "work" { + t.Errorf("narrowed whoami with the grant scope first: home_scope %v, want work", r.body["home_scope"]) + } +} + +// TestC1PinArchivedBlockOfAGrantScopeStaysHidden (green on the stubs): the +// archive read is limited to the key's own scopes; a narrowing that names a +// grant scope, first, does not make that scope the key's own. +func TestC1PinArchivedBlockOfAGrantScopeStaysHidden(t *testing.T) { + w := c1Setup(t) + get := map[string]any{"action": "get", "id": w.blocks["twoArchived"], "include_archived": true} + for _, h := range []http.Header{nil, c1Narrow(w.two), c1Narrow(w.two + ",work")} { + r := w.manage(t, w.keys["w"], h, get) + if r.status != http.StatusOK || r.body["success"] != false { + t.Errorf("get of an archived block of the grant scope (narrowing %v): HTTP %d %s, want not found", h, r.status, r.raw) + } + } + if r := w.manage(t, w.keys["two"], nil, get).must(t, "owner get"); r.body["success"] != true { + t.Fatalf("fixture: the owner does not read its own archived block: %s", r.raw) + } +} diff --git a/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go b/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go new file mode 100644 index 000000000..d1e4e1a4a --- /dev/null +++ b/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go @@ -0,0 +1,385 @@ +//go:build integration && s1red_c2 + +// Achse 02, cluster C-2 (design2/02-ctx-checkpoint.md §3.5 C-2, §7.3): a key +// can require narrowing (context_api_keys.scope_narrowing, migration 198). A +// required key answers every unnarrowed request with 403 +// scope_narrowing_required — reads, writes, /api/session/*, /mcp — except +// GET /api/whoami, which reports the column. Set through api-key-create and +// api-key-update (tenant-admin, like write_scopes); every existing key stays +// optional. Written in S1 before the column exists; the second build tag keeps +// the file out of every gate until C-2 lands. To enable, shorten the +// constraint line to `//go:build integration`. The narrowed positive case +// needs C-1 as well (integration order C-1, C-2). +// +// The HTTP tests drive the PRODUCTION router; the migration test follows the +// migration tests of internal/store (chain up to 197, seed, 198, assert). Its +// seed is plain SQL in the 197 shape: after C-2 the production key insert +// names the new column and cannot write a 197 database. +// +// go test -tags=integration,s1red_c2 -p 1 -count=1 -run '^TestC2' ./cmd/ctxd/ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/blocktype" + "github.com/GottZ/ctx/internal/config" + "github.com/GottZ/ctx/internal/dispatch" + "github.com/GottZ/ctx/internal/events" + "github.com/GottZ/ctx/internal/handler" + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" + "github.com/GottZ/ctx/migrations" +) + +// c2AdminKey is the bootstrap server-admin key (default tenant, owner). +const c2AdminKey = "c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0" + +type c2Resp struct { + status int + body map[string]any + header http.Header + raw string +} + +type c2World struct { + pool *pgxpool.Pool + router http.Handler +} + +func c2Setup(t *testing.T) *c2World { + t.Helper() + pool := testdb.SetupTestDB(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + applyEnv(t, map[string]string{}) + cc, issues := loadFromEnv() + if config.HasErrors(issues) { + t.Fatalf("env fixture invalid: %v", issues) + } + cfgStore := config.NewStore(cc) + backendPool := backends.NewPool(pool, nil) + scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) + projectHub := events.NewProjectHub(ctx, pool, cfgStore) + d := dispatch.New(nil, dispatch.DefaultSettings()) + t.Cleanup(d.Close) + scheduler.SetDispatcher(d) + if created, _, err := store.BootstrapAdminKey(ctx, pool, c2AdminKey, "c2-admin"); err != nil || !created { + t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) + } + return &c2World{pool: pool, router: NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d)} +} + +func (w *c2World) do(t *testing.T, method, path, key string, extra http.Header, body any) c2Resp { + t.Helper() + var rd io.Reader = http.NoBody + if body != nil { + b, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + rd = bytes.NewReader(b) + } + req := httptest.NewRequest(method, path, rd) + req.Header.Set("X-Context-Key", key) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + for k, vs := range extra { + for _, v := range vs { + req.Header.Add(k, v) + } + } + rec := httptest.NewRecorder() + w.router.ServeHTTP(rec, req) + var out map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &out) + return c2Resp{status: rec.Code, body: out, header: rec.Header(), raw: rec.Body.String()} +} + +func (w *c2World) manage(t *testing.T, key string, body map[string]any) c2Resp { + t.Helper() + return w.do(t, http.MethodPost, "/api/manage", key, nil, body) +} + +func (r c2Resp) must(t *testing.T, what string) c2Resp { + t.Helper() + if r.status != http.StatusOK || r.body["success"] == false { + t.Fatalf("fixture %s: HTTP %d %s", what, r.status, r.raw) + } + return r +} + +func (r c2Resp) code() string { + c, _ := r.body["code"].(string) + return c +} + +// mint creates a key through api-key-create as the admin and returns its +// plaintext and id; the answer's status is the caller's to judge. +func (w *c2World) mint(t *testing.T, data map[string]any) (c2Resp, string, string) { + t.Helper() + r := w.manage(t, c2AdminKey, map[string]any{"action": "api-key-create", "data": data}) + k, _ := r.body["api_key"].(string) + id, _ := r.body["id"].(string) + return r, k, id +} + +// scopeNarrowing is the scope_narrowing whoami reports for key ("" when the +// field is missing). +func (w *c2World) scopeNarrowing(t *testing.T, key string) string { + t.Helper() + r := w.do(t, http.MethodGet, "/api/whoami", key, nil, nil) + if r.status != http.StatusOK { + t.Errorf("whoami: HTTP %d %s, want 200 (whoami stays open to a required key)", r.status, r.raw) + return "" + } + v, _ := r.body["scope_narrowing"].(string) + return v +} + +// c2Unnarrowed are the unnarrowed requests a required key is refused: reads, +// a write, a manage read, the session surface and /mcp. +func c2Unnarrowed(blockID string) []struct { + method, path string + body any + write string +} { + return []struct { + method, path string + body any + write string + }{ + {http.MethodPost, "/api/query", map[string]any{"query": "c2probe", "synthesize": false}, ""}, + {http.MethodPost, "/api/search", map[string]any{"query": "c2probe"}, ""}, + {http.MethodPost, "/api/store", map[string]any{"category": "learnings", "title": "c2 refused write", "content": "x"}, "c2 refused write"}, + {http.MethodPost, "/api/manage", map[string]any{"action": "get", "id": blockID}, ""}, + {http.MethodPost, "/api/recent", map[string]any{}, ""}, + {http.MethodGet, "/api/session/keys", nil, ""}, + {http.MethodPost, "/api/session/select-key", map[string]any{"api_key_id": "00000000-0000-0000-0000-000000000000"}, ""}, + {http.MethodPost, "/mcp", map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, ""}, + } +} + +// wantRequired checks every unnarrowed request of key is refused with +// scope_narrowing_required, and that the refused write wrote nothing (the +// mutant "required on reads only"). +func (w *c2World) wantRequired(t *testing.T, who, key, blockID string) { + t.Helper() + mcp := http.Header{} + mcp.Set("Accept", "application/json, text/event-stream") + for _, c := range c2Unnarrowed(blockID) { + var h http.Header + if c.path == "/mcp" { + h = mcp + } + r := w.do(t, c.method, c.path, key, h, c.body) + if r.status != http.StatusForbidden || r.code() != "scope_narrowing_required" { + t.Errorf("%s: unnarrowed %s %s: HTTP %d code %q, want 403 scope_narrowing_required (%s)", who, c.method, c.path, r.status, r.code(), strings.TrimSpace(r.raw)) + } + if c.write != "" { + var n int + if err := w.pool.QueryRow(context.Background(), `SELECT count(*) FROM context_blocks WHERE title = $1`, c.write).Scan(&n); err != nil || n != 0 { + t.Errorf("%s: the refused unnarrowed write wrote %d block(s) (err %v)", who, n, err) + } + } + } +} + +// TestC2RequiredKeyRefusesEveryUnnarrowedRequest: a key minted with +// scope_narrowing "required" is refused every unnarrowed request but whoami, +// which reports "required"; narrowed, it reads (C-1 echo). +func TestC2RequiredKeyRefusesEveryUnnarrowedRequest(t *testing.T) { + w := c2Setup(t) + r := w.do(t, http.MethodPost, "/api/store", c2AdminKey, nil, map[string]any{"category": "learnings", "title": "c2 shared block", "content": "c2probe", "scope": "shared"}).must(t, "store") + blk, _ := r.body["block"].(map[string]any) + blockID, _ := blk["id"].(string) + + r, key, _ := w.mint(t, map[string]any{"label": "c2-required", "home_scope": "work", "allowed_scopes": []string{"shared"}, "scope_narrowing": "required"}) + r.must(t, "api-key-create with scope_narrowing required") + if got, _ := r.body["scope_narrowing"].(string); got != "required" { + t.Errorf("api-key-create echoes scope_narrowing %q, want required", got) + } + if got := w.scopeNarrowing(t, key); got != "required" { + t.Errorf("whoami of the required key: scope_narrowing %q, want required", got) + } + w.wantRequired(t, "required key", key, blockID) + + h := http.Header{} + h.Set(handler.HeaderReadScopes, "shared") + n := w.do(t, http.MethodPost, "/api/search", key, h, map[string]any{"query": "c2probe"}) + if n.status != http.StatusOK || n.header.Get(handler.HeaderNarrowed) != "shared;" { + t.Errorf("narrowed search of the required key: HTTP %d echo %q, want 200 with echo \"shared;\" (%s)", n.status, n.header.Get(handler.HeaderNarrowed), n.raw) + } +} + +// TestC2KeyUpdateSwitchesTheRequirement: api-key-update turns the requirement +// on and off for an existing key. +func TestC2KeyUpdateSwitchesTheRequirement(t *testing.T) { + w := c2Setup(t) + _, key, id := w.mint(t, map[string]any{"label": "c2-switch", "home_scope": "work"}) + if key == "" || id == "" { + t.Fatal("fixture: api-key-create returned no key") + } + w.do(t, http.MethodPost, "/api/search", key, nil, map[string]any{"query": "c2probe"}).must(t, "optional key searches unnarrowed") + + r := w.manage(t, c2AdminKey, map[string]any{"action": "api-key-update", "data": map[string]any{"id": id, "scope_narrowing": "required"}}) + if r.status != http.StatusOK || r.body["success"] != true { + t.Fatalf("api-key-update scope_narrowing required: HTTP %d %s", r.status, r.raw) + } + if k, _ := r.body["key"].(map[string]any); k["scope_narrowing"] != "required" { + t.Errorf("api-key-update answers key %v, want scope_narrowing required", r.body["key"]) + } + if got := w.scopeNarrowing(t, key); got != "required" { + t.Errorf("whoami after the switch: scope_narrowing %q, want required", got) + } + s := w.do(t, http.MethodPost, "/api/search", key, nil, map[string]any{"query": "c2probe"}) + if s.status != http.StatusForbidden || s.code() != "scope_narrowing_required" { + t.Errorf("unnarrowed search after the switch: HTTP %d code %q, want 403 scope_narrowing_required", s.status, s.code()) + } + + w.manage(t, c2AdminKey, map[string]any{"action": "api-key-update", "data": map[string]any{"id": id, "scope_narrowing": "optional"}}).must(t, "switch back") + w.do(t, http.MethodPost, "/api/search", key, nil, map[string]any{"query": "c2probe"}).must(t, "optional again") +} + +// TestC2ScopeNarrowingValueIsChecked: a value other than optional and required +// is a 400 on create and update, and nothing is created or changed. +func TestC2ScopeNarrowingValueIsChecked(t *testing.T) { + w := c2Setup(t) + r, _, _ := w.mint(t, map[string]any{"label": "c2-bogus", "home_scope": "work", "scope_narrowing": "sometimes"}) + if r.status != http.StatusBadRequest { + t.Errorf("api-key-create scope_narrowing sometimes: HTTP %d %s, want 400", r.status, r.raw) + } + var n int + if err := w.pool.QueryRow(context.Background(), `SELECT count(*) FROM context_api_keys WHERE label = 'c2-bogus'`).Scan(&n); err != nil || n != 0 { + t.Errorf("api-key-create with a bad value created %d key(s) (err %v)", n, err) + } + + _, key, id := w.mint(t, map[string]any{"label": "c2-keep", "home_scope": "work"}) + r = w.manage(t, c2AdminKey, map[string]any{"action": "api-key-update", "data": map[string]any{"id": id, "scope_narrowing": "sometimes"}}) + if r.status != http.StatusBadRequest { + t.Errorf("api-key-update scope_narrowing sometimes: HTTP %d %s, want 400", r.status, r.raw) + } + if got := w.scopeNarrowing(t, key); got != "optional" { + t.Errorf("whoami after the refused update: scope_narrowing %q, want optional", got) + } +} + +// TestC2KeysWithoutTheFieldStayOptional: a key minted without the field, and +// the bootstrap key, are optional and keep working unnarrowed. +func TestC2KeysWithoutTheFieldStayOptional(t *testing.T) { + w := c2Setup(t) + _, key, _ := w.mint(t, map[string]any{"label": "c2-plain", "home_scope": "work"}) + for who, k := range map[string]string{"plain key": key, "bootstrap admin": c2AdminKey} { + if got := w.scopeNarrowing(t, k); got != "optional" { + t.Errorf("%s: whoami scope_narrowing %q, want optional", who, got) + } + w.do(t, http.MethodPost, "/api/search", k, nil, map[string]any{"query": "c2probe"}).must(t, who+" searches unnarrowed") + } +} + +// c2Migration198 is the file name of migration 198, whatever C-2 calls it. +func c2Migration198(t *testing.T) string { + t.Helper() + files, err := fs.Glob(migrations.FS, "198_*.sql") + if err != nil { + t.Fatal(err) + } + if len(files) != 1 { + t.Fatalf("migration 198: %d file(s) %v in go/migrations, want exactly one", len(files), files) + } + return files[0] +} + +// c2Column describes context_api_keys.scope_narrowing: type, nullability and +// default ("" when the column does not exist). +func c2Column(t *testing.T, pool *pgxpool.Pool) string { + t.Helper() + var typ, nullable, def string + err := pool.QueryRow(context.Background(), `SELECT data_type, is_nullable, coalesce(column_default, '') + FROM information_schema.columns + WHERE table_schema = current_schema() AND table_name = 'context_api_keys' AND column_name = 'scope_narrowing'`).Scan(&typ, &nullable, &def) + if err != nil { + return "" + } + return typ + " nullable=" + nullable + " default=" + def +} + +// c2WantCheck pins the CHECK: a value outside the two is refused (23514). +func c2WantCheck(t *testing.T, pool *pgxpool.Pool, label string) { + t.Helper() + _, err := pool.Exec(context.Background(), `UPDATE context_api_keys SET scope_narrowing = 'sometimes' WHERE label = $1`, label) + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) || pgErr.Code != "23514" { + t.Errorf("scope_narrowing = 'sometimes' on %s: err %v, want a CHECK violation (23514)", label, err) + } +} + +// TestC2Migration198 (design2/02 §3.5 C-2): context_api_keys.scope_narrowing +// TEXT NOT NULL DEFAULT 'optional' CHECK (optional|required), forward on a +// fresh and on a populated database; existing keys read optional, also +// through ctx_auth and ctx_auth_by_id, whose last column it is. +func TestC2Migration198(t *testing.T) { + ctx := context.Background() + const want = "text nullable=NO default='optional'::text" + file := c2Migration198(t) + + t.Run("fresh", func(t *testing.T) { + pool := testdb.SetupTestDB(t) + if got := c2Column(t, pool); got != want { + t.Fatalf("%s on a fresh database: column %q, want %q", file, got, want) + } + if _, _, err := store.CreateApiKey(ctx, pool, "c2-fresh", "work", nil, store.DefaultTenantID); err != nil { + t.Fatal(err) + } + c2WantCheck(t, pool, "c2-fresh") + }) + + t.Run("populated", func(t *testing.T) { + pool := testdb.SetupTestDBUpTo(t, 197) + const plain = "c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0" + sum := sha256.Sum256([]byte(plain)) + var keyID string + if err := pool.QueryRow(ctx, `WITH p AS (INSERT INTO context_principals (display_name) VALUES ('c2-old') RETURNING id) + INSERT INTO context_api_keys (label, key_hash, home_scope, allowed_scopes, active, tenant_id, tenant_role, principal_id) + SELECT 'c2-old', $1, 'private', '{shared}', true, $2::uuid, 'member', p.id FROM p + RETURNING id::text`, hex.EncodeToString(sum[:]), store.DefaultTenantID).Scan(&keyID); err != nil { + t.Fatalf("seed a 197 key: %v", err) + } + if err := store.RunMigrationsUpTo(ctx, pool, 198); err != nil { + t.Fatalf("run migrations up to 198: %v", err) + } + if got := c2Column(t, pool); got != want { + t.Fatalf("%s on a populated database: column %q, want %q", file, got, want) + } + var v string + if err := pool.QueryRow(ctx, `SELECT scope_narrowing FROM context_api_keys WHERE id = $1::uuid`, keyID).Scan(&v); err != nil || v != "optional" { + t.Errorf("the existing key reads %q (err %v), want optional", v, err) + } + if err := pool.QueryRow(ctx, `SELECT scope_narrowing FROM ctx_auth($1)`, plain).Scan(&v); err != nil || v != "optional" { + t.Errorf("ctx_auth: scope_narrowing %q (err %v), want optional", v, err) + } + if err := pool.QueryRow(ctx, `SELECT scope_narrowing FROM ctx_auth_by_id($1::uuid)`, keyID).Scan(&v); err != nil || v != "optional" { + t.Errorf("ctx_auth_by_id: scope_narrowing %q (err %v), want optional", v, err) + } + c2WantCheck(t, pool, "c2-old") + if err := store.RunMigrations(ctx, pool); err != nil { + t.Fatalf("run migrations again: %v", err) + } + }) +} diff --git a/go/internal/auth/auth.go b/go/internal/auth/auth.go index 64a5973d7..8e153ae90 100644 --- a/go/internal/auth/auth.go +++ b/go/internal/auth/auth.go @@ -47,8 +47,36 @@ type AuthResult struct { // sole authorisation decision. Achse 03 (token) and 05 (session) resolve // their AuthResult through the SAME ctx_auth_by_id(uuid) SQL sibling. PrincipalID string + // Narrowed is the request's per-request narrowing (Achse 02 C-1): nil for an + // unnarrowed request. Only the Auth middleware sets it, and only on the + // AuthResult it hands to the handlers; the request key that store writes + // recheck (store.WithRequestKey) stays the unnarrowed key's. + Narrowed *Narrowing + // ScopeNarrowing is the key's scope_narrowing column (Achse 02 C-2): + // ScopeNarrowingOptional or ScopeNarrowingRequired. "" reads as optional. + ScopeNarrowing string } +// Narrowing is a request's narrowing (Achse 02 C-1). Read is the read set of +// this request, in header order; Write is its write scope ("" = the request +// writes nothing); Writable is the write set handed to the block write gate +// ([Write] when the request has a write scope, else empty). A write scope the +// UNNARROWED key cannot write, or one outside Read, never gets here: the +// narrowing is refused (403 scope_denied) before an AuthResult carries it. +type Narrowing struct { + Read []string + Write string + Writable []string +} + +// The values of a key's scope_narrowing (Achse 02 C-2): an optional key may +// narrow a request, a required key answers nothing but GET /api/whoami +// without a narrowing. +const ( + ScopeNarrowingOptional = "optional" + ScopeNarrowingRequired = "required" +) + // SanitizeKey strips all non-hex characters from an API key. func SanitizeKey(raw string) string { return hexOnly.ReplaceAllString(raw, "") diff --git a/go/internal/handler/manage_table.go b/go/internal/handler/manage_table.go index 781aa8982..ea73930ab 100644 --- a/go/internal/handler/manage_table.go +++ b/go/internal/handler/manage_table.go @@ -437,6 +437,15 @@ func (h *ManageHandler) handleManage(w http.ResponseWriter, r *http.Request, act return } + // Per-request narrowing (Achse 02 C-1, BP-25): the route rule lives in the + // Auth middleware, which must not read the body; the action rule is + // checked here, on the ONE decoded req.Action the dispatch below uses — + // never on a second reading of the body. + if authResult.Narrowed != nil && !manageActionAllowedNarrowed(req.Action) { + writeNarrowingRouteRefused(w) + return + } + action, known := actions[req.Action] if !known { writeJSON(w, http.StatusBadRequest, map[string]any{ diff --git a/go/internal/handler/middleware.go b/go/internal/handler/middleware.go index 8705eb3d9..8137c8467 100644 --- a/go/internal/handler/middleware.go +++ b/go/internal/handler/middleware.go @@ -696,11 +696,22 @@ func Auth(pool *pgxpool.Pool) func(http.Handler) http.Handler { return } - ctx := context.WithValue(r.Context(), authResultKey, result) + // Per-request narrowing (Achse 02 C-1, narrowing.go): the handlers + // see the narrowed AuthResult; the request key below stays the + // key's own. + narrowed, rej := narrowAuth(r, result) + if rej != nil { + writeJSONReject(w, rej) + return + } + + ctx := context.WithValue(r.Context(), authResultKey, narrowed) // The request's key and the scopes it granted travel to every // write the request makes (issue #555, store.WithRequestKey): a // write whose key a tenant-delete removed, or took a scope from, - // while the request ran writes nothing. + // while the request ran writes nothing. Fed from the UNNARROWED + // result: a narrowing shrinks what the request may do, never what + // the recheck holds the key to. ctx = store.WithRequestKey(ctx, store.RequestKey{ ID: result.ApiKeyID, HomeScope: result.HomeScope, diff --git a/go/internal/handler/narrowing.go b/go/internal/handler/narrowing.go new file mode 100644 index 000000000..5a7736bbe --- /dev/null +++ b/go/internal/handler/narrowing.go @@ -0,0 +1,65 @@ +// Per-request scope narrowing (Achse 02, cluster C-1; design2/02 §3.5): a +// request names the scopes it reads (X-Context-Read-Scopes) and, optionally, +// the one scope it writes (X-Context-Write-Scope), and for that request the +// key's rights shrink to exactly these. The key's own scopes stay what the +// write recheck of issue #555 (store.WithRequestKey) checks against. +// +// S1 contract: the signatures below are fixed, the bodies are inert — the +// headers are ignored and every request runs unnarrowed, byte-identical to the +// tree before this file. C-1 fills them in; C-2 adds the required-narrowing +// check to narrowAuth. +package handler + +import ( + "net/http" + + "github.com/GottZ/ctx/internal/auth" +) + +// The narrowing headers. HeaderReadScopes carries 1 to 8 scopes, +// comma-separated, in the order the request reads them; HeaderWriteScope the +// one scope the request writes. HeaderNarrowed is the echo on the answer to a +// narrowed request: "<read scopes, comma-separated>;<write scope>". +const ( + HeaderReadScopes = "X-Context-Read-Scopes" + HeaderWriteScope = "X-Context-Write-Scope" + HeaderNarrowed = "X-Context-Narrowed" +) + +// codeScopeNarrowingRoute is the code of the refusal of a narrowed request on +// a route or /api/manage action outside the narrowing's closed list. It is not +// a rejectClass of errcode.go yet: a class there is closed vocabulary that +// docs/api.md and docs/mcp.md list (TestRejectClassesAreDocumented), and the +// documentation is C-1's. C-1 moves it into errcode.go next to its +// documentation. +const codeScopeNarrowingRoute = "scope_narrowing_route" + +// narrowAuth derives the AuthResult a request runs with from the key's +// AuthResult ar and the narrowing headers of r. It returns the AuthResult to +// hand to the handlers (ar itself when the request carries no narrowing) or a +// refusal the Auth middleware answers with. It never modifies ar. +// +// S1 stub: the headers are ignored, every request is unnarrowed. +func narrowAuth(r *http.Request, ar *auth.AuthResult) (*auth.AuthResult, *writeReject) { + return ar, nil +} + +// manageActionAllowedNarrowed reports whether a narrowed /api/manage request +// may run action — the one action the dispatcher decoded (BP-25). C-1: only +// "get" and "type-list". +// +// S1 stub: no request is narrowed yet, so the dispatcher never asks; every +// action is allowed. +func manageActionAllowedNarrowed(action string) bool { + return true +} + +// writeNarrowingRouteRefused answers a narrowed request whose route or manage +// action lies outside the narrowing's closed list: 403 with the house +// {"success":false,"error":…} envelope and the code scope_narrowing_route. +func writeNarrowingRouteRefused(w http.ResponseWriter) { + writeJSONCode(w, http.StatusForbidden, codeScopeNarrowingRoute, map[string]any{ + "success": false, + "error": "this route is not available to a narrowed request", + }) +} diff --git a/go/internal/store/api_keys.go b/go/internal/store/api_keys.go index b2da1d95f..7b50f770c 100644 --- a/go/internal/store/api_keys.go +++ b/go/internal/store/api_keys.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/GottZ/ctx/internal/auth" "github.com/GottZ/ctx/internal/pgxdb" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" @@ -91,7 +92,14 @@ func validateWriteScopes(homeScope string, allowedScopes, writeScopes []string) // RETURNING now carry tenant_role — additive vs v4.0.1 (whose create path // omitted the column and returned TenantRole==""); the column has existed since // 059, so this is SQL-only, NO migration. -func insertApiKeyTx(ctx context.Context, q pgxdb.Rower, label, homeScope string, allowedScopes, writeScopes []string, tenantID, role string) (ApiKey, string, error) { +// +// scopeNarrowing is the key's scope_narrowing (auth.ScopeNarrowingOptional or +// auth.ScopeNarrowingRequired, Achse 02). The S1 contract fixes the parameter +// so the keyset mint (C-3) can be built against it; the column arrives with +// migration 198 (C-2), and until then the value is not stored — every caller +// passes auth.ScopeNarrowingOptional, which is what the column's default will +// be. +func insertApiKeyTx(ctx context.Context, q pgxdb.Rower, label, homeScope string, allowedScopes, writeScopes []string, tenantID, role, scopeNarrowing string) (ApiKey, string, error) { if label == "" { return ApiKey{}, "", fmt.Errorf("api_keys: label is required") } @@ -190,7 +198,7 @@ func insertApiKeyTx(ctx context.Context, q pgxdb.Rower, label, homeScope string, // it mints are exactly as before. Owner / quota-gated mints are separate paths // that pass their own role through the shared primitive. func CreateApiKey(ctx context.Context, pool *pgxpool.Pool, label, homeScope string, allowedScopes []string, tenantID string) (*ApiKey, string, error) { - key, plaintext, err := insertApiKeyTx(ctx, pool, label, homeScope, allowedScopes, nil, tenantID, "member") + key, plaintext, err := insertApiKeyTx(ctx, pool, label, homeScope, allowedScopes, nil, tenantID, "member", auth.ScopeNarrowingOptional) if err != nil { return nil, "", err } @@ -267,7 +275,7 @@ func MintKeyWithQuota(ctx context.Context, pool *pgxpool.Pool, label, homeScope } var err error - key, plaintext, err = insertApiKeyTx(ctx, tx, label, homeScope, allowedScopes, writeScopes, tenantID, role) + key, plaintext, err = insertApiKeyTx(ctx, tx, label, homeScope, allowedScopes, writeScopes, tenantID, role, auth.ScopeNarrowingOptional) return err }); err != nil { return ApiKey{}, "", err @@ -301,7 +309,7 @@ func MintOwnerKey(ctx context.Context, q pgxdb.Rower, label, homeScope string, a // Owner keys mint with empty write_scopes (nil): an owner's home_scope IS the // tenant's first scope and covers the bootstrap corpus; explicit write_scopes // are a later, per-key concern via api-key-update. - return insertApiKeyTx(ctx, q, label, homeScope, allowedScopes, nil, tenantID, "owner") + return insertApiKeyTx(ctx, q, label, homeScope, allowedScopes, nil, tenantID, "owner", auth.ScopeNarrowingOptional) } // ListApiKeys returns API key rows ordered by created_at desc, scoped to one diff --git a/go/internal/store/api_keys_insert_test.go b/go/internal/store/api_keys_insert_test.go index 0d8ebd20a..dfcaeb8dd 100644 --- a/go/internal/store/api_keys_insert_test.go +++ b/go/internal/store/api_keys_insert_test.go @@ -4,6 +4,8 @@ import ( "context" "strings" "testing" + + "github.com/GottZ/ctx/internal/auth" ) // insertApiKeyTx is the shared INSERT primitive behind CreateApiKey (and the @@ -36,7 +38,7 @@ func TestInsertApiKeyTx_ValidationOwnedByPrimitive(t *testing.T) { {"reserved allowed_scope", "lbl", "tenant-a", []string{"shared", "_x"}, "reserved"}, } for _, c := range cases { - _, _, err := insertApiKeyTx(ctx, nil, c.label, c.homeScope, c.allowed, nil, "", role) + _, _, err := insertApiKeyTx(ctx, nil, c.label, c.homeScope, c.allowed, nil, "", role, auth.ScopeNarrowingOptional) if err == nil { t.Errorf("role=%s %s: expected error, got nil", role, c.name) continue diff --git a/go/internal/store/api_keys_write_scopes_test.go b/go/internal/store/api_keys_write_scopes_test.go index 8b20387b1..7eac6e831 100644 --- a/go/internal/store/api_keys_write_scopes_test.go +++ b/go/internal/store/api_keys_write_scopes_test.go @@ -5,6 +5,8 @@ import ( "errors" "strings" "testing" + + "github.com/GottZ/ctx/internal/auth" ) // validateWriteScopes is the mint/update-time half of the 078 write_scopes invariant @@ -56,7 +58,7 @@ func TestValidateWriteScopes(t *testing.T) { // would fall through to q.QueryRow(nil) and panic. func TestInsertApiKeyTx_RejectsBlindWriterBeforeDB(t *testing.T) { ctx := context.Background() - _, _, err := insertApiKeyTx(ctx, nil, "lbl", "private", []string{"shared"}, []string{"work"}, "", "member") + _, _, err := insertApiKeyTx(ctx, nil, "lbl", "private", []string{"shared"}, []string{"work"}, "", "member", auth.ScopeNarrowingOptional) if !errors.Is(err, ErrWriteScopeNotAllowed) { t.Fatalf("insertApiKeyTx blind-writer err = %v, want ErrWriteScopeNotAllowed", err) } diff --git a/go/internal/store/provision.go b/go/internal/store/provision.go index 2dac1ac3a..e3373854c 100644 --- a/go/internal/store/provision.go +++ b/go/internal/store/provision.go @@ -20,6 +20,7 @@ import ( "errors" "fmt" + "github.com/GottZ/ctx/internal/auth" "github.com/GottZ/ctx/internal/backends" "github.com/GottZ/ctx/internal/pgxdb" "github.com/jackc/pgx/v5" @@ -184,7 +185,7 @@ func ProvisionProject(ctx context.Context, pool *pgxpool.Pool, p ProvisionParams // (NON-NIL empty: no '{shared}' inheritance), write = [] (NON-NIL empty). The // role is 'member' (agents never own). This is the verbindlicher Vertrag §5.5. agentKey, agentPlain, err := insertApiKeyTx(ctx, tx, - p.Slug+agentKeyLabelSuffix, p.Scope, []string{}, []string{}, tn.ID, "member") + p.Slug+agentKeyLabelSuffix, p.Scope, []string{}, []string{}, tn.ID, "member", auth.ScopeNarrowingOptional) if err != nil { return err } From 60a5dff4ec6c8a93ade98ff75ccfc031710fb62e Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 01:31:04 +0100 Subject: [PATCH 03/15] =?UTF-8?q?feat(auth):=20a=20request=20narrows=20its?= =?UTF-8?q?=20key=20to=20the=20scopes=20it=20names=20=E2=80=94=20read=20an?= =?UTF-8?q?d=20write=20scope=20headers=20on=20a=20closed=20route=20list,?= =?UTF-8?q?=20echoed,=20and=20whoami=20reports=20the=20write=20side?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A request may carry X-Context-Read-Scopes (1 to 8 scopes the key reads) and X-Context-Write-Scope (one of them, which the key may write). The Auth middleware decides the narrowing once, before any handler runs, and hands the handlers a copy of the key's AuthResult: the named read set in header order, no server-admin tier, tenant role member, and the narrowing. The home scope and everything else stay the key's, so backend chain, quota, settings overlay and archive read are the key's whatever scope comes first, and the #555 write recheck still holds the unnarrowed key. Three places read the narrowing: writableBlockScopes (its write scope alone), resolveWriteScope (a write without a scope goes there, without one it is scope_denied) and resolveGrants (no block grants). A narrowed request may take POST /api/query, /api/search, /api/store, /api/manage (get, type-list) and GET /api/whoami, compared by method and exact path; everything else is 403 scope_narrowing_route, a malformed narrowing 400 scope_narrowing_invalid. Every answer of an accepted narrowing carries X-Context-Narrowed. An archive read whose narrowing names no own scope finds nothing instead of reaching the store's empty-scope guard. whoami grows write_scopes, confirm_writes, narrowed and rate_limit_write (after the tenant overlay); TS WhoamiResponse follows with optional fields, the built bundle is byte-identical. The S1 red tests of C-1 are switched on, with the probes they left open (a scope named twice, the read set whoami reports, the overlay and the backend chain of a grant scope first, an escaped path). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/api.md | 16 +- docs/mcp.md | 4 +- docs/multi-tenancy.md | 8 + go/cmd/ctxd/narrowing_c1_integration_test.go | 14 +- .../narrowing_c1_more_integration_test.go | 138 +++++++++++++++ go/cmd/ctxd/server.go | 3 +- go/internal/handler/context_store.go | 18 ++ go/internal/handler/errcode.go | 15 +- go/internal/handler/get_archived.go | 9 +- go/internal/handler/mcp.go | 6 + go/internal/handler/middleware.go | 3 +- go/internal/handler/narrowing.go | 158 +++++++++++++++--- go/internal/handler/narrowing_test.go | 98 +++++++++++ go/internal/handler/whoami.go | 60 +++++++ go/internal/handler/whoami_test.go | 13 +- go/web/src/lib/api/types.ts | 11 ++ 16 files changed, 536 insertions(+), 38 deletions(-) create mode 100644 go/cmd/ctxd/narrowing_c1_more_integration_test.go create mode 100644 go/internal/handler/narrowing_test.go diff --git a/docs/api.md b/docs/api.md index 3c007e825..dc346d338 100644 --- a/docs/api.md +++ b/docs/api.md @@ -23,7 +23,7 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. | `GET /api/graph/overview` | Scope-pure Louvain cluster supergraph ("landkarte"); reads precomputed scope-partitioned aggregates, gated on `graph_overview.enabled` (off → 404). Read-only, no LLM. | | `GET /api/graph/cluster` | Cluster ego: the members + neighbour topics of ONE topic handle (see [Cluster ego](#cluster-ego-get-apigraphcluster)). Double-gated on `graph_overview.enabled` **and** `cluster.route_enabled` (both default off → 404, indistinguishable from an absent route). | | `POST /api/synthesize/daily` | Manual trigger of the daily synthesis (Tagesbericht) for the caller's `home_scope` — the same `GenerateDailyReport` path the 03:00 scheduler iteration runs (digest role, constant internal). Concurrency cap 1 per principal (429 fail-fast), dispatch-interactive (429 + `Retry-After` on capacity rejection). Optional `?date=YYYY-MM-DD` (M103) re-synthesizes the report titled that day over its historical window `[date-1 03:00 UTC, date 03:00 UTC)` — the backfill path; the `(category, title, scope)` upsert replaces the old report in place (same block id, embedding regenerates). A malformed date, a window that has not closed yet, or — with `scheduler.writelog_retention_days` set — a window that starts before the write-log horizon or before the eviction boundary the retention recorded on any earlier run, whatever the setting is now (its guard and dream decisions are deleted, and the replacement would lack them; issue #277) ⇒ 400; a boundary the server cannot read ⇒ 500. `{ok, block_id, scope[, date][, reason:"no_activity"]}`. The report language follows the hot `dream.language` setting, read per request: empty (default) keeps the German surface this row describes, any other tag localizes **title and tag together** (`Daily Report <date>` / `daily-report`) — so a change **starts a new series** instead of continuing the old one, and a backfill after the switch writes a second block for a day that already has a `Tagesbericht`. Deliberate and operator-triggered; see [`CTX_DREAM_LANGUAGE`](operations.md#environment-variables). | -| `GET /api/whoami` | Calling key's identity: `label`, `home_scope`, `read_scopes`, the server-global `admin` tier flag, plus the Model-C tenant identity `tenant_id` + per-tenant `role` (`owner`/`admin`/`member`), and the feature-flag bag `capabilities` (`{workflow: true}` since v4.3.0 — switches the SPA's issues/board surface visible; the field is data, so a later per-tenant gate only changes the value, not the SPA). `capabilities.model_api` carries the gateway policy as data, read per request from the `_global` settings: `{enabled, self_service, key_max_lifetime_s, rotation_grace_s, expiry_warn_s}` = `gateway.enabled`, `gateway.tenant_self_service`, `gateway.key_max_lifetime_app`, `gateway.key_rotation_grace`, `gateway.key_expiry_warn` (durations in whole seconds; the peer lifetime is not carried). Every authenticated caller receives it — server policy, no secret; the SPA derives two capabilities from it, `viewModelApi` and `mintModelKeys`, for the gateway administration surface ([multi-tenancy](multi-tenancy.md#admin-tiers)), while the manage actions enforce their own tiers ([Model consumer administration](#model-consumer-administration)). The SPA login gate probes it, derives its read-only degradation from `admin`, and tells server-admin from tenant-admin. | +| `GET /api/whoami` | Calling key's identity: `label`, `home_scope`, `read_scopes`, the server-global `admin` tier flag, plus the Model-C tenant identity `tenant_id` + per-tenant `role` (`owner`/`admin`/`member`), and the feature-flag bag `capabilities` (`{workflow: true}` since v4.3.0 — switches the SPA's issues/board surface visible; the field is data, so a later per-tenant gate only changes the value, not the SPA). `capabilities.model_api` carries the gateway policy as data, read per request from the `_global` settings: `{enabled, self_service, key_max_lifetime_s, rotation_grace_s, expiry_warn_s}` = `gateway.enabled`, `gateway.tenant_self_service`, `gateway.key_max_lifetime_app`, `gateway.key_rotation_grace`, `gateway.key_expiry_warn` (durations in whole seconds; the peer lifetime is not carried). Every authenticated caller receives it — server policy, no secret; the SPA derives two capabilities from it, `viewModelApi` and `mintModelKeys`, for the gateway administration surface ([multi-tenancy](multi-tenancy.md#admin-tiers)), while the manage actions enforce their own tiers ([Model consumer administration](#model-consumer-administration)). The SPA login gate probes it, derives its read-only degradation from `admin`, and tells server-admin from tenant-admin. Four fields describe the write side and a narrowing: `write_scopes` (the effective write set, home scope first — under a narrowing its write scope alone, or `[]`), `confirm_writes`, `narrowed` (`{read, write}` of a [narrowed request](#scope-narrowing-per-request), `null` otherwise; under a narrowing `read_scopes` is that read set, `admin` is `false` and `role` is `member`) and `rate_limit_write` (the write budget per key and 60 s that applies to this key: `query.rate_limit_write` after its tenant's overlay, `0` = unlimited). | | `POST /api/manage` | CRUD, Guard API, stats, API-key management, block-type registry (see [manage actions](#manage-actions)). | | `GET /api/types[/{name}]` | Block-type registry reads: effective type list (`_global` ∪ your tenant) and single-type policy config, **member-gated** (any valid key) (see [Block-type registry](#block-type-registry)). | | `PUT\|DELETE /api/types/{name}` | Block-type registry writes (upsert/delete), **admin-or-tenant-admin-gated**: a tenant-admin writes its own tenant namespace, `_global` types are operator-only; DELETE 409s while referenced or on a builtin (see [Block-type registry](#block-type-registry)). | @@ -46,7 +46,7 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. | `GET /api/project/events` | **Member** SSE domain-event stream (`text/event-stream`, workflow W9) for live board / issue-list updates. A key receives IDS-ONLY frames — `project` events `{kind, project_id, op, block_ids}` or the coalesced `{kind:"issues-bulk", project_id, count}`; NEVER title/content/body (the client refetches over the read API). Frames are **scope-filtered at the fan-out**: only the caller's readable project scopes, never another tenant's. Optional `?project_id=` pins the stream to one project (foreign/unknown ⇒ 404 uniform). Per-**tenant** connection cap (`project.events.max_connections`) → 429; `: ping` keepalive; a 10k-import burst collapses to one `issues-bulk` frame per tick (`project.events.flush_interval` / `coalesce_threshold`). In-stream re-auth recomputes the caller's scope tags from the FRESH read set every ~12 flush ticks: a revoked key or a tenant change ends the stream, and a revoked cross-tenant **scope grant** (tenant/role unchanged) drops that scope's frames — separate from the server-admin telemetry `/api/events`. | | `POST /api/digest` | Topic map generation. Rebuilds the linear topic map and — when `root_map.enabled` is on — also renders the **root map** (`root-map-<scope>`, cluster-per-line, capped at `root_map.budget_bytes`). It never starts a Louvain rebuild: the map is rendered from the cluster state that already exists, so the route cannot become a lever on a job bounded only by `graph_overview.rebuild_timeout`. Carries its own write rate-limit bucket (`digest`) since the root-map wave. Response gains `rootMapTitle` / `rootMapLength` **additively**; `title`, `blockCount`, `categoryCount` and `contentLength` keep their meaning, and the two corpus counts behind them now run under `root_map.count_timeout` (0 = not measured this round) instead of unbounded. The topic map is capped at 256 KiB (issue #518; [operations](operations.md#the-linear-topic-map-is-capped-at-256-kib)): below the cap it is unchanged, above it each category lists its first titles and the map says so in its text. The response carries, additively, `listedBlocks` — the blocks the map this request wrote lists by line, `0` when it wrote none (`digest.mode` stub or off, an empty window) — and `truncated`, `true` when that map leaves blocks out. Before the cap a window past about 60,000 blocks answered `500` on every call. | | `POST /api/ingest` | Obsidian vault ingestion. **Write scope:** `target_scope` names the scope every chunk of the request is written to and is resolved like `scope` on `POST /api/store`: absent or empty means the key's home scope, and a scope outside the key's writable scopes refuses the whole request with `403`, code `scope_denied` (`Cannot write to requested scope`), before a chunk is written and before the `ingest` bucket is booked. The field `scope` is **not read** on this route: `ctx ingest` through 5.48.2 sends it on every request, `"private"` unless the user named another scope, and the server never read it; honouring it would refuse those runs for every key whose home scope is not `private`, or move them into `private` where the key may write it. A `200` answer carries `scope`, the scope the request wrote to; a server without that field ignores `target_scope` and writes to the key's home scope. Chunk mode (`source_id` + `chunk_index`) needs a `context_sources` row in the scope the request writes to and never overwrites another scope's chunk — absent, foreign or foreign-held all fail the chunk as `source not found`. A chunk whose `(category, title, scope)` another active block holds fails as `another active block in this scope already has this category and title — choose another category or title` (issue #275; before, `insert chunk failed`). ctxd has no endpoint that creates `context_sources` rows; a chunk-mode client needs one created out of band with that `scope` (since 5.29.1 a source in any other scope fails every chunk). **Per-chunk failures do not change the status code:** the request answers `200` with `success: false`, `failed > 0` and `results[i].status = "failed"` plus `results[i].error` for each failed chunk, next to the ones that were `inserted`/`updated`/`skipped` — a client must read the body, not the status. Batch-wide refusals carry their own status (`400`/`413` validation, `403` reserved namespace or `scope_denied`, `429` rate limit). The request body is capped at 10 MB; a body whose JSON does not end within the cap is refused whole with `413`, `request body exceeds 10 MB cap`, before a chunk is written (before, it answered `400`, `Invalid request body`, like a malformed body). Chunk content runs the credentials detector; each accepted request books the `ingest` bucket against `query.rate_limit_write` (429 past it). A block-mode write (no `source_id`) runs the type classifier on title and metadata like `POST /api/store`; a block whose `type_source` is `'manual'` keeps its type. The registry snapshot is resolved once per request, so every block-mode chunk of a batch is classified against the same rules. A chunk answers `skipped` when its content matches the live `(category, title, scope)` row and either the write would change nothing or the matched row is not its `(source_id, chunk_index)` slot as `InsertChunk` writes it (a block-mode row, another source's chunk, a row in that slot whose `lifecycle_state` is no longer `chunk`, or a `source_id` that is not a UUID), because such a write cannot land; the no-op predicate merges request metadata while an actual chunk write replaces it, so same-slot subset metadata can answer `skipped`, and unnamed keys are dropped only when a chunk is written. Chunk-mode writes do not run the classifier; a new chunk row starts with the default type. A chunk write that replaces the slot's title or content keeps the chunk's vector marked stale until the backfill embeds the new text, in the transaction of the write; one that re-sends the same title and content (new tags or metadata only) keeps the vector current (issue #236). | -| `POST /api/blob/*` | Binary storage (store/fetch/search/manage). Write rejections additionally carry a machine-readable `"code"` (Gap-C6-c): the closed vocabulary is `unauthorized`, `invalid_body`, `missing_fields`, `invalid_sensitivity`, `invalid_encoding`, `scope_denied`, `size_cap`, `unknown_type`, `reserved_type`, `parent_required`, `unknown_parent`, `unknown_supersedes`, `unknown_block`, `supersedes_conflict`, `supersedes_not_allowed`, `reserved_category`, `reserved_metadata`, `provenance_protected`, `unknown_action`, `edit_mismatch`, `constraint`, `rate_limit`, `write_conflict`, `internal` — one code per rejection class across `/api/store`, `/api/blob/store` and the MCP `store` tool (there as `structuredContent.code`, the `Content[0].Text` prose is unchanged; a STAGED answer is deliberately uncoded — IsError plus code means refused, IsError without code means staged). Answers without a code keep their exact pre-existing envelope (no empty `code` key). `store` runs on its OWN write budget: `pool.blob_rate_limit_write` (tenant-overridable, default 10) per api key and 60-second window, counted over the separate `blob-write` action in `context_access_log` — a key at its `query.rate_limit_write` block-write limit may still upload, and uploads never consume the block budget. `0`/unset falls back to the VALUE of `query.rate_limit_write` (unlimited needs BOTH at 0). The budget is booked BEFORE the upsert, so a write that ends in a constraint violation still costs it; over budget ⇒ **429**. Each stored blob leaves one audit row referencing it through `context_access_log.blob_id`, which is intentionally unconstrained — the row survives the blob's deletion. **MCP transport (W02-8):** `blob_store` / `blob_fetch` run this same write path — required fields, name caps, base64 decode, the `writableBlockScopes` gate and the `blob-write` budget are ONE shared core (`handler/blob_core.go`), so both surfaces answer the identical code and the identical prose for the identical request. `blob_store` takes the payload as `file` (base64, same `invalid_encoding` verdict) **or** `text` (UTF-8) — exactly one of the two — and takes an optional **`scope`** (E-M4, superseding decision D4, like the `store` tool): absent ⇒ the calling key's `home_scope`, named ⇒ gated through the same `writableBlockScopes` formula the REST route uses, ahead of the budget (`scope_denied` / `Cannot write to requested scope`). A `confirm_writes` key gets the call **staged** (a `payload_hash` instead of an id, `IsError=true`, executed by `confirm`), and a payload above `pool.blob_stage_max_bytes` (tenant-overridable, default 1 MiB; `0` disables blob staging for such keys entirely) is **refused by name** rather than written direct. The budget is charged at stage time, so the confirm books nothing. `blob_fetch` reads a **byte range** of the stored payload (`offset`/`length`, default 262144, max 1048576; a larger `length` is refused, never clamped, so a short answer always means the blob ended) and names its `encoding` (`text` when the window is valid UTF-8, else base64); `meta_only` returns metadata alone. The REST fetch route is unchanged and still answers the whole blob in one piece. **Payload scan + read gate (W02-9):** the shared write core runs the same credentials detector the block path has used since G40 over the decoded payload, on both surfaces, and records the verdict in the blob's JSONB `metadata` (no new column, no migration). It is KIND-differentiated: a structured signal (PEM private-key header, JWT, AWS key id, vendor token prefix, high-entropy secret assignment) sets `metadata.sensitivity` to `credentials` plus `metadata.sensitivity_kind`, upgrade-only over a caller-supplied value; a generic high-entropy hit (64+ hex run, base64 blob) raises NOTHING and is recorded in `metadata.entropy_flags`, because on a payload those artefacts are the evidence a drill-down came for, not a secret. A payload that is not valid UTF-8, or larger than `pool.blob_scan_max_bytes` (tenant-overridable, default 16 MiB; `0` turns the scan off), is STORED with `metadata.sensitivity = "unscanned"` — the write goes through, so binary uploads and the blobs that predate this path are never collateral. A `confirm_writes` key is scanned at STAGE time, so the verdict rides inside the `payload_hash` and confirming cannot alter it. On the read side `blob_fetch` does NOT return the payload of a blob whose `metadata.sensitivity` is `credentials` (named refusal, uncoded like every other fetch refusal); `meta_only` still answers, and a missing or `unscanned` field reads as deliverable — a blob is withheld because something was found, never because nothing was looked for. Every `blob_fetch` answer that carries content is framed for a model context: `untrusted: true`, an `origin` naming blob id/category/title/scope, and a `note` that the bytes are data and not instructions; `meta_only` carries no frame. The REST fetch route keeps all of this OUT — it is an operator path, not a model context, and answers the whole payload of a credentials blob unchanged. **Blob-to-block edge (W02-10):** `context_blobs.context_block_id` finally has a write path. Both store surfaces take an optional `context_block_id` (REST body field, MCP tool field), and the third MCP tool **`blob_link`** `{id, context_block_id}` sets it afterwards in ONE indexed `UPDATE` — no payload on the wire, `file_size`/`checksum`/`updated_at` untouched, which is what makes the two-phase write of a checkpoint (payload first, manifest block second, link third) cost one payload round trip instead of two. A link is a WRITE: it books one `blob-write` row like a store, and the blob must lie in the caller's `writableBlockScopes` — outside them it is `blob not found`, the same answer an id that belongs to nothing gets. The referenced BLOCK must be visible in the caller's read scopes; a block in a foreign scope, an id that exists nowhere and a malformed id all answer `422` / `constraint` / `Referenced context_block_id not found`, byte-identically, so the write surface is no existence oracle over foreign scopes (letting the foreign key decide would have answered *success* for the foreign block and `23503` for the absent one, and built a cross-scope edge on the way). A re-`blob_store` without the field CLEARS the edge — the row is what the last write said. `blob_store`, `blob_fetch` and `blob_link` answer `context_block_id` only when it is set. A `confirm_writes` key gets `blob_link` **staged** like every other write (op `blob_link`, staged under the BLOB's own scope, budget charged at stage time), and the confirm re-validates both the scope and the block's visibility on the un-consumed row. Deleting the block leaves the blob alive with a NULL edge (`ON DELETE SET NULL`). | +| `POST /api/blob/*` | Binary storage (store/fetch/search/manage). Write rejections additionally carry a machine-readable `"code"` (Gap-C6-c): the closed vocabulary is `unauthorized`, `invalid_body`, `missing_fields`, `invalid_sensitivity`, `invalid_encoding`, `scope_denied`, `size_cap`, `unknown_type`, `reserved_type`, `parent_required`, `unknown_parent`, `unknown_supersedes`, `unknown_block`, `supersedes_conflict`, `supersedes_not_allowed`, `reserved_category`, `reserved_metadata`, `provenance_protected`, `unknown_action`, `edit_mismatch`, `constraint`, `rate_limit`, `write_conflict`, `internal`, and the two classes of a request's scope narrowing, `scope_narrowing_invalid` and `scope_narrowing_route` ([below](#scope-narrowing-per-request)) — one code per rejection class across `/api/store`, `/api/blob/store` and the MCP `store` tool (there as `structuredContent.code`, the `Content[0].Text` prose is unchanged; a STAGED answer is deliberately uncoded — IsError plus code means refused, IsError without code means staged). Answers without a code keep their exact pre-existing envelope (no empty `code` key). `store` runs on its OWN write budget: `pool.blob_rate_limit_write` (tenant-overridable, default 10) per api key and 60-second window, counted over the separate `blob-write` action in `context_access_log` — a key at its `query.rate_limit_write` block-write limit may still upload, and uploads never consume the block budget. `0`/unset falls back to the VALUE of `query.rate_limit_write` (unlimited needs BOTH at 0). The budget is booked BEFORE the upsert, so a write that ends in a constraint violation still costs it; over budget ⇒ **429**. Each stored blob leaves one audit row referencing it through `context_access_log.blob_id`, which is intentionally unconstrained — the row survives the blob's deletion. **MCP transport (W02-8):** `blob_store` / `blob_fetch` run this same write path — required fields, name caps, base64 decode, the `writableBlockScopes` gate and the `blob-write` budget are ONE shared core (`handler/blob_core.go`), so both surfaces answer the identical code and the identical prose for the identical request. `blob_store` takes the payload as `file` (base64, same `invalid_encoding` verdict) **or** `text` (UTF-8) — exactly one of the two — and takes an optional **`scope`** (E-M4, superseding decision D4, like the `store` tool): absent ⇒ the calling key's `home_scope`, named ⇒ gated through the same `writableBlockScopes` formula the REST route uses, ahead of the budget (`scope_denied` / `Cannot write to requested scope`). A `confirm_writes` key gets the call **staged** (a `payload_hash` instead of an id, `IsError=true`, executed by `confirm`), and a payload above `pool.blob_stage_max_bytes` (tenant-overridable, default 1 MiB; `0` disables blob staging for such keys entirely) is **refused by name** rather than written direct. The budget is charged at stage time, so the confirm books nothing. `blob_fetch` reads a **byte range** of the stored payload (`offset`/`length`, default 262144, max 1048576; a larger `length` is refused, never clamped, so a short answer always means the blob ended) and names its `encoding` (`text` when the window is valid UTF-8, else base64); `meta_only` returns metadata alone. The REST fetch route is unchanged and still answers the whole blob in one piece. **Payload scan + read gate (W02-9):** the shared write core runs the same credentials detector the block path has used since G40 over the decoded payload, on both surfaces, and records the verdict in the blob's JSONB `metadata` (no new column, no migration). It is KIND-differentiated: a structured signal (PEM private-key header, JWT, AWS key id, vendor token prefix, high-entropy secret assignment) sets `metadata.sensitivity` to `credentials` plus `metadata.sensitivity_kind`, upgrade-only over a caller-supplied value; a generic high-entropy hit (64+ hex run, base64 blob) raises NOTHING and is recorded in `metadata.entropy_flags`, because on a payload those artefacts are the evidence a drill-down came for, not a secret. A payload that is not valid UTF-8, or larger than `pool.blob_scan_max_bytes` (tenant-overridable, default 16 MiB; `0` turns the scan off), is STORED with `metadata.sensitivity = "unscanned"` — the write goes through, so binary uploads and the blobs that predate this path are never collateral. A `confirm_writes` key is scanned at STAGE time, so the verdict rides inside the `payload_hash` and confirming cannot alter it. On the read side `blob_fetch` does NOT return the payload of a blob whose `metadata.sensitivity` is `credentials` (named refusal, uncoded like every other fetch refusal); `meta_only` still answers, and a missing or `unscanned` field reads as deliverable — a blob is withheld because something was found, never because nothing was looked for. Every `blob_fetch` answer that carries content is framed for a model context: `untrusted: true`, an `origin` naming blob id/category/title/scope, and a `note` that the bytes are data and not instructions; `meta_only` carries no frame. The REST fetch route keeps all of this OUT — it is an operator path, not a model context, and answers the whole payload of a credentials blob unchanged. **Blob-to-block edge (W02-10):** `context_blobs.context_block_id` finally has a write path. Both store surfaces take an optional `context_block_id` (REST body field, MCP tool field), and the third MCP tool **`blob_link`** `{id, context_block_id}` sets it afterwards in ONE indexed `UPDATE` — no payload on the wire, `file_size`/`checksum`/`updated_at` untouched, which is what makes the two-phase write of a checkpoint (payload first, manifest block second, link third) cost one payload round trip instead of two. A link is a WRITE: it books one `blob-write` row like a store, and the blob must lie in the caller's `writableBlockScopes` — outside them it is `blob not found`, the same answer an id that belongs to nothing gets. The referenced BLOCK must be visible in the caller's read scopes; a block in a foreign scope, an id that exists nowhere and a malformed id all answer `422` / `constraint` / `Referenced context_block_id not found`, byte-identically, so the write surface is no existence oracle over foreign scopes (letting the foreign key decide would have answered *success* for the foreign block and `23503` for the absent one, and built a cross-scope edge on the way). A re-`blob_store` without the field CLEARS the edge — the row is what the last write said. `blob_store`, `blob_fetch` and `blob_link` answer `context_block_id` only when it is set. A `confirm_writes` key gets `blob_link` **staged** like every other write (op `blob_link`, staged under the BLOB's own scope, budget charged at stage time), and the confirm re-validates both the scope and the block's visibility on the un-consumed row. Deleting the block leaves the blob alive with a NULL edge (`ON DELETE SET NULL`). | | `POST /api/img/sign` | Camo image-proxy **mint**, **auth-gated** + per-key rate-limited. Body `{urls:[…], origin:"assistant"}` ⇒ `{signatures:{url → "/api/img/<sig>?url=…&exp=…"}}`; non-proxiable URLs (relative, `data:`, `mailto:`, a query string, userinfo, an escaped path over 512 bytes) are omitted. `origin` is `assistant` (also the default when absent); any other value is **400**, including `issue`, which pre-upgrade bundles sent for issue markdown. One distinct URL per request; more is **400**. The SPA renderer has no signing secret, so it asks the server to sign the one foreign image URL the viewer clicked (see [Camo image proxy](#camo-image-proxy)). Off (404) unless `CTX_CAMO_ENABLED`. | | `GET /api/img/{sig}` | Camo image-proxy **fetch**, **unauthenticated** — a browser `<img>` carries no api key, so the HMAC-SHA256 signature (over `url`+`exp`, keyed by a labeled subkey of `CTX_SECRETS_KEY`) IS the capability. Verifies the sig BEFORE any upstream request (forged ⇒ **403**, expired ⇒ **410**, ZERO fetch either way), then fetches under an SSRF-guarded / redirect-hop-checked / size-capped / content-type-allowlisted policy (SVG excluded — XSS) and streams the bytes from `'self'` with `X-Content-Type-Options: nosniff` + immutable cache. Upstream failure ⇒ **502/415** + `no-store`, no substitute body. Re-hosts remote images so the SPA renders them under `img-src 'self'` WITHOUT widening the CSP, and the viewer's browser never talks to the foreign origin (see [Camo image proxy](#camo-image-proxy)). | | `POST /api/chat/stream` + `/api/chat/sessions[/{id}]` | Web-chat harness (see [Web chat sessions](#web-chat-sessions)). | @@ -55,6 +55,18 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. | `GET /authorize` + `POST /token` | OAuth 2.1 authorization (PKCE) + token exchange. `GET /authorize` validates `client_id` and `redirect_uri` before it renders the consent screen (client name, `client_id`, redirect origin, warning for self-registered clients); the `POST` needs `consent=yes` besides `api_key` — without it no code is issued. `/token` enforces the client's registered `grant_types`: no `refresh_token` in the set → the code exchange returns the access token alone and the refresh grant is `400 unauthorized_client` (DCR default: `authorization_code` + `refresh_token`). | | `GET /` (unregistered paths) | Embedded admin SPA (Svelte 5 + Vite, served from the binary). History-API fallback answers HTML navigations (`Accept: text/html`) only — mistyped API URLs stay 404 for JSON clients. Hashed `/assets/*` are immutable-cached and pre-compressed (`.br`/`.gz`); binaries built without the frontend serve a 503 placeholder while all APIs stay functional. See [development](development.md#web-ui-svelte-5--typescript--vite-bun). | +### Scope narrowing per request + +A request can narrow its key's rights to scopes it names, for that one request (multi-tenancy: [Per-request scope narrowing](multi-tenancy.md#per-request-scope-narrowing)). `X-Context-Read-Scopes: <scope>,<scope>,…` names 1 to 8 scopes, each one the key reads; the request reads those and nothing else — no other scope, no block grant —, in that order. `X-Context-Write-Scope: <scope>` names the one scope the request writes: it must be one of the read scopes and one the key may write (`write_scopes` in whoami without a narrowing); without it the request writes nothing (`/api/store` answers `403 scope_denied`). Every answer of an accepted narrowing carries `X-Context-Narrowed: <read scopes, comma-separated>;<write scope or empty>` — the read set as the request ran with it; a client that sent a narrowing and gets a 2xx answer without that header knows the narrowing was lost on the way. + +| Refusal | Status, code | +|---|---| +| `X-Context-Write-Scope` without `X-Context-Read-Scopes`; a header sent twice; an empty header or list element; a scope named twice; more than 8 read scopes | `400 scope_narrowing_invalid` | +| a read scope the key does not read; a write scope outside the read scopes or one the key cannot write | `403 scope_denied` | +| any route but `POST /api/query`, `POST /api/search`, `POST /api/store`, `GET /api/whoami`, `POST /api/manage` (method and path exactly, without percent escapes); on `/api/manage` any action but `get` and `type-list` | `403 scope_narrowing_route` | + +These are decided before the route's handler runs (the `manage` action after the body is decoded, on the one action the dispatcher runs). A narrowed request is never an administration request: it runs as a `member` without the server-admin tier. The key's home scope stays its own — the backend chain, the quota and the settings overlay of a narrowed request are the key's, whatever scope the narrowing names first. A request without the headers runs as before. + ### The write budget of a single update `manage` `update` and the MCP `update` tool count an update that changes the block as one write of the key's write budget (`query.rate_limit_write`), as a store and an update item of a batch count (issue #519). The count and the booking run inside the update's transaction under the key's advisory lock — the one a batch takes —, so the booking commits with the write or not at all, and two updates of one key at the edge of the window get exactly what is left. The update takes that lock last, once it has written its row (an update that does not fit rolls its write back), and holds it until its commit; an update of a key whose budget is already used up is refused before its statement, by a count without the lock, so it writes no row version first: an update waiting for a row another transaction holds keeps no other write of the key waiting, and an update that changes nothing never waits for the lock. An update that does not fit writes nothing and answers `429`, code `rate_limit`, `Rate limit exceeded: max <n> writes per 60 seconds` (MCP: `isError`, the same code and text). An update whose fields already hold what it sends — the batch's no-op test, `updated_at` aside — is still written as before but costs nothing and is not refused. A staged update (a `confirm_writes` key, the web chat's `ctx_update`) pays one write at stage time, in the stage's transaction, and its confirm books nothing; the web chat's staged `ctx_store` pays the same way. The internal writers (guard, dream, digest, forge sync, backfill) never pass through it. diff --git a/docs/mcp.md b/docs/mcp.md index 5ddb2c762..fef9ee5ba 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -109,7 +109,9 @@ The codes are the ones the HTTP API uses for the same class: `invalid_encoding`, `scope_denied`, `size_cap`, `unknown_type`, `reserved_type`, `parent_required`, `unknown_parent`, `unknown_supersedes`, `unknown_block`, `supersedes_conflict`, `supersedes_not_allowed`, `reserved_category`, `provenance_protected`, -`reserved_metadata`, `unknown_action`, `constraint`, `edit_mismatch`, `rate_limit`, `write_conflict`, `internal` +`reserved_metadata`, `unknown_action`, `constraint`, `edit_mismatch`, `rate_limit`, `write_conflict`, `internal`; +the HTTP answers `scope_narrowing_invalid` and `scope_narrowing_route` belong to a request's scope narrowing, +which `/mcp` refuses as a whole ([api](api.md#scope-narrowing-per-request)) (`TestRejectClassesAreDocumented` holds this list and the one in [api](api.md) to the classes of the handler). Other errors (an unknown id, an invalid type filter) carry text only, so a client must not rely on a code being present. A fault of the database under a diff --git a/docs/multi-tenancy.md b/docs/multi-tenancy.md index 674e7ead6..b2cb6211e 100644 --- a/docs/multi-tenancy.md +++ b/docs/multi-tenancy.md @@ -66,6 +66,14 @@ The web chat goes further (D-W6b): it is itself a harness **without** an own gat Since D-W6c ONE confirm sequence serves every surface: `confirm_core.go` holds the shared lookup → validate → D1-M1 scope re-check → D1-M3 TOCTOU re-check → atomic consume → execute chain, and the MCP `confirm` tool and `POST /api/confirm` only map its typed outcome onto their wordings (a server fault answers an opaque message on both and its cause goes to the log — until issue #275 MCP surfaced the raw error text —, while a refusal of the payload keeps its class and code on both; TOCTOU rejects answer HTTP 409). Some refusals come after the consume, because the statement that writes decides them on the row as it is then; each answers on both surfaces with its class and code and a message that says the stage token is consumed, so the caller stages the write again instead of retrying the token: a confirmed update the write refuses — the `(category, title, scope)` of another active block (409 / `constraint`, issue #227, [api](api.md#manage-actions)), a derivative, or a re-type of an issue or a comment — opens with `confirmed update not executed, the stage token is consumed:`; a confirmed store whose supersedes target changed since staging, whose identity belongs to a derivative, or that re-types an issue or a comment opens with `confirmed store not executed, the stage token is consumed:`; a confirmed `blob_store` that hits an integrity constraint opens with `confirmed blob_store not executed, the stage token is consumed:`. That makes the confirm surfaces interchangeable — a write staged over MCP confirms over HTTP and vice versa — and the chat gains `ctx_update` (staged field-level updates with the same `update_fields`/`base_updated_at` hash-bound form as the MCP update tool; the ConfirmCard shows the field list and the lost-update reject). +## Per-request scope narrowing + +A request can narrow its key to scopes it names, for that request alone: `X-Context-Read-Scopes` (1 to 8 scopes the key reads) and optionally `X-Context-Write-Scope` (one of them, which the key may write). The Auth middleware decides it before any handler runs (`handler.narrowAuth`) and hands the handlers a copy of the key's `AuthResult` in which `read_scopes` is the named set in header order, the server-admin tier is off and the tenant role is `member`; `AuthResult.Narrowed` carries the narrowing. Three places read it: `writableBlockScopes` (the request writes its write scope and nothing else), `resolveWriteScope` (a write without a scope goes to the write scope, and without one is refused `scope_denied`) and `resolveGrants` (no block grants). Everything else stays the key's — its `home_scope` above all, which the backend chain, the quota, the settings overlay and the archive read hang on, so a narrowing that names a granted scope first does not move the request into the granting tenant. The request key that `store.WithRequestKey` hands every write (issue #555) is the unnarrowed key's: a narrowing shrinks what the request may do, never what the write recheck holds the key to. + +The routes a narrowed request may take are a closed list — `POST /api/query`, `POST /api/search`, `POST /api/store`, `GET /api/whoami`, `POST /api/manage` with the actions `get` and `type-list` —, compared by method and exact path; everything else (`/mcp`, the batch and blob writes, `recent`, the session surface) answers `403 scope_narrowing_route`. A request without the headers runs as before. Whoami reports the narrowing (`narrowed`, and `read_scopes`, `write_scopes`, `admin`, `role` as the request runs with them); every answer of an accepted narrowing echoes it in `X-Context-Narrowed`. The wire rules and refusals: [api](api.md#scope-narrowing-per-request). + +What it is for: a client that serves several groups of people with one server names the scopes of the group it serves on every request and checks the echo, so each group reads and writes exactly its scopes, whatever else the key could read. + ## Block-level grants (row level) `context_block_grants` (migration 067) shares **one** `block_id` with a `grantee_tenant` — a granularity finer than the scope-level grants. `block_id` and `grantee_tenant` are both FK `ON DELETE CASCADE` (a deleted block or offboarded grantee drops its grants — contrast `context_dream_links`, which blocks the delete); `granted_by` is an `ON DELETE SET NULL` audit pointer; `uq_block_grant (block_id, grantee_tenant)` is the idempotency guard and `idx_block_grants_grantee (grantee_tenant, block_id)` the hot-read index. Deliberately **no `permission` column** (a single-value `'read'` enum gates nothing today — additive later). New table on an empty relation, so no `context_blocks` lock and no 1M index build. diff --git a/go/cmd/ctxd/narrowing_c1_integration_test.go b/go/cmd/ctxd/narrowing_c1_integration_test.go index 2066593d8..2f36f0284 100644 --- a/go/cmd/ctxd/narrowing_c1_integration_test.go +++ b/go/cmd/ctxd/narrowing_c1_integration_test.go @@ -1,4 +1,4 @@ -//go:build integration && s1red_c1 +//go:build integration // Achse 02, cluster C-1 (design2/02-ctx-checkpoint.md §3.5 C-1, §7.3): a // request narrows its key's rights to the scopes it names — X-Context-Read- @@ -116,8 +116,8 @@ func c1EmbedHost(t *testing.T) string { } // c1Router builds the production router on a fresh database, with an embed -// backend, and the bootstrap admin key. -func c1Router(t *testing.T) (*pgxpool.Pool, http.Handler) { +// backend (plus extra, when given), and the bootstrap admin key. +func c1Router(t *testing.T, extra ...backends.Backend) (*pgxpool.Pool, http.Handler) { t.Helper() pool := testdb.SetupTestDB(t) ctx, cancel := context.WithCancel(context.Background()) @@ -134,12 +134,12 @@ func c1Router(t *testing.T) (*pgxpool.Pool, http.Handler) { cfgStore.SetOverlay(settings.TenantOverlay(pool)) backendPool := backends.NewPool(pool, nil) host := c1EmbedHost(t) - backendPool.SeedSnapshotForTest([]backends.Backend{ + backendPool.SeedSnapshotForTest(append([]backends.Backend{ {ID: "c1-embed", Name: "c1-embed", Scope: "_global", Host: host, Protocol: backends.ProtocolOllama, Model: "test-embed", Trust: backends.TrustFull, Enabled: true, Priority: 1, Roles: []string{backends.RoleEmbed}}, {ID: "c1-chat", Name: "c1-chat", Scope: "_global", Host: host, Protocol: backends.ProtocolOllama, Model: "test-chat", Trust: backends.TrustFull, Enabled: true, Priority: 1, Roles: []string{backends.RoleTranslate}}, - }) + }, extra...)) scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) projectHub := events.NewProjectHub(ctx, pool, cfgStore) d := dispatch.New(nil, dispatch.DefaultSettings()) @@ -235,9 +235,9 @@ func (w *c1World) mintKey(t *testing.T, data map[string]any) string { return k } -func c1Setup(t *testing.T) *c1World { +func c1Setup(t *testing.T, extra ...backends.Backend) *c1World { t.Helper() - pool, router := c1Router(t) + pool, router := c1Router(t, extra...) w := &c1World{pool: pool, router: router, keys: map[string]string{}, blocks: map[string]string{}} for _, n := range []string{"k", "m"} { w.manage(t, c1AdminKey, nil, map[string]any{"action": "scope-create", "data": map[string]any{"name": n}}).must(t, "scope-create "+n) diff --git a/go/cmd/ctxd/narrowing_c1_more_integration_test.go b/go/cmd/ctxd/narrowing_c1_more_integration_test.go new file mode 100644 index 000000000..9dacc1758 --- /dev/null +++ b/go/cmd/ctxd/narrowing_c1_more_integration_test.go @@ -0,0 +1,138 @@ +//go:build integration + +// Achse 02, cluster C-1, the negative probes of design2/02 §7.3 the S1 file +// (narrowing_c1_integration_test.go) leaves open: a read scope named twice, +// the read set whoami reports under a narrowing, and the pin "a grant scope +// first leaves the backend chain, the quota and the settings overlay the +// key's own" (all three hang on AuthResult.HomeScope, which a narrowing never +// rewrites). Same fixture, same production router. +// +// go test -tags=integration -p 1 -count=1 -run '^TestC1' ./cmd/ctxd/ +package main + +import ( + "context" + "net/http" + "slices" + "testing" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/llmlog" +) + +// TestC1ReadScopeNamedTwiceIsInvalid: a read scope that occurs twice in +// X-Context-Read-Scopes is 400 scope_narrowing_invalid, before any handler +// runs — the echo would otherwise not say which set the request read. +func TestC1ReadScopeNamedTwiceIsInvalid(t *testing.T) { + w := c1Setup(t) + for _, read := range []string{"work,work", "work,shared,work"} { + h := c1Narrow(read) + c1WantRefused(t, read+" (whoami)", w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], h, nil), http.StatusBadRequest, "scope_narrowing_invalid") + title := "c1 twice " + read + c1WantRefused(t, read+" (store)", w.do(t, http.MethodPost, "/api/store", w.keys["w"], c1Narrow(read, "work"), + map[string]any{"category": "learnings", "title": title, "content": "x"}), http.StatusBadRequest, "scope_narrowing_invalid") + if n := w.c1Count(t, title); n != 0 { + t.Errorf("%s: %d block(s) written, want none", read, n) + } + } +} + +// TestC1WhoamiReadScopesAreTheNarrowing: under a narrowing whoami reports the +// request's read set, in header order — not the key's — and the key's home +// scope. +func TestC1WhoamiReadScopesAreTheNarrowing(t *testing.T) { + w := c1Setup(t) + r := w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], c1Narrow("shared,"+w.two), nil) + if r.status != http.StatusOK { + t.Fatalf("narrowed whoami: HTTP %d %s", r.status, r.raw) + } + if got := c1Strings(r.body["read_scopes"]); !slices.Equal(got, []string{"shared", w.two}) { + t.Errorf("narrowed whoami: read_scopes %v, want [shared %s]", got, w.two) + } + if r.body["home_scope"] != "work" { + t.Errorf("narrowed whoami: home_scope %v, want work", r.body["home_scope"]) + } +} + +// TestC1GrantScopeFirstKeepsTheKeysSettingsOverlay: the tenant overlay a +// request reads hangs on the key's home scope (handler.RequestTenantScope); +// a narrowing that names the granting tenant's scope first does not move the +// request into that tenant's settings — rate_limit_write stays the key's. +func TestC1GrantScopeFirstKeepsTheKeysSettingsOverlay(t *testing.T) { + w := c1Setup(t) + w.do(t, http.MethodPut, "/api/settings/query.rate_limit_write", w.keys["two"], nil, map[string]any{"value": 40}).must(t, "tenant overlay of query.rate_limit_write") + if b := w.do(t, http.MethodGet, "/api/whoami", w.keys["two"], nil, nil).must(t, "owner whoami").body; b["rate_limit_write"] != float64(40) { + t.Fatalf("fixture: tenant c1two reads rate_limit_write %v, want its overlay 40", b["rate_limit_write"]) + } + r := w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], c1Narrow(w.two+",work"), nil) + if r.status != http.StatusOK || r.body["rate_limit_write"] != float64(100) { + t.Errorf("whoami of key w narrowed to %s,work: HTTP %d rate_limit_write %v, want 200 and 100 (the default tenant's)", w.two, r.status, r.body["rate_limit_write"]) + } +} + +// c1EmbedAttempts counts the query-embed rows of key keyID whose chain tried +// backend: llmlog writes one row per question embed that went on the wire, +// with every attempt of the walk in metadata.chain. +func (w *c1World) c1EmbedAttempts(t *testing.T, keyID, backend string) (rows, tried int) { + t.Helper() + ctx := context.Background() + if err := llmlog.Settle(ctx, w.pool); err != nil { + t.Fatal(err) + } + if err := w.pool.QueryRow(ctx, `SELECT count(*), count(*) FILTER (WHERE metadata->'chain' @> jsonb_build_array(jsonb_build_object('backend', $2::text))) + FROM context_llm_log WHERE pipeline = 'query-embed' AND api_key_id = $1::uuid`, keyID, backend).Scan(&rows, &tried); err != nil { + t.Fatal(err) + } + return rows, tried +} + +// c1TwoEmbed is an embed backend of tenant c1two, ranked above the global +// one. Its host is a loopback address, which the egress guard of tenant +// backends refuses to dial: a walk that tries it records the attempt +// (err_class transport), cools the backend down and falls back to the global +// backend, so every query still answers. +var c1TwoEmbed = backends.Backend{ID: "c1two-embed", Name: "c1two-embed", Scope: "c1two:main", Host: "http://127.0.0.1:9", + Protocol: backends.ProtocolOllama, Model: "c1two-embed-model", Trust: backends.TrustFull, Enabled: true, + Priority: 9, Roles: []string{backends.RoleEmbed}} + +// TestC1PinGrantScopeFirstUsesTheKeysBackendChain (green before C-1 on +// purpose, a mutant catcher): the embed chain — and with it the quota gate — +// of a query is resolved for the key's home scope. A query of key w narrowed +// to tenant c1two's scope FIRST still embeds its question on the global chain +// alone; a narrowing that made its first read scope the home scope would walk +// c1two's backend (and book c1two's quota). The question is embedded before +// the query's backfill, which may then try c1two's backend for c1two's own +// blocks — that is the owner's chain and no part of the pin. The fixture +// control runs on a world of its own (a tried backend cools down and then +// sorts last): there the owner's question does walk c1two's backend. +func TestC1PinGrantScopeFirstUsesTheKeysBackendChain(t *testing.T) { + keyID := func(w *c1World, key string) string { + id, _ := w.do(t, http.MethodGet, "/api/whoami", key, nil, nil).must(t, "whoami").body["api_key_id"].(string) + return id + } + + ctl := c1Setup(t, c1TwoEmbed) + if ctl.two != c1TwoEmbed.Scope { + t.Fatalf("fixture: tenant c1two's scope is %q, the backend is scoped to %s", ctl.two, c1TwoEmbed.Scope) + } + ctl.do(t, http.MethodPost, "/api/query", ctl.keys["two"], nil, + map[string]any{"query": "chainprobe bravo", "synthesize": false}).must(t, "the owner's query") + if _, tried := ctl.c1EmbedAttempts(t, keyID(ctl, ctl.keys["two"]), c1TwoEmbed.Name); tried == 0 { + t.Fatalf("fixture: the owner's question never tried tenant c1two's backend — the pin below would prove nothing") + } + + w := c1Setup(t, c1TwoEmbed) + r := w.do(t, http.MethodPost, "/api/query", w.keys["w"], c1Narrow(w.two+",work"), + map[string]any{"query": "chainprobe alpha", "synthesize": false}) + if r.status != http.StatusOK { + t.Fatalf("narrowed query of key w: HTTP %d %s", r.status, r.raw) + } + c1WantEcho(t, "narrowed query", r, w.two+",work;") + rows, tried := w.c1EmbedAttempts(t, keyID(w, w.keys["w"]), c1TwoEmbed.Name) + if rows == 0 { + t.Fatalf("fixture: the narrowed query of key w left no query-embed row — the pin proves nothing") + } + if tried != 0 { + t.Errorf("the question of key w (narrowed to %s first) walked tenant c1two's backend in %d of %d embed(s), want 0 — the chain must stay the key's", w.two, tried, rows) + } +} diff --git a/go/cmd/ctxd/server.go b/go/cmd/ctxd/server.go index acea275d0..e03ae599e 100644 --- a/go/cmd/ctxd/server.go +++ b/go/cmd/ctxd/server.go @@ -249,7 +249,8 @@ func buildRouter(ctx context.Context, pool *pgxpool.Pool, cfgStore *config.Store return err }) // W05-01: capabilities.model_api reads the _global gateway policy per request. - whoamiH := handler.NewWhoamiHandler(pool, whoamiModelAPIGetter(cfgStore)) + // Achse 02 C-1: rate_limit_write reads the request's tenant-resolved snapshot. + whoamiH := handler.NewWhoamiHandler(pool, whoamiModelAPIGetter(cfgStore)).WithConfig(cfgStore) // Camo image proxy service (design 07-camo). Fail-closed: disabled unless // CTX_CAMO_ENABLED is set AND the sealbox master key is present; a misconfig // logs and disables rather than crashing boot. Shared by both /api/img routes. diff --git a/go/internal/handler/context_store.go b/go/internal/handler/context_store.go index e6b80bb7a..c92a94a3a 100644 --- a/go/internal/handler/context_store.go +++ b/go/internal/handler/context_store.go @@ -434,7 +434,15 @@ func contains(slice []string, val string) bool { // write_scope left STALE by a later allowed_scopes shrink falls out of the // intersection HERE — fail-closed at one eval point, not re-checked at N write // sites. Other allowed_scopes with no matching write_scope stay read-only. +// +// A narrowed request (Achse 02 C-1) writes exactly its narrowing's write +// scope and nothing else: its set is Narrowed.Writable ([Write], or empty +// when the request names none). narrowAuth admitted that scope only if it +// lies in this formula's set of the unnarrowed key. func writableBlockScopes(ar *auth.AuthResult) []string { + if ar.Narrowed != nil { + return ar.Narrowed.Writable + } scopes := []string{ar.HomeScope} if contains(ar.AllowedScopes, "shared") { scopes = append(scopes, "shared") @@ -472,8 +480,18 @@ func writableBlockScopes(ar *auth.AuthResult) []string { // that has to know the resolved scope before the gate chain runs (the MCP // store tool's scoped hash-NOOP check) may call it twice without risking a // second, disagreeing verdict. +// +// A narrowed request resolves an absent scope to its narrowing's write scope +// instead of the home scope, and without one it writes nothing: the write is +// refused with the same scope_denied verdict. func resolveWriteScope(ar *auth.AuthResult, requested string) (scope string, explicit bool, rej *writeReject) { if requested == "" { + if ar.Narrowed != nil { + if ar.Narrowed.Write == "" { + return "", false, classScopeDenied.reject("This narrowed request names no write scope (" + HeaderWriteScope + ")") + } + return ar.Narrowed.Write, false, nil + } return ar.HomeScope, false, nil } if !contains(writableBlockScopes(ar), requested) { diff --git a/go/internal/handler/errcode.go b/go/internal/handler/errcode.go index 17111528a..887a2667e 100644 --- a/go/internal/handler/errcode.go +++ b/go/internal/handler/errcode.go @@ -22,7 +22,9 @@ // the `confirm`/`update` tools keep their uncoded envelopes; coding them is a // separate sweep, not this one. Classes added to those surfaces later arrive // coded (provenance_protected; the issue #227 identity collision as -// constraint). +// constraint). The per-request narrowing (Achse 02, narrowing.go) answers +// from the Auth middleware, on every route, with scope_denied and its own +// classes; they are listed here so the vocabulary stays one table. package handler import ( @@ -123,6 +125,17 @@ var ( classReservedMetadata = rejectClass{http.StatusForbidden, "reserved_metadata"} // classUnknownAction — the dispatcher has no handler for `action`. classUnknownAction = rejectClass{http.StatusBadRequest, "unknown_action"} + // classScopeNarrowingInvalid — the narrowing headers of a request + // (X-Context-Read-Scopes, X-Context-Write-Scope; Achse 02 C-1) are + // malformed: a write scope without read scopes, a header sent twice, an + // empty header or list element, a scope named twice, more than eight read + // scopes. Decided in the Auth middleware, on every route. + classScopeNarrowingInvalid = rejectClass{http.StatusBadRequest, "scope_narrowing_invalid"} + // classScopeNarrowingRoute — a narrowed request on a route, or an + // /api/manage action, outside the narrowing's closed list (narrowing.go). + // A separate code from scope_denied: the scopes are fine, the route is + // not one a narrowed request may take. + classScopeNarrowingRoute = rejectClass{http.StatusForbidden, "scope_narrowing_route"} // classEditMismatch — an edit of an update (issue #406) does not match the // block's content: its old occurs zero times, or more than once without // replace_all. 409 like supersedes_conflict: the payload is well-formed, the diff --git a/go/internal/handler/get_archived.go b/go/internal/handler/get_archived.go index 4251b0c1a..4da33db54 100644 --- a/go/internal/handler/get_archived.go +++ b/go/internal/handler/get_archived.go @@ -56,5 +56,12 @@ func readBlockForGet(ctx context.Context, pool *pgxpool.Pool, set *blocktype.Set if err != nil || block != nil || !includeArchived { return block, err } - return store.GetArchivedBlock(ctx, pool, set, id, ownReadScopes(ar), omit) + // A narrowed request (Achse 02 C-1) may name only granted scopes; then it + // has no own scope to read archived rows of, and the block is not found — + // an empty set must not reach the store, whose scope guard refuses it. + own := ownReadScopes(ar) + if len(own) == 0 { + return nil, nil + } + return store.GetArchivedBlock(ctx, pool, set, id, own, omit) } diff --git a/go/internal/handler/mcp.go b/go/internal/handler/mcp.go index 87d0fa08c..d51dda2f9 100644 --- a/go/internal/handler/mcp.go +++ b/go/internal/handler/mcp.go @@ -1223,7 +1223,13 @@ const tooManyGrantsMsg = "too many block grants for this tenant: the row-level g // already short-circuits an empty/whitespace tenantID to []string{}, so passing // ar.TenantID directly preserves the intended semantics (empty tenant ⇒ '{}' // ⇒ no-op OR-arm) without a nil deref. design/07 §4.1. +// +// A narrowed request (Achse 02 C-1) reads its named scopes and nothing else: +// it gets no block grants, without a lookup. func resolveGrants(ctx context.Context, pool *pgxpool.Pool, ar *auth.AuthResult) ([]string, error) { + if ar.Narrowed != nil { + return []string{}, nil + } grants, err := store.GrantedBlockIDs(ctx, pool, ar.TenantID) if err != nil { if errors.Is(err, store.ErrTooManyBlockGrants) { diff --git a/go/internal/handler/middleware.go b/go/internal/handler/middleware.go index 8137c8467..a1cfe21a8 100644 --- a/go/internal/handler/middleware.go +++ b/go/internal/handler/middleware.go @@ -698,12 +698,13 @@ func Auth(pool *pgxpool.Pool) func(http.Handler) http.Handler { // Per-request narrowing (Achse 02 C-1, narrowing.go): the handlers // see the narrowed AuthResult; the request key below stays the - // key's own. + // key's own. Every answer of an accepted narrowing carries its echo. narrowed, rej := narrowAuth(r, result) if rej != nil { writeJSONReject(w, rej) return } + setNarrowingEcho(w, narrowed) ctx := context.WithValue(r.Context(), authResultKey, narrowed) // The request's key and the scopes it granted travel to every diff --git a/go/internal/handler/narrowing.go b/go/internal/handler/narrowing.go index 5a7736bbe..ee3bdee50 100644 --- a/go/internal/handler/narrowing.go +++ b/go/internal/handler/narrowing.go @@ -4,14 +4,19 @@ // key's rights shrink to exactly these. The key's own scopes stay what the // write recheck of issue #555 (store.WithRequestKey) checks against. // -// S1 contract: the signatures below are fixed, the bodies are inert — the -// headers are ignored and every request runs unnarrowed, byte-identical to the -// tree before this file. C-1 fills them in; C-2 adds the required-narrowing -// check to narrowAuth. +// The narrowing is decided once, in the Auth middleware (narrowAuth), before +// any handler runs: the header form, the read scopes against the key's read +// set, the write scope against the key's own writable set, and the route +// against a closed list. The handlers see a narrowed AuthResult and read +// their scopes from it as they always do; three places read the narrowing +// itself — writableBlockScopes and resolveWriteScope (context_store.go) and +// resolveGrants (mcp.go) — and handleManage checks the one decoded action. package handler import ( "net/http" + "strconv" + "strings" "github.com/GottZ/ctx/internal/auth" ) @@ -26,40 +31,147 @@ const ( HeaderNarrowed = "X-Context-Narrowed" ) -// codeScopeNarrowingRoute is the code of the refusal of a narrowed request on -// a route or /api/manage action outside the narrowing's closed list. It is not -// a rejectClass of errcode.go yet: a class there is closed vocabulary that -// docs/api.md and docs/mcp.md list (TestRejectClassesAreDocumented), and the -// documentation is C-1's. C-1 moves it into errcode.go next to its -// documentation. -const codeScopeNarrowingRoute = "scope_narrowing_route" +// maxNarrowedReadScopes is the most read scopes one narrowing names +// (design2/02 §3.5 C-1). Fixed on purpose: a narrowing is the read set of one +// group binding, and the bound keeps the echo and the per-request set +// comparison small. +const maxNarrowedReadScopes = 8 + +// narrowedRoutes is the closed list of routes a narrowed request may take, +// method and path compared byte for byte: query, search, store, whoami and +// manage (whose action handleManage checks against narrowedManageActions). +// Every other route — /mcp, the batch and blob writes, recent, the session +// surface — answers scope_narrowing_route. +var narrowedRoutes = map[string]bool{ + http.MethodPost + " /api/query": true, + http.MethodPost + " /api/search": true, + http.MethodPost + " /api/store": true, + http.MethodGet + " /api/whoami": true, + http.MethodPost + " /api/manage": true, +} + +// narrowedManageActions are the /api/manage actions a narrowed request may +// run: the block read by id and the block-type list. +var narrowedManageActions = map[string]bool{ + "get": true, + "type-list": true, +} // narrowAuth derives the AuthResult a request runs with from the key's // AuthResult ar and the narrowing headers of r. It returns the AuthResult to // hand to the handlers (ar itself when the request carries no narrowing) or a // refusal the Auth middleware answers with. It never modifies ar. // -// S1 stub: the headers are ignored, every request is unnarrowed. +// A narrowed AuthResult is a copy of ar in which ReadScopes is the named read +// set (in header order), IsAdmin is false and TenantRole is member — a +// narrowed request is never an administration request — and Narrowed carries +// the narrowing. Everything else stays the key's: HomeScope (backend chain, +// quota, the settings overlay and the archive read hang on it), the raw +// AllowedScopes and WriteScopes, the tenant, the principal and the key id. func narrowAuth(r *http.Request, ar *auth.AuthResult) (*auth.AuthResult, *writeReject) { - return ar, nil + reads, writes := r.Header.Values(HeaderReadScopes), r.Header.Values(HeaderWriteScope) + if len(reads) == 0 { + if len(writes) > 0 { + return nil, classScopeNarrowingInvalid.reject(HeaderWriteScope + " needs " + HeaderReadScopes) + } + return ar, nil + } + n, rej := parseNarrowing(reads, writes) + if rej != nil { + return nil, rej + } + for _, s := range n.Read { + if !contains(ar.ReadScopes, s) { + return nil, classScopeDenied.reject("Cannot read the requested scope: " + s) + } + } + if n.Write != "" { + // The write scope is one the request also reads, and one the KEY may + // write (its unnarrowed writable set): a narrowing never widens. + if !contains(n.Read, n.Write) || !contains(writableBlockScopes(ar), n.Write) { + return nil, classScopeDenied.reject("Cannot write to requested scope: " + n.Write) + } + n.Writable = []string{n.Write} + } + if !narrowedRouteAllowed(r) { + return nil, classScopeNarrowingRoute.reject(narrowingRouteMsg) + } + out := *ar + out.ReadScopes = n.Read + out.IsAdmin = false + out.TenantRole = auth.RoleMember + out.Narrowed = n + return &out, nil +} + +// parseNarrowing reads the header values into a Narrowing: exactly one read +// header with 1 to maxNarrowedReadScopes distinct, non-empty scopes, and at +// most one non-empty write header. Spaces around a list element are dropped. +// Writable stays empty; narrowAuth fills it once the write scope is allowed. +func parseNarrowing(reads, writes []string) (*auth.Narrowing, *writeReject) { + if len(reads) != 1 || len(writes) > 1 { + return nil, classScopeNarrowingInvalid.reject("each narrowing header may occur once") + } + parts := strings.Split(reads[0], ",") + if len(parts) > maxNarrowedReadScopes { + return nil, classScopeNarrowingInvalid.reject(HeaderReadScopes + " names more than " + strconv.Itoa(maxNarrowedReadScopes) + " scopes") + } + n := &auth.Narrowing{Read: make([]string, 0, len(parts)), Writable: []string{}} + for _, p := range parts { + s := strings.TrimSpace(p) + if s == "" { + return nil, classScopeNarrowingInvalid.reject(HeaderReadScopes + " has an empty element") + } + if contains(n.Read, s) { + return nil, classScopeNarrowingInvalid.reject(HeaderReadScopes + " names a scope twice: " + s) + } + n.Read = append(n.Read, s) + } + if len(writes) == 1 { + n.Write = strings.TrimSpace(writes[0]) + if n.Write == "" { + return nil, classScopeNarrowingInvalid.reject(HeaderWriteScope + " is empty") + } + } + return n, nil +} + +// narrowedRouteAllowed reports whether r's method and path are on +// narrowedRoutes. A path the client sent with percent escapes is refused: +// the router matches the escaped form (chi routes on URL.RawPath when it is +// set), so the decoded path would not say which route runs. +func narrowedRouteAllowed(r *http.Request) bool { + if r.URL.RawPath != "" { + return false + } + return narrowedRoutes[r.Method+" "+r.URL.Path] +} + +// setNarrowingEcho puts the echo of ar's narrowing on the answer, when ar is +// narrowed: the read set as the request runs with it and the write scope, +// "<read,…>;<write>". The Auth middleware sets it before the handler runs, so +// every answer of an accepted narrowing carries it, a handler's refusal +// included; a narrowing narrowAuth refuses gets no echo. +func setNarrowingEcho(w http.ResponseWriter, ar *auth.AuthResult) { + if ar.Narrowed == nil { + return + } + w.Header().Set(HeaderNarrowed, strings.Join(ar.Narrowed.Read, ",")+";"+ar.Narrowed.Write) } // manageActionAllowedNarrowed reports whether a narrowed /api/manage request -// may run action — the one action the dispatcher decoded (BP-25). C-1: only -// "get" and "type-list". -// -// S1 stub: no request is narrowed yet, so the dispatcher never asks; every -// action is allowed. +// may run action — the one action the dispatcher decoded (BP-25): only "get" +// and "type-list". func manageActionAllowedNarrowed(action string) bool { - return true + return narrowedManageActions[action] } +// narrowingRouteMsg is the text of every scope_narrowing_route refusal. +const narrowingRouteMsg = "this route is not available to a narrowed request" + // writeNarrowingRouteRefused answers a narrowed request whose route or manage // action lies outside the narrowing's closed list: 403 with the house // {"success":false,"error":…} envelope and the code scope_narrowing_route. func writeNarrowingRouteRefused(w http.ResponseWriter) { - writeJSONCode(w, http.StatusForbidden, codeScopeNarrowingRoute, map[string]any{ - "success": false, - "error": "this route is not available to a narrowed request", - }) + writeJSONReject(w, classScopeNarrowingRoute.reject(narrowingRouteMsg)) } diff --git a/go/internal/handler/narrowing_test.go b/go/internal/handler/narrowing_test.go new file mode 100644 index 000000000..030da8166 --- /dev/null +++ b/go/internal/handler/narrowing_test.go @@ -0,0 +1,98 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "slices" + "testing" + + "github.com/GottZ/ctx/internal/auth" +) + +// narrowKey is a key with every field a narrowing may or may not touch set. +func narrowKey() *auth.AuthResult { + return &auth.AuthResult{ + ApiKeyID: "11111111-1111-1111-1111-111111111111", + HomeScope: "work", + AllowedScopes: []string{"shared", "default:k"}, + ReadScopes: []string{"work", "shared", "default:k", "two:main"}, + IsValid: true, + IsAdmin: true, + TenantID: "00000000-0000-0000-0000-0000000d3fa0", + TenantRole: auth.RoleOwner, + WriteScopes: []string{"default:k"}, + ConfirmWrites: true, + PrincipalID: "22222222-2222-2222-2222-222222222222", + } +} + +func narrowReq(method, target, read, write string) *http.Request { + r := httptest.NewRequest(method, target, nil) + if read != "" { + r.Header.Set(HeaderReadScopes, read) + } + if write != "" { + r.Header.Set(HeaderWriteScope, write) + } + return r +} + +// TestNarrowAuthLeavesTheKeyAlone: an unnarrowed request runs with the key's +// own AuthResult (the same pointer); a narrowed one gets a copy in which only +// the read set, the admin tier and the tenant role change — home scope, +// allowed and write scopes, tenant, principal and key id stay the key's +// (backend chain, quota, settings overlay and the #555 recheck hang on them) +// — and the key's AuthResult itself is not modified. +func TestNarrowAuthLeavesTheKeyAlone(t *testing.T) { + ar := narrowKey() + got, rej := narrowAuth(narrowReq(http.MethodPost, "/api/search", "", ""), ar) + if rej != nil || got != ar { + t.Fatalf("unnarrowed: got %p (rej %v), want the key's own AuthResult %p", got, rej, ar) + } + + got, rej = narrowAuth(narrowReq(http.MethodPost, "/api/store", "two:main,default:k", "default:k"), ar) + if rej != nil { + t.Fatalf("narrowed: refused %+v", rej) + } + if got == ar { + t.Fatal("narrowed: the key's own AuthResult came back") + } + if !slices.Equal(got.ReadScopes, []string{"two:main", "default:k"}) || got.IsAdmin || got.TenantRole != auth.RoleMember { + t.Errorf("narrowed: read %v admin %v role %q, want [two:main default:k] false member", got.ReadScopes, got.IsAdmin, got.TenantRole) + } + if got.HomeScope != "work" || !slices.Equal(got.AllowedScopes, ar.AllowedScopes) || !slices.Equal(got.WriteScopes, ar.WriteScopes) || + got.TenantID != ar.TenantID || got.PrincipalID != ar.PrincipalID || got.ApiKeyID != ar.ApiKeyID || !got.ConfirmWrites || !got.IsValid { + t.Errorf("narrowed: a field of the key changed: %+v", got) + } + n := got.Narrowed + if n == nil || !slices.Equal(n.Read, []string{"two:main", "default:k"}) || n.Write != "default:k" || !slices.Equal(n.Writable, []string{"default:k"}) { + t.Errorf("narrowed: Narrowed %+v, want read [two:main default:k], write default:k, writable [default:k]", n) + } + if want := narrowKey(); !slices.Equal(ar.ReadScopes, want.ReadScopes) || !ar.IsAdmin || ar.TenantRole != auth.RoleOwner || ar.Narrowed != nil { + t.Errorf("the key's AuthResult was modified: %+v", ar) + } +} + +// TestNarrowAuthRefusesAnEscapedPath: the route rule compares the request +// path byte for byte, and a path sent with percent escapes is refused — the +// router matches the escaped form (chi routes on RawPath), so a decoded path +// that reads like a listed route does not say which handler runs. +func TestNarrowAuthRefusesAnEscapedPath(t *testing.T) { + for _, target := range []string{"/api/who%61mi", "/api/%73earch", "/api%2Fsearch"} { + r := narrowReq(http.MethodPost, target, "work", "") + if target == "/api/who%61mi" { + r.Method = http.MethodGet + } + if r.URL.RawPath == "" { + t.Fatalf("premise: %s parses without RawPath", target) + } + _, rej := narrowAuth(r, narrowKey()) + if rej == nil || rej.Status != http.StatusForbidden || rej.Code != "scope_narrowing_route" { + t.Errorf("%s narrowed: %+v, want 403 scope_narrowing_route", target, rej) + } + } + // The method is part of the rule. + if _, rej := narrowAuth(narrowReq(http.MethodHead, "/api/whoami", "work", ""), narrowKey()); rej == nil || rej.Code != "scope_narrowing_route" { + t.Errorf("HEAD /api/whoami narrowed: %+v, want 403 scope_narrowing_route", rej) + } +} diff --git a/go/internal/handler/whoami.go b/go/internal/handler/whoami.go index 1928dc97f..42b877718 100644 --- a/go/internal/handler/whoami.go +++ b/go/internal/handler/whoami.go @@ -13,6 +13,8 @@ import ( "net/http" "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/auth" ) // whoamiResponse is the GET /api/whoami wire envelope (design 04-§3.2). @@ -68,6 +70,30 @@ type whoamiResponse struct { // model_api (W05-01) carries the gateway policy the same way: data the // SPA derives its model-API caps from, never an authorisation input. Capabilities whoamiCapabilities `json:"capabilities"` + // WriteScopes is the request's effective write set (writableBlockScopes): + // home scope first, then shared and the write_scopes the key may also + // read; under a narrowing (Achse 02 C-1) its write scope alone, or none. + // Additive read, appended after capabilities like the fields below. + WriteScopes []string `json:"write_scopes"` + // ConfirmWrites is the key's stage-then-confirm opt-in (090). + ConfirmWrites bool `json:"confirm_writes"` + // Narrowed is the request's narrowing (X-Context-Read-Scopes / + // X-Context-Write-Scope): the read set in header order and the write + // scope ("" when none), or null for an unnarrowed request. Under a + // narrowing read_scopes is that read set too, admin is false and role is + // member — a client binding a group reads both answers, narrowed and not. + Narrowed *whoamiNarrowed `json:"narrowed"` + // RateLimitWrite is the write budget per key and 60 s that applies to + // this key: query.rate_limit_write after the overlay of the key's tenant + // (0 = unlimited). A client that paces its writes reads it here instead + // of planning with the default. + RateLimitWrite int `json:"rate_limit_write"` +} + +// whoamiNarrowed is the narrowed field of whoami (Achse 02 C-1). +type whoamiNarrowed struct { + Read []string `json:"read"` + Write string `json:"write"` } // whoamiCapabilities is the whoami feature-flag bag (design 04-§3.2 B9). @@ -126,6 +152,10 @@ type WhoamiHandler struct { // request (the gateway.* keys are hot). cmd/ctxd builds it from the // _global snapshot; nil leaves the bag at its zero value. modelAPI func() WhoamiModelAPI + // cfg is the source of rate_limit_write (the request's tenant-resolved + // snapshot). cmd/ctxd wires it (WithConfig); nil answers 0 — test wiring + // only. + cfg ConfigStore } // NewWhoamiHandler creates a new WhoamiHandler. modelAPI is the source of @@ -136,6 +166,32 @@ func NewWhoamiHandler(pool *pgxpool.Pool, modelAPI func() WhoamiModelAPI) *Whoam return h } +// WithConfig attaches the runtime config store rate_limit_write is read +// from and returns the handler for chaining. +func (h *WhoamiHandler) WithConfig(cfg ConfigStore) *WhoamiHandler { + h.cfg = cfg + return h +} + +// rateLimitWrite is query.rate_limit_write of the request's tenant-resolved +// snapshot (handler.RequestTenantScope: the key's home scope, which a +// narrowing never rewrites), or 0 without a config store. +func (h *WhoamiHandler) rateLimitWrite(r *http.Request) int { + if h.cfg == nil { + return 0 + } + return h.cfg.SnapshotForRequest(r.Context()).Query.RateLimitWrite +} + +// whoamiNarrowing is the narrowed field for ar: nil when the request is not +// narrowed. +func whoamiNarrowing(ar *auth.AuthResult) *whoamiNarrowed { + if ar.Narrowed == nil { + return nil + } + return &whoamiNarrowed{Read: ar.Narrowed.Read, Write: ar.Narrowed.Write} +} + // modelAPIPolicy is the model_api bag of this request: the getter's answer, // or the fail-closed zero value when none is wired. func (h *WhoamiHandler) modelAPIPolicy() WhoamiModelAPI { @@ -215,5 +271,9 @@ func (h *WhoamiHandler) HandleWhoami(w http.ResponseWriter, r *http.Request) { TenantDisplayName: id.tenantDisplayName, CSRFToken: CSRFTokenFromContext(r.Context()), Capabilities: whoamiCapabilities{Workflow: true, ModelAPI: h.modelAPIPolicy()}, + WriteScopes: writableBlockScopes(ar), + ConfirmWrites: ar.ConfirmWrites, + Narrowed: whoamiNarrowing(ar), + RateLimitWrite: h.rateLimitWrite(r), }) } diff --git a/go/internal/handler/whoami_test.go b/go/internal/handler/whoami_test.go index b57261cf9..8ac105ff9 100644 --- a/go/internal/handler/whoami_test.go +++ b/go/internal/handler/whoami_test.go @@ -177,14 +177,25 @@ func TestWhoamiGoldenShape(t *testing.T) { RotationGraceSeconds: 86400, ExpiryWarnSeconds: 1209600, }}, + WriteScopes: []string{"private", "shared"}, + ConfirmWrites: false, + RateLimitWrite: 100, }) if err != nil { t.Fatalf("marshal: %v", err) } - want := `{"success":true,"label":"example-key","home_scope":"private","read_scopes":["private","shared"],"admin":true,"tenant_id":"00000000-0000-0000-0000-0000000d3fa0","role":"member","api_key_id":"11111111-1111-1111-1111-111111111111","principal_id":"22222222-2222-2222-2222-222222222222","tenant_slug":"default","tenant_display_name":"Default Tenant","capabilities":{"workflow":true,"model_api":{"enabled":true,"self_service":false,"key_max_lifetime_s":31536000,"rotation_grace_s":86400,"expiry_warn_s":1209600}}}` + want := `{"success":true,"label":"example-key","home_scope":"private","read_scopes":["private","shared"],"admin":true,"tenant_id":"00000000-0000-0000-0000-0000000d3fa0","role":"member","api_key_id":"11111111-1111-1111-1111-111111111111","principal_id":"22222222-2222-2222-2222-222222222222","tenant_slug":"default","tenant_display_name":"Default Tenant","capabilities":{"workflow":true,"model_api":{"enabled":true,"self_service":false,"key_max_lifetime_s":31536000,"rotation_grace_s":86400,"expiry_warn_s":1209600}},"write_scopes":["private","shared"],"confirm_writes":false,"narrowed":null,"rate_limit_write":100}` if string(got) != want { t.Fatalf("golden shape drift:\n got: %s\nwant: %s", got, want) } + // The narrowed field of a narrowed request (Achse 02 C-1). + got, err = json.Marshal(whoamiNarrowed{Read: []string{"shared", "private"}, Write: ""}) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if want := `{"read":["shared","private"],"write":""}`; string(got) != want { + t.Fatalf("golden shape drift of narrowed:\n got: %s\nwant: %s", got, want) + } } // whoamiModelAPIHandler builds a handler whose model_api source is get (nil = diff --git a/go/web/src/lib/api/types.ts b/go/web/src/lib/api/types.ts index d0410156f..ad407a794 100644 --- a/go/web/src/lib/api/types.ts +++ b/go/web/src/lib/api/types.ts @@ -68,6 +68,17 @@ export interface WhoamiResponse { // Feld nie. OPTIONAL + additiv wie `capabilities`; der SPA hält den Wert // in-memory und sendet ihn als X-CSRF-Token bei Mutationen. csrf_token?: string + // The write side and the per-request scope narrowing (Achse 02 C-1, + // handler/whoami.go). OPTIONAL + additive: absent on an older server; the + // SPA reads none of them (it sends no narrowing). + /** Effective write set, home scope first; a narrowed request's write scope alone, or []. */ + write_scopes?: string[] + /** The key's stage-then-confirm opt-in (migration 090). */ + confirm_writes?: boolean + /** The request's narrowing (X-Context-Read-Scopes / X-Context-Write-Scope), null when unnarrowed. */ + narrowed?: { read: string[]; write: string } | null + /** query.rate_limit_write after the key's tenant overlay; 0 = unlimited. */ + rate_limit_write?: number } /** Effective-value provenance (handler/settings.go apiSource). `install`: the From 22d89182258a479638f4527d4e0c961af7fb5a08 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 01:46:09 +0100 Subject: [PATCH 04/15] =?UTF-8?q?feat(auth):=20a=20key=20can=20require=20p?= =?UTF-8?q?er-request=20scope=20narrowing=20=E2=80=94=20scope=5Fnarrowing?= =?UTF-8?q?=20on=20the=20key=20(migration=20198),=20refused=20unnarrowed?= =?UTF-8?q?=20but=20for=20whoami?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Migration 198 adds context_api_keys.scope_narrowing TEXT NOT NULL DEFAULT 'optional' CHECK (optional | required), rebuilds ctx_auth_by_id and ctx_auth with it as their last column (read from the key row the last_used_at update locks; the sentinel rows read 'required'), and adds it to the api_key audit projection and update trigger, so a switch is an audited update. Every existing key stays optional. A required key answers every request without X-Context-Read-Scopes with 403 scope_narrowing_required — reads, writes, /mcp, the session surface — GET /api/whoami excepted, which reports scope_narrowing. The check sits in narrowAuth beside the narrowing it demands; /register in admin mode, which resolves its key outside Auth, applies narrowAuth too, and both event streams end at their next re-auth once their key requires it. api-key-create and api-key-update take scope_narrowing (tenant-admin, like write_scopes; any other value is 400), api-key-list lists it, ctx keys create takes --require-narrowing. A key that requires narrowing administers nothing, so on an owner key it is owner power: a tenant-admin cannot switch an owner key to required, and the last-owner rule of update and delete counts only owners that are active and optional. Both decide on the target as read again under the tenant row lock, not on the read before it (a concurrent switch of role, active or scope_narrowing raced the owner guards). insertApiKeyTx names the column only for a required key, so the mint paths keep working on schemas before 198 (the migration tests mint keys there); MintKeyWithQuota and UpdateApiKey take the value; the two key audit tests on a 160 database call ctx_auth directly. The S1 red tests of C-2 are switched on; added: the way back of the header, the lock window measured at 100 000 and 1 000 000 keys (46 ms, 215 ms), an authentication behind an uncommitted switch, the owner rules with and without a concurrent key write, /register, the streams. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/api.md | 7 +- docs/cli.md | 2 +- docs/mcp.md | 4 +- docs/multi-tenancy.md | 6 +- docs/operations.md | 8 + docs/security.md | 2 +- ..._narrowing_required_c2_integration_test.go | 2 +- ...owing_required_c2_more_integration_test.go | 71 +++++ go/internal/auth/auth.go | 52 ++-- go/internal/cli/commands.go | 48 ++-- go/internal/handler/context_manage.go | 61 ++++- ...t_manage_writescope_w3_integration_test.go | 2 +- go/internal/handler/errcode.go | 4 + go/internal/handler/events.go | 4 +- .../ingest_target_scope_integration_test.go | 2 +- go/internal/handler/narrowing.go | 15 + go/internal/handler/narrowing_events_test.go | 49 ++++ .../narrowing_streams_integration_test.go | 64 +++++ go/internal/handler/oauth_register.go | 8 + ...uth_register_narrowing_integration_test.go | 79 ++++++ go/internal/handler/project_events.go | 13 +- go/internal/handler/whoami.go | 14 + go/internal/handler/whoami_test.go | 3 +- go/internal/schemacontract/manifest.json | 20 +- go/internal/store/api_keys.go | 157 ++++++++--- .../store/api_keys_audit_integration_test.go | 19 +- go/internal/store/api_keys_insert_test.go | 14 + .../api_keys_mint_quota_integration_test.go | 20 +- ..._keys_owner_interleave_integration_test.go | 149 ++++++++++ .../store/api_keys_update_integration_test.go | 39 +-- .../api_keys_write_scopes_integration_test.go | 6 +- .../store/audit_classification_test.go | 30 +- .../store/migration198_integration_test.go | 241 ++++++++++++++++ .../request_key_gate_integration_test.go | 4 +- ...equest_key_gate_writes_integration_test.go | 2 +- .../tenant_prune_schema_integration_test.go | 13 +- go/migrations/198_api_key_scope_narrowing.sql | 259 ++++++++++++++++++ go/web/src/lib/api/types.ts | 2 + test.sh | 5 +- 39 files changed, 1322 insertions(+), 178 deletions(-) create mode 100644 go/cmd/ctxd/scope_narrowing_required_c2_more_integration_test.go create mode 100644 go/internal/handler/narrowing_events_test.go create mode 100644 go/internal/handler/narrowing_streams_integration_test.go create mode 100644 go/internal/handler/oauth_register_narrowing_integration_test.go create mode 100644 go/internal/store/api_keys_owner_interleave_integration_test.go create mode 100644 go/internal/store/migration198_integration_test.go create mode 100644 go/migrations/198_api_key_scope_narrowing.sql diff --git a/docs/api.md b/docs/api.md index dc346d338..e2db0112a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -23,7 +23,7 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. | `GET /api/graph/overview` | Scope-pure Louvain cluster supergraph ("landkarte"); reads precomputed scope-partitioned aggregates, gated on `graph_overview.enabled` (off → 404). Read-only, no LLM. | | `GET /api/graph/cluster` | Cluster ego: the members + neighbour topics of ONE topic handle (see [Cluster ego](#cluster-ego-get-apigraphcluster)). Double-gated on `graph_overview.enabled` **and** `cluster.route_enabled` (both default off → 404, indistinguishable from an absent route). | | `POST /api/synthesize/daily` | Manual trigger of the daily synthesis (Tagesbericht) for the caller's `home_scope` — the same `GenerateDailyReport` path the 03:00 scheduler iteration runs (digest role, constant internal). Concurrency cap 1 per principal (429 fail-fast), dispatch-interactive (429 + `Retry-After` on capacity rejection). Optional `?date=YYYY-MM-DD` (M103) re-synthesizes the report titled that day over its historical window `[date-1 03:00 UTC, date 03:00 UTC)` — the backfill path; the `(category, title, scope)` upsert replaces the old report in place (same block id, embedding regenerates). A malformed date, a window that has not closed yet, or — with `scheduler.writelog_retention_days` set — a window that starts before the write-log horizon or before the eviction boundary the retention recorded on any earlier run, whatever the setting is now (its guard and dream decisions are deleted, and the replacement would lack them; issue #277) ⇒ 400; a boundary the server cannot read ⇒ 500. `{ok, block_id, scope[, date][, reason:"no_activity"]}`. The report language follows the hot `dream.language` setting, read per request: empty (default) keeps the German surface this row describes, any other tag localizes **title and tag together** (`Daily Report <date>` / `daily-report`) — so a change **starts a new series** instead of continuing the old one, and a backfill after the switch writes a second block for a day that already has a `Tagesbericht`. Deliberate and operator-triggered; see [`CTX_DREAM_LANGUAGE`](operations.md#environment-variables). | -| `GET /api/whoami` | Calling key's identity: `label`, `home_scope`, `read_scopes`, the server-global `admin` tier flag, plus the Model-C tenant identity `tenant_id` + per-tenant `role` (`owner`/`admin`/`member`), and the feature-flag bag `capabilities` (`{workflow: true}` since v4.3.0 — switches the SPA's issues/board surface visible; the field is data, so a later per-tenant gate only changes the value, not the SPA). `capabilities.model_api` carries the gateway policy as data, read per request from the `_global` settings: `{enabled, self_service, key_max_lifetime_s, rotation_grace_s, expiry_warn_s}` = `gateway.enabled`, `gateway.tenant_self_service`, `gateway.key_max_lifetime_app`, `gateway.key_rotation_grace`, `gateway.key_expiry_warn` (durations in whole seconds; the peer lifetime is not carried). Every authenticated caller receives it — server policy, no secret; the SPA derives two capabilities from it, `viewModelApi` and `mintModelKeys`, for the gateway administration surface ([multi-tenancy](multi-tenancy.md#admin-tiers)), while the manage actions enforce their own tiers ([Model consumer administration](#model-consumer-administration)). The SPA login gate probes it, derives its read-only degradation from `admin`, and tells server-admin from tenant-admin. Four fields describe the write side and a narrowing: `write_scopes` (the effective write set, home scope first — under a narrowing its write scope alone, or `[]`), `confirm_writes`, `narrowed` (`{read, write}` of a [narrowed request](#scope-narrowing-per-request), `null` otherwise; under a narrowing `read_scopes` is that read set, `admin` is `false` and `role` is `member`) and `rate_limit_write` (the write budget per key and 60 s that applies to this key: `query.rate_limit_write` after its tenant's overlay, `0` = unlimited). | +| `GET /api/whoami` | Calling key's identity: `label`, `home_scope`, `read_scopes`, the server-global `admin` tier flag, plus the Model-C tenant identity `tenant_id` + per-tenant `role` (`owner`/`admin`/`member`), and the feature-flag bag `capabilities` (`{workflow: true}` since v4.3.0 — switches the SPA's issues/board surface visible; the field is data, so a later per-tenant gate only changes the value, not the SPA). `capabilities.model_api` carries the gateway policy as data, read per request from the `_global` settings: `{enabled, self_service, key_max_lifetime_s, rotation_grace_s, expiry_warn_s}` = `gateway.enabled`, `gateway.tenant_self_service`, `gateway.key_max_lifetime_app`, `gateway.key_rotation_grace`, `gateway.key_expiry_warn` (durations in whole seconds; the peer lifetime is not carried). Every authenticated caller receives it — server policy, no secret; the SPA derives two capabilities from it, `viewModelApi` and `mintModelKeys`, for the gateway administration surface ([multi-tenancy](multi-tenancy.md#admin-tiers)), while the manage actions enforce their own tiers ([Model consumer administration](#model-consumer-administration)). The SPA login gate probes it, derives its read-only degradation from `admin`, and tells server-admin from tenant-admin. Four fields describe the write side and a narrowing: `write_scopes` (the effective write set, home scope first — under a narrowing its write scope alone, or `[]`), `confirm_writes`, `narrowed` (`{read, write}` of a [narrowed request](#scope-narrowing-per-request), `null` otherwise; under a narrowing `read_scopes` is that read set, `admin` is `false` and `role` is `member`) `rate_limit_write` (the write budget per key and 60 s that applies to this key: `query.rate_limit_write` after its tenant's overlay, `0` = unlimited) and `scope_narrowing` (`optional` or `required`, the key's column; a key with `required` answers nothing unnarrowed but this route). | | `POST /api/manage` | CRUD, Guard API, stats, API-key management, block-type registry (see [manage actions](#manage-actions)). | | `GET /api/types[/{name}]` | Block-type registry reads: effective type list (`_global` ∪ your tenant) and single-type policy config, **member-gated** (any valid key) (see [Block-type registry](#block-type-registry)). | | `PUT\|DELETE /api/types/{name}` | Block-type registry writes (upsert/delete), **admin-or-tenant-admin-gated**: a tenant-admin writes its own tenant namespace, `_global` types are operator-only; DELETE 409s while referenced or on a builtin (see [Block-type registry](#block-type-registry)). | @@ -46,7 +46,7 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. | `GET /api/project/events` | **Member** SSE domain-event stream (`text/event-stream`, workflow W9) for live board / issue-list updates. A key receives IDS-ONLY frames — `project` events `{kind, project_id, op, block_ids}` or the coalesced `{kind:"issues-bulk", project_id, count}`; NEVER title/content/body (the client refetches over the read API). Frames are **scope-filtered at the fan-out**: only the caller's readable project scopes, never another tenant's. Optional `?project_id=` pins the stream to one project (foreign/unknown ⇒ 404 uniform). Per-**tenant** connection cap (`project.events.max_connections`) → 429; `: ping` keepalive; a 10k-import burst collapses to one `issues-bulk` frame per tick (`project.events.flush_interval` / `coalesce_threshold`). In-stream re-auth recomputes the caller's scope tags from the FRESH read set every ~12 flush ticks: a revoked key or a tenant change ends the stream, and a revoked cross-tenant **scope grant** (tenant/role unchanged) drops that scope's frames — separate from the server-admin telemetry `/api/events`. | | `POST /api/digest` | Topic map generation. Rebuilds the linear topic map and — when `root_map.enabled` is on — also renders the **root map** (`root-map-<scope>`, cluster-per-line, capped at `root_map.budget_bytes`). It never starts a Louvain rebuild: the map is rendered from the cluster state that already exists, so the route cannot become a lever on a job bounded only by `graph_overview.rebuild_timeout`. Carries its own write rate-limit bucket (`digest`) since the root-map wave. Response gains `rootMapTitle` / `rootMapLength` **additively**; `title`, `blockCount`, `categoryCount` and `contentLength` keep their meaning, and the two corpus counts behind them now run under `root_map.count_timeout` (0 = not measured this round) instead of unbounded. The topic map is capped at 256 KiB (issue #518; [operations](operations.md#the-linear-topic-map-is-capped-at-256-kib)): below the cap it is unchanged, above it each category lists its first titles and the map says so in its text. The response carries, additively, `listedBlocks` — the blocks the map this request wrote lists by line, `0` when it wrote none (`digest.mode` stub or off, an empty window) — and `truncated`, `true` when that map leaves blocks out. Before the cap a window past about 60,000 blocks answered `500` on every call. | | `POST /api/ingest` | Obsidian vault ingestion. **Write scope:** `target_scope` names the scope every chunk of the request is written to and is resolved like `scope` on `POST /api/store`: absent or empty means the key's home scope, and a scope outside the key's writable scopes refuses the whole request with `403`, code `scope_denied` (`Cannot write to requested scope`), before a chunk is written and before the `ingest` bucket is booked. The field `scope` is **not read** on this route: `ctx ingest` through 5.48.2 sends it on every request, `"private"` unless the user named another scope, and the server never read it; honouring it would refuse those runs for every key whose home scope is not `private`, or move them into `private` where the key may write it. A `200` answer carries `scope`, the scope the request wrote to; a server without that field ignores `target_scope` and writes to the key's home scope. Chunk mode (`source_id` + `chunk_index`) needs a `context_sources` row in the scope the request writes to and never overwrites another scope's chunk — absent, foreign or foreign-held all fail the chunk as `source not found`. A chunk whose `(category, title, scope)` another active block holds fails as `another active block in this scope already has this category and title — choose another category or title` (issue #275; before, `insert chunk failed`). ctxd has no endpoint that creates `context_sources` rows; a chunk-mode client needs one created out of band with that `scope` (since 5.29.1 a source in any other scope fails every chunk). **Per-chunk failures do not change the status code:** the request answers `200` with `success: false`, `failed > 0` and `results[i].status = "failed"` plus `results[i].error` for each failed chunk, next to the ones that were `inserted`/`updated`/`skipped` — a client must read the body, not the status. Batch-wide refusals carry their own status (`400`/`413` validation, `403` reserved namespace or `scope_denied`, `429` rate limit). The request body is capped at 10 MB; a body whose JSON does not end within the cap is refused whole with `413`, `request body exceeds 10 MB cap`, before a chunk is written (before, it answered `400`, `Invalid request body`, like a malformed body). Chunk content runs the credentials detector; each accepted request books the `ingest` bucket against `query.rate_limit_write` (429 past it). A block-mode write (no `source_id`) runs the type classifier on title and metadata like `POST /api/store`; a block whose `type_source` is `'manual'` keeps its type. The registry snapshot is resolved once per request, so every block-mode chunk of a batch is classified against the same rules. A chunk answers `skipped` when its content matches the live `(category, title, scope)` row and either the write would change nothing or the matched row is not its `(source_id, chunk_index)` slot as `InsertChunk` writes it (a block-mode row, another source's chunk, a row in that slot whose `lifecycle_state` is no longer `chunk`, or a `source_id` that is not a UUID), because such a write cannot land; the no-op predicate merges request metadata while an actual chunk write replaces it, so same-slot subset metadata can answer `skipped`, and unnamed keys are dropped only when a chunk is written. Chunk-mode writes do not run the classifier; a new chunk row starts with the default type. A chunk write that replaces the slot's title or content keeps the chunk's vector marked stale until the backfill embeds the new text, in the transaction of the write; one that re-sends the same title and content (new tags or metadata only) keeps the vector current (issue #236). | -| `POST /api/blob/*` | Binary storage (store/fetch/search/manage). Write rejections additionally carry a machine-readable `"code"` (Gap-C6-c): the closed vocabulary is `unauthorized`, `invalid_body`, `missing_fields`, `invalid_sensitivity`, `invalid_encoding`, `scope_denied`, `size_cap`, `unknown_type`, `reserved_type`, `parent_required`, `unknown_parent`, `unknown_supersedes`, `unknown_block`, `supersedes_conflict`, `supersedes_not_allowed`, `reserved_category`, `reserved_metadata`, `provenance_protected`, `unknown_action`, `edit_mismatch`, `constraint`, `rate_limit`, `write_conflict`, `internal`, and the two classes of a request's scope narrowing, `scope_narrowing_invalid` and `scope_narrowing_route` ([below](#scope-narrowing-per-request)) — one code per rejection class across `/api/store`, `/api/blob/store` and the MCP `store` tool (there as `structuredContent.code`, the `Content[0].Text` prose is unchanged; a STAGED answer is deliberately uncoded — IsError plus code means refused, IsError without code means staged). Answers without a code keep their exact pre-existing envelope (no empty `code` key). `store` runs on its OWN write budget: `pool.blob_rate_limit_write` (tenant-overridable, default 10) per api key and 60-second window, counted over the separate `blob-write` action in `context_access_log` — a key at its `query.rate_limit_write` block-write limit may still upload, and uploads never consume the block budget. `0`/unset falls back to the VALUE of `query.rate_limit_write` (unlimited needs BOTH at 0). The budget is booked BEFORE the upsert, so a write that ends in a constraint violation still costs it; over budget ⇒ **429**. Each stored blob leaves one audit row referencing it through `context_access_log.blob_id`, which is intentionally unconstrained — the row survives the blob's deletion. **MCP transport (W02-8):** `blob_store` / `blob_fetch` run this same write path — required fields, name caps, base64 decode, the `writableBlockScopes` gate and the `blob-write` budget are ONE shared core (`handler/blob_core.go`), so both surfaces answer the identical code and the identical prose for the identical request. `blob_store` takes the payload as `file` (base64, same `invalid_encoding` verdict) **or** `text` (UTF-8) — exactly one of the two — and takes an optional **`scope`** (E-M4, superseding decision D4, like the `store` tool): absent ⇒ the calling key's `home_scope`, named ⇒ gated through the same `writableBlockScopes` formula the REST route uses, ahead of the budget (`scope_denied` / `Cannot write to requested scope`). A `confirm_writes` key gets the call **staged** (a `payload_hash` instead of an id, `IsError=true`, executed by `confirm`), and a payload above `pool.blob_stage_max_bytes` (tenant-overridable, default 1 MiB; `0` disables blob staging for such keys entirely) is **refused by name** rather than written direct. The budget is charged at stage time, so the confirm books nothing. `blob_fetch` reads a **byte range** of the stored payload (`offset`/`length`, default 262144, max 1048576; a larger `length` is refused, never clamped, so a short answer always means the blob ended) and names its `encoding` (`text` when the window is valid UTF-8, else base64); `meta_only` returns metadata alone. The REST fetch route is unchanged and still answers the whole blob in one piece. **Payload scan + read gate (W02-9):** the shared write core runs the same credentials detector the block path has used since G40 over the decoded payload, on both surfaces, and records the verdict in the blob's JSONB `metadata` (no new column, no migration). It is KIND-differentiated: a structured signal (PEM private-key header, JWT, AWS key id, vendor token prefix, high-entropy secret assignment) sets `metadata.sensitivity` to `credentials` plus `metadata.sensitivity_kind`, upgrade-only over a caller-supplied value; a generic high-entropy hit (64+ hex run, base64 blob) raises NOTHING and is recorded in `metadata.entropy_flags`, because on a payload those artefacts are the evidence a drill-down came for, not a secret. A payload that is not valid UTF-8, or larger than `pool.blob_scan_max_bytes` (tenant-overridable, default 16 MiB; `0` turns the scan off), is STORED with `metadata.sensitivity = "unscanned"` — the write goes through, so binary uploads and the blobs that predate this path are never collateral. A `confirm_writes` key is scanned at STAGE time, so the verdict rides inside the `payload_hash` and confirming cannot alter it. On the read side `blob_fetch` does NOT return the payload of a blob whose `metadata.sensitivity` is `credentials` (named refusal, uncoded like every other fetch refusal); `meta_only` still answers, and a missing or `unscanned` field reads as deliverable — a blob is withheld because something was found, never because nothing was looked for. Every `blob_fetch` answer that carries content is framed for a model context: `untrusted: true`, an `origin` naming blob id/category/title/scope, and a `note` that the bytes are data and not instructions; `meta_only` carries no frame. The REST fetch route keeps all of this OUT — it is an operator path, not a model context, and answers the whole payload of a credentials blob unchanged. **Blob-to-block edge (W02-10):** `context_blobs.context_block_id` finally has a write path. Both store surfaces take an optional `context_block_id` (REST body field, MCP tool field), and the third MCP tool **`blob_link`** `{id, context_block_id}` sets it afterwards in ONE indexed `UPDATE` — no payload on the wire, `file_size`/`checksum`/`updated_at` untouched, which is what makes the two-phase write of a checkpoint (payload first, manifest block second, link third) cost one payload round trip instead of two. A link is a WRITE: it books one `blob-write` row like a store, and the blob must lie in the caller's `writableBlockScopes` — outside them it is `blob not found`, the same answer an id that belongs to nothing gets. The referenced BLOCK must be visible in the caller's read scopes; a block in a foreign scope, an id that exists nowhere and a malformed id all answer `422` / `constraint` / `Referenced context_block_id not found`, byte-identically, so the write surface is no existence oracle over foreign scopes (letting the foreign key decide would have answered *success* for the foreign block and `23503` for the absent one, and built a cross-scope edge on the way). A re-`blob_store` without the field CLEARS the edge — the row is what the last write said. `blob_store`, `blob_fetch` and `blob_link` answer `context_block_id` only when it is set. A `confirm_writes` key gets `blob_link` **staged** like every other write (op `blob_link`, staged under the BLOB's own scope, budget charged at stage time), and the confirm re-validates both the scope and the block's visibility on the un-consumed row. Deleting the block leaves the blob alive with a NULL edge (`ON DELETE SET NULL`). | +| `POST /api/blob/*` | Binary storage (store/fetch/search/manage). Write rejections additionally carry a machine-readable `"code"` (Gap-C6-c): the closed vocabulary is `unauthorized`, `invalid_body`, `missing_fields`, `invalid_sensitivity`, `invalid_encoding`, `scope_denied`, `size_cap`, `unknown_type`, `reserved_type`, `parent_required`, `unknown_parent`, `unknown_supersedes`, `unknown_block`, `supersedes_conflict`, `supersedes_not_allowed`, `reserved_category`, `reserved_metadata`, `provenance_protected`, `unknown_action`, `edit_mismatch`, `constraint`, `rate_limit`, `write_conflict`, `internal`, and the three classes of a request's scope narrowing, `scope_narrowing_invalid`, `scope_narrowing_route` and `scope_narrowing_required` ([below](#scope-narrowing-per-request)) — one code per rejection class across `/api/store`, `/api/blob/store` and the MCP `store` tool (there as `structuredContent.code`, the `Content[0].Text` prose is unchanged; a STAGED answer is deliberately uncoded — IsError plus code means refused, IsError without code means staged). Answers without a code keep their exact pre-existing envelope (no empty `code` key). `store` runs on its OWN write budget: `pool.blob_rate_limit_write` (tenant-overridable, default 10) per api key and 60-second window, counted over the separate `blob-write` action in `context_access_log` — a key at its `query.rate_limit_write` block-write limit may still upload, and uploads never consume the block budget. `0`/unset falls back to the VALUE of `query.rate_limit_write` (unlimited needs BOTH at 0). The budget is booked BEFORE the upsert, so a write that ends in a constraint violation still costs it; over budget ⇒ **429**. Each stored blob leaves one audit row referencing it through `context_access_log.blob_id`, which is intentionally unconstrained — the row survives the blob's deletion. **MCP transport (W02-8):** `blob_store` / `blob_fetch` run this same write path — required fields, name caps, base64 decode, the `writableBlockScopes` gate and the `blob-write` budget are ONE shared core (`handler/blob_core.go`), so both surfaces answer the identical code and the identical prose for the identical request. `blob_store` takes the payload as `file` (base64, same `invalid_encoding` verdict) **or** `text` (UTF-8) — exactly one of the two — and takes an optional **`scope`** (E-M4, superseding decision D4, like the `store` tool): absent ⇒ the calling key's `home_scope`, named ⇒ gated through the same `writableBlockScopes` formula the REST route uses, ahead of the budget (`scope_denied` / `Cannot write to requested scope`). A `confirm_writes` key gets the call **staged** (a `payload_hash` instead of an id, `IsError=true`, executed by `confirm`), and a payload above `pool.blob_stage_max_bytes` (tenant-overridable, default 1 MiB; `0` disables blob staging for such keys entirely) is **refused by name** rather than written direct. The budget is charged at stage time, so the confirm books nothing. `blob_fetch` reads a **byte range** of the stored payload (`offset`/`length`, default 262144, max 1048576; a larger `length` is refused, never clamped, so a short answer always means the blob ended) and names its `encoding` (`text` when the window is valid UTF-8, else base64); `meta_only` returns metadata alone. The REST fetch route is unchanged and still answers the whole blob in one piece. **Payload scan + read gate (W02-9):** the shared write core runs the same credentials detector the block path has used since G40 over the decoded payload, on both surfaces, and records the verdict in the blob's JSONB `metadata` (no new column, no migration). It is KIND-differentiated: a structured signal (PEM private-key header, JWT, AWS key id, vendor token prefix, high-entropy secret assignment) sets `metadata.sensitivity` to `credentials` plus `metadata.sensitivity_kind`, upgrade-only over a caller-supplied value; a generic high-entropy hit (64+ hex run, base64 blob) raises NOTHING and is recorded in `metadata.entropy_flags`, because on a payload those artefacts are the evidence a drill-down came for, not a secret. A payload that is not valid UTF-8, or larger than `pool.blob_scan_max_bytes` (tenant-overridable, default 16 MiB; `0` turns the scan off), is STORED with `metadata.sensitivity = "unscanned"` — the write goes through, so binary uploads and the blobs that predate this path are never collateral. A `confirm_writes` key is scanned at STAGE time, so the verdict rides inside the `payload_hash` and confirming cannot alter it. On the read side `blob_fetch` does NOT return the payload of a blob whose `metadata.sensitivity` is `credentials` (named refusal, uncoded like every other fetch refusal); `meta_only` still answers, and a missing or `unscanned` field reads as deliverable — a blob is withheld because something was found, never because nothing was looked for. Every `blob_fetch` answer that carries content is framed for a model context: `untrusted: true`, an `origin` naming blob id/category/title/scope, and a `note` that the bytes are data and not instructions; `meta_only` carries no frame. The REST fetch route keeps all of this OUT — it is an operator path, not a model context, and answers the whole payload of a credentials blob unchanged. **Blob-to-block edge (W02-10):** `context_blobs.context_block_id` finally has a write path. Both store surfaces take an optional `context_block_id` (REST body field, MCP tool field), and the third MCP tool **`blob_link`** `{id, context_block_id}` sets it afterwards in ONE indexed `UPDATE` — no payload on the wire, `file_size`/`checksum`/`updated_at` untouched, which is what makes the two-phase write of a checkpoint (payload first, manifest block second, link third) cost one payload round trip instead of two. A link is a WRITE: it books one `blob-write` row like a store, and the blob must lie in the caller's `writableBlockScopes` — outside them it is `blob not found`, the same answer an id that belongs to nothing gets. The referenced BLOCK must be visible in the caller's read scopes; a block in a foreign scope, an id that exists nowhere and a malformed id all answer `422` / `constraint` / `Referenced context_block_id not found`, byte-identically, so the write surface is no existence oracle over foreign scopes (letting the foreign key decide would have answered *success* for the foreign block and `23503` for the absent one, and built a cross-scope edge on the way). A re-`blob_store` without the field CLEARS the edge — the row is what the last write said. `blob_store`, `blob_fetch` and `blob_link` answer `context_block_id` only when it is set. A `confirm_writes` key gets `blob_link` **staged** like every other write (op `blob_link`, staged under the BLOB's own scope, budget charged at stage time), and the confirm re-validates both the scope and the block's visibility on the un-consumed row. Deleting the block leaves the blob alive with a NULL edge (`ON DELETE SET NULL`). | | `POST /api/img/sign` | Camo image-proxy **mint**, **auth-gated** + per-key rate-limited. Body `{urls:[…], origin:"assistant"}` ⇒ `{signatures:{url → "/api/img/<sig>?url=…&exp=…"}}`; non-proxiable URLs (relative, `data:`, `mailto:`, a query string, userinfo, an escaped path over 512 bytes) are omitted. `origin` is `assistant` (also the default when absent); any other value is **400**, including `issue`, which pre-upgrade bundles sent for issue markdown. One distinct URL per request; more is **400**. The SPA renderer has no signing secret, so it asks the server to sign the one foreign image URL the viewer clicked (see [Camo image proxy](#camo-image-proxy)). Off (404) unless `CTX_CAMO_ENABLED`. | | `GET /api/img/{sig}` | Camo image-proxy **fetch**, **unauthenticated** — a browser `<img>` carries no api key, so the HMAC-SHA256 signature (over `url`+`exp`, keyed by a labeled subkey of `CTX_SECRETS_KEY`) IS the capability. Verifies the sig BEFORE any upstream request (forged ⇒ **403**, expired ⇒ **410**, ZERO fetch either way), then fetches under an SSRF-guarded / redirect-hop-checked / size-capped / content-type-allowlisted policy (SVG excluded — XSS) and streams the bytes from `'self'` with `X-Content-Type-Options: nosniff` + immutable cache. Upstream failure ⇒ **502/415** + `no-store`, no substitute body. Re-hosts remote images so the SPA renders them under `img-src 'self'` WITHOUT widening the CSP, and the viewer's browser never talks to the foreign origin (see [Camo image proxy](#camo-image-proxy)). | | `POST /api/chat/stream` + `/api/chat/sessions[/{id}]` | Web-chat harness (see [Web chat sessions](#web-chat-sessions)). | @@ -64,6 +64,7 @@ A request can narrow its key's rights to scopes it names, for that one request ( | `X-Context-Write-Scope` without `X-Context-Read-Scopes`; a header sent twice; an empty header or list element; a scope named twice; more than 8 read scopes | `400 scope_narrowing_invalid` | | a read scope the key does not read; a write scope outside the read scopes or one the key cannot write | `403 scope_denied` | | any route but `POST /api/query`, `POST /api/search`, `POST /api/store`, `GET /api/whoami`, `POST /api/manage` (method and path exactly, without percent escapes); on `/api/manage` any action but `get` and `type-list` | `403 scope_narrowing_route` | +| a request without a narrowing by a key whose `scope_narrowing` is `required` (migration 198), on any route but `GET /api/whoami` | `403 scope_narrowing_required` | These are decided before the route's handler runs (the `manage` action after the body is decoded, on the one action the dispatcher runs). A narrowed request is never an administration request: it runs as a `member` without the server-admin tier. The key's home scope stays its own — the backend chain, the quota and the settings overlay of a narrowed request are the key's, whatever scope the narrowing names first. A request without the headers runs as before. @@ -85,7 +86,7 @@ PostgreSQL stores a NUL character (U+0000) neither in text nor in JSON, so no va - **Scope purge (hard delete, issue #202):** `purge` (tierTenantAdmin) removes block data inside **one** scope for good — the narrow counterpart of `tenant-delete`, for rows that should never have been written (a test or import run into a production tenant); `delete` only archives. `data`: `scope` (required) and optional filters, each of which narrows: `tags` (the block carries **every** listed tag; an empty list is no filter), `category`, `created_before` / `created_after` (RFC 3339, exclusive bounds on `created_at`), `archived_only`; and `keepalive` (below), which is no filter. No filter drains the scope. Unknown fields are `400`, so a misspelt filter cannot widen the purge. A tenant-admin reaches only the scopes its own tenant owns — another tenant's scope and an unknown one answer the same `404 scope not found`; a server-admin reaches every scope; an empty scope and the `_` system namespace are `400`; a key without an admin role is `403`, its home scope included. **Without `confirm_blocks` the call is a dry run** that deletes nothing and answers `{action, success, scope, filter, dry_run: true, as_of, counted: {blocks, cascaded_children, dream_links, blobs, derived_skipped, children_outside_scope, derived_children}, confirm_blocks}`. The real run sends `confirm_blocks` set to the dry run's `counted.blocks`: the purge counts again and deletes only when the number is unchanged (otherwise `409` with the fresh `counted`, nothing deleted), and it never touches a block or blob created after that count (`as_of`): a batch that would take the run past the confirmed number, or reach a child created after `as_of`, rolls back and ends the run with the same `409`. The confirmed run continues when the client disconnects or times out; its result is then in the server log (`manage: scope purged`) and a new dry run shows what is left. A client that waits gets the answer of a long run: the write deadline rolls while the purge works, so the answer is delivered past the server's 120 s write timeout with its status and body unchanged (issue #277). `keepalive: true` also writes one space every 25 s from the start, for a reverse proxy whose read timeout only bytes reset (nginx `proxy_read_timeout`, 60 s by default): the first space commits `200`, a refusal after it is that `200` with `success: false` and the error in the body (leading whitespace is valid JSON), and an answer within the first 25 s keeps its status and body. `ctx manage purge` waits for the answer without the CLI's 120 s timeout. What goes: the matching blocks; the blocks below them through `parent_id` (an issue's comments — `parent_id` cascades, so they count in `blocks` and separately in `cascaded_children`; a child in **another** scope refuses the run with `409`, see `children_outside_scope`, and so does a derivative below a matched block, see `derived_children` — the cascade would take it); every dream link that references one of them; and, only for a purge without any filter, the scope's blobs (a filter describes blocks — a filtered purge keeps the blobs and clears their link to a purged block). Rows that hang on a block by foreign key go or are cleared with it (temporal index, structural links, block grants, cluster membership, the embed-failure memo, the forge sync mapping — a synced project re-imports its issues on the next sync — and the block references of the access and write logs), and a surviving block that a purged block superseded is reconciled as `dream-link-resolve` does. A block carrying a derived `provenance` is never purged and is counted in `derived_skipped`. Context sources, chat sessions, secrets, keys and the scope itself stay. The run answers `dry_run: false`, `counted` and `deleted: {blocks, dream_links, blobs}`; it works in batches of 2 000 matched blocks plus their children, one transaction each (a batch that collides with a dream run — deadlock or serialization failure — is repeated up to three times), so an error after the first batch answers `500` (or the `409` above) with what was already `deleted` — a new dry run shows the rest. Each run that deletes anything writes one audit row before its first delete (`GET /api/audit?entity=scope_purge`, `entity_key` = the scope, `new_value` = filter, counts and `as_of`). REST and CLI only, no MCP tool: `ctx manage purge '' '{"scope":"…","tags":["…"]}'`, then the same with `"confirm_blocks":N`. Operator notes in [operations](operations.md#removing-rows-written-by-mistake-manage-purge). - **Backfill memo release (issue #236):** `embed-backfill-release` (tierTenantAdmin) drops regular embed-backfill failure memos (`context_embed_failures` rows with `migration_id` NULL) so the backfill takes their blocks again — after `embed_backfill.max_tokens` was raised, the embed backend moved to a larger context, or a backend outage ended; without it a parked block came back only through a change of its title or content. `data`: exactly one of `block_id` (a UUID) or `class` (`wire` or `oversize`), optional `limit` (the page size, at most and by default `1000`; a larger value is clamped), and `confirm_memos` together with `as_of`; unknown fields, a second selector, another class, a malformed id, a negative number and a `confirm_memos` without `as_of` (or the reverse) are `400`. A `caller_timeout` memo is never taken, not even by `block_id`: it is no park — the background arm takes such a block at once, and with the arm off the query path retries it after its hold —, and deleting it would hand the block back to the requests' `sync_budget` with its attempts restarted. A tenant-admin reaches the memos of blocks in its own tenant's scopes (a scope or a block granted to the tenant is not its own) — another tenant's block and an unknown one answer the same `counted: 0`; a server-admin reaches every memo; a key without an admin role is `403`. A re-embed migration's memos are never touched. **Without `confirm_memos` the call is a dry run** answering `{action, success, dry_run: true, as_of, counted, confirm_memos, held}` (and `held_until` when `held` is above 0); the real call sends `confirm_memos` and `as_of` of that answer, takes only the memos that were there when the dry run counted (a memo written after `as_of` — a released block that was parked again, a new park — is neither counted nor released, so paging ends), counts them again and releases only when the number is unchanged (otherwise `409` with the fresh `counted` and `confirm_memos`, and the `as_of` the call sent), releases at most `limit` of them — the count and the release decide which memos the reader may release at one instant (one transaction, issue #536), so a hold that ends between the two neither counts nor releases its memo in that call — and answers `{action, success, dry_run: false, as_of, counted, released, remaining, confirm_memos, held}` — `remaining` (and `confirm_memos`, the number to confirm for the next page with the same `as_of`) is what is left of them, including a memo another transaction held at that moment, which the release skips instead of waiting for. Two releases of the same memos at once each count what both may take: one of them releases fewer than it counted and answers a `remaining` the other has already released, and its next page answers `409` with the fresh count. Only memos that keep a block out of the pick (`next_attempt_at` in the future) count. **A server-admin's release deletes the memo; a tenant-admin's keeps it and makes it due**, with its attempts and with the time of the release in `first_seen`, so a block the backend still cannot take is parked again on the same row. A tenant-admin releases such an `oversize` memo again (more than one attempt) only once `embed_backfill.release_hold` × 2^(attempts − 2) has passed since that release, at most `embed_backfill.backoff_cap` (defaults 1 h and 24 h; a cap of 0 sets none; the hold must be above 0, V70); until then it is answered in `held`, with the earliest end in `held_until`. Without the hold a tenant-admin releasing its blocks in a loop while they kept not fitting took one turn of the background arm in every round of the tenants for good, where its way back without the action, an edit per block, costs a write each. The first release of every memo is not held, a `wire` memo is not held (its failure holds the tenant in the arm for `embed_backfill.interval`, and its next failure backs off longer, since the attempts stay), and a server-admin's release and a change of the block's title or content (which deletes the memo) start the count again. For a tenant-admin the count and the page of a class read the tenant's own scopes and their pending blocks, so their cost grows with the tenant's pending blocks, not with other tenants' memos. The next backfill pick of each released block embeds it when it fits now and parks it again after one attempt when it does not. CLI: `ctx admin embed-backfill release --class oversize`, then the same with `--confirm N --as-of T`; `--limit N` is sent as given, so a negative one is answered with the `400` (until issue #536 the CLI left a `--limit` of 0 or below out of the request and the server paged by its maximum). Operator notes in [operations](operations.md#embedding-backend-tuning-cpu-llamacpp), paragraph "Backfill failure memo". - **Block counters (issue #266):** `stats`, `guard-stats` and `list-categories` read per-scope counters that triggers on `context_blocks` keep with every write (migration 170), and so do the per-scope block counts of `scope-overview` (issue #271); the answers are unchanged. `guard-stats`' `pending_count` and `dirty_since` are counted on demand since migration 181: the blocks of the caller's read scopes the guard still has to check, and the oldest `updated_at` among them (`null` when none waits) — before 181 a global count of block writes since the last guard run, the same for every key ([operations](operations.md#migration-181-no-block-writer-waits-on-the-guards-state-row-guard-stats-counts-the-waiting-blocks)). `stats-reconcile` (server-admin) recounts and corrects them: `data` `{}` reconciles every scope, `{"scope": "<scope>"}` one; any other field is a `400`. It answers `{action, success, scopes, corrections, corrections_total, pruned, failed}` — `corrections` lists the corrected keys as `{scope, category, is_archived, guard_status, counted, actual}`, at most the first 1 000 of the pass, and `corrections_total` counts all of them (every one is corrected and logged; issue #271), `pruned` the folded counter rows at 0 it removed, `failed` the scopes whose reconcile failed (the pass goes on with the others; then `success` is `false` and the status `500`). The scheduler runs the same pass on `scheduler.block_count_reconcile_interval` — see [operations](operations.md#migration-170-block-counters-behind-stats-guard-stats-and-list-categories). -- **Keys/clients:** `api-key-create` requires `home_scope`; key + MCP-client management and mutating `dream-mode` require an **admin key** since migration 052 (see [security](security.md#admin-tier)). `api-key-create`/`api-key-update` accept optional `write_scopes` (078, E4b) — explicit per-key write scopes that must be ⊆ `allowed_scopes ∪ {home_scope}` (else 400); the effective block-write gate and its double enforcement are in [multi-tenancy](multi-tenancy.md#per-key-write-scopes-e4b-migration-078). Per-tenant scoping of the `api-key-*` actions and the tenant lifecycle (`tenant-*`, `tenant-grant-*`, `scope-*`, `tenant-limit-set`, `tenant-usage-get`, `tenant-quota-*`, `block-grant-*`) are in [multi-tenancy](multi-tenancy.md). +- **Keys/clients:** `api-key-create` requires `home_scope`; key + MCP-client management and mutating `dream-mode` require an **admin key** since migration 052 (see [security](security.md#admin-tier)). `api-key-create`/`api-key-update` accept optional `write_scopes` (078, E4b) — explicit per-key write scopes that must be ⊆ `allowed_scopes ∪ {home_scope}` (else 400); the effective block-write gate and its double enforcement are in [multi-tenancy](multi-tenancy.md#per-key-write-scopes-e4b-migration-078). They also accept `scope_narrowing` (migration 198): `required` makes the key answer every request without a [narrowing](#scope-narrowing-per-request) with `403 scope_narrowing_required`, `GET /api/whoami` excepted; `optional` (every existing key, the default) keeps today's behaviour; any other value is 400. Both answers carry the value; `api-key-list` lists it. Per-tenant scoping of the `api-key-*` actions and the tenant lifecycle (`tenant-*`, `tenant-grant-*`, `scope-*`, `tenant-limit-set`, `tenant-usage-get`, `tenant-quota-*`, `block-grant-*`) are in [multi-tenancy](multi-tenancy.md). - **Block-type registry:** `type-list`/`type-get` are open reads; `type-create`/`type-update`/`type-delete` are the **operator transport** (server-admin, `_global` namespace) of the same store logic the REST `PUT/DELETE /api/types/{name}` surface uses — kept functional for MCP/CLI consumers, not superseded (see [Block-type registry](#block-type-registry)). `manage update` accepts a registry-validated `type` field; `list-meta` accepts the `types`/`types_exclude` filters. - **Issue corpus:** `issue-create`/`issue-update`/`issue-get`/`issue-list`/`issue-comment-create`/`issue-link-create`/`issue-link-delete` are the **operator transport** (all tierOpen; isolation is store-layer scope filtering, not an admin tier) over the same store issue logic the REST `/api/project` issue surface (W6/W7) uses — kept reachable for MCP/CLI operators, not the primary UI surface (see [Issue corpus](#issue-corpus)). - **Backend pool:** `backend-list`/`create`/`update`/`delete`/`test` — see [Backend pool](#backend-pool). diff --git a/docs/cli.md b/docs/cli.md index f1f340a4e..6f03a3be4 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -110,7 +110,7 @@ Three deliberate exceptions, unchanged: | Command | Description | |---------|-------------| -| `ctx keys create <label> --home <scope> [--allowed a,b] [--write a]` | Provision API key (v2.0.0: `--home` required, no default scope; admin key required since migration 052). `--write` (078, E4b) grants extra write scopes; each must be ⊆ home + allowed (else 400) | +| `ctx keys create <label> --home <scope> [--allowed a,b] [--write a] [--require-narrowing]` | Provision API key (v2.0.0: `--home` required, no default scope; admin key required since migration 052). `--write` (078, E4b) grants extra write scopes; each must be ⊆ home + allowed (else 400). `--require-narrowing` (migration 198) mints the key with `scope_narrowing: required`: it answers only requests that name their scopes (`X-Context-Read-Scopes`), `whoami` excepted; `keys list` marks such keys `narrowing=required` | | `ctx keys [list\|delete]` | List / revoke provisioned API keys (admin key required since 052); `list` shows `write=[…]` when a key carries write scopes | | `ctx tenant [list\|get\|create\|update\|delete]` | Tenant lifecycle (**server-admin key**). `create <slug> <name>` is the compound bootstrap: tenant + initial scope `<slug>:main` + owner key (plaintext shown once). `delete <id>` waits for the server's answer without the 120 s client timeout — the delete runs to its end on the server either way; a request that ends before the answer, or a proxy's `502`/`504`, says that the delete may still be running and the tenant stays offboarding until it ends ([operations](operations.md), issue #555). TTY: table, pipe: JSON; API failures (403/404/400) exit 1 | | `ctx tenant grant [create\|list\|delete]` | Cross-tenant read grants (**server-admin key**): grant another tenant read access to one scope; delete revokes immediately | diff --git a/docs/mcp.md b/docs/mcp.md index fef9ee5ba..c73b22e50 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -110,8 +110,8 @@ The codes are the ones the HTTP API uses for the same class: `parent_required`, `unknown_parent`, `unknown_supersedes`, `unknown_block`, `supersedes_conflict`, `supersedes_not_allowed`, `reserved_category`, `provenance_protected`, `reserved_metadata`, `unknown_action`, `constraint`, `edit_mismatch`, `rate_limit`, `write_conflict`, `internal`; -the HTTP answers `scope_narrowing_invalid` and `scope_narrowing_route` belong to a request's scope narrowing, -which `/mcp` refuses as a whole ([api](api.md#scope-narrowing-per-request)) +the HTTP answers `scope_narrowing_invalid`, `scope_narrowing_route` and `scope_narrowing_required` belong to a request's +scope narrowing, which `/mcp` refuses as a whole (and a key that requires one gets no `/mcp` at all) ([api](api.md#scope-narrowing-per-request)) (`TestRejectClassesAreDocumented` holds this list and the one in [api](api.md) to the classes of the handler). Other errors (an unknown id, an invalid type filter) carry text only, so a client must not rely on a code being present. A fault of the database under a diff --git a/docs/multi-tenancy.md b/docs/multi-tenancy.md index b2cb6211e..644a6ec7e 100644 --- a/docs/multi-tenancy.md +++ b/docs/multi-tenancy.md @@ -74,6 +74,10 @@ The routes a narrowed request may take are a closed list — `POST /api/query`, What it is for: a client that serves several groups of people with one server names the scopes of the group it serves on every request and checks the echo, so each group reads and writes exactly its scopes, whatever else the key could read. +### Required narrowing (migration 198) + +Migration 198 adds `context_api_keys.scope_narrowing TEXT NOT NULL DEFAULT 'optional' CHECK (optional | required)` and rebuilds `ctx_auth_by_id` and `ctx_auth` with it as the **12th** return column (appended after `principal_id`, the 078/090/095 convention). A key with `required` answers every request **without** a narrowing with `403 scope_narrowing_required` — reads, writes, `/mcp`, the session surface —, `GET /api/whoami` excepted, which reports `scope_narrowing`. The check sits in `narrowAuth`, beside the narrowing it demands. A key that belongs to one group of people is minted `required` (`ctx keys create … --require-narrowing`, or `scope_narrowing: "required"` on `api-key-create`): then the key itself is the boundary, not the care of its client — an old client, a client that forgets the headers, or another tool holding the same key reaches nothing, and with a narrowing it may only shrink the key's rights. Every existing key is `optional` and behaves as before; `api-key-update {scope_narrowing}` switches it (tenant-admin, like `write_scopes`; a server-admin key only by a server-admin). The switch applies from the next request: `ctx_auth_by_id` reads the column from the key row it locks for `last_used_at`, and nothing caches an authentication. Turning it on or off writes an `api_key` audit row like any other key change ([security](security.md)). On an owner key the requirement is owner power: a key that requires narrowing administers nothing (unnarrowed it gets only whoami, narrowed it runs as a `member`), so only an owner or a server-admin switches an owner key to `required`, and never the last owner that can still administer the tenant — an owner counts for the last-owner invariant only while it is active and `optional`. The two event streams (`/api/project/events`, `/api/events`) re-authenticate their key periodically and end once it requires narrowing (they are never narrowed); `/register` in admin mode, which resolves its key outside the Auth middleware, applies the same rules (a key that requires narrowing, or a narrowed request, registers nothing). + ## Block-level grants (row level) `context_block_grants` (migration 067) shares **one** `block_id` with a `grantee_tenant` — a granularity finer than the scope-level grants. `block_id` and `grantee_tenant` are both FK `ON DELETE CASCADE` (a deleted block or offboarded grantee drops its grants — contrast `context_dream_links`, which blocks the delete); `granted_by` is an `ON DELETE SET NULL` audit pointer; `uq_block_grant (block_id, grantee_tenant)` is the idempotency guard and `idx_block_grants_grantee (grantee_tenant, block_id)` the hot-read index. Deliberately **no `permission` column** (a single-value `'read'` enum gates nothing today — additive later). New table on an empty relation, so no `context_blocks` lock and no 1M index build. @@ -256,7 +260,7 @@ Migration 069 adds structural per-tenant count-limits on `context_tenants`: `max | `tenant-limit-set` | server-admin | Sets a tenant's structural ceiling (both `max_scopes`/`max_keys` required, range `0..1_000_000`, explicit null = unlimited); optionally seeded at `tenant-create` over the 069 defaults. A tenant-admin raising its own limit would void it. The optional `max_model_consumers` (same range, null = unlimited, absent = unchanged; migration 161 default 64 for every tenant) caps the tenant's **active** model consumers: `model-consumer-create` and a reactivation beyond it answer `429`; `0` freezes. Tenant answers carry the value. | | `tenant-usage-get` | tenant-admin (own) | Scope/key counts vs limits; a server-admin may target any. | | `api-key-create` | tenant-admin | Enforces `max_keys` transactionally (429, active-only count); a server-admin may mint into another tenant via `tenant_id` (foreign-target T22 — the new key's scopes must belong to the target; a non-server-admin's `tenant_id` → 403, AM2). New keys are always `member` (a smuggled `tenant_role` is ignored, AM3). Optional `write_scopes` (078, E4b) must be ⊆ `allowed_scopes ∪ {home_scope}` else 400 (see [Per-key write scopes](#per-key-write-scopes-e4b-migration-078)). | -| `api-key-update` | tenant-admin | Role delegation (`{tenant_role?, active?, write_scopes?}`): only an owner (or server-admin) may change a key's role — a non-owner tenant-admin → 403, so admin→owner self-elevation is structurally impossible (no `is_admin` field means the server-global tier can never be set here). Demoting/deactivating the last active owner → 409 (last-owner invariant); an admin cannot neutralize an owner key → 403 (enforced at both update and the `api-key-delete` revoke path). A server-admin key (`is_admin`) is managed by server-admins only: any tenant-owner/-admin patch or revoke of it → 403, so a default-tenant admin cannot disable the operator's key. `write_scopes` (078, E4b) is validated ⊆ the key's existing `allowed_scopes ∪ {home_scope}` → 400 on a blind-writer; `[]` clears, absent leaves unchanged. | +| `api-key-update` | tenant-admin | Role delegation (`{tenant_role?, active?, write_scopes?}`): only an owner (or server-admin) may change a key's role — a non-owner tenant-admin → 403, so admin→owner self-elevation is structurally impossible (no `is_admin` field means the server-global tier can never be set here). Demoting/deactivating the last active owner → 409 (last-owner invariant); an admin cannot neutralize an owner key → 403 (enforced at both update and the `api-key-delete` revoke path). A server-admin key (`is_admin`) is managed by server-admins only: any tenant-owner/-admin patch or revoke of it → 403, so a default-tenant admin cannot disable the operator's key. `write_scopes` (078, E4b) is validated ⊆ the key's existing `allowed_scopes ∪ {home_scope}` → 400 on a blind-writer; `[]` clears, absent leaves unchanged. `scope_narrowing` (198): switching an owner key to `required` takes its administration away, so it counts as neutralizing it (admin → 403) and the last-owner invariant counts only owners that are active **and** `optional` (409 for the last one, also on `api-key-delete`). Both actions decide the owner rules on the target as it is under the tenant row lock every key write takes, so a concurrent change of its role, `active` or `scope_narrowing` is seen, not raced. | | `gateway-limits-get` | tenant-admin (own) | Reads the limits rows of an own consumer or the own tenant with the ceiling and the effective values ([api](api.md#gateway-limits-gateway-limits-)); instance and envelope values stay server-admin. | | `gateway-limits-set` | tenant-admin (own) | Writes the caller's **tenant-tier** row of an own consumer or the own tenant — narrowing only (each value at or under the ceiling of the levels above, else 400 with the field; `allow_external` only `false`). A server-admin writes the server tier freely, including `instance` and `tenant_envelope`. | | `gateway-limits-delete` | tenant-admin (own) | Removes the caller's tier row; the dimension inherits again. | diff --git a/docs/operations.md b/docs/operations.md index 49c988dae..f33af6487 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -2394,6 +2394,14 @@ Issue #571. `context_model_consumers.record_bodies BOOLEAN NOT NULL DEFAULT fals **Rolling deploy and way back.** The release before (v5.89.0) runs unchanged on a database with 197 (executed: its auth, model-key door, consumer administration and `/v1` chat-row tests over a schema with 197): its door selects `ctx_model_auth`'s columns by name and does not see the new one, its consumer writes leave the column at its default, and it serves a recording consumer as before — **without recording it** (it knows neither the switch nor the table). Run the two side by side only while no consumer records, or accept that the older process's share of that consumer's requests is not held — that is the rolling deploy; it does not carry over to the way back. Its schema-contract check reports the unknown migration as for every release ahead of it (`schema_contract: attention`; mode `enforce` refuses to start). The way back: first stop every ctxd process of a release that embeds migration 197 and keep it stopped until the steps below are done and only the older release runs — a process of 197 that keeps running fails at its model-key door once `ctx_model_auth` has its 161 shape again, and one that starts after the `_migrations` row is gone applies 197 again and undoes the way back. Then, in this order: `DROP TABLE context_llm_recordings;` (its rows go with it — read them out first); `DROP FUNCTION ctx_model_auth(TEXT, INET, BOOLEAN);` the `CREATE OR REPLACE FUNCTION ctx_model_auth` of migration 161 (section 8); the `CREATE OR REPLACE FUNCTION audit_state_model_consumer` of 161 (section 7); `DROP TRIGGER trg_model_consumers_audit_upd ON context_model_consumers;` and the `CREATE TRIGGER trg_model_consumers_audit_upd` of 161; `ALTER TABLE context_model_consumers DROP COLUMN record_bodies;` `DELETE FROM _migrations WHERE version = 197;` — `TestMigration197Idempotent` runs exactly these and compares the catalog with 196's. +### Migration 198: a key can require per-request scope narrowing + +`context_api_keys.scope_narrowing TEXT NOT NULL DEFAULT 'optional' CHECK (optional | required)` — every key reads `optional` after the upgrade and behaves as before (the value names no scope: a tenant's offboarding deletes its keys with it as before); a key switched to `required` answers every request without `X-Context-Read-Scopes` with `403 scope_narrowing_required`, `GET /api/whoami` excepted ([multi-tenancy](multi-tenancy.md#required-narrowing-migration-198)). `ctx_auth_by_id` and `ctx_auth` gain the column as their last one; the audit projection `audit_state_api_key` and the trigger `trg_api_keys_audit_upd` gain it, so every switch is an `update` row of `api_key`. + +**Locks.** `ADD COLUMN` with a constant default rewrites no row, but its `CHECK` reads every key once, under the `ACCESS EXCLUSIVE` lock on `context_api_keys` that lasts to the commit — while it is held every authentication waits (`ctx_auth_by_id` writes `last_used_at`). Measured with `TestMigration198LockWindow` (`CTX_M198_KEYS=100000,1000000`, a test container on the build host, warm cache): the whole file took 46 ms on 100 000 keys and 215 ms on 1 000 000 keys, where an authentication started 50 ms in answered after 167 ms. The scan grows with the number of keys, not of blocks; a key table of ten million rows would hold authentications for about two seconds by that line (not measured). `CREATE TRIGGER` and the function rebuild add no lock wait of their own; `lock_timeout` 3 s. After the upgrade a switch of `scope_narrowing` applies from the next authentication: `ctx_auth_by_id` reads the column from the key row its `last_used_at` update locks, so an authentication that meets an uncommitted switch waits for it and answers the committed value (executed: `TestMigration198AuthReadsTheLockedRow`, with the switch held open on a second connection). + +**Rolling deploy and way back.** A binary before 198 on a database with 198 selects `ctx_auth`'s columns by name (executed: the eleven-column statement answers at 198, `TestMigration198WayBack`), mints keys that read `optional`, and serves **every** key without the requirement — the check lives in the binary. Before rolling the binary back, deactivate the keys that require narrowing (`api-key-update {active: false}`), or accept that each then reaches everything its own rights allow. The way back of the schema is in the header of `198_api_key_scope_narrowing.sql` and executed by `TestMigration198WayBack`; after it, and after 198 runs again, every key reads `optional` — the requirements are not restored. + ### `graph_overview.csr_loader`: the rebuild's input substrate `CTX_GRAPH_OVERVIEW_CSR_LOADER` (default `false`, hot) switches how the rebuild gets its graph into memory. It changes no result — the partition, the modularity and the intra-cluster degrees are byte-identical either way, and that identity is a gate, not a hope. diff --git a/docs/security.md b/docs/security.md index b40b96dbd..c725488ff 100644 --- a/docs/security.md +++ b/docs/security.md @@ -47,7 +47,7 @@ PGPASSWORD="$CONTEXT_DB_PASSWORD" docker compose exec -e PGPASSWORD db \ **Actions.** Keys: `create`, `update`, `revoke` (active true → false), `reactivate` (false → true), `delete`. `api-key-delete` is the soft revoke and records `revoke`; `delete` is the hard delete of a tenant's keys by `tenant-delete`, or a `psql` `DELETE`. Quotas: `create`, `update`, `delete`. Model consumers: `create`, `deactivate` (active true → false), `reactivate`, `update`, `prune`; model keys: `create`, `revoke` (`revoked_at` set), `update`, `prune`; model aliases: `create`, `update`, `delete`; model grants: `grant`, `ungrant` (a grant is only added or removed — its `consumer_id` and `alias_id` are immutable, SQLSTATE `23514`, `psql` included — so there is no `update`; a grant that goes with its alias is an `ungrant` attributed to the alias's deleter, the tenant prune removes a tenant's grants as `ungrant` rows of the offboarding); the instance identity: `rotate` (`instance_id` changed), `update` (`created_at`/`rotated_at` only), `delete` (the row removed — ctxd then refuses to start), `create` (a row inserted by hand; the migration's own creation writes no row). Deactivating a consumer revokes every live key it has and refuses new ones (a key insert into an inactive consumer fails with SQLSTATE `23514`; an insert and a deactivation running at the same time wait for each other on the consumer row, so under READ COMMITTED, which ctx uses for every write, the new key is either revoked or refused — a deactivation run by hand under `REPEATABLE READ` does not revoke a key committed after its snapshot), `psql` included, and records one `revoke` row per key; `prune` is the hard delete of a tenant's consumers and keys (offboarding) or a `psql` `DELETE`. `snapshot` rows are the state migration 160 found (one per key and quota row that had no history yet). An `UPDATE` that changes nothing audited records nothing — a re-set of the same quota, and above all the `last_used_at` write of every authenticated request: authentication never adds an audit row. -**What a row carries.** `old_value`/`new_value` hold a whitelist of columns, never the row as such. Keys: `label`, `home_scope`, `allowed_scopes`, `write_scopes`, `active`, `is_admin`, `tenant_id`, `tenant_role`, `confirm_writes`, `principal_id`. Quotas: `scope`, `daily_cost_usd`, `monthly_cost_usd`, `daily_calls`, `on_exceed`, `enabled`. Model consumers: `tenant_id`, `label`, `description`, `kind`, `tenant_scope`, `all_models`, `prompt_sensitivity`, `fair_weight`, `admission_lane`, `allowed_cidrs`, `allow_plaintext`, `active`, `peer_instance_id`, `peer_bound_at` (binding a peer and resetting the binding are identity events). Model keys: `consumer_id`, `key_hint`, `expires_at`, `revoked_at`, `rotated_from`. Model aliases: `scope`, `name`, `kind`, `role`, `sensitivity`, `policy`, `description`, `enabled` (the alias's `id` is the `entity_key`). Model grants: `consumer_id`, `alias_id`. Instance identity: `instance_id`, `created_at`, `rotated_at`. Never recorded: `instance_secret` (a write of it alone adds no row), `key_hash` of either key kind, `last_used_at` (the per-request write of knowledge-key authentication, the batched usage stamp of model keys), the `created_at`/`updated_at` bookkeeping, the actor columns (the quota's `updated_by`, the model tables' `created_by_*`/`revoked_by_*` — the actor travels in `api_key_id`, `actor_label` and `metadata`; their reset when the actor's key is deleted writes no row) and the quota's free-form `metadata`. A test pins every column of these tables as audited or excluded, and every table an audit trigger writes for as classified; a column a later migration adds stays red until someone classifies it, so a new secret cannot slip into the audit table unnoticed. A consumer's `tenant_id` and a key's `consumer_id` are immutable (a trigger refuses the change with SQLSTATE `23514`, `psql` included): a key never moves to another consumer's policy, a consumer never takes its keys into another tenant. The same holds for an alias's `id`, `name`, `kind` and `scope`: a model id keeps its meaning, its history stays under one key, and an alias never carries one tenant's releases into another (renaming is delete + create, and releases bind the alias id). A `TRUNCATE` of the alias table bypasses the row triggers and so the trail — remove aliases with `DELETE`. +**What a row carries.** `old_value`/`new_value` hold a whitelist of columns, never the row as such. Keys: `label`, `home_scope`, `allowed_scopes`, `write_scopes`, `active`, `is_admin`, `tenant_id`, `tenant_role`, `confirm_writes`, `principal_id`, `scope_narrowing` (since migration 198; older rows lack the key). Quotas: `scope`, `daily_cost_usd`, `monthly_cost_usd`, `daily_calls`, `on_exceed`, `enabled`. Model consumers: `tenant_id`, `label`, `description`, `kind`, `tenant_scope`, `all_models`, `prompt_sensitivity`, `fair_weight`, `admission_lane`, `allowed_cidrs`, `allow_plaintext`, `active`, `peer_instance_id`, `peer_bound_at` (binding a peer and resetting the binding are identity events). Model keys: `consumer_id`, `key_hint`, `expires_at`, `revoked_at`, `rotated_from`. Model aliases: `scope`, `name`, `kind`, `role`, `sensitivity`, `policy`, `description`, `enabled` (the alias's `id` is the `entity_key`). Model grants: `consumer_id`, `alias_id`. Instance identity: `instance_id`, `created_at`, `rotated_at`. Never recorded: `instance_secret` (a write of it alone adds no row), `key_hash` of either key kind, `last_used_at` (the per-request write of knowledge-key authentication, the batched usage stamp of model keys), the `created_at`/`updated_at` bookkeeping, the actor columns (the quota's `updated_by`, the model tables' `created_by_*`/`revoked_by_*` — the actor travels in `api_key_id`, `actor_label` and `metadata`; their reset when the actor's key is deleted writes no row) and the quota's free-form `metadata`. A test pins every column of these tables as audited or excluded, and every table an audit trigger writes for as classified; a column a later migration adds stays red until someone classifies it, so a new secret cannot slip into the audit table unnoticed. A consumer's `tenant_id` and a key's `consumer_id` are immutable (a trigger refuses the change with SQLSTATE `23514`, `psql` included): a key never moves to another consumer's policy, a consumer never takes its keys into another tenant. The same holds for an alias's `id`, `name`, `kind` and `scope`: a model id keeps its meaning, its history stays under one key, and an alias never carries one tenant's releases into another (renaming is delete + create, and releases bind the alias id). A `TRUNCATE` of the alias table bypasses the row triggers and so the trail — remove aliases with `DELETE`. **Who and how.** `api_key_id` and `actor_label` name the acting key (the label as it was at write time); `metadata` adds `actor_principal`, `actor_tenant_id` and `actor_server_admin` (the reader needs them to hide server-admin actors from tenant-admins), `request_id` (the `X-Request-ID` the response carries — a correlation id, the caller's own when it sent a valid one), `tenant_id` (the tenant the key, quota, model consumer or model alias belongs to — a model key row takes it from its consumer, a model alias row from the tenant owning its scope, and a `_global` alias has none, so the operator catalog's history is server-admin-only; the filter a tenant-admin view applies), `consumer_id` on model consumer, model key and model grant rows, `alias_id` on model grant rows (a grant row takes `tenant_id` from its consumer), `confirm_sensitivity_downgrade` (`true`) on a model alias row whose writer confirmed lowering the alias's sensitivity, and `via`, the channel: diff --git a/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go b/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go index d1e4e1a4a..e8d9e629d 100644 --- a/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go +++ b/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go @@ -1,4 +1,4 @@ -//go:build integration && s1red_c2 +//go:build integration // Achse 02, cluster C-2 (design2/02-ctx-checkpoint.md §3.5 C-2, §7.3): a key // can require narrowing (context_api_keys.scope_narrowing, migration 198). A diff --git a/go/cmd/ctxd/scope_narrowing_required_c2_more_integration_test.go b/go/cmd/ctxd/scope_narrowing_required_c2_more_integration_test.go new file mode 100644 index 000000000..2c8e33c01 --- /dev/null +++ b/go/cmd/ctxd/scope_narrowing_required_c2_more_integration_test.go @@ -0,0 +1,71 @@ +//go:build integration + +// Achse 02, cluster C-2: requiring narrowing takes a key's administration +// away — unnarrowed it answers nothing but whoami, and a narrowed request is +// never an administration request. On an OWNER key that is owner power: +// only an owner or a server-admin may switch it on there, and never on the +// last owner that can still administer the tenant. +// +// go test -tags=integration -p 1 -count=1 -run '^TestC2' ./cmd/ctxd/ +package main + +import ( + "net/http" + "testing" +) + +// TestC2RequiredNarrowingOnAnOwnerKeyIsOwnerPower: a tenant-admin cannot +// switch the owner's key to required (403, like deactivating it); the owner +// cannot switch the tenant's last usable owner key to required (409); with a +// second owner it can, and then that second owner — the last one without the +// requirement — can neither step down nor revoke itself (409). +func TestC2RequiredNarrowingOnAnOwnerKeyIsOwnerPower(t *testing.T) { + w := c2Setup(t) + r := w.manage(t, c2AdminKey, map[string]any{"action": "tenant-create", + "data": map[string]any{"slug": "c2own", "display_name": "C2 owner"}}).must(t, "tenant-create") + owner, _ := r.body["owner_key"].(string) + scope, _ := r.body["scope"].(string) + if owner == "" || scope == "" { + t.Fatalf("fixture tenant-create: %s", r.raw) + } + ownerID, _ := w.do(t, http.MethodGet, "/api/whoami", owner, nil, nil).must(t, "owner whoami").body["api_key_id"].(string) + r = w.manage(t, owner, map[string]any{"action": "api-key-create", "data": map[string]any{"label": "c2own-admin", "home_scope": scope}}).must(t, "owner mints a key") + adminKey, _ := r.body["api_key"].(string) + adminID, _ := r.body["id"].(string) + w.manage(t, owner, map[string]any{"action": "api-key-update", "data": map[string]any{"id": adminID, "tenant_role": "admin"}}).must(t, "owner makes it an admin") + + update := func(caller, id, narrowing string) c2Resp { + t.Helper() + return w.manage(t, caller, map[string]any{"action": "api-key-update", "data": map[string]any{"id": id, "scope_narrowing": narrowing}}) + } + // Control: the owner guard refuses the admin's deactivation of the owner key. + if r := w.manage(t, adminKey, map[string]any{"action": "api-key-update", "data": map[string]any{"id": ownerID, "active": false}}); r.status != http.StatusForbidden { + t.Fatalf("fixture: the admin deactivates the owner key: HTTP %d %s, want 403", r.status, r.raw) + } + + if r := update(adminKey, ownerID, "required"); r.status != http.StatusForbidden { + t.Errorf("the admin switches the owner key to required: HTTP %d %s, want 403", r.status, r.raw) + } + if r := update(owner, ownerID, "required"); r.status != http.StatusConflict { + t.Errorf("the owner switches the tenant's last owner key to required: HTTP %d %s, want 409", r.status, r.raw) + } + if got := w.scopeNarrowing(t, owner); got != "optional" { + t.Fatalf("after the refusals the owner key reads %q, want optional", got) + } + + // A second owner: now the first may require narrowing ... + w.manage(t, owner, map[string]any{"action": "api-key-update", "data": map[string]any{"id": adminID, "tenant_role": "owner"}}).must(t, "owner makes the admin a second owner") + update(owner, ownerID, "required").must(t, "the owner switches itself to required beside a second owner") + // ... and the second, the last owner without the requirement, cannot step down. + if r := w.manage(t, adminKey, map[string]any{"action": "api-key-update", "data": map[string]any{"id": adminID, "tenant_role": "member"}}); r.status != http.StatusConflict { + t.Errorf("the last owner without the requirement steps down: HTTP %d %s, want 409", r.status, r.raw) + } + if r := update(adminKey, adminID, "required"); r.status != http.StatusConflict { + t.Errorf("the last owner without the requirement switches itself to required: HTTP %d %s, want 409", r.status, r.raw) + } + if r := w.manage(t, adminKey, map[string]any{"action": "api-key-delete", "data": map[string]any{"id": adminID}}); r.status != http.StatusConflict { + t.Errorf("the last owner without the requirement revokes itself: HTTP %d %s, want 409", r.status, r.raw) + } + // The way back stays open to it. + update(adminKey, ownerID, "optional").must(t, "the second owner lifts the first owner's requirement") +} diff --git a/go/internal/auth/auth.go b/go/internal/auth/auth.go index 8e153ae90..34f924666 100644 --- a/go/internal/auth/auth.go +++ b/go/internal/auth/auth.go @@ -113,32 +113,34 @@ func Authenticate(ctx context.Context, pool *pgxpool.Pool, apiKey string) (*Auth readScopes []string isValid bool isAdmin bool - tenantID *string // nullable UUID (NULL in the miss/suspended sentinel paths) - tenantRole string // never NULL ('' in the sentinel paths) + tenantID *string // nullable UUID (NULL in the miss/suspended sentinel paths) + tenantRole string // never NULL ('' in the sentinel paths) writeScopes []string // 078 (E4b): RAW write-scope set; '{}' in the sentinel paths confirmWrites bool // 090 (D-W4): per-key confirm opt-in; false in the sentinel paths principalID *string // 095 (F2): nullable UUID (NULL in the sentinel paths) + narrowing string // 198 (Achse 02 C-2): optional|required; 'required' in the sentinel paths ) - // principal_id is the LAST ctx_auth column (095, appended after - // confirm_writes so this named SELECT stays valid across the DROP+CREATE). + // scope_narrowing is the LAST ctx_auth column (198, appended after + // principal_id so this named SELECT stays valid across the DROP+CREATE). err := pool.QueryRow(ctx, - `SELECT api_key_id, home_scope, allowed_scopes, read_scopes, is_valid, is_admin, tenant_id, tenant_role, write_scopes, confirm_writes, principal_id FROM ctx_auth($1)`, + `SELECT api_key_id, home_scope, allowed_scopes, read_scopes, is_valid, is_admin, tenant_id, tenant_role, write_scopes, confirm_writes, principal_id, scope_narrowing FROM ctx_auth($1)`, apiKey, - ).Scan(&apiKeyID, &homeScope, &allowedScopes, &readScopes, &isValid, &isAdmin, &tenantID, &tenantRole, &writeScopes, &confirmWrites, &principalID) + ).Scan(&apiKeyID, &homeScope, &allowedScopes, &readScopes, &isValid, &isAdmin, &tenantID, &tenantRole, &writeScopes, &confirmWrites, &principalID, &narrowing) if err != nil { return nil, fmt.Errorf("auth: query ctx_auth: %w", err) } result := &AuthResult{ - HomeScope: homeScope, - AllowedScopes: allowedScopes, - ReadScopes: readScopes, - IsValid: isValid, - IsAdmin: isAdmin, - TenantRole: Role(tenantRole), // text column → named Role type (domain pinned to 059 CHECK, K4) - WriteScopes: writeScopes, - ConfirmWrites: confirmWrites, + HomeScope: homeScope, + AllowedScopes: allowedScopes, + ReadScopes: readScopes, + IsValid: isValid, + IsAdmin: isAdmin, + TenantRole: Role(tenantRole), // text column → named Role type (domain pinned to 059 CHECK, K4) + WriteScopes: writeScopes, + ConfirmWrites: confirmWrites, + ScopeNarrowing: narrowing, } if apiKeyID != nil { @@ -179,25 +181,27 @@ func AuthenticateByID(ctx context.Context, pool *pgxpool.Pool, apiKeyID string) writeScopes []string confirmWrites bool principalID *string + narrowing string ) err := pool.QueryRow(ctx, - `SELECT api_key_id, home_scope, allowed_scopes, read_scopes, is_valid, is_admin, tenant_id, tenant_role, write_scopes, confirm_writes, principal_id FROM ctx_auth_by_id($1::uuid)`, + `SELECT api_key_id, home_scope, allowed_scopes, read_scopes, is_valid, is_admin, tenant_id, tenant_role, write_scopes, confirm_writes, principal_id, scope_narrowing FROM ctx_auth_by_id($1::uuid)`, apiKeyID, - ).Scan(&keyID, &homeScope, &allowedScopes, &readScopes, &isValid, &isAdmin, &tenantID, &tenantRole, &writeScopes, &confirmWrites, &principalID) + ).Scan(&keyID, &homeScope, &allowedScopes, &readScopes, &isValid, &isAdmin, &tenantID, &tenantRole, &writeScopes, &confirmWrites, &principalID, &narrowing) if err != nil { return nil, fmt.Errorf("auth: query ctx_auth_by_id: %w", err) } result := &AuthResult{ - HomeScope: homeScope, - AllowedScopes: allowedScopes, - ReadScopes: readScopes, - IsValid: isValid, - IsAdmin: isAdmin, - TenantRole: Role(tenantRole), - WriteScopes: writeScopes, - ConfirmWrites: confirmWrites, + HomeScope: homeScope, + AllowedScopes: allowedScopes, + ReadScopes: readScopes, + IsValid: isValid, + IsAdmin: isAdmin, + TenantRole: Role(tenantRole), + WriteScopes: writeScopes, + ConfirmWrites: confirmWrites, + ScopeNarrowing: narrowing, } if keyID != nil { diff --git a/go/internal/cli/commands.go b/go/internal/cli/commands.go index 1f790e906..fadc908fc 100644 --- a/go/internal/cli/commands.go +++ b/go/internal/cli/commands.go @@ -1348,9 +1348,10 @@ func keysCmd(getClient func() (*Client, error)) *cobra.Command { func keysCreateCmd(getClient func() (*Client, error)) *cobra.Command { var ( - homeScope string - allowedScopes []string - writeScopes []string + homeScope string + allowedScopes []string + writeScopes []string + requireNarrowing bool ) cmd := &cobra.Command{ Use: "create <label>", @@ -1358,6 +1359,7 @@ func keysCreateCmd(getClient func() (*Client, error)) *cobra.Command { Example: ` ctx keys create bench-crag --home crag ctx keys create work-key --home work --allowed shared,work ctx keys create writer --home private --allowed shared,work --write work + ctx keys create group-key --home members --allowed knowledge --require-narrowing ctx keys create temp --home private --allowed shared`, Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -1381,6 +1383,11 @@ func keysCreateCmd(getClient func() (*Client, error)) *cobra.Command { if len(writeScopes) > 0 { data["write_scopes"] = writeScopes } + // scope_narrowing (198): the key answers only requests that name + // their scopes (X-Context-Read-Scopes), whoami excepted. + if requireNarrowing { + data["scope_narrowing"] = "required" + } resp, err := c.Post("manage", map[string]any{ "action": "api-key-create", "data": data, @@ -1389,12 +1396,13 @@ func keysCreateCmd(getClient func() (*Client, error)) *cobra.Command { return err } var result struct { - ID string `json:"id"` - Label string `json:"label"` - HomeScope string `json:"home_scope"` - AllowedScopes []string `json:"allowed_scopes"` - WriteScopes []string `json:"write_scopes"` - ApiKey string `json:"api_key"` + ID string `json:"id"` + Label string `json:"label"` + HomeScope string `json:"home_scope"` + AllowedScopes []string `json:"allowed_scopes"` + WriteScopes []string `json:"write_scopes"` + ScopeNarrowing string `json:"scope_narrowing"` + ApiKey string `json:"api_key"` } if err := json.Unmarshal(resp, &result); err != nil { PrintJSON(resp) @@ -1408,6 +1416,9 @@ func keysCreateCmd(getClient func() (*Client, error)) *cobra.Command { fmt.Printf(" home_scope: %s\n", result.HomeScope) fmt.Printf(" allowed_scopes: %v\n", result.AllowedScopes) fmt.Printf(" write_scopes: %v\n", result.WriteScopes) + if result.ScopeNarrowing != "" { + fmt.Printf(" scope_narrowing: %s\n", result.ScopeNarrowing) + } fmt.Printf(" api_key: %s\n", result.ApiKey) fmt.Printf("\n Save the key now — it cannot be retrieved later.\n") return nil @@ -1416,6 +1427,7 @@ func keysCreateCmd(getClient func() (*Client, error)) *cobra.Command { cmd.Flags().StringVar(&homeScope, "home", "", "home_scope for the new key (REQUIRED, e.g. 'private', 'work', 'crag')") cmd.Flags().StringSliceVar(&allowedScopes, "allowed", nil, "additional allowed read scopes (comma-separated, default: shared)") cmd.Flags().StringSliceVar(&writeScopes, "write", nil, "additional write scopes (comma-separated; must be ⊆ home + allowed) [078]") + cmd.Flags().BoolVar(&requireNarrowing, "require-narrowing", false, "the key answers only requests that name their scopes (X-Context-Read-Scopes); whoami excepted [198]") return cmd } @@ -1446,13 +1458,14 @@ func keysListRun(getClient func() (*Client, error)) error { } var result struct { Keys []struct { - ID string `json:"id"` - Label string `json:"label"` - HomeScope string `json:"home_scope"` - AllowedScopes []string `json:"allowed_scopes"` - WriteScopes []string `json:"write_scopes"` - Active bool `json:"active"` - CreatedAt string `json:"created_at"` + ID string `json:"id"` + Label string `json:"label"` + HomeScope string `json:"home_scope"` + AllowedScopes []string `json:"allowed_scopes"` + WriteScopes []string `json:"write_scopes"` + ScopeNarrowing string `json:"scope_narrowing"` + Active bool `json:"active"` + CreatedAt string `json:"created_at"` } `json:"keys"` } if err := json.Unmarshal(resp, &result); err != nil { @@ -1476,6 +1489,9 @@ func keysListRun(getClient func() (*Client, error)) error { if len(k.WriteScopes) > 0 { write = fmt.Sprintf(" write=%v", k.WriteScopes) } + if k.ScopeNarrowing == "required" { + write += " narrowing=required" + } fmt.Printf(" %s %s home=%s%s [%s] %s\n", k.ID, k.Label, k.HomeScope, write, status, created) } return nil diff --git a/go/internal/handler/context_manage.go b/go/internal/handler/context_manage.go index 274e17d90..c6b3a0598 100644 --- a/go/internal/handler/context_manage.go +++ b/go/internal/handler/context_manage.go @@ -1595,6 +1595,25 @@ type apiKeyCreateRequest struct { // default reproduces v4.2.x (home_scope ∪ shared-when-allowed) exactly. WriteScopes []string `json:"write_scopes,omitempty"` TenantID string `json:"tenant_id,omitempty"` // SERVER-ADMIN ONLY + // ScopeNarrowing (198, Achse 02 C-2): "required" makes the key answer + // nothing without a per-request narrowing but GET /api/whoami; "" or + // "optional" mints it as every key before 198. + ScopeNarrowing string `json:"scope_narrowing,omitempty"` +} + +// scopeNarrowingValue validates the scope_narrowing of an api-key-create or +// api-key-update: "" leaves the default (create) or the key's value (update), +// anything but optional and required is refused with 400 before any lookup. +// ok=false means the 400 has been written. +func scopeNarrowingValue(w http.ResponseWriter, v string) (string, bool) { + switch v { + case "", auth.ScopeNarrowingOptional, auth.ScopeNarrowingRequired: + return v, true + } + writeJSON(w, http.StatusBadRequest, map[string]any{ + "success": false, "error": "scope_narrowing must be optional or required", + }) + return "", false } func (h *ManageHandler) handleApiKeyCreate(w http.ResponseWriter, r *http.Request, req manageRequest) { @@ -1633,6 +1652,13 @@ func (h *ManageHandler) handleApiKeyCreate(w http.ResponseWriter, r *http.Reques }) return } + narrowing, ok := scopeNarrowingValue(w, data.ScopeNarrowing) + if !ok { + return + } + if narrowing == "" { + narrowing = auth.ScopeNarrowingOptional + } ar := AuthResultFromContext(r.Context()) if ar == nil { @@ -1675,7 +1701,7 @@ func (h *ManageHandler) handleApiKeyCreate(w http.ResponseWriter, r *http.Reques // context_tenants-row lock (race-tight, active-only), the structural limit a // self-service tenant cannot exceed. key, plaintext, err := store.MintKeyWithQuota(r.Context(), h.pool, - data.Label, data.HomeScope, data.AllowedScopes, data.WriteScopes, bindingTenant, "member", maxKeys, + data.Label, data.HomeScope, data.AllowedScopes, data.WriteScopes, bindingTenant, "member", narrowing, maxKeys, auditStamp(r, ar)) if err != nil { switch { @@ -1695,14 +1721,15 @@ func (h *ManageHandler) handleApiKeyCreate(w http.ResponseWriter, r *http.Reques } writeJSON(w, http.StatusOK, map[string]any{ - "success": true, - "id": key.ID, - "label": key.Label, - "home_scope": key.HomeScope, - "allowed_scopes": key.AllowedScopes, - "write_scopes": key.WriteScopes, // 078: echoed so the caller sees the effective set. - "tenant_role": key.TenantRole, // Always 'member' on create (AM3). - "api_key": plaintext, // Shown once. + "success": true, + "id": key.ID, + "label": key.Label, + "home_scope": key.HomeScope, + "allowed_scopes": key.AllowedScopes, + "write_scopes": key.WriteScopes, // 078: echoed so the caller sees the effective set. + "scope_narrowing": key.ScopeNarrowing, // 198: echoed like write_scopes. + "tenant_role": key.TenantRole, // Always 'member' on create (AM3). + "api_key": plaintext, // Shown once. }) } @@ -1885,6 +1912,9 @@ type apiKeyUpdateRequest struct { // {home_scope} in the store (path (a) on update; home/allowed are not mutable // here, so the persisted row is the authority). WriteScopes *[]string `json:"write_scopes,omitempty"` + // ScopeNarrowing (198, Achse 02 C-2): "required" or "optional"; absent + // ("") leaves the key's value. + ScopeNarrowing string `json:"scope_narrowing,omitempty"` } // handleApiKeyUpdate mutates the tenant_role and/or active flag of one api key @@ -1909,12 +1939,15 @@ func (h *ManageHandler) handleApiKeyUpdate(w http.ResponseWriter, r *http.Reques writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": "id is required"}) return } - if data.TenantRole == "" && data.Active == nil && data.WriteScopes == nil { + if data.TenantRole == "" && data.Active == nil && data.WriteScopes == nil && data.ScopeNarrowing == "" { writeJSON(w, http.StatusBadRequest, map[string]any{ - "success": false, "error": "nothing to update (provide tenant_role, active and/or write_scopes)", + "success": false, "error": "nothing to update (provide tenant_role, active, write_scopes and/or scope_narrowing)", }) return } + if _, ok := scopeNarrowingValue(w, data.ScopeNarrowing); !ok { + return + } ar := AuthResultFromContext(r.Context()) if ar == nil { @@ -1939,9 +1972,13 @@ func (h *ManageHandler) handleApiKeyUpdate(w http.ResponseWriter, r *http.Reques if data.TenantRole != "" { rolePtr = &data.TenantRole } + var narrowingPtr *string + if data.ScopeNarrowing != "" { + narrowingPtr = &data.ScopeNarrowing + } updatedKey, changed, err := store.UpdateApiKey(r.Context(), h.pool, data.ID, ar.TenantID, - ar.IsServerAdmin(), callerMayManageOwner, rolePtr, data.Active, data.WriteScopes, auditStamp(r, ar)) + ar.IsServerAdmin(), callerMayManageOwner, rolePtr, data.Active, data.WriteScopes, narrowingPtr, auditStamp(r, ar)) if err != nil { switch { case errors.Is(err, store.ErrOwnerProtected): diff --git a/go/internal/handler/context_manage_writescope_w3_integration_test.go b/go/internal/handler/context_manage_writescope_w3_integration_test.go index 8c6fe0de3..6f4e87897 100644 --- a/go/internal/handler/context_manage_writescope_w3_integration_test.go +++ b/go/internal/handler/context_manage_writescope_w3_integration_test.go @@ -37,7 +37,7 @@ func TestManageWriteScope_W3StaleNeutralised(t *testing.T) { // Mint a key that LEGITIMATELY may write 'work': allowed=[shared,work] ⊇ write=[work]. key, plaintext, err := store.MintKeyWithQuota(ctx, pool, "w3-stale", "private", []string{"shared", "work"}, []string{"work"}, - store.DefaultTenantID, "member", nil, store.AuditStamp{}) + store.DefaultTenantID, "member", "optional", nil, store.AuditStamp{}) if err != nil { t.Fatalf("mint write-key: %v", err) } diff --git a/go/internal/handler/errcode.go b/go/internal/handler/errcode.go index 887a2667e..6aee7288a 100644 --- a/go/internal/handler/errcode.go +++ b/go/internal/handler/errcode.go @@ -136,6 +136,10 @@ var ( // A separate code from scope_denied: the scopes are fine, the route is // not one a narrowed request may take. classScopeNarrowingRoute = rejectClass{http.StatusForbidden, "scope_narrowing_route"} + // classScopeNarrowingRequired — a request without a narrowing by a key + // whose scope_narrowing is required (Achse 02 C-2, migration 198): such a + // key answers nothing unnarrowed but GET /api/whoami. + classScopeNarrowingRequired = rejectClass{http.StatusForbidden, "scope_narrowing_required"} // classEditMismatch — an edit of an update (issue #406) does not match the // block's content: its old occurs zero times, or more than once without // replace_all. 409 like supersedes_conflict: the payload is well-formed, the diff --git a/go/internal/handler/events.go b/go/internal/handler/events.go index ab130bf80..b8b5cf67d 100644 --- a/go/internal/handler/events.go +++ b/go/internal/handler/events.go @@ -750,7 +750,9 @@ func (h *EventsHandler) HandleEvents(w http.ResponseWriter, r *http.Request) { // !(server-admin || tenant-admin-of-own-tenant) AND on a tenant_id/role // change mid-stream (a re-pointed key must not keep the old telemetry). res, err := h.hub.authenticate(r.Context(), key, keyIsSession) - if err != nil || res == nil || !res.IsValid || !res.IsAdmin { + // So does a key switched to required narrowing (Achse 02 C-2): + // this route is never narrowed. + if err != nil || res == nil || !res.IsValid || !res.IsAdmin || res.ScopeNarrowing == auth.ScopeNarrowingRequired { _ = sw.event("error", "", []byte(`{"error":"session revoked"}`)) return } diff --git a/go/internal/handler/ingest_target_scope_integration_test.go b/go/internal/handler/ingest_target_scope_integration_test.go index 78b2c0ecd..c20a63c2e 100644 --- a/go/internal/handler/ingest_target_scope_integration_test.go +++ b/go/internal/handler/ingest_target_scope_integration_test.go @@ -41,7 +41,7 @@ import ( func tsKey(t *testing.T, pool *pgxpool.Pool, label, home string, allowed, write []string, tenantID string) *auth.AuthResult { t.Helper() ctx := context.Background() - _, plain, err := store.MintKeyWithQuota(ctx, pool, label, home, allowed, write, tenantID, "member", nil, store.AuditStamp{}) + _, plain, err := store.MintKeyWithQuota(ctx, pool, label, home, allowed, write, tenantID, "member", "optional", nil, store.AuditStamp{}) if err != nil { t.Fatalf("mint key %s: %v", label, err) } diff --git a/go/internal/handler/narrowing.go b/go/internal/handler/narrowing.go index ee3bdee50..31aca4d4b 100644 --- a/go/internal/handler/narrowing.go +++ b/go/internal/handler/narrowing.go @@ -11,6 +11,10 @@ // their scopes from it as they always do; three places read the narrowing // itself — writableBlockScopes and resolveWriteScope (context_store.go) and // resolveGrants (mcp.go) — and handleManage checks the one decoded action. +// +// A key whose scope_narrowing is required (cluster C-2, migration 198) +// answers every request without a narrowing with scope_narrowing_required, +// GET /api/whoami excepted; that check lives here too, never in Auth. package handler import ( @@ -74,6 +78,9 @@ func narrowAuth(r *http.Request, ar *auth.AuthResult) (*auth.AuthResult, *writeR if len(writes) > 0 { return nil, classScopeNarrowingInvalid.reject(HeaderWriteScope + " needs " + HeaderReadScopes) } + if ar.ScopeNarrowing == auth.ScopeNarrowingRequired && !unnarrowedAllowedForRequired(r) { + return nil, classScopeNarrowingRequired.reject("this key answers narrowed requests only: name the scopes in " + HeaderReadScopes) + } return ar, nil } n, rej := parseNarrowing(reads, writes) @@ -136,6 +143,14 @@ func parseNarrowing(reads, writes []string) (*auth.Narrowing, *writeReject) { return n, nil } +// unnarrowedAllowedForRequired reports whether r is the one request a key +// with required narrowing (Achse 02 C-2) may send without a narrowing: GET +// /api/whoami, so a client can read the key's identity and requirement before +// it narrows. Same comparison as narrowedRouteAllowed. +func unnarrowedAllowedForRequired(r *http.Request) bool { + return r.Method == http.MethodGet && r.URL.Path == "/api/whoami" && r.URL.RawPath == "" +} + // narrowedRouteAllowed reports whether r's method and path are on // narrowedRoutes. A path the client sent with percent escapes is refused: // the router matches the escaped form (chi routes on URL.RawPath when it is diff --git a/go/internal/handler/narrowing_events_test.go b/go/internal/handler/narrowing_events_test.go new file mode 100644 index 000000000..19c6d86e5 --- /dev/null +++ b/go/internal/handler/narrowing_events_test.go @@ -0,0 +1,49 @@ +package handler + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/GottZ/ctx/internal/auth" + "github.com/GottZ/ctx/internal/backends" +) + +// TestEventsReAuthEndsStreamOnRequiredNarrowing (Achse 02 C-2): the telemetry +// stream is never narrowed, so a server-admin key switched to +// scope_narrowing=required while its stream runs ends the stream at the next +// re-auth, as a revoked admin key does. +func TestEventsReAuthEndsStreamOnRequiredNarrowing(t *testing.T) { + orig := sseWriteWindow + sseWriteWindow = time.Second + defer func() { sseWriteWindow = orig }() + + life, cancel := context.WithCancel(context.Background()) + defer cancel() + fs := &fakeStatus{snap: statusResponse{AsOf: time.Unix(1, 0), Backends: []backends.BackendStatus{}}} + // tick 5ms → re-auth fires at 12*5ms = 60ms. + h := newTestHub(life, fs, eventsCfgStore(5*time.Millisecond, time.Second, 8)) + h.authenticate = func(context.Context, string, bool) (*auth.AuthResult, error) { + return &auth.AuthResult{IsValid: true, IsAdmin: true, ScopeNarrowing: auth.ScopeNarrowingRequired}, nil + } + eh := &EventsHandler{hub: h} + srv := httptest.NewServer(http.HandlerFunc(eh.HandleEvents)) + defer srv.Close() + + ctx, stop := context.WithTimeout(context.Background(), 3*time.Second) + defer stop() + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("request failed: %v", err) + } + defer func() { _ = resp.Body.Close() }() + body, _ := io.ReadAll(resp.Body) // ends with the handler, or with ctx after 3 s + if s := string(body); !strings.Contains(s, "event: error") || !strings.Contains(s, "session revoked") { + t.Errorf("the stream of a key switched to required narrowing did not end with a revoke: %q", s) + } +} diff --git a/go/internal/handler/narrowing_streams_integration_test.go b/go/internal/handler/narrowing_streams_integration_test.go new file mode 100644 index 000000000..01b287144 --- /dev/null +++ b/go/internal/handler/narrowing_streams_integration_test.go @@ -0,0 +1,64 @@ +//go:build integration + +package handler + +import ( + "context" + "net/http" + "strings" + "testing" + "time" + + "github.com/GottZ/ctx/internal/auth" + "github.com/GottZ/ctx/internal/config" + "github.com/GottZ/ctx/internal/events" + "github.com/GottZ/ctx/internal/testdb" +) + +// TestW9SSERequiredNarrowingEndsStream (Achse 02 C-2): a project event stream +// is never narrowed (its route is outside the narrowing's list), so a key that +// is switched to scope_narrowing=required while its stream runs answers the +// stream's next re-auth like a revoked key — the stream ends instead of +// carrying the key's whole read set on. +func TestW9SSERequiredNarrowingEndsStream(t *testing.T) { + pool := testdb.SetupTestDB(t) + ctx, cancel := context.WithCancel(context.Background()) + + old := projectSSEReauthOverride + projectSSEReauthOverride = 80 * time.Millisecond + defer func() { projectSSEReauthOverride = old }() + + _, scopeA := w9SSESeedProject(t, pool, "w9req") + hub := events.NewProjectHub(ctx, pool, config.NewStore(&config.Config{})) + cfg := w9SSEConfig() + + initial := &auth.AuthResult{IsValid: true, TenantID: "tn-1", ReadScopes: []string{scopeA}, ScopeNarrowing: auth.ScopeNarrowingOptional} + required := *initial + required.ScopeNarrowing = auth.ScopeNarrowingRequired + fake := func(context.Context, string, bool) (*auth.AuthResult, error) { return &required, nil } + srv := w9SSEServer(t, hub, pool, cfg, initial, fake) + defer srv.Close() + defer cancel() + + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/api/project/events", nil) + req.Header.Set("X-Context-Key", "deadbeef") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("GET events: %v", err) + } + ch := readSSE(ctx, resp) + deadline := time.After(3 * time.Second) + for { + select { + case ev, ok := <-ch: + if !ok { + t.Fatal("stream closed without a 'session revoked' error event") + } + if ev.name == "error" && strings.Contains(ev.data, "revoked") { + return + } + case <-deadline: + t.Fatal("the stream of a key switched to required narrowing did not end within 3 s") + } + } +} diff --git a/go/internal/handler/oauth_register.go b/go/internal/handler/oauth_register.go index 2f50b77c5..6ffee60e2 100644 --- a/go/internal/handler/oauth_register.go +++ b/go/internal/handler/oauth_register.go @@ -99,6 +99,14 @@ func (h *OAuthHandler) Register(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"}) return } + // /register resolves its key outside the Auth middleware, so it applies + // the narrowing rules itself (Achse 02, narrowing.go): it is no route a + // narrowed request may take, and a key that requires narrowing answers + // nothing unnarrowed. + if _, rej := narrowAuth(r, ar); rej != nil { + writeJSONReject(w, rej) + return + } if !ar.IsAdmin { writeJSON(w, http.StatusForbidden, map[string]string{"error": "admin key required"}) return diff --git a/go/internal/handler/oauth_register_narrowing_integration_test.go b/go/internal/handler/oauth_register_narrowing_integration_test.go new file mode 100644 index 000000000..a54af0e6b --- /dev/null +++ b/go/internal/handler/oauth_register_narrowing_integration_test.go @@ -0,0 +1,79 @@ +//go:build integration + +package handler + +import ( + "context" + "encoding/json" + "net/http/httptest" + "strings" + "testing" + + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" +) + +// TestDCRRegisterAdminModeKeepsTheNarrowingRules (Achse 02 C-1/C-2): /register +// in admin mode resolves its key itself, outside the Auth middleware, so it +// applies the narrowing rules itself: a key that requires narrowing registers +// nothing (403 scope_narrowing_required), and a narrowed request is refused +// like on any route outside the narrowing's list (403 scope_narrowing_route). +// The same admin key registers once the requirement is lifted (control). +func TestDCRRegisterAdminModeKeepsTheNarrowingRules(t *testing.T) { + pool := testdb.SetupTestDB(t) + ctx := context.Background() + h := NewOAuthHandler(pool) + t.Setenv(EnvDCRMode, "admin") + + key, plain, err := store.CreateApiKey(ctx, pool, "dcr-narrowing-admin", "private", nil, "") + if err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `UPDATE context_api_keys SET is_admin = true, scope_narrowing = 'required' WHERE id = $1::uuid`, key.ID); err != nil { + t.Fatal(err) + } + post := func(hdr map[string]string) (int, string) { + t.Helper() + req := httptest.NewRequest("POST", "/register", strings.NewReader(`{"redirect_uris":["https://client.example/cb"]}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+plain) + req.RemoteAddr = dcrTestAddr() + for k, v := range hdr { + req.Header.Set(k, v) + } + rec := httptest.NewRecorder() + h.Register(rec, req) + var doc map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &doc) + code, _ := doc["code"].(string) + return rec.Code, code + } + clients := func() int { + t.Helper() + var n int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM context_oauth_clients WHERE created_by = $1::uuid`, key.ID).Scan(&n); err != nil { + t.Fatal(err) + } + return n + } + + if status, code := post(nil); status != 403 || code != "scope_narrowing_required" { + t.Errorf("admin key with required narrowing, unnarrowed: %d %q, want 403 scope_narrowing_required", status, code) + } + if status, code := post(map[string]string{HeaderReadScopes: "private"}); status != 403 || code != "scope_narrowing_route" { + t.Errorf("admin key with required narrowing, narrowed: %d %q, want 403 scope_narrowing_route", status, code) + } + if n := clients(); n != 0 { + t.Errorf("the refused requests registered %d client(s)", n) + } + + if _, err := pool.Exec(ctx, `UPDATE context_api_keys SET scope_narrowing = 'optional' WHERE id = $1::uuid`, key.ID); err != nil { + t.Fatal(err) + } + if status, _ := post(map[string]string{HeaderReadScopes: "private"}); status != 403 { + t.Errorf("optional admin key, narrowed: %d, want 403 (no narrowed request registers)", status) + } + if status, _ := post(nil); status != 201 { + t.Errorf("control: optional admin key, unnarrowed: %d, want 201", status) + } +} diff --git a/go/internal/handler/project_events.go b/go/internal/handler/project_events.go index d5379eadf..360466502 100644 --- a/go/internal/handler/project_events.go +++ b/go/internal/handler/project_events.go @@ -126,6 +126,15 @@ func reauthTags(fresh *auth.AuthResult, filterScope string) []string { return nil // grant to the filtered scope revoked → no frames (stream lives on) } +// projectStreamKeyGone reports whether the re-auth of a running project event +// stream ends it: revocation, an invalid key or a TENANT change (a re-pointed +// key must not keep the old tenant's domain events), and a key switched to +// required narrowing (Achse 02 C-2) — this route is never narrowed. +func projectStreamKeyGone(fresh *auth.AuthResult, err error, tenantID string) bool { + return err != nil || fresh == nil || !fresh.IsValid || fresh.TenantID != tenantID || + fresh.ScopeNarrowing == auth.ScopeNarrowingRequired +} + // HandleProjectEvents serves the member SSE domain-event stream. Flow: identity + // optional project filter → per-tenant cap-check → commit stream header → fan-out // frames / pings / periodic re-auth until the client disconnects, the server @@ -209,9 +218,7 @@ func (h *ProjectEventsHandler) HandleProjectEvents(w http.ResponseWriter, r *htt } case <-reauthT.C: fresh, err := h.authenticate(r.Context(), key, keyIsSession) - // Revocation / invalid / TENANT change ends the stream outright (a - // re-pointed key must not keep the old tenant's domain events). - if err != nil || fresh == nil || !fresh.IsValid || fresh.TenantID != ar.TenantID { + if projectStreamKeyGone(fresh, err, ar.TenantID) { _ = sw.event("error", "", []byte(`{"error":"session revoked"}`)) return } diff --git a/go/internal/handler/whoami.go b/go/internal/handler/whoami.go index 42b877718..7dc3a9157 100644 --- a/go/internal/handler/whoami.go +++ b/go/internal/handler/whoami.go @@ -88,6 +88,10 @@ type whoamiResponse struct { // (0 = unlimited). A client that paces its writes reads it here instead // of planning with the default. RateLimitWrite int `json:"rate_limit_write"` + // ScopeNarrowing is the key's scope_narrowing (Achse 02 C-2, migration + // 198): "optional" or "required". A required key answers nothing + // unnarrowed but this route, so a client learns the requirement here. + ScopeNarrowing string `json:"scope_narrowing"` } // whoamiNarrowed is the narrowed field of whoami (Achse 02 C-1). @@ -192,6 +196,15 @@ func whoamiNarrowing(ar *auth.AuthResult) *whoamiNarrowed { return &whoamiNarrowed{Read: ar.Narrowed.Read, Write: ar.Narrowed.Write} } +// whoamiScopeNarrowing is the key's scope_narrowing as whoami reports it: +// "" (an AuthResult that did not read the column) reads as optional. +func whoamiScopeNarrowing(ar *auth.AuthResult) string { + if ar.ScopeNarrowing == "" { + return auth.ScopeNarrowingOptional + } + return ar.ScopeNarrowing +} + // modelAPIPolicy is the model_api bag of this request: the getter's answer, // or the fail-closed zero value when none is wired. func (h *WhoamiHandler) modelAPIPolicy() WhoamiModelAPI { @@ -275,5 +288,6 @@ func (h *WhoamiHandler) HandleWhoami(w http.ResponseWriter, r *http.Request) { ConfirmWrites: ar.ConfirmWrites, Narrowed: whoamiNarrowing(ar), RateLimitWrite: h.rateLimitWrite(r), + ScopeNarrowing: whoamiScopeNarrowing(ar), }) } diff --git a/go/internal/handler/whoami_test.go b/go/internal/handler/whoami_test.go index 8ac105ff9..eb923de17 100644 --- a/go/internal/handler/whoami_test.go +++ b/go/internal/handler/whoami_test.go @@ -180,11 +180,12 @@ func TestWhoamiGoldenShape(t *testing.T) { WriteScopes: []string{"private", "shared"}, ConfirmWrites: false, RateLimitWrite: 100, + ScopeNarrowing: "optional", }) if err != nil { t.Fatalf("marshal: %v", err) } - want := `{"success":true,"label":"example-key","home_scope":"private","read_scopes":["private","shared"],"admin":true,"tenant_id":"00000000-0000-0000-0000-0000000d3fa0","role":"member","api_key_id":"11111111-1111-1111-1111-111111111111","principal_id":"22222222-2222-2222-2222-222222222222","tenant_slug":"default","tenant_display_name":"Default Tenant","capabilities":{"workflow":true,"model_api":{"enabled":true,"self_service":false,"key_max_lifetime_s":31536000,"rotation_grace_s":86400,"expiry_warn_s":1209600}},"write_scopes":["private","shared"],"confirm_writes":false,"narrowed":null,"rate_limit_write":100}` + want := `{"success":true,"label":"example-key","home_scope":"private","read_scopes":["private","shared"],"admin":true,"tenant_id":"00000000-0000-0000-0000-0000000d3fa0","role":"member","api_key_id":"11111111-1111-1111-1111-111111111111","principal_id":"22222222-2222-2222-2222-222222222222","tenant_slug":"default","tenant_display_name":"Default Tenant","capabilities":{"workflow":true,"model_api":{"enabled":true,"self_service":false,"key_max_lifetime_s":31536000,"rotation_grace_s":86400,"expiry_warn_s":1209600}},"write_scopes":["private","shared"],"confirm_writes":false,"narrowed":null,"rate_limit_write":100,"scope_narrowing":"optional"}` if string(got) != want { t.Fatalf("golden shape drift:\n got: %s\nwant: %s", got, want) } diff --git a/go/internal/schemacontract/manifest.json b/go/internal/schemacontract/manifest.json index 4cd6d1078..afb3c0b30 100644 --- a/go/internal/schemacontract/manifest.json +++ b/go/internal/schemacontract/manifest.json @@ -1,9 +1,9 @@ { "manifest_version": 1, "generated_against": { - "migration_max": 197, - "migration_count": 85, - "migration_chain_sha256": "ba7bd47e98be4683d68c4aca1ffbb681202a8d05876067a372a500ca87f20eeb", + "migration_max": 198, + "migration_count": 86, + "migration_chain_sha256": "26d1e2575ae5ceb0bc68e7f9e0f56045699a87079a08de3f7ecd55d89afdd33b", "pg_major": 18, "image": "pgvector-timescaledb:pg18" }, @@ -293,6 +293,12 @@ "type": "uuid", "not_null": true, "storage": "p" + }, + { + "name": "scope_narrowing", + "type": "text", + "not_null": true, + "storage": "x" } ], "row_security": false @@ -6248,7 +6254,7 @@ "src_hash": "f9d742798eb0ba9e10cd4522c2c723a68ef67971314d4c1e485f884846549f95" }, "audit_state_api_key(k context_api_keys)": { - "src_hash": "b864dab1db4ba08570476b70f13d2b396caab4afd119fd49f9c0c7e7001c6981" + "src_hash": "11c4bfbd20ee9590b2afcfd2427108f7887a44a2902a164a9429538005a2eece" }, "audit_state_gateway_limit(l context_gateway_limits)": { "src_hash": "86cdba908391601ddab93ccfc6e1cef1e390df95ec627a8ba36bdffa3056de8d" @@ -6302,10 +6308,10 @@ "src_hash": "be4660e871031a914ac9a9d689a476508dcfaac1f9c5fdba260584127010e7a5" }, "ctx_auth(p_api_key text)": { - "src_hash": "a5b51033a10c0016c1e560c15721d218bad483757fc31e49706ce5c660c01d58" + "src_hash": "762372a1a084cd71f9b5ea542e6940bdc79c06cf55f00a37728ab8e354d987b3" }, "ctx_auth_by_id(p_api_key_id uuid)": { - "src_hash": "4b5add16d06a48cb0783435e48748263c962ed6c33c9f7bb1e7fb270a4deff4e" + "src_hash": "12fe6aaef512e4d39263153852942706e15bf6356a614f916716beb02a235309" }, "ctx_block_type_never_embedded(p_name text)": { "src_hash": "c49f0fca7880acce18b8efeab59f12ef400179fcd83b6c90a637c4f2d12abf63" @@ -6397,7 +6403,7 @@ "def_hash": "d63cf34e4548f6abd3651b023a18aaacd69a4736d1f2efe3f8905d512fafbea0" }, "context_api_keys.trg_api_keys_audit_upd": { - "def_hash": "7854aa4fd01b4ff2fceb3be4cac5778b7ee864adff461b9743507676ce5661d7" + "def_hash": "8dc5a71a00fb52e591c0453a63b8cbb1b08a05e361bd9bac8ebba5b349f8b467" }, "context_backends.trg_backends_audit": { "def_hash": "fd75674ba3bbb9cb40428f944ccf4b72789f81f0e1bc57ca9907bf821a60d3d2" diff --git a/go/internal/store/api_keys.go b/go/internal/store/api_keys.go index 7b50f770c..4d62d1f94 100644 --- a/go/internal/store/api_keys.go +++ b/go/internal/store/api_keys.go @@ -41,10 +41,14 @@ type ApiKey struct { // (column DEFAULT '{}'). The invariant write_scopes ⊆ allowed_scopes ∪ // {home_scope} is enforced at mint/update (validateWriteScopes) AND at the // read-time write gate (handler.writableBlockScopes) — double, fail-closed. - WriteScopes []string `json:"write_scopes"` - Active bool `json:"active"` - LastUsedAt *time.Time `json:"last_used_at,omitempty"` - CreatedAt time.Time `json:"created_at"` + WriteScopes []string `json:"write_scopes"` + // ScopeNarrowing is the key's scope_narrowing (migration 198, Achse 02 + // C-2): "optional" (every existing key) or "required" — a required key + // answers nothing without a per-request narrowing but GET /api/whoami. + ScopeNarrowing string `json:"scope_narrowing"` + Active bool `json:"active"` + LastUsedAt *time.Time `json:"last_used_at,omitempty"` + CreatedAt time.Time `json:"created_at"` } // ErrWriteScopeNotAllowed is returned by the mint/update paths when a requested @@ -56,6 +60,12 @@ type ApiKey struct { // later allowed_scopes shrink. var ErrWriteScopeNotAllowed = errors.New("store: write_scope not in allowed_scopes ∪ home_scope") +// ErrScopeNarrowingInvalid is returned by the mint/update paths for a +// scope_narrowing other than optional and required (migration 198). The +// handler checks the value first and answers 400; the store refuses it as the +// last line before the row, as the column's CHECK does after it. +var ErrScopeNarrowingInvalid = errors.New("store: scope_narrowing must be optional or required") + // validateWriteScopes enforces write_scopes ⊆ allowed_scopes ∪ {home_scope} and the // '_'-reserved namespace, the mint/update-time half of the 078 double invariant. A // nil writeScopes (unchanged / none) passes trivially. It returns the FIRST @@ -94,11 +104,11 @@ func validateWriteScopes(homeScope string, allowedScopes, writeScopes []string) // 059, so this is SQL-only, NO migration. // // scopeNarrowing is the key's scope_narrowing (auth.ScopeNarrowingOptional or -// auth.ScopeNarrowingRequired, Achse 02). The S1 contract fixes the parameter -// so the keyset mint (C-3) can be built against it; the column arrives with -// migration 198 (C-2), and until then the value is not stored — every caller -// passes auth.ScopeNarrowingOptional, which is what the column's default will -// be. +// auth.ScopeNarrowingRequired, Achse 02 C-2, migration 198); any other value +// is refused before the INSERT. The INSERT names the column only for a +// required key: an optional one gets the column default, so the mint paths +// keep working on a database before 198 (the migration tests mint keys on +// older schemas). func insertApiKeyTx(ctx context.Context, q pgxdb.Rower, label, homeScope string, allowedScopes, writeScopes []string, tenantID, role, scopeNarrowing string) (ApiKey, string, error) { if label == "" { return ApiKey{}, "", fmt.Errorf("api_keys: label is required") @@ -142,6 +152,9 @@ func insertApiKeyTx(ctx context.Context, q pgxdb.Rower, label, homeScope string, if err := validateWriteScopes(homeScope, allowedScopes, writeScopes); err != nil { return ApiKey{}, "", err } + if scopeNarrowing != auth.ScopeNarrowingOptional && scopeNarrowing != auth.ScopeNarrowingRequired { + return ApiKey{}, "", fmt.Errorf("%w: %q", ErrScopeNarrowingInvalid, scopeNarrowing) + } keyBytes := make([]byte, 32) if _, err := rand.Read(keyBytes); err != nil { @@ -163,19 +176,27 @@ func insertApiKeyTx(ctx context.Context, q pgxdb.Rower, label, homeScope string, // principal back with it, no rights-less orphan row. Linking a new key to // an EXISTING principal (second key of a person) is a later, explicit flow // (Achse 05 key selector / 04 SSO onboarding) — never an implicit default. + // scope_narrowing (198): named only for a required key (see above). + cols, vals := "", "" + args := []any{label, keyHash, homeScope, allowedScopes, writeScopes, tenantID, role} + if scopeNarrowing == auth.ScopeNarrowingRequired { + cols, vals = ", scope_narrowing", ", $8" + args = append(args, scopeNarrowing) + } var row ApiKey err := q.QueryRow(ctx, `WITH p AS ( INSERT INTO context_principals (display_name) VALUES ($1) RETURNING id ) - INSERT INTO context_api_keys (label, key_hash, home_scope, allowed_scopes, write_scopes, active, tenant_id, tenant_role, principal_id) - SELECT $1, $2, $3, COALESCE($4::text[], '{shared}'::text[]), COALESCE($5::text[], '{}'::text[]), true, $6::uuid, $7, p.id FROM p + INSERT INTO context_api_keys (label, key_hash, home_scope, allowed_scopes, write_scopes, active, tenant_id, tenant_role, principal_id`+cols+`) + SELECT $1, $2, $3, COALESCE($4::text[], '{shared}'::text[]), COALESCE($5::text[], '{}'::text[]), true, $6::uuid, $7, p.id`+vals+` FROM p RETURNING id, label, home_scope, allowed_scopes, write_scopes, tenant_role, active, last_used_at, created_at`, - label, keyHash, homeScope, allowedScopes, writeScopes, tenantID, role, + args..., ).Scan(&row.ID, &row.Label, &row.HomeScope, &row.AllowedScopes, &row.WriteScopes, &row.TenantRole, &row.Active, &row.LastUsedAt, &row.CreatedAt) if err != nil { return ApiKey{}, "", fmt.Errorf("api_keys: insert: %w", err) } + row.ScopeNarrowing = scopeNarrowing return row, plaintext, nil } @@ -237,7 +258,11 @@ var ErrKeyQuotaExceeded = errors.New("store: tenant key quota exceeded") // stamp attributes the mint in the audit trail (migration 160): it is applied // to the transaction before the INSERT, so the create row names the acting key, // the request id and the channel (the handler passes APIStamp). -func MintKeyWithQuota(ctx context.Context, pool *pgxpool.Pool, label, homeScope string, allowedScopes, writeScopes []string, tenantID, role string, maxKeys *int, stamp AuditStamp) (ApiKey, string, error) { +// +// scopeNarrowing is the new key's scope_narrowing (auth.ScopeNarrowingOptional +// or auth.ScopeNarrowingRequired, migration 198); insertApiKeyTx refuses any +// other value. +func MintKeyWithQuota(ctx context.Context, pool *pgxpool.Pool, label, homeScope string, allowedScopes, writeScopes []string, tenantID, role, scopeNarrowing string, maxKeys *int, stamp AuditStamp) (ApiKey, string, error) { var ( key ApiKey plaintext string @@ -275,7 +300,7 @@ func MintKeyWithQuota(ctx context.Context, pool *pgxpool.Pool, label, homeScope } var err error - key, plaintext, err = insertApiKeyTx(ctx, tx, label, homeScope, allowedScopes, writeScopes, tenantID, role, auth.ScopeNarrowingOptional) + key, plaintext, err = insertApiKeyTx(ctx, tx, label, homeScope, allowedScopes, writeScopes, tenantID, role, scopeNarrowing) return err }); err != nil { return ApiKey{}, "", err @@ -324,7 +349,7 @@ func ListApiKeys(ctx context.Context, pool *pgxpool.Pool, tenantFilter string, a tenantArg = &tenantFilter } rows, err := pool.Query(ctx, - `SELECT id, label, home_scope, allowed_scopes, write_scopes, tenant_role, active, last_used_at, created_at + `SELECT id, label, home_scope, allowed_scopes, write_scopes, scope_narrowing, tenant_role, active, last_used_at, created_at FROM context_api_keys WHERE ($1::uuid IS NULL OR tenant_id = $1::uuid) AND (NOT $2::boolean OR active) @@ -338,7 +363,7 @@ func ListApiKeys(ctx context.Context, pool *pgxpool.Pool, tenantFilter string, a var keys []ApiKey for rows.Next() { var k ApiKey - if err := rows.Scan(&k.ID, &k.Label, &k.HomeScope, &k.AllowedScopes, &k.WriteScopes, &k.TenantRole, &k.Active, &k.LastUsedAt, &k.CreatedAt); err != nil { + if err := rows.Scan(&k.ID, &k.Label, &k.HomeScope, &k.AllowedScopes, &k.WriteScopes, &k.ScopeNarrowing, &k.TenantRole, &k.Active, &k.LastUsedAt, &k.CreatedAt); err != nil { return nil, fmt.Errorf("api_keys: scan: %w", err) } keys = append(keys, k) @@ -430,7 +455,7 @@ func DeleteApiKey(ctx context.Context, pool *pgxpool.Pool, id, callerTenant stri if !found { return pgxdb.ErrRollback // foreign / absent / malformed id — no oracle (L2) } - targetTenant, curRole, curActive := rk.tenant, rk.role, rk.active + targetTenant, curActive := rk.tenant, rk.active // (1b) Server-admin protection (§9i): only a server-admin revokes a // server-admin key. is_admin is never written by any code path, so the @@ -447,6 +472,18 @@ func DeleteApiKey(ctx context.Context, pool *pgxpool.Pool, id, callerTenant stri `SELECT id FROM context_tenants WHERE id = $1::uuid FOR UPDATE`, targetTenant).Scan(&lockedTenant); err != nil { return fmt.Errorf("api_keys: delete tenant lock: %w", err) } + // The owner rules below decide on the target as it is UNDER the lock: the + // read in (1) ran before it, and a key write that held the lock meanwhile + // may have changed the target's role, active or scope_narrowing (every key + // write of this file takes the tenant lock first; Präambel 9a, case b). + if rk, found, err = resolveKeyForUpdate(ctx, tx, id, isServerAdmin, tenantArg); err != nil { + return err + } + if !found { + return pgxdb.ErrRollback // gone meanwhile — the same no-oracle miss as (1) + } + curRole := rk.role + curActive = rk.active const ownerRole = "owner" // A revoke removes owner power only when the target is currently active (active @@ -465,12 +502,14 @@ func DeleteApiKey(ctx context.Context, pool *pgxpool.Pool, id, callerTenant stri // the active-owner count below one. Count the OTHER active owners (id <> target) // — "does >= 1 owner remain after the revoke". Read under the lock, a serialised // concurrent revoke of a DIFFERENT owner key is already committed → the second - // call sees zero others → ErrLastOwner (the race riegel). - if curRole == ownerRole && curActive { + // call sees zero others → ErrLastOwner (the race riegel). An owner key that + // requires narrowing (198) administers nothing and counts on neither side. + if curRole == ownerRole && curActive && rk.narrowing != auth.ScopeNarrowingRequired { var others int if err = tx.QueryRow(ctx, `SELECT count(*) FROM context_api_keys - WHERE tenant_id = $1::uuid AND tenant_role = 'owner' AND active = true AND id <> $2::uuid`, + WHERE tenant_id = $1::uuid AND tenant_role = 'owner' AND active = true + AND scope_narrowing = 'optional' AND id <> $2::uuid`, targetTenant, id).Scan(&others); err != nil { return fmt.Errorf("api_keys: delete owner count: %w", err) } @@ -512,6 +551,10 @@ func DeleteApiKey(ctx context.Context, pool *pgxpool.Pool, id, callerTenant stri // tenant ALWAYS keeps >= 1 active owner key, so it can never lock itself out of // administration. Self-revoke of one's own key stays allowed UNLESS it is the // last owner. The handler maps this to 409. +// +// Since migration 198 an owner counts only while it can administer: active and +// without required scope narrowing (a required key answers nothing unnarrowed +// but whoami, and a narrowed request is never an administration request). var ErrLastOwner = errors.New("store: would remove the last active owner of the tenant") // ErrOwnerProtected is returned by UpdateApiKey when a caller that may NOT manage @@ -533,8 +576,9 @@ var ErrServerAdminProtected = errors.New("store: server-admin key may only be ma // UpdateApiKey mutates the tenant_role and/or active flag of one api key, // tenant-isolated, owner-invariant-safe, and TOCTOU-free. role / active nil = -// "leave unchanged" (COALESCE in the final UPDATE). It writes ONLY tenant_role + -// active — never is_admin: the server-global admin tier has NO code path here, so +// "leave unchanged" (COALESCE in the final UPDATE), as are writeScopes (078) and +// scopeNarrowing (198). It writes ONLY tenant_role, active, write_scopes and +// scope_narrowing — never is_admin: the server-global admin tier has NO code path here, so // this action cannot escalate a key to server-admin (design/04 §D-C, AM4). // // On success the final UPDATE RETURNs the patched row, so the caller gets it back @@ -568,7 +612,7 @@ var ErrServerAdminProtected = errors.New("store: server-admin key may only be ma // stamp attributes the patch in the audit trail (migration 160: update, revoke // or reactivate); it is applied before the UPDATE. func UpdateApiKey(ctx context.Context, pool *pgxpool.Pool, id, callerTenant string, - isServerAdmin, callerMayManageOwner bool, role *string, active *bool, writeScopes *[]string, stamp AuditStamp) (updated ApiKey, changed bool, err error) { + isServerAdmin, callerMayManageOwner bool, role *string, active *bool, writeScopes *[]string, scopeNarrowing *string, stamp AuditStamp) (updated ApiKey, changed bool, err error) { var row ApiKey if err = pgxdb.Write(ctx, pool, @@ -614,6 +658,10 @@ func UpdateApiKey(ctx context.Context, pool *pgxpool.Pool, id, callerTenant stri return verr } } + // (2b) scope_narrowing (198): one of the two values; nil = unchanged. + if scopeNarrowing != nil && *scopeNarrowing != auth.ScopeNarrowingOptional && *scopeNarrowing != auth.ScopeNarrowingRequired { + return fmt.Errorf("%w: %q", ErrScopeNarrowingInvalid, *scopeNarrowing) + } // (2) Serialisation point: lock the target key's TENANT row (see the lock-target // rationale in the doc comment). tenant_id is a NOT NULL FK to context_tenants, @@ -623,17 +671,28 @@ func UpdateApiKey(ctx context.Context, pool *pgxpool.Pool, id, callerTenant stri `SELECT id FROM context_tenants WHERE id = $1::uuid FOR UPDATE`, targetTenant).Scan(&lockedTenant); err != nil { return fmt.Errorf("api_keys: update tenant lock: %w", err) } + // The owner guards below decide on the target as it is UNDER the lock: the + // read in (1) ran before it, and a key write that held the lock meanwhile + // may have changed the target's role, active or scope_narrowing (every key + // write of this file takes the tenant lock first; Präambel 9a, case b). + if rk, found, err = resolveKeyForUpdate(ctx, tx, id, isServerAdmin, tenantArg); err != nil { + return err + } + if !found { + return pgxdb.ErrRollback // gone meanwhile — the same no-oracle miss as (1) + } // (3)+(4) AM6 owner guards under the tenant lock: Owner-Protection (an admin may // not strip owner power) and Last-Owner (never drop the tenant's active-owner count // below one). Extracted to keep this function under the cyclop ceiling. - if err = enforceOwnerInvariantsTx(ctx, tx, rk, id, role, active, callerMayManageOwner); err != nil { + if err = enforceOwnerInvariantsTx(ctx, tx, rk, id, role, active, scopeNarrowing, callerMayManageOwner); err != nil { return err } // Apply. Tenant constraint repeated in the WHERE (no cross-tenant patch); // COALESCE keeps the existing value for a nil patch field. Writes ONLY - // tenant_role + active — the SQL names neither is_admin nor any other column. + // tenant_role, active, write_scopes and scope_narrowing — the SQL names + // neither is_admin nor any other column. // RETURNING hands the patched row straight back so the handler need not re-read // it for the {success, key} response. The row was resolved (found) and its // tenant locked above, so this UPDATE matches exactly one row; an ErrNoRows @@ -652,14 +711,15 @@ func UpdateApiKey(ctx context.Context, pool *pgxpool.Pool, id, callerTenant stri } err = tx.QueryRow(ctx, `UPDATE context_api_keys - SET tenant_role = COALESCE($2::text, tenant_role), - active = COALESCE($3::boolean, active), - write_scopes = COALESCE($6::text[], write_scopes), - updated_at = now() + SET tenant_role = COALESCE($2::text, tenant_role), + active = COALESCE($3::boolean, active), + write_scopes = COALESCE($6::text[], write_scopes), + scope_narrowing = COALESCE($7::text, scope_narrowing), + updated_at = now() WHERE id = $1::uuid AND ($4::boolean OR tenant_id = $5::uuid) - RETURNING id, label, home_scope, allowed_scopes, write_scopes, tenant_role, active, last_used_at, created_at`, - id, role, active, isServerAdmin, tenantArg, wsArg, - ).Scan(&row.ID, &row.Label, &row.HomeScope, &row.AllowedScopes, &row.WriteScopes, &row.TenantRole, &row.Active, &row.LastUsedAt, &row.CreatedAt) + RETURNING id, label, home_scope, allowed_scopes, write_scopes, scope_narrowing, tenant_role, active, last_used_at, created_at`, + id, role, active, isServerAdmin, tenantArg, wsArg, scopeNarrowing, + ).Scan(&row.ID, &row.Label, &row.HomeScope, &row.AllowedScopes, &row.WriteScopes, &row.ScopeNarrowing, &row.TenantRole, &row.Active, &row.LastUsedAt, &row.CreatedAt) if err != nil { if errors.Is(err, pgx.ErrNoRows) { // The row vanished post-resolve (impossible under the lock): @@ -687,8 +747,13 @@ func UpdateApiKey(ctx context.Context, pool *pgxpool.Pool, id, callerTenant stri // keep it under the cyclop ceiling; the owner-count read runs under the caller's lock, // so the last-owner race riegel is preserved (a serialised concurrent demotion is // already committed and no longer counts). +// +// scopeNarrowing (198) is owner power too: a key that requires narrowing answers +// nothing unnarrowed but whoami, and a narrowed request is never an administration +// request, so switching an owner key to required strips its administration like a +// demotion. An owner counts as one that can administer — active and not required. func enforceOwnerInvariantsTx(ctx context.Context, tx pgx.Tx, rk resolvedKey, id string, - role *string, active *bool, callerMayManageOwner bool) error { + role *string, active *bool, scopeNarrowing *string, callerMayManageOwner bool) error { const ownerRole = "owner" effRole := rk.role if role != nil { @@ -698,23 +763,30 @@ func enforceOwnerInvariantsTx(ctx context.Context, tx pgx.Tx, rk resolvedKey, id if active != nil { effActive = *active } + effNarrowing := rk.narrowing + if scopeNarrowing != nil { + effNarrowing = *scopeNarrowing + } // (3) Owner-Protection (AM6(b)): fires only for a same-tenant owner target — a // foreign target already collapsed to !found before the role was known (no oracle). targetIsOwner := rk.role == ownerRole - removesOwnerPower := (role != nil && *role != ownerRole) || (active != nil && !*active && rk.active) + requiresNow := rk.narrowing != auth.ScopeNarrowingRequired && effNarrowing == auth.ScopeNarrowingRequired + removesOwnerPower := (role != nil && *role != ownerRole) || (active != nil && !*active && rk.active) || requiresNow if targetIsOwner && removesOwnerPower && !callerMayManageOwner { return ErrOwnerProtected } - // (4) Last-Owner (AM6(a)): only the active-owner → not-active-owner transition can - // drop the count. Count the OTHER active owners (id <> target) — "does >= 1 owner - // remain after the patch". Excluding the target by id is robust to a stale self-read. - wasActiveOwner := rk.role == ownerRole && rk.active - willBeActiveOwner := effRole == ownerRole && effActive + // (4) Last-Owner (AM6(a)): only the administering-owner → not-administering-owner + // transition can drop the count. Count the OTHER administering owners (id <> target) + // — "does >= 1 owner remain after the patch". Excluding the target by id is robust + // to a stale self-read. + wasActiveOwner := rk.role == ownerRole && rk.active && rk.narrowing != auth.ScopeNarrowingRequired + willBeActiveOwner := effRole == ownerRole && effActive && effNarrowing != auth.ScopeNarrowingRequired if wasActiveOwner && !willBeActiveOwner { var others int if err := tx.QueryRow(ctx, `SELECT count(*) FROM context_api_keys - WHERE tenant_id = $1::uuid AND tenant_role = 'owner' AND active = true AND id <> $2::uuid`, + WHERE tenant_id = $1::uuid AND tenant_role = 'owner' AND active = true + AND scope_narrowing = 'optional' AND id <> $2::uuid`, rk.tenant, id).Scan(&others); err != nil { return fmt.Errorf("api_keys: update owner count: %w", err) } @@ -732,11 +804,11 @@ func enforceOwnerInvariantsTx(ctx context.Context, tx pgx.Tx, rk resolvedKey, id // complexity under the cyclop limit. func resolveKeyForUpdate(ctx context.Context, q pgxdb.Rower, id string, isServerAdmin bool, tenantArg *string) (r resolvedKey, found bool, err error) { err = q.QueryRow(ctx, - `SELECT tenant_id::text, tenant_role, active, is_admin, home_scope, allowed_scopes + `SELECT tenant_id::text, tenant_role, active, is_admin, home_scope, allowed_scopes, scope_narrowing FROM context_api_keys WHERE id = $1::uuid AND ($2::boolean OR tenant_id = $3::uuid)`, id, isServerAdmin, tenantArg, - ).Scan(&r.tenant, &r.role, &r.active, &r.isAdmin, &r.homeScope, &r.allowedScopes) + ).Scan(&r.tenant, &r.role, &r.active, &r.isAdmin, &r.homeScope, &r.allowedScopes, &r.narrowing) if err == nil { return r, true, nil } @@ -759,4 +831,5 @@ type resolvedKey struct { isAdmin bool // server-global tier; gates ErrServerAdminProtected (§9i) homeScope string allowedScopes []string + narrowing string // scope_narrowing (198): a required owner key administers nothing } diff --git a/go/internal/store/api_keys_audit_integration_test.go b/go/internal/store/api_keys_audit_integration_test.go index 9009878e4..d0d034d80 100644 --- a/go/internal/store/api_keys_audit_integration_test.go +++ b/go/internal/store/api_keys_audit_integration_test.go @@ -42,7 +42,6 @@ import ( "github.com/jackc/pgx/v5/pgxpool" - "github.com/GottZ/ctx/internal/auth" "github.com/GottZ/ctx/internal/store" "github.com/GottZ/ctx/internal/testdb" "github.com/GottZ/ctx/migrations" @@ -244,13 +243,15 @@ func TestKeyAuditAuthWritesNoRow(t *testing.T) { } before := kaCount(ctx, t, pool, `entity_type = 'api_key'`) + // The SQL functions themselves, not auth.Authenticate: this database stands + // at 160, and the Go side reads the columns of the newest ctx_auth (198). for i := 0; i < 3; i++ { - ar, err := auth.Authenticate(ctx, pool, plain) - if err != nil || ar == nil || !ar.IsValid { - t.Fatalf("authenticate #%d: ar=%v err=%v", i, ar, err) + var valid bool + if err := pool.QueryRow(ctx, `SELECT is_valid FROM ctx_auth($1)`, plain).Scan(&valid); err != nil || !valid { + t.Fatalf("authenticate #%d: valid=%v err=%v", i, valid, err) } - if ar, err = auth.AuthenticateByID(ctx, pool, key.ID); err != nil || ar == nil || !ar.IsValid { - t.Fatalf("authenticate by id #%d: ar=%v err=%v", i, ar, err) + if err := pool.QueryRow(ctx, `SELECT is_valid FROM ctx_auth_by_id($1::uuid)`, key.ID).Scan(&valid); err != nil || !valid { + t.Fatalf("authenticate by id #%d: valid=%v err=%v", i, valid, err) } } var used bool @@ -280,8 +281,10 @@ func TestKeyAuditStateWhitelist(t *testing.T) { if err != nil { t.Fatalf("mint: %v", err) } - if _, err := auth.Authenticate(ctx, pool, plain); err != nil { - t.Fatalf("authenticate: %v", err) + // ctx_auth itself (the database stands at 160, see TestKeyAuditAuthWritesNoRow). + var valid bool + if err := pool.QueryRow(ctx, `SELECT is_valid FROM ctx_auth($1)`, plain).Scan(&valid); err != nil || !valid { + t.Fatalf("authenticate: valid=%v err=%v", valid, err) } var keyHash string if err := pool.QueryRow(ctx, `SELECT key_hash FROM context_api_keys WHERE id = $1::uuid`, key.ID).Scan(&keyHash); err != nil { diff --git a/go/internal/store/api_keys_insert_test.go b/go/internal/store/api_keys_insert_test.go index dfcaeb8dd..994584b14 100644 --- a/go/internal/store/api_keys_insert_test.go +++ b/go/internal/store/api_keys_insert_test.go @@ -2,6 +2,7 @@ package store import ( "context" + "errors" "strings" "testing" @@ -49,3 +50,16 @@ func TestInsertApiKeyTx_ValidationOwnedByPrimitive(t *testing.T) { } } } + +// TestInsertApiKeyTx_ScopeNarrowingValue (migration 198): the primitive takes +// exactly the two values of the column's CHECK and refuses any other before +// the INSERT (nil querier: the refusal returns before q.QueryRow) — the last +// line before the row, behind the handler's own 400. +func TestInsertApiKeyTx_ScopeNarrowingValue(t *testing.T) { + for _, v := range []string{"", "sometimes", "Required", "required "} { + _, _, err := insertApiKeyTx(context.Background(), nil, "lbl", "private", nil, nil, "", "member", v) + if !errors.Is(err, ErrScopeNarrowingInvalid) { + t.Errorf("scope_narrowing %q: err = %v, want ErrScopeNarrowingInvalid", v, err) + } + } +} diff --git a/go/internal/store/api_keys_mint_quota_integration_test.go b/go/internal/store/api_keys_mint_quota_integration_test.go index 5b87798d6..b961eee3b 100644 --- a/go/internal/store/api_keys_mint_quota_integration_test.go +++ b/go/internal/store/api_keys_mint_quota_integration_test.go @@ -67,12 +67,12 @@ func TestMintKeyWithQuota_Integration(t *testing.T) { const max = 2 for i := 0; i < max; i++ { if _, _, err := store.MintKeyWithQuota(ctx, pool, - "be6w2-cap-k", "private", nil, nil, tid, "member", intPtr(max), store.AuditStamp{}); err != nil { + "be6w2-cap-k", "private", nil, nil, tid, "member", "optional", intPtr(max), store.AuditStamp{}); err != nil { t.Fatalf("mint %d/%d under cap = %v, want nil", i+1, max, err) } } if _, _, err := store.MintKeyWithQuota(ctx, pool, - "be6w2-cap-over", "private", nil, nil, tid, "member", intPtr(max), store.AuditStamp{}); !errors.Is(err, store.ErrKeyQuotaExceeded) { + "be6w2-cap-over", "private", nil, nil, tid, "member", "optional", intPtr(max), store.AuditStamp{}); !errors.Is(err, store.ErrKeyQuotaExceeded) { t.Fatalf("mint over cap err = %v, want ErrKeyQuotaExceeded", err) } if n := activeKeyCount(t, pool, tid); n != max { @@ -96,7 +96,7 @@ func TestMintKeyWithQuota_Integration(t *testing.T) { go func(i int) { defer wg.Done() _, _, errs[i] = store.MintKeyWithQuota(ctx, pool, - "be6w2-race-k", "private", nil, nil, tid, "member", intPtr(1), store.AuditStamp{}) + "be6w2-race-k", "private", nil, nil, tid, "member", "optional", intPtr(1), store.AuditStamp{}) }(i) } wg.Wait() @@ -127,12 +127,12 @@ func TestMintKeyWithQuota_Integration(t *testing.T) { t.Run("N8r_revoke_reclaims_budget", func(t *testing.T) { tid := freshTenant(t, ctx, pool, "be6w2-reclaim") first, _, err := store.MintKeyWithQuota(ctx, pool, - "be6w2-reclaim-k1", "private", nil, nil, tid, "member", intPtr(1), store.AuditStamp{}) + "be6w2-reclaim-k1", "private", nil, nil, tid, "member", "optional", intPtr(1), store.AuditStamp{}) if err != nil { t.Fatalf("first mint = %v, want nil", err) } if _, _, err := store.MintKeyWithQuota(ctx, pool, - "be6w2-reclaim-k2", "private", nil, nil, tid, "member", intPtr(1), store.AuditStamp{}); !errors.Is(err, store.ErrKeyQuotaExceeded) { + "be6w2-reclaim-k2", "private", nil, nil, tid, "member", "optional", intPtr(1), store.AuditStamp{}); !errors.Is(err, store.ErrKeyQuotaExceeded) { t.Fatalf("second mint at cap err = %v, want ErrKeyQuotaExceeded", err) } // Revoke the first key (soft-delete: active=false) — frees its slot. @@ -141,7 +141,7 @@ func TestMintKeyWithQuota_Integration(t *testing.T) { t.Fatalf("revoke first key: %v", err) } if _, _, err := store.MintKeyWithQuota(ctx, pool, - "be6w2-reclaim-k3", "private", nil, nil, tid, "member", intPtr(1), store.AuditStamp{}); err != nil { + "be6w2-reclaim-k3", "private", nil, nil, tid, "member", "optional", intPtr(1), store.AuditStamp{}); err != nil { t.Fatalf("mint after revoke = %v, want nil (active-only count reclaims the slot)", err) } if n := activeKeyCount(t, pool, tid); n != 1 { @@ -154,12 +154,12 @@ func TestMintKeyWithQuota_Integration(t *testing.T) { t.Run("unknown_tenant_returns_ErrTenantNotFound", func(t *testing.T) { if _, _, err := store.MintKeyWithQuota(ctx, pool, "be6w2-orphan", "private", nil, nil, - "11111111-2222-3333-4444-555566667777", "member", intPtr(5), store.AuditStamp{}); !errors.Is(err, store.ErrTenantNotFound) { + "11111111-2222-3333-4444-555566667777", "member", "optional", intPtr(5), store.AuditStamp{}); !errors.Is(err, store.ErrTenantNotFound) { t.Fatalf("unknown tenant err = %v, want ErrTenantNotFound", err) } if _, _, err := store.MintKeyWithQuota(ctx, pool, "be6w2-orphan2", "private", nil, nil, - "not-a-uuid", "member", intPtr(5), store.AuditStamp{}); !errors.Is(err, store.ErrTenantNotFound) { + "not-a-uuid", "member", "optional", intPtr(5), store.AuditStamp{}); !errors.Is(err, store.ErrTenantNotFound) { t.Fatalf("malformed tenant id err = %v, want ErrTenantNotFound (22P02 no oracle)", err) } }) @@ -167,10 +167,10 @@ func TestMintKeyWithQuota_Integration(t *testing.T) { // Unlimited (maxKeys=nil) and negative both skip the cap: many keys all commit. t.Run("unlimited_nil_or_negative_skips_cap", func(t *testing.T) { tid := freshTenant(t, ctx, pool, "be6w2-unl") - if _, _, err := store.MintKeyWithQuota(ctx, pool, "be6w2-unl-a", "private", nil, nil, tid, "member", nil, store.AuditStamp{}); err != nil { + if _, _, err := store.MintKeyWithQuota(ctx, pool, "be6w2-unl-a", "private", nil, nil, tid, "member", "optional", nil, store.AuditStamp{}); err != nil { t.Fatalf("nil-maxKeys mint = %v, want nil", err) } - if _, _, err := store.MintKeyWithQuota(ctx, pool, "be6w2-unl-b", "private", nil, nil, tid, "member", intPtr(-1), store.AuditStamp{}); err != nil { + if _, _, err := store.MintKeyWithQuota(ctx, pool, "be6w2-unl-b", "private", nil, nil, tid, "member", "optional", intPtr(-1), store.AuditStamp{}); err != nil { t.Fatalf("negative-maxKeys mint = %v, want nil", err) } if n := activeKeyCount(t, pool, tid); n != 2 { diff --git a/go/internal/store/api_keys_owner_interleave_integration_test.go b/go/internal/store/api_keys_owner_interleave_integration_test.go new file mode 100644 index 000000000..c3e0a5c3b --- /dev/null +++ b/go/internal/store/api_keys_owner_interleave_integration_test.go @@ -0,0 +1,149 @@ +//go:build integration + +// The owner rules of api-key-update and api-key-delete under a concurrent key +// write (Präambel 9a, case b): both read the target key before they take the +// tenant row lock that serialises every key write of api_keys.go. A decision +// made on that early read can be stale by the time the lock is held — the +// target's scope_narrowing (migration 198), active or role changed under it. +// Each test holds the tenant lock on a second connection, changes the target +// there, starts the store call (which reads the target, then waits for the +// lock), commits, and checks the call decided on the committed target. +// +// go test -tags=integration -p 1 -count=1 -run 'TestOwnerRulesReadTheTargetUnderTheLock' ./internal/store/ +package store_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" +) + +// ownerInterleave holds the tenant lock on a second connection, runs change +// there, starts call, waits until call waits for a lock, commits and returns +// call's error. +func ownerInterleave(ctx context.Context, t *testing.T, pool *pgxpool.Pool, tid string, change func(pgx.Tx), call func() error) error { + t.Helper() + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, `SELECT id FROM context_tenants WHERE id = $1::uuid FOR UPDATE`, tid); err != nil { + t.Fatal(err) + } + change(tx) + done := make(chan error, 1) + go func() { done <- call() }() + deadline := time.Now().Add(5 * time.Second) + for { + var waiting int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM pg_stat_activity + WHERE datname = current_database() AND wait_event_type = 'Lock' AND pid <> pg_backend_pid()`).Scan(&waiting); err != nil { + t.Fatal(err) + } + if waiting > 0 { + break + } + select { + case err := <-done: + t.Fatalf("the store call did not wait for the tenant lock: %v", err) + default: + } + if time.Now().After(deadline) { + t.Fatal("the store call never waited for the tenant lock") + } + time.Sleep(10 * time.Millisecond) + } + if err := tx.Commit(ctx); err != nil { + t.Fatal(err) + } + return <-done +} + +func ownerNarrowing(ctx context.Context, t *testing.T, pool *pgxpool.Pool, id string) string { + t.Helper() + var v string + if err := pool.QueryRow(ctx, `SELECT scope_narrowing FROM context_api_keys WHERE id = $1::uuid`, id).Scan(&v); err != nil { + t.Fatal(err) + } + return v +} + +// TestOwnerRulesReadTheTargetUnderTheLock_Update: owner key A requires +// narrowing; an owner lifts that while a tenant-admin switches A to required. +// Read before the lock, A already "requires" — the switch would look like no +// change and pass the owner guard; read under the lock it strips A's +// administration again, which a tenant-admin may not do (ErrOwnerProtected). +func TestOwnerRulesReadTheTargetUnderTheLock_Update(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + tid := freshTenant(t, ctx, pool, "ilv-upd") + a := seedKeyRole(t, pool, "ilv-upd-a", tid, "owner", true) + seedKeyRole(t, pool, "ilv-upd-b", tid, "owner", true) + required := "required" + if _, _, err := store.UpdateApiKey(ctx, pool, a, tid, false, true, nil, nil, nil, &required, store.AuditStamp{}); err != nil { + t.Fatalf("fixture: the owner switches key A to required: %v", err) + } + + err := ownerInterleave(ctx, t, pool, tid, + func(tx pgx.Tx) { + if _, err := tx.Exec(ctx, `UPDATE context_api_keys SET scope_narrowing = 'optional' WHERE id = $1::uuid`, a); err != nil { + t.Fatal(err) + } + }, + func() error { + _, _, err := store.UpdateApiKey(ctx, pool, a, tid, false, false /*tenant-admin*/, nil, nil, nil, &required, store.AuditStamp{}) + return err + }) + if !errors.Is(err, store.ErrOwnerProtected) { + t.Errorf("a tenant-admin switches owner key A to required behind a committed lift: err %v, want ErrOwnerProtected", err) + } + if got := ownerNarrowing(ctx, t, pool, a); got != "optional" { + t.Errorf("owner key A reads %q, want optional (the lift stands)", got) + } +} + +// TestOwnerRulesReadTheTargetUnderTheLock_Delete: owner key A requires +// narrowing, owner key B does not. Concurrently the requirement moves from A +// to B. Read before the lock, A administers nothing and revoking it needs no +// count; read under the lock A is the tenant's last owner that administers, +// and revoking it is refused (ErrLastOwner). +func TestOwnerRulesReadTheTargetUnderTheLock_Delete(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + tid := freshTenant(t, ctx, pool, "ilv-del") + a := seedKeyRole(t, pool, "ilv-del-a", tid, "owner", true) + b := seedKeyRole(t, pool, "ilv-del-b", tid, "owner", true) + required := "required" + if _, _, err := store.UpdateApiKey(ctx, pool, a, tid, false, true, nil, nil, nil, &required, store.AuditStamp{}); err != nil { + t.Fatalf("fixture: the owner switches key A to required: %v", err) + } + + err := ownerInterleave(ctx, t, pool, tid, + func(tx pgx.Tx) { + if _, err := tx.Exec(ctx, `UPDATE context_api_keys SET scope_narrowing = 'optional' WHERE id = $1::uuid`, a); err != nil { + t.Fatal(err) + } + if _, err := tx.Exec(ctx, `UPDATE context_api_keys SET scope_narrowing = 'required' WHERE id = $1::uuid`, b); err != nil { + t.Fatal(err) + } + }, + func() error { + _, err := store.DeleteApiKey(ctx, pool, a, tid, false, true /*owner caller*/, store.AuditStamp{}) + return err + }) + if !errors.Is(err, store.ErrLastOwner) { + t.Errorf("an owner revokes key A, after the commit the last owner that administers: err %v, want ErrLastOwner", err) + } + var active bool + if err := pool.QueryRow(ctx, `SELECT active FROM context_api_keys WHERE id = $1::uuid`, a).Scan(&active); err != nil || !active { + t.Errorf("owner key A active %v (err %v), want it kept", active, err) + } +} diff --git a/go/internal/store/api_keys_update_integration_test.go b/go/internal/store/api_keys_update_integration_test.go index 88dc87ab5..a46a55fec 100644 --- a/go/internal/store/api_keys_update_integration_test.go +++ b/go/internal/store/api_keys_update_integration_test.go @@ -96,7 +96,7 @@ func TestUpdateApiKey_Integration(t *testing.T) { owner := seedKeyRole(t, pool, "be6w3-lastdemote-o1", tid, "owner", true) _, changed, err := store.UpdateApiKey(ctx, pool, owner, tid, - false /*isServerAdmin*/, true /*callerMayManageOwner*/, rolePtr("member"), nil, nil, store.AuditStamp{}) + false /*isServerAdmin*/, true /*callerMayManageOwner*/, rolePtr("member"), nil, nil, nil, store.AuditStamp{}) if !errors.Is(err, store.ErrLastOwner) { t.Fatalf("demote last owner err = %v, want ErrLastOwner", err) } @@ -115,7 +115,7 @@ func TestUpdateApiKey_Integration(t *testing.T) { owner := seedKeyRole(t, pool, "be6w3-lastdeact-o1", tid, "owner", true) _, changed, err := store.UpdateApiKey(ctx, pool, owner, tid, - false, true, nil, activePtr(false), nil, store.AuditStamp{}) + false, true, nil, activePtr(false), nil, nil, store.AuditStamp{}) if !errors.Is(err, store.ErrLastOwner) { t.Fatalf("deactivate last owner err = %v, want ErrLastOwner", err) } @@ -149,7 +149,7 @@ func TestUpdateApiKey_Integration(t *testing.T) { // server-admin caller (callerMayManageOwner=true) isolates the // last-owner mechanic from owner-protection / tenant constraint. _, changeds[i], errs[i] = store.UpdateApiKey(ctx, pool, owners[i], "", - true /*isServerAdmin*/, true, rolePtr("member"), nil, nil, store.AuditStamp{}) + true /*isServerAdmin*/, true, rolePtr("member"), nil, nil, nil, store.AuditStamp{}) }(i) } wg.Wait() @@ -181,7 +181,7 @@ func TestUpdateApiKey_Integration(t *testing.T) { keyB := seedKeyRole(t, pool, "be6w3-foreign-bkey", tidB, "admin", true) _, changed, err := store.UpdateApiKey(ctx, pool, keyB, tidA, - false /*isServerAdmin*/, false /*callerMayManageOwner*/, rolePtr("member"), activePtr(false), nil, store.AuditStamp{}) + false /*isServerAdmin*/, false /*callerMayManageOwner*/, rolePtr("member"), activePtr(false), nil, nil, store.AuditStamp{}) if err != nil { t.Fatalf("foreign-tenant patch err = %v, want nil (no oracle)", err) } @@ -202,7 +202,7 @@ func TestUpdateApiKey_Integration(t *testing.T) { seedKeyRole(t, pool, "be6w3-ownerprot-o2", tid, "owner", true) // second owner → non-last _, changed, err := store.UpdateApiKey(ctx, pool, o1, tid, - false /*isServerAdmin*/, false /*callerMayManageOwner = admin*/, nil, activePtr(false), nil, store.AuditStamp{}) + false /*isServerAdmin*/, false /*callerMayManageOwner = admin*/, nil, activePtr(false), nil, nil, store.AuditStamp{}) if !errors.Is(err, store.ErrOwnerProtected) { t.Fatalf("admin deactivate owner err = %v, want ErrOwnerProtected", err) } @@ -222,7 +222,7 @@ func TestUpdateApiKey_Integration(t *testing.T) { member := seedKeyRole(t, pool, "be6w3-promote-m1", tid, "member", true) updated, changed, err := store.UpdateApiKey(ctx, pool, member, tid, - false /*isServerAdmin*/, true /*owner caller*/, rolePtr("admin"), nil, nil, store.AuditStamp{}) + false /*isServerAdmin*/, true /*owner caller*/, rolePtr("admin"), nil, nil, nil, store.AuditStamp{}) if err != nil || !changed { t.Fatalf("promote member→admin = (changed=%v, err=%v), want (true, nil)", changed, err) } @@ -242,7 +242,7 @@ func TestUpdateApiKey_Integration(t *testing.T) { member := seedKeyRole(t, pool, "be6w3-reactivate-m1", tid, "member", false) updated, changed, err := store.UpdateApiKey(ctx, pool, member, "", - true /*isServerAdmin*/, true, nil, activePtr(true), nil, store.AuditStamp{}) + true /*isServerAdmin*/, true, nil, activePtr(true), nil, nil, store.AuditStamp{}) if err != nil || !changed { t.Fatalf("reactivate key = (changed=%v, err=%v), want (true, nil)", changed, err) } @@ -268,16 +268,19 @@ func TestUpdateApiKey_ServerAdminProtected(t *testing.T) { empty := []string{} patches := []struct { - name string - role *string - active *bool - writeScopes *[]string - startActive bool + name string + role *string + active *bool + writeScopes *[]string + startActive bool + scopeNarrowing *string }{ - {"deactivate", nil, activePtr(false), nil, true}, - {"demote", rolePtr("member"), nil, nil, true}, - {"write_scopes", nil, nil, &empty, true}, - {"reactivate", nil, activePtr(true), nil, false}, + {"deactivate", nil, activePtr(false), nil, true, nil}, + {"demote", rolePtr("member"), nil, nil, true, nil}, + {"write_scopes", nil, nil, &empty, true, nil}, + {"reactivate", nil, activePtr(true), nil, false, nil}, + // migration 198: requiring narrowing re-scopes the key too. + {"scope_narrowing", nil, nil, nil, true, rolePtr("required")}, } for _, caller := range []struct { name string @@ -292,7 +295,7 @@ func TestUpdateApiKey_ServerAdminProtected(t *testing.T) { markServerAdmin(t, pool, sa) _, changed, err := store.UpdateApiKey(ctx, pool, sa, tid, false /*isServerAdmin*/, - caller.callerMayManageOwner, p.role, p.active, p.writeScopes, store.AuditStamp{}) + caller.callerMayManageOwner, p.role, p.active, p.writeScopes, p.scopeNarrowing, store.AuditStamp{}) if !errors.Is(err, store.ErrServerAdminProtected) { t.Fatalf("patch server-admin key err = %v, want ErrServerAdminProtected", err) } @@ -313,7 +316,7 @@ func TestUpdateApiKey_ServerAdminProtected(t *testing.T) { sa := seedKeyRole(t, pool, "upd-s9i-sa-ok-sa", tid, "admin", true) markServerAdmin(t, pool, sa) - _, changed, err := store.UpdateApiKey(ctx, pool, sa, "", true /*isServerAdmin*/, true, nil, activePtr(false), nil, store.AuditStamp{}) + _, changed, err := store.UpdateApiKey(ctx, pool, sa, "", true /*isServerAdmin*/, true, nil, activePtr(false), nil, nil, store.AuditStamp{}) if err != nil || !changed { t.Fatalf("server-admin patch = (changed=%v, err=%v), want (true, nil)", changed, err) } diff --git a/go/internal/store/api_keys_write_scopes_integration_test.go b/go/internal/store/api_keys_write_scopes_integration_test.go index 225a02b45..544432dd3 100644 --- a/go/internal/store/api_keys_write_scopes_integration_test.go +++ b/go/internal/store/api_keys_write_scopes_integration_test.go @@ -86,7 +86,7 @@ func TestWriteScopes_Migration078_Integration(t *testing.T) { t.Run("MintPersistsAndCtxAuthReturnsWriteScopes", func(t *testing.T) { tid := freshTenant(t, ctx, pool, "w3-persist") key, plaintext, err := store.MintKeyWithQuota(ctx, pool, - "w3-writer", "private", []string{"shared", "work"}, []string{"work"}, tid, "member", nil, store.AuditStamp{}) + "w3-writer", "private", []string{"shared", "work"}, []string{"work"}, tid, "member", "optional", nil, store.AuditStamp{}) if err != nil { t.Fatalf("mint with valid write_scope = %v, want nil", err) } @@ -110,7 +110,7 @@ func TestWriteScopes_Migration078_Integration(t *testing.T) { tid := freshTenant(t, ctx, pool, "w3-blind") // 'work' is NOT in allowed_scopes ∪ {home_scope} → a blind-writer → rejected. key, _, err := store.MintKeyWithQuota(ctx, pool, - "w3-blind-writer", "private", []string{"shared"}, []string{"work"}, tid, "member", nil, store.AuditStamp{}) + "w3-blind-writer", "private", []string{"shared"}, []string{"work"}, tid, "member", "optional", nil, store.AuditStamp{}) if !errors.Is(err, store.ErrWriteScopeNotAllowed) { t.Fatalf("mint blind-writer err = %v (key id %q), want ErrWriteScopeNotAllowed", err, key.ID) } @@ -128,7 +128,7 @@ func TestWriteScopes_Migration078_Integration(t *testing.T) { t.Run("CompatEmptyWriteScopes", func(t *testing.T) { tid := freshTenant(t, ctx, pool, "w3-compat") key, plaintext, err := store.MintKeyWithQuota(ctx, pool, - "w3-compat-key", "private", []string{"shared"}, nil, tid, "member", nil, store.AuditStamp{}) + "w3-compat-key", "private", []string{"shared"}, nil, tid, "member", "optional", nil, store.AuditStamp{}) if err != nil { t.Fatalf("mint without write_scopes = %v, want nil", err) } diff --git a/go/internal/store/audit_classification_test.go b/go/internal/store/audit_classification_test.go index ddeeca7d0..8916161bc 100644 --- a/go/internal/store/audit_classification_test.go +++ b/go/internal/store/audit_classification_test.go @@ -78,7 +78,7 @@ var auditClassification = []auditedTable{ stateFn: "audit_state_api_key", audited: []string{ "label", "home_scope", "allowed_scopes", "write_scopes", "active", "is_admin", - "tenant_id", "tenant_role", "confirm_writes", "principal_id", + "tenant_id", "tenant_role", "confirm_writes", "principal_id", "scope_narrowing", }, excluded: map[string]string{ "id": "identity of the row, written as entity_key", @@ -446,16 +446,17 @@ func (p auditProbeSet) rowKey() (col, typ string) { var auditColumnProbes = map[string]auditProbeSet{ "context_api_keys": { audited: map[string]string{ - "label": "label || '-p'", - "home_scope": "home_scope || 'p'", - "allowed_scopes": "allowed_scopes || '{pinprobe}'::text[]", - "write_scopes": "write_scopes || '{pinprobe}'::text[]", - "active": "NOT active", - "is_admin": "NOT is_admin", - "tenant_id": "'%[1]s'::uuid", - "tenant_role": "CASE WHEN tenant_role = 'member' THEN 'admin' ELSE 'member' END", - "confirm_writes": "NOT confirm_writes", - "principal_id": "'%[2]s'::uuid", + "label": "label || '-p'", + "home_scope": "home_scope || 'p'", + "allowed_scopes": "allowed_scopes || '{pinprobe}'::text[]", + "write_scopes": "write_scopes || '{pinprobe}'::text[]", + "active": "NOT active", + "is_admin": "NOT is_admin", + "tenant_id": "'%[1]s'::uuid", + "tenant_role": "CASE WHEN tenant_role = 'member' THEN 'admin' ELSE 'member' END", + "confirm_writes": "NOT confirm_writes", + "principal_id": "'%[2]s'::uuid", + "scope_narrowing": "CASE WHEN scope_narrowing = 'optional' THEN 'required' ELSE 'optional' END", }, excluded: map[string]string{ "key_hash": "key_hash || 'p'", @@ -660,6 +661,13 @@ func TestAuditClassificationPerColumn(t *testing.T) { t.Fatalf("read 197: %v", err) } kaExecInTx(ctx, t, pool, string(m197Body)) + // 198 (Achse 02 C-2) adds scope_narrowing to the key and its audit; it + // needs only 160's objects and the 095 auth functions it replaces. + m198Body, err := migrations.FS.ReadFile("198_api_key_scope_narrowing.sql") + if err != nil { + t.Fatalf("read 198: %v", err) + } + kaExecInTx(ctx, t, pool, string(m198Body)) otherTenant := freshTenant(t, ctx, pool, "ka-pin-other") var otherPrincipal string diff --git a/go/internal/store/migration198_integration_test.go b/go/internal/store/migration198_integration_test.go new file mode 100644 index 000000000..6bbfe42ad --- /dev/null +++ b/go/internal/store/migration198_integration_test.go @@ -0,0 +1,241 @@ +//go:build integration + +// Migration 198 (Achse 02 C-2): context_api_keys.scope_narrowing, its audit, +// and ctx_auth / ctx_auth_by_id carrying it. The forward runs on a fresh and a +// populated database are cmd/ctxd's TestC2Migration198; this file holds the +// way back its header documents and the size measurement of its lock window. +// +// go test -tags=integration -p 1 -count=1 -run 'TestMigration198' ./internal/store/ +package store_test + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "io/fs" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" + "github.com/GottZ/ctx/migrations" +) + +const m198Version = 198 + +// m198Between returns the text of src from the LAST occurrence of from up to +// and including the first occurrence of to after it. +func m198Between(t *testing.T, src, from, to string) string { + t.Helper() + i := strings.LastIndex(src, from) + if i < 0 { + t.Fatalf("migration text: %q not found", from) + } + j := strings.Index(src[i:], to) + if j < 0 { + t.Fatalf("migration text: %q not found after %q", to, from) + } + return src[i : i+j+len(to)] +} + +// m198Read reads one migration file of the chain. +func m198Read(t *testing.T, name string) string { + t.Helper() + raw, err := fs.ReadFile(migrations.FS, name) + if err != nil { + t.Fatal(err) + } + return string(raw) +} + +// m198SeedKey writes one key in the 197 shape (plain SQL: the store's insert +// is the 198 one) and returns its plaintext and id. +func m198SeedKey(ctx context.Context, t *testing.T, pool *pgxpool.Pool, label string) (string, string) { + t.Helper() + plain := strings.Repeat(hex.EncodeToString([]byte(label))[:8], 8) + sum := sha256.Sum256([]byte(plain)) + var id string + if err := pool.QueryRow(ctx, `WITH p AS (INSERT INTO context_principals (display_name) VALUES ($1) RETURNING id) + INSERT INTO context_api_keys (label, key_hash, home_scope, allowed_scopes, active, tenant_id, tenant_role, principal_id) + SELECT $1, $2, 'private', '{shared}', true, $3::uuid, 'member', p.id FROM p RETURNING id::text`, + label, hex.EncodeToString(sum[:]), store.DefaultTenantID).Scan(&id); err != nil { + t.Fatalf("seed key %s: %v", label, err) + } + return plain, id +} + +// m198AuthColumns is the result signature of ctx_auth. +func m198AuthColumns(ctx context.Context, t *testing.T, pool *pgxpool.Pool) string { + t.Helper() + var res string + // By name at run time: a regprocedure literal resolves to the OID once, + // when the statement is prepared, and the way back drops that OID. + if err := pool.QueryRow(ctx, `SELECT pg_get_function_result(p.oid) FROM pg_proc p WHERE p.proname = 'ctx_auth'`).Scan(&res); err != nil { + t.Fatal(err) + } + return res +} + +// TestMigration198WayBack runs the way back of 198's header, statement by +// statement, on a database where a key requires narrowing: afterwards the +// column, its audit key and the twelfth ctx_auth column are gone and the key +// authenticates as before 198; the next migration run applies 198 again and +// the key reads optional (the requirement is not restored — the header says +// so). +func TestMigration198WayBack(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDBUpTo(t, m198Version-1) + plain, id := m198SeedKey(ctx, t, pool, "m198-way-back") + if err := store.RunMigrationsUpTo(ctx, pool, m198Version); err != nil { + t.Fatalf("migrate to 198: %v", err) + } + if !strings.HasSuffix(m198AuthColumns(ctx, t, pool), "principal_id uuid, scope_narrowing text)") { + t.Fatalf("ctx_auth at 198 returns %s, want scope_narrowing text last", m198AuthColumns(ctx, t, pool)) + } + // A binary before 198 selects the eleven 095 columns by name: that + // statement still answers at 198. + var oldValid bool + if err := pool.QueryRow(ctx, `SELECT api_key_id, home_scope, allowed_scopes, read_scopes, is_valid, is_admin, tenant_id, tenant_role, write_scopes, confirm_writes, principal_id FROM ctx_auth($1)`, + plain).Scan(nil, nil, nil, nil, &oldValid, nil, nil, nil, nil, nil, nil); err != nil || !oldValid { + t.Errorf("the 197 binary's ctx_auth statement at 198: valid %v (err %v), want it to authenticate", oldValid, err) + } + if _, err := pool.Exec(ctx, `UPDATE context_api_keys SET scope_narrowing = 'required' WHERE id = $1::uuid`, id); err != nil { + t.Fatal(err) + } + var auditKeys int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM context_settings_audit WHERE entity_type = 'api_key' AND entity_key = $1 + AND action = 'update' AND new_value->>'scope_narrowing' = 'required' AND old_value->>'scope_narrowing' = 'optional'`, id).Scan(&auditKeys); err != nil || auditKeys != 1 { + t.Errorf("switching the requirement on wrote %d audit row(s) carrying it (err %v), want 1", auditKeys, err) + } + + base := m198Read(t, "113_baseline.sql") + m160 := m198Read(t, "160_audit_keys_quota.sql") + steps := []string{ + `DROP FUNCTION ctx_auth(TEXT)`, + `DROP FUNCTION ctx_auth_by_id(UUID)`, + m198Between(t, base, "CREATE FUNCTION ctx_auth_by_id(p_api_key_id UUID)", "\n$$;"), + m198Between(t, base, "CREATE FUNCTION ctx_auth(p_api_key TEXT)", "\n$$;"), + m198Between(t, m160, "CREATE OR REPLACE FUNCTION audit_state_api_key", "$$ LANGUAGE sql IMMUTABLE;"), + `DROP TRIGGER trg_api_keys_audit_upd ON context_api_keys`, + m198Between(t, m160, "CREATE TRIGGER trg_api_keys_audit_upd", "EXECUTE FUNCTION audit_api_keys_write();"), + `ALTER TABLE context_api_keys DROP COLUMN scope_narrowing`, + `DELETE FROM _migrations WHERE version = 198`, + } + for i, sql := range steps { + if _, err := pool.Exec(ctx, sql); err != nil { + t.Fatalf("way back, step %d: %v\n%s", i+1, err, sql) + } + } + if got := m198AuthColumns(ctx, t, pool); !strings.HasSuffix(got, "confirm_writes boolean, principal_id uuid)") { + t.Errorf("ctx_auth after the way back returns %s, want the 095 columns", got) + } + var valid bool + if err := pool.QueryRow(ctx, `SELECT is_valid FROM ctx_auth($1)`, plain).Scan(&valid); err != nil || !valid { + t.Errorf("the key after the way back: valid %v (err %v), want it to authenticate", valid, err) + } + if _, err := pool.Exec(ctx, `UPDATE context_api_keys SET label = 'm198-way-back-2' WHERE id = $1::uuid`, id); err != nil { + t.Errorf("an audited update after the way back: %v", err) + } + + if err := store.RunMigrations(ctx, pool); err != nil { + t.Fatalf("migrate again: %v", err) + } + var narrowing string + if err := pool.QueryRow(ctx, `SELECT scope_narrowing FROM ctx_auth($1)`, plain).Scan(&narrowing); err != nil || narrowing != "optional" { + t.Errorf("the key after 198 ran again: scope_narrowing %q (err %v), want optional", narrowing, err) + } +} + +// TestMigration198AuthReadsTheLockedRow (Präambel 9a, case b): an +// authentication that meets a key row an uncommitted api-key-update holds +// waits for it and answers the value that update committed — ctx_auth_by_id +// reads scope_narrowing in the RETURNING of its own last_used_at UPDATE, not +// from a snapshot taken before the lock. A version that read the column +// before the lock would answer optional here and let the key run unnarrowed +// once more after its switch committed. +func TestMigration198AuthReadsTheLockedRow(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + key, plain, err := store.CreateApiKey(ctx, pool, "m198-interleave", "private", nil, "") + if err != nil { + t.Fatal(err) + } + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, `UPDATE context_api_keys SET scope_narrowing = 'required' WHERE id = $1::uuid`, key.ID); err != nil { + t.Fatal(err) + } + type answer struct { + narrowing string + err error + } + done := make(chan answer, 1) + go func() { + var a answer + a.err = pool.QueryRow(ctx, `SELECT scope_narrowing FROM ctx_auth($1)`, plain).Scan(&a.narrowing) + done <- a + }() + select { + case a := <-done: + t.Fatalf("the authentication did not wait for the key row: %+v", a) + case <-time.After(300 * time.Millisecond): + } + if err := tx.Commit(ctx); err != nil { + t.Fatal(err) + } + if a := <-done; a.err != nil || a.narrowing != "required" { + t.Errorf("the authentication behind the committed switch: scope_narrowing %q (err %v), want required", a.narrowing, a.err) + } +} + +// TestMigration198LockWindow measures the file on a key table of the given +// sizes (CTX_M198_KEYS, comma-separated; skipped without it): the time 198 +// holds context_api_keys, and how long an authentication on a second +// connection waits for it. Measurement only; docs/operations.md +// "Migration 198" carries the numbers. +func TestMigration198LockWindow(t *testing.T) { + sizes := os.Getenv("CTX_M198_KEYS") + if sizes == "" { + t.Skip("CTX_M198_KEYS unset: measurement only") + } + ctx := context.Background() + for _, n := range strings.Split(sizes, ",") { + t.Run("keys="+n, func(t *testing.T) { + pool := testdb.SetupTestDBUpTo(t, m198Version-1) + plain, _ := m198SeedKey(ctx, t, pool, "m198-probe") + if _, err := pool.Exec(ctx, `WITH p AS ( + INSERT INTO context_principals (display_name) SELECT 'm198-' || g FROM generate_series(1, $1::int) g RETURNING id, display_name) + INSERT INTO context_api_keys (label, key_hash, home_scope, allowed_scopes, active, tenant_id, tenant_role, principal_id) + SELECT p.display_name, encode(digest(p.display_name, 'sha256'), 'hex'), 'private', '{shared}', true, $2::uuid, 'member', p.id FROM p`, + n, store.DefaultTenantID); err != nil { + t.Fatalf("seed %s keys: %v", n, err) + } + if _, err := pool.Exec(ctx, `VACUUM ANALYZE context_api_keys`); err != nil { + t.Fatal(err) + } + done := make(chan time.Duration, 1) + start := time.Now() + go func() { + // The authentication starts once the migration holds its lock. + time.Sleep(50 * time.Millisecond) + s := time.Now() + var v bool + _ = pool.QueryRow(ctx, `SELECT is_valid FROM ctx_auth($1)`, plain).Scan(&v) + done <- time.Since(s) + }() + if err := store.RunMigrationsUpTo(ctx, pool, m198Version); err != nil { + t.Fatalf("migrate to 198: %v", err) + } + file := time.Since(start) + wait := <-done + t.Logf("keys=%s: migration 198 took %s; an authentication started 50 ms in answered after %s", n, file, wait) + }) + } +} diff --git a/go/internal/store/request_key_gate_integration_test.go b/go/internal/store/request_key_gate_integration_test.go index c364dabfc..323d6509f 100644 --- a/go/internal/store/request_key_gate_integration_test.go +++ b/go/internal/store/request_key_gate_integration_test.go @@ -397,7 +397,7 @@ func TestTenantDeleteTakesItsScopesFromOtherKeys(t *testing.T) { if err != nil { t.Fatal(err) } - _, rawList, err := store.MintKeyWithQuota(ctx, f.pool, "bridge list", "private", []string{"private", scopes[1]}, []string{scopes[1]}, store.DefaultTenantID, "member", nil, store.AuditStamp{}) + _, rawList, err := store.MintKeyWithQuota(ctx, f.pool, "bridge list", "private", []string{"private", scopes[1]}, []string{scopes[1]}, store.DefaultTenantID, "member", "optional", nil, store.AuditStamp{}) if err != nil { t.Fatal(err) } @@ -738,7 +738,7 @@ func TestKeyStepHoldsNoGateOfAKeyItKeeps(t *testing.T) { f := newP547Fixture(t) ctx := context.Background() tenantID, scopes, _ := pruneWritersTenant(t, f, "gkk", 1) - _, raw, err := store.MintKeyWithQuota(ctx, f.pool, "keeps", "private", []string{"private", scopes[0]}, []string{scopes[0]}, store.DefaultTenantID, "member", nil, store.AuditStamp{}) + _, raw, err := store.MintKeyWithQuota(ctx, f.pool, "keeps", "private", []string{"private", scopes[0]}, []string{scopes[0]}, store.DefaultTenantID, "member", "optional", nil, store.AuditStamp{}) if err != nil { t.Fatal(err) } diff --git a/go/internal/store/request_key_gate_writes_integration_test.go b/go/internal/store/request_key_gate_writes_integration_test.go index 40d76753c..68d0bee7a 100644 --- a/go/internal/store/request_key_gate_writes_integration_test.go +++ b/go/internal/store/request_key_gate_writes_integration_test.go @@ -28,7 +28,7 @@ func TestEveryGatedWriteRefusesAKeyThatLostItsScope(t *testing.T) { ctx := context.Background() tenantID, scopes, _ := pruneWritersTenant(t, f, "gaw", 1) s := scopes[0] - _, raw, err := store.MintKeyWithQuota(ctx, f.pool, "listing", "private", []string{"private", s}, []string{s}, store.DefaultTenantID, "member", nil, store.AuditStamp{}) + _, raw, err := store.MintKeyWithQuota(ctx, f.pool, "listing", "private", []string{"private", s}, []string{s}, store.DefaultTenantID, "member", "optional", nil, store.AuditStamp{}) if err != nil { t.Fatal(err) } diff --git a/go/internal/store/tenant_prune_schema_integration_test.go b/go/internal/store/tenant_prune_schema_integration_test.go index b0476f119..538443a25 100644 --- a/go/internal/store/tenant_prune_schema_integration_test.go +++ b/go/internal/store/tenant_prune_schema_integration_test.go @@ -82,11 +82,12 @@ type tpsEntry struct { // the schema has and this map lacks fails the test. var tpsColumns = map[string]tpsEntry{ // Keys: the tenant's own, and keys of another tenant that name its scopes. - "context_api_keys.home_scope": {tpsDrained, "a key homed in a scope of the tenant reads and writes the next owner of that name"}, - "context_api_keys.allowed_scopes": {tpsDrained, "a key reading a scope of the tenant reads the next owner of that name"}, - "context_api_keys.write_scopes": {tpsDrained, "a key writing a scope of the tenant writes into the next owner of that name"}, - "context_api_keys.tenant_id": {tpsDrained, "the tenant's keys"}, - "context_api_keys.tenant_role": {tpsNotCtxScope, "a role name (owner/member), not a tenant"}, + "context_api_keys.home_scope": {tpsDrained, "a key homed in a scope of the tenant reads and writes the next owner of that name"}, + "context_api_keys.allowed_scopes": {tpsDrained, "a key reading a scope of the tenant reads the next owner of that name"}, + "context_api_keys.write_scopes": {tpsDrained, "a key writing a scope of the tenant writes into the next owner of that name"}, + "context_api_keys.tenant_id": {tpsDrained, "the tenant's keys"}, + "context_api_keys.tenant_role": {tpsNotCtxScope, "a role name (owner/member), not a tenant"}, + "context_api_keys.scope_narrowing": {tpsNotCtxScope, "optional/required (migration 198), not a scope"}, // Scope-carried data. "context_blocks.scope": {tpsDrained, "block content of the tenant"}, "context_dream_links.scope": {tpsDrained, "links between blocks of the tenant"}, @@ -558,7 +559,7 @@ func tpsFill(t *testing.T, f *p547Fixture, o *tpsOwner, defaultBlock string) { t.Fatalf("foreign home key: %v", err) } o.foreignHomeKey = plainHome - dw, plainWrite, err := store.MintKeyWithQuota(ctx, pool, o.slug+" foreign write", "private", []string{s1}, []string{s1}, store.DefaultTenantID, "member", nil, store.AuditStamp{}) + dw, plainWrite, err := store.MintKeyWithQuota(ctx, pool, o.slug+" foreign write", "private", []string{s1}, []string{s1}, store.DefaultTenantID, "member", "optional", nil, store.AuditStamp{}) if err != nil { t.Fatalf("foreign write key: %v", err) } diff --git a/go/migrations/198_api_key_scope_narrowing.sql b/go/migrations/198_api_key_scope_narrowing.sql new file mode 100644 index 000000000..ccf660f85 --- /dev/null +++ b/go/migrations/198_api_key_scope_narrowing.sql @@ -0,0 +1,259 @@ +-- ============================================================================= +-- 198_api_key_scope_narrowing.sql — a key can require per-request scope +-- narrowing: context_api_keys.scope_narrowing, its audit, and ctx_auth / +-- ctx_auth_by_id carrying it (Achse 02, cluster C-2) +-- Part of ctx by GottZ (https://github.com/GottZ/ctx) +-- ============================================================================= +-- What. A request may narrow its key to scopes it names (X-Context-Read- +-- Scopes / X-Context-Write-Scope, handler/narrowing.go). A key with +-- scope_narrowing = 'required' answers every request WITHOUT a narrowing with +-- 403 scope_narrowing_required, except GET /api/whoami, so a client that +-- forgets the narrowing, an old client, or another tool holding the same key +-- reaches nothing; with a narrowing it may do exactly what the narrowing +-- allows. 'optional' — every existing key, and the default — keeps today's +-- behaviour. Set through api-key-create and api-key-update (tenant-admin, +-- like write_scopes); the check is the handler's (narrowAuth), the column is +-- the state. +-- +-- (1) context_api_keys.scope_narrowing TEXT NOT NULL DEFAULT 'optional' +-- CHECK (optional | required) — the tenant_role pattern of 059. NOT part +-- of the store's shared key reads that migration tests run against older +-- schemas: insertApiKeyTx names the column only for a 'required' key (an +-- 'optional' one gets the default), so the mint paths keep working on a +-- database before 198. +-- (2) The audit (160): audit_state_api_key gains the key scope_narrowing and +-- trg_api_keys_audit_upd fires on it — turning the requirement on or off +-- is an audited 'update' row like a change of write_scopes +-- (internal/store/audit_classification_test.go pins the column audited). +-- From this migration on every api_key audit row carries the key; older +-- rows stay as written. +-- (3) ctx_auth_by_id and ctx_auth of 095 gain the column scope_narrowing, +-- LAST (named SELECTs in internal/auth: an older binary on the same +-- database selects its eleven columns and does not see the new one). The +-- result type changes, so both functions are dropped and created in this +-- transaction. ctx_auth_by_id reads the column in the RETURNING of its +-- last_used_at UPDATE, i.e. from the row version it locked: a concurrent +-- api-key-update of the key is waited for and its committed value read. +-- Nothing caches an authentication, so a switch applies from the next +-- request on; a request already running keeps the value it was admitted +-- with. The sentinel rows (unknown or inactive key, inactive tenant or +-- principal) read 'required': they authorise nothing, and a reader of +-- the column of an invalid row reads the stricter value. +-- +-- Cost and locks. ADD COLUMN with a constant default rewrites no row; the +-- CHECK is verified with one scan of context_api_keys, under the ACCESS +-- EXCLUSIVE lock the ADD COLUMN takes until the commit. During that window +-- every authentication waits (ctx_auth_by_id writes last_used_at), as does +-- every key write of another ctx process on the same database. The table +-- holds one row per api key (max_keys per tenant, 50 by default); measured +-- (TestMigration198LockWindow, docs/operations.md "Migration 198"): the +-- whole file 46 ms on 100 000 keys and 215 ms on 1 000 000, where an +-- authentication that started 50 ms in waited 167 ms. Done inline, without a +-- row threshold: the scan is linear in keys, not in blocks. CREATE TRIGGER +-- takes SHARE ROW EXCLUSIVE on the same table, inside the same window. +-- DROP/CREATE FUNCTION locks no table; a session that calls ctx_auth +-- meanwhile uses the old definition until the commit. lock_timeout 3s fails +-- the boot instead of queueing behind a long transaction; the next start +-- retries. +-- +-- An older binary on a database with 198 selects its named columns and +-- serves every key, a required one included, WITHOUT the requirement: the +-- check lives in the binary. Before rolling the binary back, deactivate the +-- keys that require narrowing, or accept that each of them then reaches +-- everything its own rights allow. +-- +-- Idempotent: ADD COLUMN IF NOT EXISTS (with its CHECK only when the column +-- is new), CREATE OR REPLACE FUNCTION, DROP TRIGGER IF EXISTS + CREATE, DROP +-- FUNCTION IF EXISTS + CREATE. +-- +-- Way back, in this order, one statement each: DROP FUNCTION ctx_auth(TEXT); +-- DROP FUNCTION ctx_auth_by_id(UUID); the CREATE FUNCTION ctx_auth_by_id and +-- CREATE FUNCTION ctx_auth of 095 (113_baseline.sql, section +-- 095_ctx_auth_principal.sql); the CREATE OR REPLACE FUNCTION +-- audit_state_api_key of 160; DROP TRIGGER trg_api_keys_audit_upd ON +-- context_api_keys and the CREATE TRIGGER of 160; ALTER TABLE +-- context_api_keys DROP COLUMN scope_narrowing; DELETE FROM _migrations +-- WHERE version = 198 (so a later upgrade applies it again). A key that +-- required narrowing answers unnarrowed requests again after that. The audit +-- rows stay (append-only history). TestMigration198WayBack runs exactly +-- these statements. +-- ============================================================================= + +SET LOCAL lock_timeout = '3s'; + +-- 1. The requirement. +ALTER TABLE context_api_keys + ADD COLUMN IF NOT EXISTS scope_narrowing TEXT NOT NULL DEFAULT 'optional' + CHECK (scope_narrowing IN ('optional', 'required')); + +-- 2. The audit: the projection and the update trigger of 160, with +-- scope_narrowing. +CREATE OR REPLACE FUNCTION audit_state_api_key(k context_api_keys) + RETURNS JSONB AS $$ + SELECT jsonb_build_object( + 'label', k.label, 'home_scope', k.home_scope, + 'allowed_scopes', to_jsonb(k.allowed_scopes), 'write_scopes', to_jsonb(k.write_scopes), + 'active', k.active, 'is_admin', k.is_admin, + 'tenant_id', k.tenant_id, 'tenant_role', k.tenant_role, + 'confirm_writes', k.confirm_writes, 'principal_id', k.principal_id, + 'scope_narrowing', k.scope_narrowing) +$$ LANGUAGE sql IMMUTABLE; + +DROP TRIGGER IF EXISTS trg_api_keys_audit_upd ON context_api_keys; +CREATE TRIGGER trg_api_keys_audit_upd + AFTER UPDATE OF label, home_scope, allowed_scopes, write_scopes, active, is_admin, + tenant_id, tenant_role, confirm_writes, principal_id, scope_narrowing + ON context_api_keys FOR EACH ROW + WHEN ((OLD.label, OLD.home_scope, OLD.allowed_scopes, OLD.write_scopes, OLD.active, + OLD.is_admin, OLD.tenant_id, OLD.tenant_role, OLD.confirm_writes, OLD.principal_id, + OLD.scope_narrowing) + IS DISTINCT FROM + (NEW.label, NEW.home_scope, NEW.allowed_scopes, NEW.write_scopes, NEW.active, + NEW.is_admin, NEW.tenant_id, NEW.tenant_role, NEW.confirm_writes, NEW.principal_id, + NEW.scope_narrowing)) + EXECUTE FUNCTION audit_api_keys_write(); + +-- 3. ctx_auth_by_id and ctx_auth of 095 with scope_narrowing as the last +-- column. Unchanged otherwise: the three fail-closed gates, the +-- last_used_at write and the positional read_scopes build. +DROP FUNCTION IF EXISTS ctx_auth(TEXT); +DROP FUNCTION IF EXISTS ctx_auth_by_id(UUID); + +CREATE FUNCTION ctx_auth_by_id(p_api_key_id UUID) +RETURNS TABLE ( + api_key_id UUID, + home_scope VARCHAR(50), + allowed_scopes TEXT[], + read_scopes TEXT[], + is_valid BOOLEAN, + is_admin BOOLEAN, + tenant_id UUID, + tenant_role TEXT, + write_scopes TEXT[], + confirm_writes BOOLEAN, + principal_id UUID, + scope_narrowing TEXT +) LANGUAGE plpgsql AS $$ +DECLARE + v_api_key_id UUID; + v_home_scope VARCHAR(50); + v_allowed_scopes TEXT[]; + v_is_admin BOOLEAN; + v_tenant_id UUID; + v_tenant_role TEXT; + v_status TEXT; + v_read_scopes TEXT[]; + v_cand TEXT[]; + v_s TEXT; + v_write_scopes TEXT[]; + v_confirm_writes BOOLEAN; + v_principal_id UUID; + v_principal_active BOOLEAN; + v_scope_narrowing TEXT; +BEGIN + -- Gate 1: the key exists AND is active (soft-revoke gate). The UPDATE by + -- id touches last_used_at only for active=true; its RETURNING reads the + -- row version it locked. + UPDATE context_api_keys + SET last_used_at = now() + WHERE context_api_keys.id = p_api_key_id + AND context_api_keys.active = true + RETURNING + context_api_keys.id, + context_api_keys.home_scope, + context_api_keys.allowed_scopes, + context_api_keys.is_admin, + context_api_keys.tenant_id, + context_api_keys.tenant_role, + context_api_keys.write_scopes, + context_api_keys.confirm_writes, + context_api_keys.principal_id, + context_api_keys.scope_narrowing + INTO v_api_key_id, v_home_scope, v_allowed_scopes, v_is_admin, v_tenant_id, + v_tenant_role, v_write_scopes, v_confirm_writes, v_principal_id, v_scope_narrowing; + + IF v_api_key_id IS NULL THEN + api_key_id := NULL; home_scope := '__UNAUTHORIZED__'; allowed_scopes := '{}'::TEXT[]; + read_scopes := '{}'::TEXT[]; is_valid := false; is_admin := false; + tenant_id := NULL; tenant_role := ''; write_scopes := '{}'::TEXT[]; + confirm_writes := false; principal_id := NULL; scope_narrowing := 'required'; + RETURN NEXT; RETURN; + END IF; + + -- Gate 2: tenant status (design/01 §5.2), before the read_scopes build. + SELECT status INTO v_status FROM context_tenants WHERE id = v_tenant_id; + IF v_status IS NULL OR v_status <> 'active' THEN + api_key_id := NULL; home_scope := '__UNAUTHORIZED__'; allowed_scopes := '{}'::TEXT[]; + read_scopes := '{}'::TEXT[]; is_valid := false; is_admin := false; + tenant_id := NULL; tenant_role := ''; write_scopes := '{}'::TEXT[]; + confirm_writes := false; principal_id := NULL; scope_narrowing := 'required'; + RETURN NEXT; RETURN; + END IF; + + -- Gate 3 (F2): the principal is active — the revoke-all mechanism. + SELECT is_active INTO v_principal_active FROM context_principals WHERE id = v_principal_id; + IF v_principal_active IS NULL OR v_principal_active = false THEN + api_key_id := NULL; home_scope := '__UNAUTHORIZED__'; allowed_scopes := '{}'::TEXT[]; + read_scopes := '{}'::TEXT[]; is_valid := false; is_admin := false; + tenant_id := NULL; tenant_role := ''; write_scopes := '{}'::TEXT[]; + confirm_writes := false; principal_id := NULL; scope_narrowing := 'required'; + RETURN NEXT; RETURN; + END IF; + + -- read_scopes POSITIONAL (design/02 §4.1 variant A), unchanged since 090. + v_read_scopes := ARRAY[v_home_scope::TEXT]; + v_cand := COALESCE(v_allowed_scopes, '{}'::TEXT[]) + || COALESCE((SELECT array_agg(g.granted_scope ORDER BY g.granted_scope) + FROM context_tenant_grants g + WHERE g.grantee_tenant = v_tenant_id), '{}'::TEXT[]); + FOREACH v_s IN ARRAY v_cand LOOP + IF v_s NOT LIKE '\_%' AND NOT (v_s = ANY(v_read_scopes)) THEN + v_read_scopes := v_read_scopes || v_s; + END IF; + END LOOP; + + api_key_id := v_api_key_id; + home_scope := v_home_scope; + allowed_scopes := v_allowed_scopes; + read_scopes := COALESCE(NULLIF(v_read_scopes, '{}'::TEXT[]), ARRAY[v_home_scope]::TEXT[]); + is_valid := true; + is_admin := v_is_admin; + tenant_id := v_tenant_id; + tenant_role := v_tenant_role; + write_scopes := COALESCE(v_write_scopes, '{}'::TEXT[]); + confirm_writes := COALESCE(v_confirm_writes, false); + principal_id := v_principal_id; + scope_narrowing := v_scope_narrowing; + RETURN NEXT; + RETURN; +END; +$$; + +CREATE FUNCTION ctx_auth(p_api_key TEXT) +RETURNS TABLE ( + api_key_id UUID, + home_scope VARCHAR(50), + allowed_scopes TEXT[], + read_scopes TEXT[], + is_valid BOOLEAN, + is_admin BOOLEAN, + tenant_id UUID, + tenant_role TEXT, + write_scopes TEXT[], + confirm_writes BOOLEAN, + principal_id UUID, + scope_narrowing TEXT +) LANGUAGE plpgsql AS $$ +DECLARE + v_api_key_id UUID; +BEGIN + -- Credential to identity only; every gate and the last_used_at write live + -- in ctx_auth_by_id. A key_hash miss leaves v_api_key_id NULL, and + -- ctx_auth_by_id answers the sentinel row. + SELECT context_api_keys.id INTO v_api_key_id + FROM context_api_keys + WHERE context_api_keys.key_hash = encode(digest(p_api_key, 'sha256'), 'hex'); + + RETURN QUERY SELECT * FROM ctx_auth_by_id(v_api_key_id); +END; +$$; diff --git a/go/web/src/lib/api/types.ts b/go/web/src/lib/api/types.ts index ad407a794..094e2db59 100644 --- a/go/web/src/lib/api/types.ts +++ b/go/web/src/lib/api/types.ts @@ -79,6 +79,8 @@ export interface WhoamiResponse { narrowed?: { read: string[]; write: string } | null /** query.rate_limit_write after the key's tenant overlay; 0 = unlimited. */ rate_limit_write?: number + /** The key's scope_narrowing (migration 198): 'optional' | 'required'. Bare string for forward-compat. */ + scope_narrowing?: string } /** Effective-value provenance (handler/settings.go apiSource). `install`: the diff --git a/test.sh b/test.sh index 04f12038c..7a92728f6 100755 --- a/test.sh +++ b/test.sh @@ -423,7 +423,8 @@ T="T07 SCHEMA_INTEGRITY" # hinzu → 71 Tabellen, context_blocks-Spalten unverändert; 191 fügt keine # Tabelle hinzu; 192 fügt context_install hinzu → 72 Tabellen, Spalten # unverändert; 197 fügt context_llm_recordings hinzu → 73 Tabellen, -# context_blocks-Spalten unverändert). +# context_blocks-Spalten unverändert; 198 fügt context_api_keys.scope_narrowing +# hinzu → 73 Tabellen, context_blocks-Spalten unverändert). T07_EXPECT_TABLES=73 T07_EXPECT_COLUMNS=45 @@ -435,7 +436,7 @@ t07_count_fallback() { if [[ "$tc" == "$T07_EXPECT_TABLES" ]] && [[ "$col" == "$T07_EXPECT_COLUMNS" ]]; then pass "$T (contract-CLI nicht verfügbar — Zähl-Fallback (Prä-Deploy); tables=$tc, columns=$col; $reason)" else - fail "$T" "Zähl-Fallback (Prä-Deploy, $reason): expected $T07_EXPECT_TABLES tables + $T07_EXPECT_COLUMNS columns (Stand Mig 197), got tables=$tc columns=$col" + fail "$T" "Zähl-Fallback (Prä-Deploy, $reason): expected $T07_EXPECT_TABLES tables + $T07_EXPECT_COLUMNS columns (Stand Mig 198), got tables=$tc columns=$col" fi } From 0032500e2e26a10c384822ba6ed2fb8460ef9a4a Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 04:15:13 +0100 Subject: [PATCH 05/15] =?UTF-8?q?feat(store):=20manage=20get=20takes=20up?= =?UTF-8?q?=20to=2016=20ids=20and=20reads=20their=20blocks=20with=20one=20?= =?UTF-8?q?statement=20=E2=80=94=20misses=20are=20entries,=20an=20unseen?= =?UTF-8?q?=20id=20answers=20like=20a=20missing=20one=20(C-4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POST /api/manage {"action":"get","ids":[...]} answers {action, success, blocks}: one entry per asked id, in the order asked — the object a single get answers under "block" (fields and the content window apply to each), or a miss entry {id, code, error} with the id as asked: not_found for an unknown, foreign, ungranted or archived id alike, invalid_id for a short prefix, ambiguous_id with matches. A miss never fails the request. Each id resolves as the id of a single get does (ResolveBlockID over the read scopes and the block grants), so a narrowed request reads its named scopes and no grant. The blocks of all full ids are read with one statement (store.GetBlocksOmitting: id = ANY($1::uuid[]), a primary-key probe per id), which shares the select list, scan and visibility condition of GetBlock (blockByIDColumns, scanBlockByID, liveVisibleSQL; the single read's SQL text is unchanged). Only delivered blocks are booked in the read record, each once. ids beside id, an empty list or more than 16 ids, anything but a list of strings, and include_archived are a 400 invalid_body before any lookup; ids sent as null counts as not sent, and a body without ids answers byte for byte as before. The S1 contract tests of C-4 are switched on; probes for refusals, entry parity with the single get, prefixes and misses, narrowed misses, the read record and the statement count, unit tests, and a cost pin of the read (custom and generic plan, random_page_cost 1.1 and 4). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/api.md | 1 + docs/multi-tenancy.md | 2 +- .../manage_get_ids_c4_integration_test.go | 30 +- ...manage_get_ids_c4_more_integration_test.go | 334 ++++++++++++++++++ go/internal/handler/context_manage.go | 9 + go/internal/handler/get_ids.go | 225 ++++++++++++ go/internal/handler/get_ids_test.go | 61 ++++ go/internal/store/blocks.go | 55 ++- go/internal/store/blocks_get_many.go | 64 ++++ .../store/get_blocks_cost_integration_test.go | 131 +++++++ 10 files changed, 894 insertions(+), 18 deletions(-) create mode 100644 go/cmd/ctxd/manage_get_ids_c4_more_integration_test.go create mode 100644 go/internal/handler/get_ids.go create mode 100644 go/internal/handler/get_ids_test.go create mode 100644 go/internal/store/blocks_get_many.go create mode 100644 go/internal/store/get_blocks_cost_integration_test.go diff --git a/docs/api.md b/docs/api.md index e2db0112a..c6ca6b287 100644 --- a/docs/api.md +++ b/docs/api.md @@ -82,6 +82,7 @@ PostgreSQL stores a NUL character (U+0000) neither in text nor in JSON, so no va - **Blocks by id:** `get` (`id`: full UUID or unambiguous prefix) answers `{action, success, block, graph_visible}` for a live block of the caller's read scopes or one granted to its tenant; an unknown, foreign or archived id answers `{success:false, error:"Block not found"}` alike — so does an id or prefix with a character no block id carries (a prefix is lowercase hex digits and hyphens: `%` and `_` are not wildcards, invalid UTF-8 names no block, and a NUL is refused as in every request value, `400` naming the field, issue #519; a full id is a UUID in either case, and any other 36 characters of its shape name no block; issue #547), on every surface that takes an id prefix (`get`, `update`, `delete`, the MCP `get`, `update` and `archive` tools, an update item of a block batch). `delete` archives (`is_archived = true`, never a row delete) a block in a scope the key may write; a block grant gives no write access, and a block carrying a derived `provenance` is refused `403 provenance_protected`. **Reading an archived block** (issue #201): `get` with `include_archived: true` and the **full** block id also answers an archived block — from the key's own scopes only (home and allowed scopes; never through a block grant or a cross-tenant scope grant) — with `block.archived: true` and `graph_visible: false`; an id prefix with `include_archived` is a `400` before any lookup, and an unknown, foreign or granted archived id still answers `Block not found`. Without the field the answer is unchanged. The MCP `get` tool takes the same field, the MCP `archive` tool is `delete`'s twin, and the CLI sends the field with `ctx get --include-archived <id>`. - **Part of a block (issue #407):** `get` takes `fields` (a list of keys of `block`: `id`, `category`, `tags`, `title`, `content`, `metadata`, `scope`, `sensitivity`, `sensitivity_source`, `type`, `lifecycle_state`, `type_source`, `untrusted`, `untrusted_origin`, `archived`, `created_at`, `updated_at`) and a content window, `content_offset` and `content_limit` (integers ≥ 0, counted in Unicode code points, never cutting inside one). With `fields`, `block` carries `id` and exactly the named keys, plus the marks `untrusted`, `untrusted_origin` and `archived` whenever they apply; the `content` and `metadata` columns are read from the database only when named. With the window, `block.content` is the cut — from `content_offset` (default 0), at most `content_limit` characters (default: to the end) — and `block` adds `content_length` (the whole content's length) and `content_truncated` (true when the content goes on after the window; the next window then starts at `content_offset + content_limit`); an offset past the end answers an empty, untruncated `content`. `action`, `success` and `graph_visible` stay around `block`. An unknown name (listed with the valid ones in the error), a value of the wrong type, a negative value, or a window beside a `fields` list without `content` is a `400` before any lookup; an empty list is the whole block, and a key sent as `null` counts as not sent. The projected `block` keeps the key order of the full answer, with `content_length` and `content_truncated` right after `content`. Visibility, the not-found answer, the ambiguous-prefix `matches`, `include_archived` and the read record are those of a full read, and a body without the three keys answers byte for byte as before. The MCP `get` tool takes the same options through the same function — see [MCP `get`](mcp.md#get). +- **Several blocks by id:** `get` with `ids` in place of `id` — a list of 1 to 16 ids, each a full UUID or an unambiguous prefix — answers `{action, success, blocks}` with one entry per asked id, in the order asked. The entry of a found block is the object a single `get` answers under `block` (`fields` and the content window apply to each entry). An id that names no block the caller sees is an entry `{id, code, error}` carrying the id as asked, never a failure of the whole request: code `not_found` with `error: "Block not found"` for an unknown, foreign, ungranted or archived id and for an id with a character no block id carries, alike; `invalid_id` for a prefix shorter than 8 characters; `ambiguous_id` with `matches` for a prefix of more than one visible block. Visibility is that of a single `get` — the read scopes plus the blocks granted to the tenant; under a narrowing ([Scope narrowing per request](#scope-narrowing-per-request)) the named scopes and no block grant. The blocks of all full ids are read with one database statement; a prefix costs the lookup a single `get` makes for it. The read record books each delivered block once and no miss. The answer carries no `graph_visible`. `ids` beside `id`, an empty list or more than 16 ids, a value that is not a list of strings (a `null` element included), and `include_archived` (which reads one block by its full id) are a `400` with code `invalid_body` before any lookup, as are the refusals of `fields` and the window beside `ids` (a single `get` answers those without a code); `ids` sent as `null` counts as not sent, and a body without `ids` answers byte for byte as before. The MCP `get` tool and the CLI's `ctx get` read one id. - **Block listing (issue #212):** `list-meta` answers `{action, success, blocks}`: every live block of the caller's read scopes without content (`id`, `title`, `category`, `tags`, `scope`, `type`, `lifecycle_state`, `type_source`, `updated_at`), ordered by `category, title, scope`, at most 10 000 per answer. It takes the `types` / `types_exclude` filters. An answer cut at 10 000 rows says so: it adds `truncated: true` and `next_after` (`{after_category, after_title, after_scope}`, the position of its last row); send that object back as `after` for the rows that follow (`{}` is the first page; any other value, another cursor's shape included, is a `400`). A complete answer carries neither key, as before. The position is a position only: each page applies the read scopes and filters of its own request. Until #212 the listing stopped at 10 000 rows and the answer looked complete; rows of one category and title in two scopes came in no defined order. - **Scope purge (hard delete, issue #202):** `purge` (tierTenantAdmin) removes block data inside **one** scope for good — the narrow counterpart of `tenant-delete`, for rows that should never have been written (a test or import run into a production tenant); `delete` only archives. `data`: `scope` (required) and optional filters, each of which narrows: `tags` (the block carries **every** listed tag; an empty list is no filter), `category`, `created_before` / `created_after` (RFC 3339, exclusive bounds on `created_at`), `archived_only`; and `keepalive` (below), which is no filter. No filter drains the scope. Unknown fields are `400`, so a misspelt filter cannot widen the purge. A tenant-admin reaches only the scopes its own tenant owns — another tenant's scope and an unknown one answer the same `404 scope not found`; a server-admin reaches every scope; an empty scope and the `_` system namespace are `400`; a key without an admin role is `403`, its home scope included. **Without `confirm_blocks` the call is a dry run** that deletes nothing and answers `{action, success, scope, filter, dry_run: true, as_of, counted: {blocks, cascaded_children, dream_links, blobs, derived_skipped, children_outside_scope, derived_children}, confirm_blocks}`. The real run sends `confirm_blocks` set to the dry run's `counted.blocks`: the purge counts again and deletes only when the number is unchanged (otherwise `409` with the fresh `counted`, nothing deleted), and it never touches a block or blob created after that count (`as_of`): a batch that would take the run past the confirmed number, or reach a child created after `as_of`, rolls back and ends the run with the same `409`. The confirmed run continues when the client disconnects or times out; its result is then in the server log (`manage: scope purged`) and a new dry run shows what is left. A client that waits gets the answer of a long run: the write deadline rolls while the purge works, so the answer is delivered past the server's 120 s write timeout with its status and body unchanged (issue #277). `keepalive: true` also writes one space every 25 s from the start, for a reverse proxy whose read timeout only bytes reset (nginx `proxy_read_timeout`, 60 s by default): the first space commits `200`, a refusal after it is that `200` with `success: false` and the error in the body (leading whitespace is valid JSON), and an answer within the first 25 s keeps its status and body. `ctx manage purge` waits for the answer without the CLI's 120 s timeout. What goes: the matching blocks; the blocks below them through `parent_id` (an issue's comments — `parent_id` cascades, so they count in `blocks` and separately in `cascaded_children`; a child in **another** scope refuses the run with `409`, see `children_outside_scope`, and so does a derivative below a matched block, see `derived_children` — the cascade would take it); every dream link that references one of them; and, only for a purge without any filter, the scope's blobs (a filter describes blocks — a filtered purge keeps the blobs and clears their link to a purged block). Rows that hang on a block by foreign key go or are cleared with it (temporal index, structural links, block grants, cluster membership, the embed-failure memo, the forge sync mapping — a synced project re-imports its issues on the next sync — and the block references of the access and write logs), and a surviving block that a purged block superseded is reconciled as `dream-link-resolve` does. A block carrying a derived `provenance` is never purged and is counted in `derived_skipped`. Context sources, chat sessions, secrets, keys and the scope itself stay. The run answers `dry_run: false`, `counted` and `deleted: {blocks, dream_links, blobs}`; it works in batches of 2 000 matched blocks plus their children, one transaction each (a batch that collides with a dream run — deadlock or serialization failure — is repeated up to three times), so an error after the first batch answers `500` (or the `409` above) with what was already `deleted` — a new dry run shows the rest. Each run that deletes anything writes one audit row before its first delete (`GET /api/audit?entity=scope_purge`, `entity_key` = the scope, `new_value` = filter, counts and `as_of`). REST and CLI only, no MCP tool: `ctx manage purge '' '{"scope":"…","tags":["…"]}'`, then the same with `"confirm_blocks":N`. Operator notes in [operations](operations.md#removing-rows-written-by-mistake-manage-purge). - **Backfill memo release (issue #236):** `embed-backfill-release` (tierTenantAdmin) drops regular embed-backfill failure memos (`context_embed_failures` rows with `migration_id` NULL) so the backfill takes their blocks again — after `embed_backfill.max_tokens` was raised, the embed backend moved to a larger context, or a backend outage ended; without it a parked block came back only through a change of its title or content. `data`: exactly one of `block_id` (a UUID) or `class` (`wire` or `oversize`), optional `limit` (the page size, at most and by default `1000`; a larger value is clamped), and `confirm_memos` together with `as_of`; unknown fields, a second selector, another class, a malformed id, a negative number and a `confirm_memos` without `as_of` (or the reverse) are `400`. A `caller_timeout` memo is never taken, not even by `block_id`: it is no park — the background arm takes such a block at once, and with the arm off the query path retries it after its hold —, and deleting it would hand the block back to the requests' `sync_budget` with its attempts restarted. A tenant-admin reaches the memos of blocks in its own tenant's scopes (a scope or a block granted to the tenant is not its own) — another tenant's block and an unknown one answer the same `counted: 0`; a server-admin reaches every memo; a key without an admin role is `403`. A re-embed migration's memos are never touched. **Without `confirm_memos` the call is a dry run** answering `{action, success, dry_run: true, as_of, counted, confirm_memos, held}` (and `held_until` when `held` is above 0); the real call sends `confirm_memos` and `as_of` of that answer, takes only the memos that were there when the dry run counted (a memo written after `as_of` — a released block that was parked again, a new park — is neither counted nor released, so paging ends), counts them again and releases only when the number is unchanged (otherwise `409` with the fresh `counted` and `confirm_memos`, and the `as_of` the call sent), releases at most `limit` of them — the count and the release decide which memos the reader may release at one instant (one transaction, issue #536), so a hold that ends between the two neither counts nor releases its memo in that call — and answers `{action, success, dry_run: false, as_of, counted, released, remaining, confirm_memos, held}` — `remaining` (and `confirm_memos`, the number to confirm for the next page with the same `as_of`) is what is left of them, including a memo another transaction held at that moment, which the release skips instead of waiting for. Two releases of the same memos at once each count what both may take: one of them releases fewer than it counted and answers a `remaining` the other has already released, and its next page answers `409` with the fresh count. Only memos that keep a block out of the pick (`next_attempt_at` in the future) count. **A server-admin's release deletes the memo; a tenant-admin's keeps it and makes it due**, with its attempts and with the time of the release in `first_seen`, so a block the backend still cannot take is parked again on the same row. A tenant-admin releases such an `oversize` memo again (more than one attempt) only once `embed_backfill.release_hold` × 2^(attempts − 2) has passed since that release, at most `embed_backfill.backoff_cap` (defaults 1 h and 24 h; a cap of 0 sets none; the hold must be above 0, V70); until then it is answered in `held`, with the earliest end in `held_until`. Without the hold a tenant-admin releasing its blocks in a loop while they kept not fitting took one turn of the background arm in every round of the tenants for good, where its way back without the action, an edit per block, costs a write each. The first release of every memo is not held, a `wire` memo is not held (its failure holds the tenant in the arm for `embed_backfill.interval`, and its next failure backs off longer, since the attempts stay), and a server-admin's release and a change of the block's title or content (which deletes the memo) start the count again. For a tenant-admin the count and the page of a class read the tenant's own scopes and their pending blocks, so their cost grows with the tenant's pending blocks, not with other tenants' memos. The next backfill pick of each released block embeds it when it fits now and parks it again after one attempt when it does not. CLI: `ctx admin embed-backfill release --class oversize`, then the same with `--confirm N --as-of T`; `--limit N` is sent as given, so a negative one is answered with the `400` (until issue #536 the CLI left a `--limit` of 0 or below out of the request and the server paged by its maximum). Operator notes in [operations](operations.md#embedding-backend-tuning-cpu-llamacpp), paragraph "Backfill failure memo". diff --git a/docs/multi-tenancy.md b/docs/multi-tenancy.md index 644a6ec7e..38c3b4f1d 100644 --- a/docs/multi-tenancy.md +++ b/docs/multi-tenancy.md @@ -70,7 +70,7 @@ Since D-W6c ONE confirm sequence serves every surface: `confirm_core.go` holds t A request can narrow its key to scopes it names, for that request alone: `X-Context-Read-Scopes` (1 to 8 scopes the key reads) and optionally `X-Context-Write-Scope` (one of them, which the key may write). The Auth middleware decides it before any handler runs (`handler.narrowAuth`) and hands the handlers a copy of the key's `AuthResult` in which `read_scopes` is the named set in header order, the server-admin tier is off and the tenant role is `member`; `AuthResult.Narrowed` carries the narrowing. Three places read it: `writableBlockScopes` (the request writes its write scope and nothing else), `resolveWriteScope` (a write without a scope goes to the write scope, and without one is refused `scope_denied`) and `resolveGrants` (no block grants). Everything else stays the key's — its `home_scope` above all, which the backend chain, the quota, the settings overlay and the archive read hang on, so a narrowing that names a granted scope first does not move the request into the granting tenant. The request key that `store.WithRequestKey` hands every write (issue #555) is the unnarrowed key's: a narrowing shrinks what the request may do, never what the write recheck holds the key to. -The routes a narrowed request may take are a closed list — `POST /api/query`, `POST /api/search`, `POST /api/store`, `GET /api/whoami`, `POST /api/manage` with the actions `get` and `type-list` —, compared by method and exact path; everything else (`/mcp`, the batch and blob writes, `recent`, the session surface) answers `403 scope_narrowing_route`. A request without the headers runs as before. Whoami reports the narrowing (`narrowed`, and `read_scopes`, `write_scopes`, `admin`, `role` as the request runs with them); every answer of an accepted narrowing echoes it in `X-Context-Narrowed`. The wire rules and refusals: [api](api.md#scope-narrowing-per-request). +The routes a narrowed request may take are a closed list — `POST /api/query`, `POST /api/search`, `POST /api/store`, `GET /api/whoami`, `POST /api/manage` with the actions `get` (one `id`, or up to 16 `ids` in one request) and `type-list` —, compared by method and exact path; everything else (`/mcp`, the batch and blob writes, `recent`, the session surface) answers `403 scope_narrowing_route`. A request without the headers runs as before. Whoami reports the narrowing (`narrowed`, and `read_scopes`, `write_scopes`, `admin`, `role` as the request runs with them); every answer of an accepted narrowing echoes it in `X-Context-Narrowed`. The wire rules and refusals: [api](api.md#scope-narrowing-per-request). What it is for: a client that serves several groups of people with one server names the scopes of the group it serves on every request and checks the echo, so each group reads and writes exactly its scopes, whatever else the key could read. diff --git a/go/cmd/ctxd/manage_get_ids_c4_integration_test.go b/go/cmd/ctxd/manage_get_ids_c4_integration_test.go index 22384951f..e0ea52e10 100644 --- a/go/cmd/ctxd/manage_get_ids_c4_integration_test.go +++ b/go/cmd/ctxd/manage_get_ids_c4_integration_test.go @@ -1,4 +1,4 @@ -//go:build integration && s1red_c4 +//go:build integration // Achse 02, cluster C-4 (design2/02-ctx-checkpoint.md §3.5 C-4, §7.3): // POST /api/manage {"action":"get","ids":[…]} with 1 to 16 ids answers the @@ -35,6 +35,9 @@ import ( "strings" "testing" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/GottZ/ctx/internal/backends" "github.com/GottZ/ctx/internal/blocktype" "github.com/GottZ/ctx/internal/config" @@ -63,7 +66,9 @@ type c4Resp struct { // a single block), private (not granted), shared, work (two), default:k. type c4World struct { router http.Handler + pool *pgxpool.Pool // the pool the router runs on (traced when asked) w string + kw string // home default:k, the writer of block k blocks map[string]string } @@ -108,9 +113,29 @@ func (r c4Resp) must(t *testing.T, what string) c4Resp { } func c4Setup(t *testing.T) *c4World { + t.Helper() + return c4SetupTraced(t, nil) +} + +// c4SetupTraced is c4Setup on a pool whose connections report every +// statement to tracer (nil: the plain pool). +func c4SetupTraced(t *testing.T, tracer pgx.QueryTracer) *c4World { t.Helper() pool := testdb.SetupTestDB(t) ctx, cancel := context.WithCancel(context.Background()) + if tracer != nil { + cfg := pool.Config() + cfg.ConnConfig.Tracer = tracer + traced, err := pgxpool.NewWithConfig(context.Background(), cfg) + if err != nil { + t.Fatalf("traced pool: %v", err) + } + t.Cleanup(func() { + _ = store.SettleBlockReads(context.Background(), traced) + traced.Close() + }) + pool = traced + } t.Cleanup(cancel) applyEnv(t, map[string]string{}) cc, issues := loadFromEnv() @@ -127,7 +152,7 @@ func c4Setup(t *testing.T) *c4World { if created, _, err := store.BootstrapAdminKey(ctx, pool, c4AdminKey, "c4-admin"); err != nil || !created { t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) } - c := &c4World{router: NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d), blocks: map[string]string{}} + c := &c4World{router: NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d), pool: pool, blocks: map[string]string{}} c.do(t, c4AdminKey, nil, map[string]any{"action": "scope-create", "data": map[string]any{"name": "k"}}).must(t, "scope-create k") mint := func(data map[string]any) string { @@ -137,6 +162,7 @@ func c4Setup(t *testing.T) *c4World { } c.w = mint(map[string]any{"label": "c4-w", "home_scope": "work", "allowed_scopes": []string{"shared", "default:k"}}) kw := mint(map[string]any{"label": "c4-kw", "home_scope": "default:k"}) + c.kw = kw put := func(name, key, scope string) { body := map[string]any{"category": "learnings", "title": "c4 " + name, "content": "c4 " + name + " content"} if scope != "" { diff --git a/go/cmd/ctxd/manage_get_ids_c4_more_integration_test.go b/go/cmd/ctxd/manage_get_ids_c4_more_integration_test.go new file mode 100644 index 000000000..a77129d5a --- /dev/null +++ b/go/cmd/ctxd/manage_get_ids_c4_more_integration_test.go @@ -0,0 +1,334 @@ +//go:build integration + +// Achse 02, cluster C-4, the probes beyond the S1 tests +// (manage_get_ids_c4_integration_test.go): refusals before any lookup, the +// entry of a found block is byte for byte the block of a single get, prefixes +// and misses, no existence oracle in the entries or in the read record, and +// one statement reads every block of the request. +// +// go test -tags=integration -p 1 -count=1 -run '^TestC4' ./cmd/ctxd/ +package main + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "slices" + "sort" + "strings" + "sync" + "testing" + + "github.com/jackc/pgx/v5" + + "github.com/GottZ/ctx/internal/handler" + "github.com/GottZ/ctx/internal/store" +) + +// c4Raw decodes an answer into its raw parts. +type c4Raw struct { + Block json.RawMessage `json:"block"` + Blocks []json.RawMessage `json:"blocks"` + Code string `json:"code"` +} + +func c4RawOf(t *testing.T, r c4Resp) c4Raw { + t.Helper() + var out c4Raw + if err := json.Unmarshal([]byte(r.raw), &out); err != nil { + t.Fatalf("decode %s: %v", r.raw, err) + } + return out +} + +// c4Reads is the read record of manage get: block id → rows, after every +// queued record has been written. +func (c *c4World) c4Reads(t *testing.T) map[string]int { + t.Helper() + ctx := context.Background() + if err := store.SettleBlockReads(ctx, c.pool); err != nil { + t.Fatal(err) + } + rows, err := c.pool.Query(ctx, `SELECT block_id::text FROM context_access_log WHERE action = $1`, store.ActionManageGet) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + out := map[string]int{} + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + t.Fatal(err) + } + out[id]++ + } + return out +} + +// TestC4GetIdsRefusesBeforeAnyLookup: a malformed get with ids is a 400 with +// code invalid_body that books nothing; ids sent as null is no list, and the +// get reads its id exactly as without the key. +func TestC4GetIdsRefusesBeforeAnyLookup(t *testing.T) { + c := c4Setup(t) + w1 := c.blocks["work1"] + for _, tc := range []struct { + name string + body map[string]any + want string + }{ + {"id beside ids", map[string]any{"action": "get", "id": w1, "ids": []string{w1}}, "exclude each other"}, + {"empty list", map[string]any{"action": "get", "ids": []string{}}, "1 to 16"}, + {"a string", map[string]any{"action": "get", "ids": w1}, "list of block ids"}, + {"a number in the list", map[string]any{"action": "get", "ids": []any{w1, 7}}, "list of block ids"}, + {"include_archived", map[string]any{"action": "get", "ids": []string{w1}, "include_archived": true}, "include_archived"}, + {"unknown field", map[string]any{"action": "get", "ids": []string{w1}, "fields": []string{"nope"}}, "nope"}, + {"window without content", map[string]any{"action": "get", "ids": []string{w1}, "fields": []string{"title"}, "content_limit": 3}, "content"}, + } { + r := c.do(t, c.w, nil, tc.body) + if r.status != http.StatusBadRequest || r.body["success"] != false || r.body["code"] != "invalid_body" || !strings.Contains(r.raw, tc.want) { + t.Errorf("%s: HTTP %d %s, want 400 invalid_body naming %q", tc.name, r.status, r.raw, tc.want) + } + } + if got := c.c4Reads(t); len(got) != 0 { + t.Errorf("refusals booked reads %v, want none", got) + } + + plain := c.do(t, c.w, nil, map[string]any{"action": "get", "id": w1}) + withNull := c.do(t, c.w, nil, map[string]any{"action": "get", "id": w1, "ids": nil}) + if plain.status != http.StatusOK || withNull.status != plain.status || withNull.raw != plain.raw { + t.Errorf("ids null beside id: HTTP %d %s, want the single get's bytes HTTP %d %s", withNull.status, withNull.raw, plain.status, plain.raw) + } + if r := c.do(t, c.w, nil, map[string]any{"action": "get", "ids": nil}); r.status != http.StatusBadRequest || !strings.Contains(r.raw, "Missing required field: id") { + t.Errorf("ids null alone: HTTP %d %s, want the single get's missing-id refusal", r.status, r.raw) + } +} + +// TestC4GetIdsEntryIsTheSingleGetsBlock: a found entry is byte for byte the +// "block" a single get answers for the id — with the whole block, and with +// fields and a content window, which apply to every entry. The guard's +// guard_matched_id is redacted when it names a block the reader does not see +// (work1 → private) and kept when it does (work2 → work1), as on every raw +// read path; the guard writes the key, a client cannot, so it is set here +// directly. +func TestC4GetIdsEntryIsTheSingleGetsBlock(t *testing.T) { + c := c4Setup(t) + for name, matched := range map[string]string{"work1": "private", "work2": "work1"} { + if _, err := c.pool.Exec(context.Background(), + `UPDATE context_blocks SET metadata = coalesce(metadata, '{}'::jsonb) || jsonb_build_object('guard_matched_id', $2::text) WHERE id = $1`, + c.blocks[name], c.blocks[matched]); err != nil { + t.Fatal(err) + } + } + for _, opts := range []map[string]any{ + {}, + {"fields": []string{"title", "content"}, "content_offset": 1, "content_limit": 4}, + {"fields": []string{"scope", "metadata"}}, + } { + multi := map[string]any{"action": "get", "ids": []string{c.blocks["work1"], c4Missing, c.blocks["granted"], c.blocks["work2"]}} + for k, v := range opts { + multi[k] = v + } + m := c4RawOf(t, c.do(t, c.w, nil, multi).must(t, "multi get")) + if len(m.Blocks) != 4 { + t.Fatalf("opts %v: %d entries, want 4", opts, len(m.Blocks)) + } + if fields, named := opts["fields"].([]string); !named || slices.Contains(fields, "metadata") { + if strings.Contains(string(m.Blocks[0]), "guard_matched_id") || !strings.Contains(string(m.Blocks[3]), `"guard_matched_id":"`+c.blocks["work1"]+`"`) { + t.Errorf("opts %v: guard_matched_id of work1 %s (names private: want redacted), of work2 %s (names work1: want kept)", opts, m.Blocks[0], m.Blocks[3]) + } + } + for i, name := range map[int]string{0: "work1", 2: "granted", 3: "work2"} { + single := map[string]any{"action": "get", "id": c.blocks[name]} + for k, v := range opts { + single[k] = v + } + s := c4RawOf(t, c.do(t, c.w, nil, single).must(t, "single get")) + if !bytes.Equal(m.Blocks[i], s.Block) { + t.Errorf("opts %v: entry %d = %s, want the single get's block %s", opts, i, m.Blocks[i], s.Block) + } + } + } +} + +// TestC4GetIdsPrefixesAndMisses: each id resolves as a single get's id does — +// a unique prefix and an id in upper case find the block, a short prefix is +// an invalid_id entry, a prefix of two visible blocks an ambiguous_id entry +// with its matches; text of an id's shape that is no uuid, an archived block, +// a block the key may not read and an id no block has answer the same +// not_found entry. An id asked twice is answered twice and recorded once. +func TestC4GetIdsPrefixesAndMisses(t *testing.T) { + c := c4Setup(t) + w1, w2 := c.blocks["work1"], c.blocks["work2"] + c.do(t, c.kw, nil, map[string]any{"action": "delete", "id": c.blocks["k"]}).must(t, "archive k") + bad := "zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz" + asked := []string{w1[:35], strings.ToUpper(w1), "abc", bad, c.blocks["k"], c.blocks["private"], c4Missing, w1} + r := c.do(t, c.w, nil, map[string]any{"action": "get", "ids": asked}).must(t, "multi get") + e := c4Entries(t, r) + if len(e) != len(asked) { + t.Fatalf("%d entries, want %d", len(e), len(asked)) + } + for _, i := range []int{0, 1, 7} { + if e[i].id != w1 || e[i].code != "" { + t.Errorf("entry %d (%s): %+v, want block %s", i, asked[i], e[i], w1) + } + } + if e[2].id != "abc" || e[2].code != "invalid_id" || !strings.Contains(e[2].err, "at least") { + t.Errorf("short prefix: %+v, want an invalid_id entry", e[2]) + } + for _, i := range []int{3, 4, 5, 6} { + if e[i].id != asked[i] || e[i].code != "not_found" || e[i].err != e[6].err { + t.Errorf("entry %d (%s): %+v, want the not_found entry of a missing id %+v", i, asked[i], e[i], e[6]) + } + } + if got := c.c4Reads(t); len(got) != 1 || got[w1] != 1 { + t.Errorf("read record %v, want one row for %s", got, w1) + } + + // Two blocks stored moments apart share the time prefix of their UUIDv7. + common := 0 + for common < len(w1) && w1[common] == w2[common] { + common++ + } + if common < store.MinIDPrefixLen { + t.Skipf("work1 %s and work2 %s share %d characters, fewer than a prefix needs", w1, w2, common) + } + r = c.do(t, c.w, nil, map[string]any{"action": "get", "ids": []string{w1[:common], w2}}).must(t, "ambiguous") + var amb struct { + Blocks []struct { + ID string `json:"id"` + Code string `json:"code"` + Matches []struct { + ID string `json:"id"` + } `json:"matches"` + } `json:"blocks"` + } + if err := json.Unmarshal([]byte(r.raw), &amb); err != nil || len(amb.Blocks) != 2 { + t.Fatalf("ambiguous answer %s: %v", r.raw, err) + } + var got []string + for _, m := range amb.Blocks[0].Matches { + got = append(got, m.ID) + } + sort.Strings(got) + // The matches are every live block w sees whose id starts with the + // prefix — work1 and work2 at least; shared and granted when they were + // stored within the same time prefix. Never private (w does not read it) + // nor k (archived above). + var want []string + for _, name := range []string{"work1", "work2", "shared", "granted"} { + if strings.HasPrefix(c.blocks[name], w1[:common]) { + want = append(want, c.blocks[name]) + } + } + sort.Strings(want) + if amb.Blocks[0].Code != "ambiguous_id" || amb.Blocks[0].ID != w1[:common] || strings.Join(got, ",") != strings.Join(want, ",") { + t.Errorf("ambiguous prefix: %s, want an ambiguous_id entry matching %v", r.raw, want) + } + if amb.Blocks[1].ID != w2 || amb.Blocks[1].Code != "" { + t.Errorf("entry after the ambiguous one: %s", r.raw) + } +} + +// TestC4NarrowedMissIsTheMissOfAMissingId: under a narrowing, a block of a +// scope the key reads but the narrowing does not name and a granted block +// answer exactly the entry of an id no block has, and only the delivered +// block is recorded. +func TestC4NarrowedMissIsTheMissOfAMissingId(t *testing.T) { + c := c4Setup(t) + h := http.Header{} + h.Set(handler.HeaderReadScopes, "work") + asked := []string{c.blocks["k"], c.blocks["granted"], c4Missing, c.blocks["work1"], c.blocks["k"][:35], c.blocks["work1"][:35]} + e := c4Entries(t, c.do(t, c.w, h, map[string]any{"action": "get", "ids": asked}).must(t, "narrowed")) + if len(e) != len(asked) { + t.Fatalf("%d entries, want %d", len(e), len(asked)) + } + for _, i := range []int{0, 1, 2, 4} { + if e[i].id != asked[i] || e[i].code != e[2].code || e[i].err != e[2].err || e[i].code != "not_found" { + t.Errorf("entry %d %+v, want the missing id's entry %+v", i, e[i], e[2]) + } + } + for _, i := range []int{3, 5} { + if e[i].id != c.blocks["work1"] || e[i].code != "" { + t.Errorf("entry %d (%s) %+v, want block work1", i, asked[i], e[i]) + } + } + if got := c.c4Reads(t); len(got) != 1 || got[c.blocks["work1"]] != 1 { + t.Errorf("read record %v, want one row for work1 only", got) + } +} + +// c4Tracer records the SQL text of every statement of the router's pool. +type c4Tracer struct { + mu sync.Mutex + sql []string +} + +func (tr *c4Tracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context { + tr.mu.Lock() + tr.sql = append(tr.sql, d.SQL) + tr.mu.Unlock() + return ctx +} + +func (tr *c4Tracer) TraceQueryEnd(context.Context, *pgx.Conn, pgx.TraceQueryEndData) {} + +// take returns the statements since the last call that read blocks and that +// read the block-grant set (the read record's insert, which joins blocks, is +// not a read of the request). +func (tr *c4Tracer) take() (blockReads, grantReads []string) { + tr.mu.Lock() + defer tr.mu.Unlock() + for _, s := range tr.sql { + switch { + case strings.HasPrefix(strings.TrimSpace(s), "INSERT"): + case strings.Contains(s, "FROM context_blocks"): + blockReads = append(blockReads, s) + case strings.Contains(s, "FROM context_block_grants"): + grantReads = append(grantReads, s) + } + } + tr.sql = nil + return blockReads, grantReads +} + +// TestC4GetIdsReadsAllBlocksWithOneStatement: 16 full ids — found, missing, +// foreign and granted — cost one statement that reads blocks, besides the +// block-grant set (none under a narrowing); a single get costs one per id. +func TestC4GetIdsReadsAllBlocksWithOneStatement(t *testing.T) { + tr := &c4Tracer{} + c := c4SetupTraced(t, tr) + ids := []string{c.blocks["work1"], c.blocks["shared"], c.blocks["k"], c.blocks["granted"], c.blocks["private"], c.blocks["work2"]} + for len(ids) < maxIDsForTest { + ids = append(ids, c4Missing) + } + for _, tc := range []struct { + name string + header string + grants int + }{ + {"unnarrowed", "", 1}, + {"narrowed", "work,shared,default:k", 0}, + } { + h := http.Header{} + if tc.header != "" { + h.Set(handler.HeaderReadScopes, tc.header) + } + _ = store.SettleBlockReads(context.Background(), c.pool) + tr.take() + c.do(t, c.w, h, map[string]any{"action": "get", "ids": ids}).must(t, tc.name) + blocks, grants := tr.take() + if len(blocks) != 1 || len(grants) != tc.grants { + t.Errorf("%s: %d block reads, %d grant reads, want 1 and %d:\n%s", tc.name, len(blocks), len(grants), tc.grants, strings.Join(blocks, "\n---\n")) + } + } + c.do(t, c.w, nil, map[string]any{"action": "get", "id": c.blocks["work1"]}).must(t, "single") + c.do(t, c.w, nil, map[string]any{"action": "get", "id": c.blocks["work2"]}).must(t, "single") + if blocks, _ := tr.take(); len(blocks) != 2 { + t.Errorf("two single gets: %d block reads, want 2 (control)", len(blocks)) + } +} + +// maxIDsForTest is the bound of the API (16), written out: the test pins the +// wire, not the constant. +const maxIDsForTest = 16 diff --git a/go/internal/handler/context_manage.go b/go/internal/handler/context_manage.go index c6b3a0598..f0f2d11c5 100644 --- a/go/internal/handler/context_manage.go +++ b/go/internal/handler/context_manage.go @@ -206,6 +206,9 @@ type manageRequest struct { Fields json.RawMessage `json:"fields"` ContentOffset json.RawMessage `json:"content_offset"` ContentLimit json.RawMessage `json:"content_limit"` + // IDs (Achse 02 C-4) is get's list of block ids, decoded by get alone + // (decodeGetIDs) — raw for the reason After is. + IDs json.RawMessage `json:"ids"` } // handleOverviewRebuildStart kicks the cluster-overview rebuild ahead of its @@ -436,6 +439,12 @@ func (h *ManageHandler) handleGet(w http.ResponseWriter, r *http.Request, ar *au ctx := r.Context() reqID := RequestIDFromContext(ctx) + // Achse 02 C-4: a body that carries ids reads several blocks (get_ids.go); + // without the key, or with it null, get reads one id exactly as before. + if ids, given, err := decodeGetIDs(req.IDs); given { + h.handleGetIDs(w, r, ar, req, ids, err) + return + } if req.ID == "" { writeJSON(w, http.StatusBadRequest, map[string]any{ "success": false, "error": "Missing required field: id", diff --git a/go/internal/handler/get_ids.go b/go/internal/handler/get_ids.go new file mode 100644 index 000000000..8418ee071 --- /dev/null +++ b/go/internal/handler/get_ids.go @@ -0,0 +1,225 @@ +// Achse 02 C-4 (design2/02-ctx-checkpoint.md §3.5): manage `get` with `ids` +// answers several blocks by id in one request — a hook that renders up to 16 +// blocks makes one request instead of one per id. Each id resolves as the id +// of a single get does (store.ResolveBlockID over the read scopes and the +// block grants, so a narrowed request reads its named scopes and no grant); +// the blocks of all full ids are read with one statement +// (store.GetBlocksOmitting). The answer lists one entry per asked id, in the +// order asked: the block as a single get answers it under "block", or a miss +// entry {id, code, error}. An id the caller may not see answers exactly like +// an id no block has. A body without `ids` never reaches this file. +package handler + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/auth" + "github.com/GottZ/ctx/internal/store" +) + +// maxGetIDs is the most ids one get takes: the most base blocks the plugin +// ctx_checkpoint renders for one access group (design A02-L2), and a bound on +// the rows one request reads (each up to 50 KB of content). +const maxGetIDs = 16 + +// The codes of a miss entry. A miss never fails the whole request. +const ( + getIDNotFound = "not_found" // no block the caller sees has this id + getIDAmbiguous = "ambiguous_id" // a prefix of more than one visible block; matches lists them + getIDInvalid = "invalid_id" // a prefix shorter than store.MinIDPrefixLen +) + +const ( + getIDsListMsg = "ids must be a list of block ids" + getIDsWithIDMsg = "id and ids exclude each other: send one block id in id, or a list in ids" + getIDsArchivedMsg = "include_archived reads one block by its full id: send it in id, not in ids" +) + +// getIDsCountMsg names the bound, so a caller that sent too many knows it. +var getIDsCountMsg = fmt.Sprintf("ids takes 1 to %d block ids", maxGetIDs) + +// getIDMiss is the entry of an asked id that names no block the caller sees. +// id is the id as asked; error is the single get's text for the same case. +type getIDMiss struct { + ID string `json:"id"` + Code string `json:"code"` + Error string `json:"error"` + Matches []store.BlockMeta `json:"matches,omitempty"` +} + +func getIDNotFoundEntry(asked string) *getIDMiss { + return &getIDMiss{ID: asked, Code: getIDNotFound, Error: "Block not found"} +} + +// decodeGetIDs reads the ids of a manage get. given is false when the body +// carries no ids or carries them as null — like the other optional keys of +// get, a null counts as not sent; a value that is not a list of strings is +// given and an error, a null element included (decoded into a string it would +// pass as ""). +func decodeGetIDs(raw json.RawMessage) (ids []string, given bool, err error) { + if len(raw) == 0 { + return nil, false, nil + } + var elems []*string + if err := json.Unmarshal(raw, &elems); err != nil { + return nil, true, errors.New(getIDsListMsg) + } + if elems == nil { + return nil, false, nil + } + ids = make([]string, len(elems)) + for i, e := range elems { + if e == nil { + return nil, true, errors.New(getIDsListMsg) + } + ids[i] = *e + } + return ids, true, nil +} + +// getIDsRefusal is the text of a 400 that refuses a get with ids before any +// lookup — it depends on the arguments only, never on what is stored — or "" +// when the request is well formed. +func getIDsRefusal(req manageRequest, ids []string, decodeErr error) string { + switch { + case decodeErr != nil: + return decodeErr.Error() + case req.ID != "": + return getIDsWithIDMsg + case len(ids) < 1 || len(ids) > maxGetIDs: + return getIDsCountMsg + case req.IncludeArchived: + return getIDsArchivedMsg + } + return "" +} + +// getIDSlot is what one asked id resolved to: the block id to read (lower +// case), or the miss entry it answers. +type getIDSlot struct { + id string + miss *getIDMiss +} + +// resolveGetIDs resolves each asked id as a single get does. A full id costs +// no statement (ResolveBlockID returns it as it is); a prefix costs the +// statement a single get makes for it. An error fails the request. +func resolveGetIDs(ctx context.Context, pool *pgxpool.Pool, ids, readScopes, grants []string) ([]getIDSlot, error) { + slots := make([]getIDSlot, len(ids)) + for i, asked := range ids { + id, matches, err := store.ResolveBlockID(ctx, pool, asked, readScopes, grants) + switch { + case errors.Is(err, store.ErrAmbiguousID): + slots[i].miss = &getIDMiss{ID: asked, Code: getIDAmbiguous, Error: "Ambiguous id prefix", Matches: matches} + case errors.Is(err, store.ErrIDPrefixTooShort): + slots[i].miss = &getIDMiss{ID: asked, Code: getIDInvalid, Error: err.Error()} + case err != nil: + return nil, err + case id == "": + slots[i].miss = getIDNotFoundEntry(asked) + default: + slots[i].id = strings.ToLower(id) + } + } + return slots, nil +} + +// getIDsAnswer lays the entries out in the order asked and names the blocks +// it delivers, each once, for the read record. +func getIDsAnswer(ids []string, slots []getIDSlot, found map[string]*store.Block, opts *getOptions) ([]any, []string, error) { + entries := make([]any, len(ids)) + var delivered []string + seen := make(map[string]bool, len(found)) + for i, slot := range slots { + if slot.miss != nil { + entries[i] = slot.miss + continue + } + block := found[slot.id] + if block == nil { + entries[i] = getIDNotFoundEntry(ids[i]) + continue + } + answer, err := opts.answer(block) + if err != nil { + return nil, nil, err + } + entries[i] = answer + if !seen[block.ID] { + seen[block.ID] = true + delivered = append(delivered, block.ID) + } + } + return entries, delivered, nil +} + +// handleGetIDs answers manage get with ids: {action, success, blocks}, one +// entry per asked id in the order asked. Statements: the block-grant set +// (none under a narrowing), one per id prefix, and one read for every block +// of the request — never one per full id. +func (h *ManageHandler) handleGetIDs(w http.ResponseWriter, r *http.Request, ar *auth.AuthResult, req manageRequest, ids []string, decodeErr error) { + ctx := r.Context() + reqID := RequestIDFromContext(ctx) + + if msg := getIDsRefusal(req, ids, decodeErr); msg != "" { + writeJSONReject(w, classInvalidBody.reject(msg)) + return + } + // #407: fields and the content window apply to every block of the answer. + opts, err := decodeGetOptions(req) + if err != nil { + writeJSONReject(w, classInvalidBody.reject(err.Error())) + return + } + grants, err := resolveGrants(ctx, h.pool, ar) + if errors.Is(err, store.ErrTooManyBlockGrants) { // T04-20: refuse, never read scope-only + writeJSON(w, http.StatusInternalServerError, map[string]any{ + "success": false, "error": tooManyGrantsMsg, + }) + return + } + slots, err := resolveGetIDs(ctx, h.pool, ids, ar.ReadScopes, grants) + if err != nil { + getIDsFailed(ctx, w, "manage: get ids resolve error", err, reqID) + return + } + read := make([]string, 0, len(slots)) + for _, slot := range slots { + if slot.id != "" { + read = append(read, slot.id) + } + } + found, err := store.GetBlocksOmitting(ctx, h.pool, h.typeSnapshot(ctx), read, ar.ReadScopes, grants, opts.omit()) + if err != nil { + getIDsFailed(ctx, w, "manage: get ids read error", err, reqID) + return + } + entries, delivered, err := getIDsAnswer(ids, slots, found, opts) + if err != nil { + getIDsFailed(ctx, w, "manage: get ids answer error", err, reqID) + return + } + // G9 (design/07 §5.5): only delivered blocks are recorded — a miss leaves + // no trace in the access log, as on the single get. + store.RecordBlockReads(h.pool, ar.ApiKeyID, store.ActionManageGet, delivered) + writeJSON(w, http.StatusOK, map[string]any{ + "action": "get", + "success": true, + "blocks": entries, + }) +} + +// getIDsFailed answers a server fault of a get with ids as the single get does. +func getIDsFailed(ctx context.Context, w http.ResponseWriter, msg string, err error, reqID string) { + logRequestError(ctx, msg, "error", err, "request_id", reqID) + writeJSON(w, http.StatusInternalServerError, map[string]any{ + "success": false, "error": "Internal server error", + }) +} diff --git a/go/internal/handler/get_ids_test.go b/go/internal/handler/get_ids_test.go new file mode 100644 index 000000000..8ce4ae00f --- /dev/null +++ b/go/internal/handler/get_ids_test.go @@ -0,0 +1,61 @@ +package handler + +import ( + "encoding/json" + "errors" + "strings" + "testing" +) + +// TestDecodeGetIDs: ids absent or null is no list (get reads its id as +// before); an empty list is a list (and refused for its count); anything but a +// list of strings is an error. +func TestDecodeGetIDs(t *testing.T) { + for _, tc := range []struct { + raw string + given bool + n int + err bool + }{ + {"", false, 0, false}, + {"null", false, 0, false}, + {"[]", true, 0, false}, + {`["a","b"]`, true, 2, false}, + {`"a"`, true, 0, true}, + {`[1]`, true, 0, true}, + {`{"a":1}`, true, 0, true}, + {`[null]`, true, 0, true}, + {`["a",null]`, true, 0, true}, + } { + ids, given, err := decodeGetIDs(json.RawMessage(tc.raw)) + if given != tc.given || len(ids) != tc.n || (err != nil) != tc.err { + t.Errorf("decodeGetIDs(%s) = %v, %v, %v; want %d ids, given %v, error %v", tc.raw, ids, given, err, tc.n, tc.given, tc.err) + } + } +} + +// TestGetIDsRefusal: the bound is 1 to 16 ids; id beside ids, include_archived +// and a list that did not decode are refused; a well-formed request is not. +func TestGetIDsRefusal(t *testing.T) { + n := func(k int) []string { return make([]string, k) } + for _, tc := range []struct { + name string + req manageRequest + ids []string + err error + want string + }{ + {"one", manageRequest{}, n(1), nil, ""}, + {"sixteen", manageRequest{}, n(16), nil, ""}, + {"none", manageRequest{}, n(0), nil, "1 to 16"}, + {"seventeen", manageRequest{}, n(17), nil, "1 to 16"}, + {"id beside ids", manageRequest{ID: "x"}, n(1), nil, "exclude"}, + {"include_archived", manageRequest{IncludeArchived: true}, n(1), nil, "include_archived"}, + {"not a list", manageRequest{}, nil, errors.New(getIDsListMsg), "list"}, + } { + got := getIDsRefusal(tc.req, tc.ids, tc.err) + if (tc.want == "") != (got == "") || !strings.Contains(got, tc.want) { + t.Errorf("%s: refusal %q, want %q", tc.name, got, tc.want) + } + } +} diff --git a/go/internal/store/blocks.go b/go/internal/store/blocks.go index 59f8d4d0a..44fb6228d 100644 --- a/go/internal/store/blocks.go +++ b/go/internal/store/blocks.go @@ -1620,10 +1620,17 @@ func GetBlockOmitting(ctx context.Context, pool *pgxpool.Pool, set *blocktype.Se grantedBlockIDs = []string{} // deterministic '{}'::uuid[], never NULL } return readBlockByID(ctx, pool, set, omit, "store: get block", - `WHERE id = $1 AND NOT is_archived AND (scope = ANY($2::text[]) OR id = ANY($3::uuid[]))`, + `WHERE id = $1 AND `+liveVisibleSQL, id, readScopes, grantedBlockIDs) } +// liveVisibleSQL is the visibility of the by-id reads of live blocks +// (GetBlockOmitting, GetBlocksOmitting): not archived, and in one of the read +// scopes bound as $2 or among the granted block ids bound as $3. The +// parentheses keep NOT is_archived outside the scope/grant OR — a granted +// archived block must not surface. +const liveVisibleSQL = `NOT is_archived AND (scope = ANY($2::text[]) OR id = ANY($3::uuid[]))` + // GetArchivedBlock reads one ARCHIVED block by its full id (issue #201: the // opt-in `include_archived` of MCP get and manage get — a citing block names // the id, and a reader must be able to check what the cited block said). @@ -1656,30 +1663,48 @@ func GetArchivedBlock(ctx context.Context, pool *pgxpool.Pool, set *blocktype.Se // call sites, never user input. omit swaps an omitted column for a constant of // its type, so the scan stays one and the statement takes one of four shapes. func readBlockByID(ctx context.Context, pool *pgxpool.Pool, set *blocktype.Set, omit BlockReadOmit, op, where string, args ...any) (*Block, error) { - content, metadata := "content", guardRedactedMetadataSQL("$2") - if omit.Content { - content = "''::text AS content" - } - if omit.Metadata { - metadata = "NULL::jsonb AS metadata" - } - b := &Block{} - err := pool.QueryRow(ctx, - `SELECT id, category, tags, title, `+content+`, `+metadata+`, scope, sensitivity, sensitivity_source, type_name, lifecycle_state, type_source, created_at, updated_at, - `+untrustedOriginCol+` + b, err := scanBlockByID(pool.QueryRow(ctx, + `SELECT `+blockByIDColumns(omit)+` FROM context_blocks `+where+` LIMIT 1`, args..., - ).Scan(&b.ID, &b.Category, &b.Tags, &b.Title, &b.Content, &b.Metadata, &b.Scope, - &b.Sensitivity, &b.SensitivitySource, &b.TypeName, &b.LifecycleState, &b.TypeSource, &b.CreatedAt, &b.UpdatedAt, - &b.UntrustedOrigin) + ), set) if errors.Is(err, pgx.ErrNoRows) { return nil, nil } if err != nil { return nil, fmt.Errorf("%s: %w", op, err) } + return b, nil +} + +// blockByIDColumns is the select list of every by-id block read +// (readBlockByID and GetBlocksOmitting), which scanBlockByID scans: one list, +// so a block read by id has one shape whichever read found it. The metadata +// redaction reads the caller's read scopes from $2 — each statement binds them +// there. omit swaps an omitted column for a constant of its type. +func blockByIDColumns(omit BlockReadOmit) string { + content, metadata := "content", guardRedactedMetadataSQL("$2") + if omit.Content { + content = "''::text AS content" + } + if omit.Metadata { + metadata = "NULL::jsonb AS metadata" + } + return `id, category, tags, title, ` + content + `, ` + metadata + `, scope, sensitivity, sensitivity_source, type_name, lifecycle_state, type_source, created_at, updated_at, + ` + untrustedOriginCol +} + +// scanBlockByID scans one row of blockByIDColumns and fills the V-11 framing +// from the caller's registry snapshot. +func scanBlockByID(row pgx.Row, set *blocktype.Set) (*Block, error) { + b := &Block{} + if err := row.Scan(&b.ID, &b.Category, &b.Tags, &b.Title, &b.Content, &b.Metadata, &b.Scope, + &b.Sensitivity, &b.SensitivitySource, &b.TypeName, &b.LifecycleState, &b.TypeSource, &b.CreatedAt, &b.UpdatedAt, + &b.UntrustedOrigin); err != nil { + return nil, err + } b.Untrusted = untrustedOf(set, b.TypeName) // V-11 return b, nil } diff --git a/go/internal/store/blocks_get_many.go b/go/internal/store/blocks_get_many.go new file mode 100644 index 000000000..05973f2de --- /dev/null +++ b/go/internal/store/blocks_get_many.go @@ -0,0 +1,64 @@ +// Achse 02 C-4: the by-id read of several blocks in one statement — the read +// behind manage `get` with `ids`, which a hook of the Hermes plugin +// ctx_checkpoint makes with up to 16 block ids where it would otherwise make +// one request per id. +package store + +import ( + "context" + "fmt" + "strings" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/blocktype" +) + +// GetBlocksOmitting reads the blocks among ids that GetBlockOmitting answers — +// the same visibility (live, and in one of readScopes or among the granted +// block ids), the same columns, metadata redaction and framing — with one +// statement for the whole list: a primary-key probe per id. It answers the +// found blocks by their id (lower case, as the database writes a uuid); an +// unknown id, a block the caller does not see and an archived block are all +// simply absent, so a caller cannot tell them apart. ids are full block ids as +// ResolveBlockID answers them; any other text names no block and is left out +// before the statement, and a list without a block id issues no statement at +// all. The caller bounds the list (manage get: 16). +func GetBlocksOmitting(ctx context.Context, pool *pgxpool.Pool, set *blocktype.Set, ids []string, readScopes []string, grantedBlockIDs []string, omit BlockReadOmit) (map[string]*Block, error) { + if err := RequireScopes(readScopes); err != nil { // T07 fail-closed (design/01 §5.4) + return nil, err + } + if grantedBlockIDs == nil { + grantedBlockIDs = []string{} // deterministic '{}'::uuid[], never NULL + } + want := make([]string, 0, len(ids)) + for _, id := range ids { + if IsFullUUID(id) && idIsUUIDText(id) { + want = append(want, strings.ToLower(id)) + } + } + found := make(map[string]*Block, len(want)) + if len(want) == 0 { + return found, nil + } + rows, err := pool.Query(ctx, + `SELECT `+blockByIDColumns(omit)+` + FROM context_blocks + WHERE id = ANY($1::uuid[]) AND `+liveVisibleSQL, + want, readScopes, grantedBlockIDs) + if err != nil { + return nil, fmt.Errorf("store: get blocks: %w", err) + } + defer rows.Close() + for rows.Next() { + b, err := scanBlockByID(rows, set) + if err != nil { + return nil, fmt.Errorf("store: get blocks scan: %w", err) + } + found[b.ID] = b + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("store: get blocks rows: %w", err) + } + return found, nil +} diff --git a/go/internal/store/get_blocks_cost_integration_test.go b/go/internal/store/get_blocks_cost_integration_test.go new file mode 100644 index 000000000..50a8dc6c4 --- /dev/null +++ b/go/internal/store/get_blocks_cost_integration_test.go @@ -0,0 +1,131 @@ +//go:build integration + +package store_test + +// Achse 02 C-4 cost pin: GetBlocksOmitting reads 16 ids with one statement +// whose buffers do not grow with the corpus — a primary-key probe per id, at +// 2 000 and at 20 000 blocks in the reader's scope, as a custom and as a +// generic plan, under random_page_cost 1.1 and 4 (testdb.RandomPageCosts). +// The statement is the one the function sends (recorded by a tracer), not a +// copy of it. + +import ( + "context" + "strings" + "sync" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" +) + +type getBlocksTracer struct { + mu sync.Mutex + sql string + args []any +} + +func (tr *getBlocksTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context { + if strings.Contains(d.SQL, "id = ANY($1::uuid[])") { + tr.mu.Lock() + tr.sql, tr.args = d.SQL, d.Args + tr.mu.Unlock() + } + return ctx +} + +func (tr *getBlocksTracer) TraceQueryEnd(context.Context, *pgx.Conn, pgx.TraceQueryEndData) {} + +func costIDs(t *testing.T, pool *pgxpool.Pool, where string, n int) []string { + t.Helper() + rows, err := pool.Query(context.Background(), `SELECT id::text FROM context_blocks WHERE `+where+` ORDER BY title LIMIT $1`, n) + if err != nil { + t.Fatal(err) + } + ids, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil || len(ids) != n { + t.Fatalf("ids %s: %d of %d: %v", where, len(ids), n, err) + } + return ids +} + +func TestGetBlocksOmitting_CostIndependentOfCorpus(t *testing.T) { + if testing.Short() { + t.Skip("integration test") + } + pool := testdb.SetupTestDB(t) + ctx := context.Background() + const small, large = 2000, 20000 + seedCostBlocks(t, pool, "cost-y", 1, 50) + seedCostBlocks(t, pool, "cost-x", 1, small) + + // 16 ids: 8 live blocks of the reader's scope, 3 archived ones, 3 of a + // scope it does not read, 2 that no block has. + ids := costIDs(t, pool, `scope = 'cost-x' AND NOT is_archived`, 8) + ids = append(ids, costIDs(t, pool, `scope = 'cost-x' AND is_archived`, 3)...) + ids = append(ids, costIDs(t, pool, `scope = 'cost-y' AND NOT is_archived`, 3)...) + ids = append(ids, "00000000-0000-7000-8000-0000000000c4", "00000000-0000-7000-8000-0000000000c5") + + tr := &getBlocksTracer{} + cfg := pool.Config() + cfg.ConnConfig.Tracer = tr + traced, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatal(err) + } + defer traced.Close() + found, err := store.GetBlocksOmitting(ctx, traced, nil, ids, []string{"cost-x"}, nil, store.BlockReadOmit{}) + if err != nil || len(found) != 8 { + t.Fatalf("GetBlocksOmitting: %d blocks, %v; want the 8 live blocks of cost-x", len(found), err) + } + if tr.sql == "" || len(tr.args) != 3 { + t.Fatalf("no statement recorded (%q, %d args)", tr.sql, len(tr.args)) + } + args := []any{ids, []string{"cost-x"}, []string{}} + + planners := map[string]*pgxpool.Pool{} + for _, rpc := range testdb.RandomPageCosts { + planners[rpc] = testdb.WithRandomPageCost(t, pool, rpc) + } + measure := func(rpc string, generic bool) testdb.PlanCost { + // One unmeasured run first: the first read after the bulk insert sets + // hint bits, a cost of the write (see statementBuffers). + _ = testdb.ExplainCustom(t, planners[rpc], tr.sql, args...) + if generic { + return testdb.ExplainGeneric(t, planners[rpc], tr.sql, args...) + } + return testdb.ExplainCustom(t, planners[rpc], tr.sql, args...) + } + type key struct { + generic bool + rpc string + } + before := map[key]int64{} + for _, rpc := range testdb.RandomPageCosts { + for _, g := range []bool{false, true} { + pc := measure(rpc, g) + before[key{g, rpc}] = pc.Buffers + if !strings.Contains(pc.Plan, `"Index Name": "context_blocks_pkey"`) { + t.Errorf("generic=%v random_page_cost %s: the plan does not probe the primary key:\n%s", g, rpc, pc.Plan) + } + } + } + seedCostBlocks(t, pool, "cost-x", small+1, large) + for _, rpc := range testdb.RandomPageCosts { + for _, g := range []bool{false, true} { + pc := measure(rpc, g) + k := key{g, rpc} + t.Logf("generic=%-5v random_page_cost=%-3s buffers %d blocks: %d, %d blocks: %d (%s)", g, rpc, small, before[k], large, pc.Buffers, pc) + if pc.Buffers > before[k]+costSlackBuffers { + t.Errorf("generic=%v random_page_cost %s: %d buffers at %d blocks vs %d at %d — the read grows with the corpus", + g, rpc, pc.Buffers, large, before[k], small) + } + if !strings.Contains(pc.Plan, `"Index Name": "context_blocks_pkey"`) { + t.Errorf("generic=%v random_page_cost %s at %d blocks: the plan does not probe the primary key:\n%s", g, rpc, large, pc.Plan) + } + } + } +} From 8e07e8f9761e19685f057f934dd63bfbda9cc8eb Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 04:03:54 +0100 Subject: [PATCH 06/15] =?UTF-8?q?feat(auth):=20keyset-provision=20creates?= =?UTF-8?q?=20the=20scopes=20and=20keys=20of=20a=20set=20in=20one=20transa?= =?UTF-8?q?ction=20under=20the=20tenant=20lock=20=E2=80=94=20member=20keys?= =?UTF-8?q?=20with=20their=20own=20principal,=20replace=5Flabel=20for=20on?= =?UTF-8?q?e=20active=20key=20per=20label?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new manage action, tenant-admin in the caller's own tenant (a server-admin may name data.tenant_id): scope-create and api-key-create for up to 64 scopes and 64 keys at once, all or nothing. store.ProvisionKeyset takes the tenant row lock first and reads status, max_scopes, max_keys, the owners of every named scope, the roles of the keys replace_label would deactivate and the active key count under it; a scope of another tenant, or one the tenant neither has nor creates, is a 403; a set past max_scopes or max_keys a 429 with limit, count and requested. The new scopes' groups of migration 176 are locked in sorted order before the one INSERT, so assigning several scopes keeps the order the scope trigger keeps (row by row it could deadlock with a block write). Keys go through insertApiKeyTx (role member, a fresh principal, exactly the scopes named, the audit row of the caller). replace_label deactivates the tenant's active member keys of the label in the same transaction and refuses a label an owner, admin or server-admin key carries, so it never takes a key past the owner rules of api-key-delete. A new scope refreshes the quota accountant like scope-create. No migration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/api.md | 1 + docs/multi-tenancy.md | 5 + .../keyset_provision_c3_integration_test.go | 11 +- ...yset_provision_c3_more_integration_test.go | 349 ++++++++++++++++ go/internal/handler/keyset_provision.go | 280 +++++++++++++ ...keyset_provision_quota_integration_test.go | 57 +++ go/internal/handler/keyset_provision_test.go | 96 +++++ .../handler/manage_action_fixture_test.go | 20 +- go/internal/handler/manage_table.go | 5 +- go/internal/store/keyset.go | 360 +++++++++++++++++ go/internal/store/keyset_integration_test.go | 372 ++++++++++++++++++ 11 files changed, 1541 insertions(+), 15 deletions(-) create mode 100644 go/cmd/ctxd/keyset_provision_c3_more_integration_test.go create mode 100644 go/internal/handler/keyset_provision.go create mode 100644 go/internal/handler/keyset_provision_quota_integration_test.go create mode 100644 go/internal/handler/keyset_provision_test.go create mode 100644 go/internal/store/keyset.go create mode 100644 go/internal/store/keyset_integration_test.go diff --git a/docs/api.md b/docs/api.md index e2db0112a..565d3eace 100644 --- a/docs/api.md +++ b/docs/api.md @@ -87,6 +87,7 @@ PostgreSQL stores a NUL character (U+0000) neither in text nor in JSON, so no va - **Backfill memo release (issue #236):** `embed-backfill-release` (tierTenantAdmin) drops regular embed-backfill failure memos (`context_embed_failures` rows with `migration_id` NULL) so the backfill takes their blocks again — after `embed_backfill.max_tokens` was raised, the embed backend moved to a larger context, or a backend outage ended; without it a parked block came back only through a change of its title or content. `data`: exactly one of `block_id` (a UUID) or `class` (`wire` or `oversize`), optional `limit` (the page size, at most and by default `1000`; a larger value is clamped), and `confirm_memos` together with `as_of`; unknown fields, a second selector, another class, a malformed id, a negative number and a `confirm_memos` without `as_of` (or the reverse) are `400`. A `caller_timeout` memo is never taken, not even by `block_id`: it is no park — the background arm takes such a block at once, and with the arm off the query path retries it after its hold —, and deleting it would hand the block back to the requests' `sync_budget` with its attempts restarted. A tenant-admin reaches the memos of blocks in its own tenant's scopes (a scope or a block granted to the tenant is not its own) — another tenant's block and an unknown one answer the same `counted: 0`; a server-admin reaches every memo; a key without an admin role is `403`. A re-embed migration's memos are never touched. **Without `confirm_memos` the call is a dry run** answering `{action, success, dry_run: true, as_of, counted, confirm_memos, held}` (and `held_until` when `held` is above 0); the real call sends `confirm_memos` and `as_of` of that answer, takes only the memos that were there when the dry run counted (a memo written after `as_of` — a released block that was parked again, a new park — is neither counted nor released, so paging ends), counts them again and releases only when the number is unchanged (otherwise `409` with the fresh `counted` and `confirm_memos`, and the `as_of` the call sent), releases at most `limit` of them — the count and the release decide which memos the reader may release at one instant (one transaction, issue #536), so a hold that ends between the two neither counts nor releases its memo in that call — and answers `{action, success, dry_run: false, as_of, counted, released, remaining, confirm_memos, held}` — `remaining` (and `confirm_memos`, the number to confirm for the next page with the same `as_of`) is what is left of them, including a memo another transaction held at that moment, which the release skips instead of waiting for. Two releases of the same memos at once each count what both may take: one of them releases fewer than it counted and answers a `remaining` the other has already released, and its next page answers `409` with the fresh count. Only memos that keep a block out of the pick (`next_attempt_at` in the future) count. **A server-admin's release deletes the memo; a tenant-admin's keeps it and makes it due**, with its attempts and with the time of the release in `first_seen`, so a block the backend still cannot take is parked again on the same row. A tenant-admin releases such an `oversize` memo again (more than one attempt) only once `embed_backfill.release_hold` × 2^(attempts − 2) has passed since that release, at most `embed_backfill.backoff_cap` (defaults 1 h and 24 h; a cap of 0 sets none; the hold must be above 0, V70); until then it is answered in `held`, with the earliest end in `held_until`. Without the hold a tenant-admin releasing its blocks in a loop while they kept not fitting took one turn of the background arm in every round of the tenants for good, where its way back without the action, an edit per block, costs a write each. The first release of every memo is not held, a `wire` memo is not held (its failure holds the tenant in the arm for `embed_backfill.interval`, and its next failure backs off longer, since the attempts stay), and a server-admin's release and a change of the block's title or content (which deletes the memo) start the count again. For a tenant-admin the count and the page of a class read the tenant's own scopes and their pending blocks, so their cost grows with the tenant's pending blocks, not with other tenants' memos. The next backfill pick of each released block embeds it when it fits now and parks it again after one attempt when it does not. CLI: `ctx admin embed-backfill release --class oversize`, then the same with `--confirm N --as-of T`; `--limit N` is sent as given, so a negative one is answered with the `400` (until issue #536 the CLI left a `--limit` of 0 or below out of the request and the server paged by its maximum). Operator notes in [operations](operations.md#embedding-backend-tuning-cpu-llamacpp), paragraph "Backfill failure memo". - **Block counters (issue #266):** `stats`, `guard-stats` and `list-categories` read per-scope counters that triggers on `context_blocks` keep with every write (migration 170), and so do the per-scope block counts of `scope-overview` (issue #271); the answers are unchanged. `guard-stats`' `pending_count` and `dirty_since` are counted on demand since migration 181: the blocks of the caller's read scopes the guard still has to check, and the oldest `updated_at` among them (`null` when none waits) — before 181 a global count of block writes since the last guard run, the same for every key ([operations](operations.md#migration-181-no-block-writer-waits-on-the-guards-state-row-guard-stats-counts-the-waiting-blocks)). `stats-reconcile` (server-admin) recounts and corrects them: `data` `{}` reconciles every scope, `{"scope": "<scope>"}` one; any other field is a `400`. It answers `{action, success, scopes, corrections, corrections_total, pruned, failed}` — `corrections` lists the corrected keys as `{scope, category, is_archived, guard_status, counted, actual}`, at most the first 1 000 of the pass, and `corrections_total` counts all of them (every one is corrected and logged; issue #271), `pruned` the folded counter rows at 0 it removed, `failed` the scopes whose reconcile failed (the pass goes on with the others; then `success` is `false` and the status `500`). The scheduler runs the same pass on `scheduler.block_count_reconcile_interval` — see [operations](operations.md#migration-170-block-counters-behind-stats-guard-stats-and-list-categories). - **Keys/clients:** `api-key-create` requires `home_scope`; key + MCP-client management and mutating `dream-mode` require an **admin key** since migration 052 (see [security](security.md#admin-tier)). `api-key-create`/`api-key-update` accept optional `write_scopes` (078, E4b) — explicit per-key write scopes that must be ⊆ `allowed_scopes ∪ {home_scope}` (else 400); the effective block-write gate and its double enforcement are in [multi-tenancy](multi-tenancy.md#per-key-write-scopes-e4b-migration-078). They also accept `scope_narrowing` (migration 198): `required` makes the key answer every request without a [narrowing](#scope-narrowing-per-request) with `403 scope_narrowing_required`, `GET /api/whoami` excepted; `optional` (every existing key, the default) keeps today's behaviour; any other value is 400. Both answers carry the value; `api-key-list` lists it. Per-tenant scoping of the `api-key-*` actions and the tenant lifecycle (`tenant-*`, `tenant-grant-*`, `scope-*`, `tenant-limit-set`, `tenant-usage-get`, `tenant-quota-*`, `block-grant-*`) are in [multi-tenancy](multi-tenancy.md). +- **Key sets:** `keyset-provision` (tenant-admin, in the caller's own tenant; a server-admin may name `tenant_id`, anyone else naming it gets 403) creates the scopes and the keys of one set — say the groups of one community — in one transaction: either the whole set exists afterwards or nothing of it does. `data`: `scopes` (at most 64 bare scope names, scope-create's rule; the server puts the tenant's `<slug>:` in front; a scope the tenant already has is kept) and `keys` (at most 64, each `{label, home_scope, allowed_scopes, write_scopes, scope_narrowing, replace_label}`; a key's scope is a bare name or a full `<slug>:<name>` and must be the tenant's own or one the set creates; a name without `:` always gets the prefix, so scopes outside that form — the default tenant's `private`, `work` and `shared` — cannot be named). The answer lists `scopes` as `{scope, created}` and `keys` as `{id, label, home_scope, allowed_scopes, write_scopes, scope_narrowing, api_key}`, both in the order of the call; each `api_key` (the plaintext) is in this answer only. Every key is a `member` key with exactly the scopes it names (no implicit `shared`, also in the default tenant) and its own principal; `scope_narrowing` left out is `optional`. `replace_label: true` deactivates the tenant's active keys with that label in the same transaction, before `max_keys` is counted, so a repeated call leaves one active key per label; on a label an owner, admin or server-admin key carries it refuses the set with `409`. Refusals: a scope of another tenant, or one the tenant neither has nor creates, `403`; `write_scopes ⊄ allowed_scopes ∪ {home_scope}`, a malformed scope name, an unknown field, a label missing or named twice in the set, a value the column cannot hold, a `scope_narrowing` other than `optional`/`required`, more than 64 scopes or keys, `400`; past `max_scopes` or `max_keys`, `429` with `limit`, `count` (the tenant's count before the set; for keys after its replacements) and `requested`; a tenant being deleted, or a scope registered meanwhile past the tenant lock (only a hand edit can), `409`; a top-level `id`, `400` (the target tenant is `data.tenant_id`). A narrowed request never reaches it ([above](#scope-narrowing-per-request)). How it serialises with the other key and scope writes: [multi-tenancy](multi-tenancy.md#key-sets-keyset-provision). - **Block-type registry:** `type-list`/`type-get` are open reads; `type-create`/`type-update`/`type-delete` are the **operator transport** (server-admin, `_global` namespace) of the same store logic the REST `PUT/DELETE /api/types/{name}` surface uses — kept functional for MCP/CLI consumers, not superseded (see [Block-type registry](#block-type-registry)). `manage update` accepts a registry-validated `type` field; `list-meta` accepts the `types`/`types_exclude` filters. - **Issue corpus:** `issue-create`/`issue-update`/`issue-get`/`issue-list`/`issue-comment-create`/`issue-link-create`/`issue-link-delete` are the **operator transport** (all tierOpen; isolation is store-layer scope filtering, not an admin tier) over the same store issue logic the REST `/api/project` issue surface (W6/W7) uses — kept reachable for MCP/CLI operators, not the primary UI surface (see [Issue corpus](#issue-corpus)). - **Backend pool:** `backend-list`/`create`/`update`/`delete`/`test` — see [Backend pool](#backend-pool). diff --git a/docs/multi-tenancy.md b/docs/multi-tenancy.md index 644a6ec7e..1cd844e5a 100644 --- a/docs/multi-tenancy.md +++ b/docs/multi-tenancy.md @@ -145,6 +145,10 @@ The `whoami` endpoint carries this on the wire: alongside the server-global `adm - **`ListApiKeys(tenantFilter, activeOnly)`** scopes a non-server-admin to its own tenant (leak-path L1) and — a **named behavior change** — defaults to returning only ACTIVE keys; soft-deleted keys reappear only with explicit `active_only=false`. - **`CreateApiKey`** is tenant-bound (leak-path L3/L5): the `{shared}` allowed-scopes default is tenant-aware (only the default tenant inherits `shared` — a fresh foreign-tenant key gets an empty set, no implicit cross-tenant read); a non-server-admin's every requested scope must be one its own tenant owns (resolved against `store.TenantScopes` — Model C, not a `home_scope == tenant_id` string compare), else 403 on the first foreign scope. +### Key sets (`keyset-provision`) + +`keyset-provision` is `scope-create` plus `api-key-create` for a whole set — the scopes and keys of the groups of one community, for instance — in **one** transaction ([api](api.md#manage-actions) has the wire form). It knows no community, bot or group: labels, scopes and rights come from the call. `store.ProvisionKeyset` takes the tenant row lock first (`FOR UPDATE` — the row lock `scope-create` and `api-key-create` take first and `api-key-update`/`api-key-delete` take before their decisive read of the key, and which `tenant-limit-set` and the tenant delete's mark, both an `UPDATE` of the row, wait for) and reads everything it decides on under it, each in a statement of its own: the tenant's status and both limits from the locked row, the owners of every scope the set names, the scope count, the roles of the keys `replace_label` would deactivate, the active key count after those replacements. A concurrent `tenant-limit-set`, `scope-create` or role change of the same tenant is therefore seen, not raced, and two sets that replace the same label one after the other leave one active key of it. Order inside the lock: scopes (refused when one belongs to another tenant, or when a key names a scope the tenant neither has nor creates — foreign and unknown answer alike, and a key never names a scope it could read only once someone registers it; the new scopes counted against `max_scopes`, their groups of migration 176 locked in sorted order — the order the scope trigger keeps, which a row-by-row assignment of several scopes would break — and then one `INSERT`), then `replace_label` (member keys only — a label an owner, admin or server-admin key carries refuses the set, so it can never take a key past the owner rules of `api-key-delete`), then `max_keys` (active keys after the replacements), then each key through `insertApiKeyTx`, the one INSERT path of a key: role `member`, a fresh principal, exactly the scopes named, the audit row (`create`, or `revoke` for a replaced key) attributed to the calling key `via=api`. A failure anywhere rolls the set back. A tenant whose delete has begun takes no set (409), the rule `scope-create` follows since issue #555. When the set created a scope the handler refreshes the quota accountant, as `scope-create` does, so a key homed there is under the tenant's quota from its first call. Cost: one statement per step plus one INSERT per key while the tenant lock is held — measured 41 ms for 64 new scopes and 64 keys and 34 ms for the same set again with 64 replacements, in a tenant holding 20 000 other keys and 2 000 other scopes (`TestKeysetSixtyFourCost`); the replacement, its check and the key count read the tenant's keys (there is no index on the label; a tenant with many keys pays a scan of its own keys, three times per set). Until the commit, other scope and key writes of the same tenant wait, so do inserts that reference the tenant row, block writes of never-embedded types into the tenant's scopes when the set creates a scope (they take the tenant's group of migration 176, which the scope trigger then holds), and the authentication of a key the set replaces (its row is locked by the replacement); the authentication of every other key does not wait (it takes no tenant lock). + ## Per-tenant settings & secrets Every config registry leaf carries a mandatory **`tenancy`** axis (T28) — `tenant-overridable` or `global-only` — enforced by a boot panic on any untagged leaf. Of the 185 registry keys, **63 are tenant-overridable** (the per-tenant query/retrieval/dream-tuning surface: thresholds, rate limits, rerank/graph knobs, dream back-off, scope + sensitivity policy, web-chat budgets, prompt-budget fallbacks) and **122 are global-only** (process-shared resources: DSN/listener, scheduler/collector cadences, the graph-overview and recall-check machinery, egress-audit retention). Backend topology no longer appears on either side of that split: hosts, models, protocols and provider credentials left the registry with the [tuple retirement](operations.md#environment-variables) and live in `context_backends`, whose own per-tenant isolation is the [pool section](#backend-pool-isolation-egress) below — a tenant that wants its own provider key creates a pool row with an `api_key_ref`, it does not override a settings key. @@ -261,6 +265,7 @@ Migration 069 adds structural per-tenant count-limits on `context_tenants`: `max | `tenant-usage-get` | tenant-admin (own) | Scope/key counts vs limits; a server-admin may target any. | | `api-key-create` | tenant-admin | Enforces `max_keys` transactionally (429, active-only count); a server-admin may mint into another tenant via `tenant_id` (foreign-target T22 — the new key's scopes must belong to the target; a non-server-admin's `tenant_id` → 403, AM2). New keys are always `member` (a smuggled `tenant_role` is ignored, AM3). Optional `write_scopes` (078, E4b) must be ⊆ `allowed_scopes ∪ {home_scope}` else 400 (see [Per-key write scopes](#per-key-write-scopes-e4b-migration-078)). | | `api-key-update` | tenant-admin | Role delegation (`{tenant_role?, active?, write_scopes?}`): only an owner (or server-admin) may change a key's role — a non-owner tenant-admin → 403, so admin→owner self-elevation is structurally impossible (no `is_admin` field means the server-global tier can never be set here). Demoting/deactivating the last active owner → 409 (last-owner invariant); an admin cannot neutralize an owner key → 403 (enforced at both update and the `api-key-delete` revoke path). A server-admin key (`is_admin`) is managed by server-admins only: any tenant-owner/-admin patch or revoke of it → 403, so a default-tenant admin cannot disable the operator's key. `write_scopes` (078, E4b) is validated ⊆ the key's existing `allowed_scopes ∪ {home_scope}` → 400 on a blind-writer; `[]` clears, absent leaves unchanged. `scope_narrowing` (198): switching an owner key to `required` takes its administration away, so it counts as neutralizing it (admin → 403) and the last-owner invariant counts only owners that are active **and** `optional` (409 for the last one, also on `api-key-delete`). Both actions decide the owner rules on the target as it is under the tenant row lock every key write takes, so a concurrent change of its role, `active` or `scope_narrowing` is seen, not raced. | +| `keyset-provision` | tenant-admin | `scope-create` and `api-key-create` for a set of up to 64 scopes and 64 keys in one transaction under the tenant row lock: all or nothing, `max_scopes`/`max_keys` counted for the whole set (429 with `limit`, `count`, `requested`), member keys with their own principal, `replace_label` deactivates the tenant's active member keys of a label in the same transaction (409 on a label an owner, admin or server-admin key carries); a server-admin may target another tenant via `tenant_id` (a non-server-admin's `tenant_id` → 403). See [Key sets](#key-sets-keyset-provision). | | `gateway-limits-get` | tenant-admin (own) | Reads the limits rows of an own consumer or the own tenant with the ceiling and the effective values ([api](api.md#gateway-limits-gateway-limits-)); instance and envelope values stay server-admin. | | `gateway-limits-set` | tenant-admin (own) | Writes the caller's **tenant-tier** row of an own consumer or the own tenant — narrowing only (each value at or under the ceiling of the levels above, else 400 with the field; `allow_external` only `false`). A server-admin writes the server tier freely, including `instance` and `tenant_envelope`. | | `gateway-limits-delete` | tenant-admin (own) | Removes the caller's tier row; the dimension inherits again. | diff --git a/go/cmd/ctxd/keyset_provision_c3_integration_test.go b/go/cmd/ctxd/keyset_provision_c3_integration_test.go index f1074158f..7aa7b8e9a 100644 --- a/go/cmd/ctxd/keyset_provision_c3_integration_test.go +++ b/go/cmd/ctxd/keyset_provision_c3_integration_test.go @@ -1,4 +1,4 @@ -//go:build integration && s1red_c3 +//go:build integration // Achse 02, cluster C-3 (design2/02-ctx-checkpoint.md §3.5 C-3, §7.3, BP-26): // the manage action keyset-provision creates, for a tenant-admin in its own @@ -7,10 +7,9 @@ // api-key-create (name rules, max_scopes, max_keys, write_scopes ⊆ // allowed ∪ {home}), at most 64 scopes and 64 keys per call, each key its own // principal; replace_label deactivates the active keys of the same label in -// the same transaction. Written in S1, where the action does not exist; the -// second build tag keeps the file out of every gate until C-3 lands. To -// enable, shorten the constraint line to `//go:build integration`. The -// required keys need C-2 (integration order C-1, C-2, C-4, C-3). +// the same transaction. Written in S1, where the action did not exist, +// behind a second build tag; enabled with C-3. The required keys need C-2 +// (integration order C-1, C-2, C-4, C-3). // // Wire form fixed by these tests (S1 contract, design §3.5 plus the lead's // reading where the design is silent): @@ -30,7 +29,7 @@ // on a tree without the action the refusals would pass for the wrong reason // (an unknown action is a 400 that creates nothing too). // -// go test -tags=integration,s1red_c3 -p 1 -count=1 -run '^TestC3' ./cmd/ctxd/ +// go test -tags=integration -p 1 -count=1 -run '^TestC3' ./cmd/ctxd/ package main import ( diff --git a/go/cmd/ctxd/keyset_provision_c3_more_integration_test.go b/go/cmd/ctxd/keyset_provision_c3_more_integration_test.go new file mode 100644 index 000000000..11f354992 --- /dev/null +++ b/go/cmd/ctxd/keyset_provision_c3_more_integration_test.go @@ -0,0 +1,349 @@ +//go:build integration + +// Achse 02, cluster C-3, the refusals the S1 file does not hold +// (keyset_provision_c3_integration_test.go): replace_label never revokes an +// owner, admin or server-admin key; a refusal after replace_label leaves the +// replaced key active (one transaction); a fault in the middle of the set +// leaves no scope, key or principal behind and no key material in the log; +// the audit trail names the caller and carries no key material; malformed +// sets are refused before anything is written; a narrowed request and an +// offboarding tenant provision nothing. Every refusal test ends with a valid +// call of the same caller (its control), as in the S1 file. +// +// go test -tags=integration -p 1 -count=1 -run '^TestC3' ./cmd/ctxd/ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "testing" +) + +// TestC3ReplaceLabelNeverRevokesAnAdministrativeKey: replace_label deactivates +// member keys only. Named on the label of the tenant's owner key, of an admin +// key or of the server-admin key, the whole call is a 409 and the key keeps +// working — an admin cannot revoke the owner this way, an owner not the last +// owner, nobody the server-admin key. +func TestC3ReplaceLabelNeverRevokesAnAdministrativeKey(t *testing.T) { + w := c3Setup(t) + ownerLabel, _ := w.whoami(t, w.owner)["label"].(string) + r := w.manage(t, w.owner, map[string]any{"action": "api-key-create", "data": map[string]any{"label": "c3-tadmin", "home_scope": "c3t:main"}}).must(t, "admin key") + tadmin, _ := r.body["api_key"].(string) + tadminID, _ := r.body["id"].(string) + w.manage(t, w.owner, map[string]any{"action": "api-key-update", "data": map[string]any{"id": tadminID, "tenant_role": "admin"}}).must(t, "promote to admin") + scopes, labels := w.state(t) + + for _, tc := range []struct { + caller, label, what string + }{ + {tadmin, ownerLabel, "an admin on the owner's label"}, + {w.owner, ownerLabel, "the owner on its own label"}, + {w.owner, "c3-tadmin", "the owner on an admin key's label"}, + } { + k := c3Key(tc.label, "members", nil, nil, "required") + k["replace_label"] = true + r := w.provision(t, tc.caller, []string{"members"}, k) + if r.status != http.StatusConflict { + t.Errorf("%s: HTTP %d %s, want 409", tc.what, r.status, r.raw) + } + w.wantUnchanged(t, tc.what, scopes, labels) + } + for key, name := range map[string]string{w.owner: "owner", tadmin: "admin"} { + if s := w.do(t, http.MethodGet, "/api/whoami", key, nil); s.status != http.StatusOK { + t.Errorf("the %s key no longer authenticates: HTTP %d", name, s.status) + } + } + + // The server-admin key, in its own default tenant, by the server-admin. + k := c3Key("c3-admin", "c3x", nil, nil, "required") + k["replace_label"] = true + if r := w.provision(t, c3AdminKey, []string{"c3x"}, k); r.status != http.StatusConflict { + t.Errorf("replace_label on the server-admin key's label: HTTP %d %s, want 409", r.status, r.raw) + } + if s := w.do(t, http.MethodGet, "/api/whoami", c3AdminKey, nil); s.status != http.StatusOK { + t.Errorf("the server-admin key no longer authenticates: HTTP %d", s.status) + } + + k = c3Key("c3-fresh-label", "members", nil, nil, "required") + k["replace_label"] = true + w.provision(t, tadmin, []string{"members"}, k).must(t, "control: replace_label on a label no key carries, by the admin") +} + +// TestC3ARefusalKeepsTheReplacedKey: replace_label and the rest of the set are +// one transaction — when a later step of the same call is refused (a foreign +// scope of another key, max_keys), the key it would have replaced stays +// active and nothing of the set exists. +func TestC3ARefusalKeepsTheReplacedKey(t *testing.T) { + w := c3Setup(t) + const label = "hermes:discord:333:members" + r := w.provision(t, w.owner, []string{"members"}, c3Key(label, "members", nil, nil, "required")).must(t, "first provision") + _, _, first := c3KeysOf(r) + r = w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3y", "display_name": "C3 other"}}).must(t, "second tenant") + foreign, _ := r.body["scope"].(string) + scopes, labels := w.state(t) + + k := c3Key(label, "members", nil, nil, "required") + k["replace_label"] = true + if r := w.provision(t, w.owner, []string{"mods"}, k, c3Key("c3-foreign", "mods", []string{foreign}, nil, "required")); r.status != http.StatusForbidden { + t.Errorf("replace_label with a foreign scope in the set: HTTP %d %s, want 403", r.status, r.raw) + } + w.wantUnchanged(t, "after the foreign-scope refusal", scopes, labels) + + // max_keys: owner + the first key = 2 active; replacing frees one, two + // new keys pass the limit of 2 anyway. + w.manage(t, c3AdminKey, map[string]any{"action": "tenant-limit-set", "id": w.tenantID, "data": map[string]any{"max_scopes": 25, "max_keys": 2}}).must(t, "tenant-limit-set") + if r := w.provision(t, w.owner, nil, k, c3Key("c3-second", "members", nil, nil, "required")); r.status != http.StatusTooManyRequests { + t.Errorf("replace_label plus one key over max_keys: HTTP %d %s, want 429", r.status, r.raw) + } + w.wantUnchanged(t, "after the key-quota refusal", scopes, labels) + if s := w.do(t, http.MethodGet, "/api/whoami", first[label], nil); s.status != http.StatusOK { + t.Errorf("the key the refused call would have replaced no longer authenticates: HTTP %d", s.status) + } + w.provision(t, w.owner, nil, k).must(t, "control: the replacement alone") +} + +// TestC3AFaultInTheMiddleLeavesNothing: the database refuses the second key +// of a set (a trigger), after the scopes and the first key were written in +// the transaction. The answer is a 500 with one line; no scope, key or +// principal of the set remains, and the line carries no key material. +func TestC3AFaultInTheMiddleLeavesNothing(t *testing.T) { + w := c3Setup(t) + ctx := context.Background() + for _, q := range []string{ + `CREATE FUNCTION c3_refuse_second() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN IF NEW.label = 'c3-fault-b' THEN RAISE EXCEPTION 'c3 probe fault'; END IF; RETURN NEW; END $$`, + `CREATE TRIGGER c3_refuse_second BEFORE INSERT ON context_api_keys FOR EACH ROW EXECUTE FUNCTION c3_refuse_second()`, + } { + if _, err := w.pool.Exec(ctx, q); err != nil { + t.Fatalf("fault fixture: %v", err) + } + } + principals := func() int { + var n int + if err := w.pool.QueryRow(ctx, `SELECT count(*) FROM context_principals`).Scan(&n); err != nil { + t.Fatal(err) + } + return n + } + scopes, labels := w.state(t) + before := principals() + + var logs bytes.Buffer + prev := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))) + r := w.provision(t, w.owner, []string{"fa", "fb"}, + c3Key("c3-fault-a", "fa", nil, nil, "required"), + c3Key("c3-fault-b", "fb", []string{"fa"}, nil, "required")) + slog.SetDefault(prev) + if r.status != http.StatusInternalServerError { + t.Errorf("a fault on the second key: HTTP %d %s, want 500", r.status, r.raw) + } + w.wantUnchanged(t, "after the fault", scopes, labels) + if after := principals(); after != before { + t.Errorf("principals %d → %d, want none left behind", before, after) + } + line := logs.String() + if !strings.Contains(line, "manage: keyset-provision failed") { + t.Errorf("no failure line for the fault: %q", line) + } + if hex64 := regexp.MustCompile(`[0-9a-f]{64}`).FindString(line); hex64 != "" { + t.Errorf("the log carries a 64-hex token (key material?): %q", line) + } + + if _, err := w.pool.Exec(ctx, `DROP TRIGGER c3_refuse_second ON context_api_keys`); err != nil { + t.Fatal(err) + } + w.provision(t, w.owner, []string{"fa", "fb"}, + c3Key("c3-fault-a", "fa", nil, nil, "required"), + c3Key("c3-fault-b", "fb", []string{"fa"}, nil, "required")).must(t, "control: the same set without the fault") +} + +// TestC3AuditNamesTheCallerAndNoKeyMaterial: each key of a set writes one +// audit row 'create' and each replaced key one 'revoke', attributed to the +// calling key over the API; no audit row carries a plaintext or a key hash. +func TestC3AuditNamesTheCallerAndNoKeyMaterial(t *testing.T) { + w := c3Setup(t) + ctx := context.Background() + ownerID, _ := w.whoami(t, w.owner)["api_key_id"].(string) + r := w.provision(t, w.owner, []string{"members"}, c3Key("c3-audit", "members", nil, nil, "required")).must(t, "first provision") + _, ids1, plains1 := c3KeysOf(r) + k := c3Key("c3-audit", "members", nil, nil, "required") + k["replace_label"] = true + r = w.provision(t, w.owner, nil, k, c3Key("c3-audit-2", "members", nil, nil, "optional")).must(t, "second provision") + _, ids2, plains2 := c3KeysOf(r) + + type row struct{ key, action, via, actor string } + want := []row{ + {ids1["c3-audit"], "create", "api", ownerID}, + {ids1["c3-audit"], "revoke", "api", ownerID}, + {ids2["c3-audit"], "create", "api", ownerID}, + {ids2["c3-audit-2"], "create", "api", ownerID}, + } + for _, wr := range want { + var n int + if err := w.pool.QueryRow(ctx, `SELECT count(*) FROM context_settings_audit + WHERE entity_type = 'api_key' AND entity_key = $1 AND action = $2 + AND metadata->>'via' = $3 AND api_key_id = $4::uuid`, wr.key, wr.action, wr.via, wr.actor).Scan(&n); err != nil || n != 1 { + t.Errorf("audit %s of %s by %s via %s: %d row(s) (err %v), want 1", wr.action, wr.key, wr.actor, wr.via, n, err) + } + } + var dump string + if err := w.pool.QueryRow(ctx, `SELECT coalesce(string_agg(a::text, E'\n'), '') FROM context_settings_audit a WHERE entity_type = 'api_key'`).Scan(&dump); err != nil { + t.Fatal(err) + } + for _, plains := range []map[string]string{plains1, plains2} { + for l, p := range plains { + h := sha256.Sum256([]byte(p)) + if strings.Contains(dump, p) || strings.Contains(dump, hex.EncodeToString(h[:])) { + t.Errorf("the audit trail carries the plaintext or the hash of %s", l) + } + } + } +} + +// TestC3MalformedSetsCreateNothing: what the call gets wrong is a 400 before +// anything is written — the caller's typo of replace_label above all, which +// would otherwise leave the old key active beside the new one. +func TestC3MalformedSetsCreateNothing(t *testing.T) { + w := c3Setup(t) + scopes, labels := w.state(t) + long := strings.Repeat("l", 101) + typo := c3Key("c3-typo", "members", nil, nil, "required") + typo["replace-label"] = true + for _, tc := range []struct { + what string + data map[string]any + }{ + {"unknown key field", map[string]any{"scopes": []string{"members"}, "keys": []any{typo}}}, + {"unknown data field", map[string]any{"scope": []string{"members"}}}, + {"nothing to provision", map[string]any{"scopes": []string{}, "keys": []any{}}}, + {"no label", map[string]any{"scopes": []string{"members"}, "keys": []any{c3Key("", "members", nil, nil, "required")}}}, + {"label over 100 characters", map[string]any{"scopes": []string{"members"}, "keys": []any{c3Key(long, "members", nil, nil, "required")}}}, + {"label named twice", map[string]any{"scopes": []string{"members"}, "keys": []any{c3Key("c3-twice", "members", nil, nil, "required"), c3Key("c3-twice", "members", nil, nil, "required")}}}, + {"no home scope", map[string]any{"scopes": []string{"members"}, "keys": []any{c3Key("c3-nohome", "", nil, nil, "required")}}}, + {"scope named twice", map[string]any{"scopes": []string{"members", "members"}}}, + {"full name in scopes", map[string]any{"scopes": []string{"c3t:members"}}}, + {"bad scope name", map[string]any{"scopes": []string{"Members_1"}}}, + {"bad key scope name", map[string]any{"scopes": []string{"members"}, "keys": []any{c3Key("c3-bad", "Members_1", nil, nil, "required")}}}, + {"reserved key scope", map[string]any{"scopes": []string{"members"}, "keys": []any{c3Key("c3-reserved", "members", []string{"_global"}, nil, "required")}}}, + {"scope_narrowing value", map[string]any{"scopes": []string{"members"}, "keys": []any{c3Key("c3-sometimes", "members", nil, nil, "sometimes")}}}, + } { + r := w.manage(t, w.owner, map[string]any{"action": "keyset-provision", "data": tc.data}) + if r.status != http.StatusBadRequest { + t.Errorf("%s: HTTP %d %s, want 400", tc.what, r.status, r.raw) + } + w.wantUnchanged(t, tc.what, scopes, labels) + } + // A top-level id is no target tenant here (scope-create reads it as one + // for a server-admin; this action takes data.tenant_id only): refused + // rather than provisioning into the caller's own tenant unasked. + for _, key := range []string{w.owner, c3AdminKey} { + body := map[string]any{"action": "keyset-provision", "id": w.tenantID, "data": map[string]any{"scopes": []string{"members"}}} + if r := w.manage(t, key, body); r.status != http.StatusBadRequest { + t.Errorf("a top-level id: HTTP %d %s, want 400", r.status, r.raw) + } + } + w.wantUnchanged(t, "after the top-level id", scopes, labels) + r := w.provision(t, w.owner, []string{"members"}, c3Key(strings.Repeat("l", 100), "members", nil, nil, "")) + r.must(t, "control: a label of 100 characters, scope_narrowing left out") + if _, _, plains := c3KeysOf(r); len(plains) == 1 { + for _, p := range plains { + if b := w.whoami(t, p); b["scope_narrowing"] != "optional" { + t.Errorf("scope_narrowing left out: whoami %v, want optional (api-key-create's default)", b["scope_narrowing"]) + } + } + } +} + +// TestC3UnknownScopeIsRefusedLikeAForeignOne: a key that names a scope no +// tenant holds — another prefix, or the tenant's own prefix the set does not +// create — is refused with the answer a foreign scope gets: such a key would +// read the scope the moment someone registers it, and the two answers alike +// tell nobody whether a name is taken. +func TestC3UnknownScopeIsRefusedLikeAForeignOne(t *testing.T) { + w := c3Setup(t) + r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3z", "display_name": "C3 other"}}).must(t, "second tenant") + foreign, _ := r.body["scope"].(string) + scopes, labels := w.state(t) + answers := map[string]string{} + for _, name := range []string{foreign, "c3nobody:main", "c3t:ghost"} { + r := w.provision(t, w.owner, []string{"members"}, c3Key("c3-unknown", "members", []string{name}, nil, "required")) + if r.status != http.StatusForbidden { + t.Errorf("a key naming %s: HTTP %d %s, want 403", name, r.status, r.raw) + } + e, _ := r.body["error"].(string) + answers[name] = strings.TrimSuffix(e, name) + w.wantUnchanged(t, name, scopes, labels) + } + if answers[foreign] == "" || answers[foreign] != answers["c3nobody:main"] || answers[foreign] != answers["c3t:ghost"] { + t.Errorf("the answers differ between a foreign and an unknown scope: %q", answers) + } + w.provision(t, w.owner, []string{"members", "ghost"}, c3Key("c3-unknown", "members", []string{"c3t:ghost"}, nil, "required")).must(t, "control: the set creates the scope it names") +} + +// TestC3DefaultTenantKeysGetNoImplicitShared: in the default tenant, +// api-key-create gives a key without allowed_scopes the 'shared' scope +// (R-LEAK5). A set's key gets exactly the scopes the call names — a group key +// of the operator's own tenant reads no shared layer it was not given. +func TestC3DefaultTenantKeysGetNoImplicitShared(t *testing.T) { + w := c3Setup(t) + r := w.provision(t, c3AdminKey, []string{"c3grp"}, c3Key("c3-default-group", "c3grp", nil, nil, "required")).must(t, "server-admin set in the default tenant") + _, _, plains := c3KeysOf(r) + b := w.whoami(t, plains["c3-default-group"]) + if rs := fmt.Sprint(b["read_scopes"]); rs != "[default:c3grp]" { + t.Errorf("the set's key reads %s, want [default:c3grp] alone", rs) + } +} + +// TestC3IsNeverANarrowedAction: a narrowed request is never an +// administration request (C-1) — keyset-provision under a narrowing is a 403 +// and creates nothing; the same caller unnarrowed is the control. +func TestC3IsNeverANarrowedAction(t *testing.T) { + w := c3Setup(t) + scopes, labels := w.state(t) + body := map[string]any{"action": "keyset-provision", "data": map[string]any{"scopes": []string{"members"}, "keys": []any{c3Key("c3-narrowed", "members", nil, nil, "required")}}} + raw, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodPost, "/api/manage", bytes.NewReader(raw)) + req.Header.Set("X-Context-Key", w.owner) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Context-Read-Scopes", "c3t:main") + rec := httptest.NewRecorder() + w.router.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Errorf("narrowed keyset-provision: HTTP %d %s, want 403", rec.Code, rec.Body.String()) + } + w.wantUnchanged(t, "after the narrowed call", scopes, labels) + w.manage(t, w.owner, body).must(t, "control: the same call unnarrowed") +} + +// TestC3OffboardingTenantTakesNoSet: a tenant whose delete has begun takes no +// scope and no key (issue #555's rule of scope-create), also from a +// server-admin naming it. +func TestC3OffboardingTenantTakesNoSet(t *testing.T) { + w := c3Setup(t) + scopes, labels := w.state(t) + if _, err := w.pool.Exec(context.Background(), `UPDATE context_tenants SET status = 'offboarding' WHERE id = $1::uuid`, w.tenantID); err != nil { + t.Fatal(err) + } + data := map[string]any{"tenant_id": w.tenantID, "scopes": []string{"members"}, "keys": []any{c3Key("c3-late", "members", nil, nil, "required")}} + if r := w.manage(t, c3AdminKey, map[string]any{"action": "keyset-provision", "data": data}); r.status != http.StatusConflict { + t.Errorf("offboarding tenant: HTTP %d %s, want 409", r.status, r.raw) + } + w.wantUnchanged(t, "after the offboarding refusal", scopes, labels) + if _, err := w.pool.Exec(context.Background(), `UPDATE context_tenants SET status = 'active' WHERE id = $1::uuid`, w.tenantID); err != nil { + t.Fatal(err) + } + w.manage(t, c3AdminKey, map[string]any{"action": "keyset-provision", "data": data}).must(t, "control: the tenant active again") +} diff --git a/go/internal/handler/keyset_provision.go b/go/internal/handler/keyset_provision.go new file mode 100644 index 000000000..bb63033dd --- /dev/null +++ b/go/internal/handler/keyset_provision.go @@ -0,0 +1,280 @@ +package handler + +import ( + "errors" + "fmt" + "log/slog" + "net/http" + "strings" + + "github.com/GottZ/ctx/internal/auth" + "github.com/GottZ/ctx/internal/store" +) + +// keyset-provision (Achse 02 C-3): the scopes and keys of one set in one +// call and one transaction — scope-create and api-key-create for a whole set, +// all or nothing. Tier tenant-admin in the caller's own tenant; a server-admin +// may name another tenant with data.tenant_id (like api-key-create). The set's +// labels, scopes and rights come from the call as they are: the action knows +// no community, no bot and no group. +// +// {"action":"keyset-provision","data":{"tenant_id"?, "scopes":[<name>…], +// "keys":[{"label","home_scope","allowed_scopes","write_scopes", +// "scope_narrowing","replace_label"}…]}} +// +// The names in scopes are bare scope names (scope-create's rule; the server +// puts the tenant's '<slug>:' in front). A key's scopes are bare names or full +// '<slug>:<name>' names, which must be the tenant's own or created by the set. +// The answer lists the scopes ({scope, created}) and the keys ({id, label, +// home_scope, allowed_scopes, write_scopes, scope_narrowing, api_key}) in the +// order of the call; a key's plaintext (api_key) is in this answer only. + +// keysetMaxScopes and keysetMaxKeys bound one call (design §3.5 C-3): a set is +// the groups of one community, and the tenant's row lock is held while all of +// it is written. Fixed bounds of the request shape, not tenant policy — the +// tenant's ceilings are max_scopes and max_keys. +const ( + keysetMaxScopes = 64 + keysetMaxKeys = 64 +) + +// keysetProvisionSpec is req.Data of keyset-provision, decoded strictly (an +// unknown field — a misspelt replace_label among them — is a 400, not a set +// that silently keeps the old key active). +type keysetProvisionSpec struct { + TenantID string `json:"tenant_id,omitempty"` // SERVER-ADMIN ONLY + Scopes []string `json:"scopes"` + Keys []keysetKeySpec `json:"keys"` +} + +// keysetKeySpec is one key of the set as the call names it. scope_narrowing +// empty means optional, as on api-key-create; the role is always member. +type keysetKeySpec struct { + Label string `json:"label"` + HomeScope string `json:"home_scope"` + AllowedScopes []string `json:"allowed_scopes"` + WriteScopes []string `json:"write_scopes"` + ScopeNarrowing string `json:"scope_narrowing"` + ReplaceLabel bool `json:"replace_label"` +} + +func (h *ManageHandler) handleKeysetProvision(w http.ResponseWriter, r *http.Request, ar *auth.AuthResult, req manageRequest) { + if ar == nil { + // Defense in depth — the tier gate already rejected anon callers. + writeJSON(w, http.StatusUnauthorized, map[string]any{"success": false, "error": "unauthorized"}) + return + } + // The target tenant is data.tenant_id only. scope-create and + // tenant-limit-set read a top-level id as one; here it would be ignored + // and the set would land in the caller's own tenant unasked. + if req.ID != "" { + writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": "keyset-provision takes no id; a server-admin names the tenant in data.tenant_id"}) + return + } + var spec keysetProvisionSpec + if msg := decodeStrict(req.Data, &spec); msg != "" { + writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": msg}) + return + } + if msg := checkKeysetShape(spec); msg != "" { + writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": msg}) + return + } + // The binding tenant (AM2, as api-key-create): tenant_id is server-admin + // only; a non-server-admin naming any tenant is refused before the field + // is read as a binding, whatever its value (no existence oracle). + binding := ar.TenantID + if spec.TenantID != "" { + if !ar.IsServerAdmin() { + writeJSON(w, http.StatusForbidden, map[string]any{"success": false, "error": "tenant_id is server-admin only"}) + return + } + binding = spec.TenantID + } + tn, err := store.GetTenant(r.Context(), h.pool, binding) + if errors.Is(err, store.ErrTenantNotFound) { + writeJSON(w, http.StatusNotFound, map[string]any{"success": false, "error": "tenant not found"}) + return + } + if err != nil { + logRequestError(r.Context(), "manage: keyset-provision tenant lookup failed", "error", err) + writeJSON(w, http.StatusInternalServerError, map[string]any{"success": false, "error": "get tenant failed"}) + return + } + // The slug is the prefix of every scope the set names; re-validated like + // scope-create does, fail-closed. A tenant's slug never changes after its + // create (tenant-update writes status and display name), so reading it + // before the store's lock decides nothing that lock protects. + if !slugPattern.MatchString(tn.Slug) { + writeJSON(w, http.StatusInternalServerError, map[string]any{"success": false, "error": "tenant slug is not prefix-safe"}) + return + } + scopes, keys, msg := resolveKeysetNames(tn.Slug, spec) + if msg != "" { + writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": msg}) + return + } + set, err := store.ProvisionKeyset(r.Context(), h.pool, binding, scopes, keys, auditStamp(r, ar)) + if err != nil { + writeKeysetError(w, r, err) + return + } + // A new scope is unknown to the quota accountant until its next refresh + // (= ungated); refreshed now, as scope-create does, so a key homed there + // is under the tenant's quota from its first call (GHSA 2026-10-31 §4). + if h.quota != nil && keysetCreatedAny(set) { + if err := h.quota.RefreshNow(r.Context()); err != nil { + slog.Warn("keyset-provision: quota refresh failed; the new scopes are gated after the next TTL refresh", "error", err) + } + } + writeJSON(w, http.StatusOK, keysetAnswer(set)) +} + +// checkKeysetShape checks what needs neither the tenant nor the database: the +// size bounds and one label per key of the set. Empty = ok, else the 400 +// message. A label the column cannot hold (over 100 characters) is the +// database's 400 (writeCallerDataError); a scope_narrowing other than +// optional and required is insertApiKeyTx's — both refuse the whole set. +func checkKeysetShape(spec keysetProvisionSpec) string { + if len(spec.Scopes) > keysetMaxScopes { + return fmt.Sprintf("at most %d scopes per call", keysetMaxScopes) + } + if len(spec.Keys) > keysetMaxKeys { + return fmt.Sprintf("at most %d keys per call", keysetMaxKeys) + } + if len(spec.Scopes) == 0 && len(spec.Keys) == 0 { + return "data needs scopes or keys" + } + labels := make(map[string]bool, len(spec.Keys)) + for i, k := range spec.Keys { + switch { + case k.Label == "": + return fmt.Sprintf("keys[%d]: label is required", i) + case labels[k.Label]: + // One key per label and set: two would both stay active, and + // replace_label could not tell them apart afterwards. + return fmt.Sprintf("keys[%d]: label %q named twice", i, k.Label) + } + labels[k.Label] = true + } + return "" +} + +// resolveKeysetNames turns the call's scope names into full scope names of +// the tenant with slug: a bare name ('<name>', scopeNamePattern) gets +// '<slug>:' in front; a key's name with a ':' is taken as a full name, whose +// ownership the store decides (a foreign, an unknown and a '_'-reserved name +// are all "not a scope of this tenant"). Empty msg = ok, else the 400 message. +func resolveKeysetNames(slug string, spec keysetProvisionSpec) (scopes []string, keys []store.KeysetKey, msg string) { + scopes = make([]string, 0, len(spec.Scopes)) + seen := make(map[string]bool, len(spec.Scopes)) + for i, name := range spec.Scopes { + if !scopeNamePattern.MatchString(name) { + return nil, nil, fmt.Sprintf("scopes[%d]: name must be 1-24 chars of a-z, 0-9, '-' (no leading/trailing '-', no ':')", i) + } + full := slug + ":" + name + if seen[full] { + return nil, nil, fmt.Sprintf("scopes[%d]: scope %q named twice", i, name) + } + seen[full] = true + scopes = append(scopes, full) + } + keys = make([]store.KeysetKey, 0, len(spec.Keys)) + for i, k := range spec.Keys { + names := append(append([]string{k.HomeScope}, k.AllowedScopes...), k.WriteScopes...) + full := make([]string, len(names)) + for j, n := range names { + switch { + case strings.Contains(n, ":"): + full[j] = n + case scopeNamePattern.MatchString(n): + full[j] = slug + ":" + n + default: + return nil, nil, fmt.Sprintf("keys[%d]: scope %q is neither a scope name (1-24 chars of a-z, 0-9, '-') nor a full '<tenant>:<name>' scope", i, n) + } + } + narrowing := k.ScopeNarrowing + if narrowing == "" { + narrowing = auth.ScopeNarrowingOptional + } + nAllowed := len(k.AllowedScopes) + keys = append(keys, store.KeysetKey{ + Label: k.Label, + HomeScope: full[0], + AllowedScopes: full[1 : 1+nAllowed], + WriteScopes: full[1+nAllowed:], + ScopeNarrowing: narrowing, + ReplaceLabel: k.ReplaceLabel, + }) + } + return scopes, keys, "" +} + +func keysetCreatedAny(set store.Keyset) bool { + for _, s := range set.Scopes { + if s.Created { + return true + } + } + return false +} + +// keysetAnswer is the 200 answer: scopes and keys in the order of the call, +// each key's plaintext under api_key (shown once, like api-key-create). +func keysetAnswer(set store.Keyset) map[string]any { + scopes := make([]map[string]any, 0, len(set.Scopes)) + for _, s := range set.Scopes { + scopes = append(scopes, map[string]any{"scope": s.Scope, "created": s.Created}) + } + keys := make([]map[string]any, 0, len(set.Keys)) + for _, m := range set.Keys { + keys = append(keys, map[string]any{ + "id": m.Key.ID, + "label": m.Key.Label, + "home_scope": m.Key.HomeScope, + "allowed_scopes": m.Key.AllowedScopes, + "write_scopes": m.Key.WriteScopes, + "scope_narrowing": m.Key.ScopeNarrowing, + "api_key": m.Plaintext, // Shown once. + }) + } + return map[string]any{"success": true, "scopes": scopes, "keys": keys} +} + +// writeKeysetError answers a refused or failed set; in every case nothing of +// the set was written. The texts name the caller's own scope or label, never +// a key's plaintext or hash. +func writeKeysetError(w http.ResponseWriter, r *http.Request, err error) { + var ( + quota *store.KeysetQuotaError + refusal *store.KeysetRefusal + ) + switch { + case errors.As(err, "a): + text := "tenant scope quota exceeded" + if quota.Keys { + text = "tenant key quota exceeded" + } + writeJSON(w, http.StatusTooManyRequests, map[string]any{"success": false, "error": text, + "limit": quota.Limit, "count": quota.Count, "requested": quota.Requested}) + case errors.As(err, &refusal) && errors.Is(refusal.Err, store.ErrKeysetScopeOutsideTenant): + writeJSON(w, http.StatusForbidden, map[string]any{"success": false, + "error": "not a scope of this tenant: " + refusal.Subject}) + case errors.As(err, &refusal) && errors.Is(refusal.Err, store.ErrKeysetLabelProtected): + writeJSON(w, http.StatusConflict, map[string]any{"success": false, + "error": "replace_label: an active key labelled " + fmt.Sprintf("%q", refusal.Subject) + " is not a member key; revoke it with api-key-delete"}) + case errors.Is(err, store.ErrWriteScopeNotAllowed): + // write_scopes ⊄ allowed_scopes ∪ {home_scope} (078, E4b): a blind writer. + writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": err.Error()}) + case errors.Is(err, store.ErrScopeNarrowingInvalid): + writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": "scope_narrowing must be optional or required"}) + case errors.Is(err, store.ErrTenantNotFound): + writeJSON(w, http.StatusNotFound, map[string]any{"success": false, "error": "tenant not found"}) + case errors.Is(err, store.ErrTenantOffboarding): + writeJSON(w, http.StatusConflict, map[string]any{"success": false, "error": "the tenant is being deleted; it takes no further scope and no further key"}) + case errors.Is(err, store.ErrScopeExists): + writeJSON(w, http.StatusConflict, map[string]any{"success": false, "error": "scope already exists"}) + default: + writeAdminFailure(w, r, "manage: keyset-provision failed", err, writeOutcome(err), "keyset provision failed") + } +} diff --git a/go/internal/handler/keyset_provision_quota_integration_test.go b/go/internal/handler/keyset_provision_quota_integration_test.go new file mode 100644 index 000000000..cdf56113f --- /dev/null +++ b/go/internal/handler/keyset_provision_quota_integration_test.go @@ -0,0 +1,57 @@ +//go:build integration + +package handler + +// Achse 02 C-3: keyset-provision creates scopes like scope-create does, so it +// closes the same window (GHSA 2026-10-31 §4): the accountant maps scope → +// tenant from its cached generation, and a scope it has not seen is ungated +// until the next TTL refresh. keyset-provision refreshes it; a key homed in a +// scope the set created is under the tenant's quota from its first call. +// +// go test -tags=integration -p 1 -count=1 -run TestQuotaKeysetProvisionRefreshes ./internal/handler/ + +import ( + "context" + "errors" + "net/http" + "testing" + "time" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/testdb" +) + +func TestQuotaKeysetProvisionRefreshes(t *testing.T) { + if testing.Short() { + t.Skip("integration test") + } + pool := testdb.SetupTestDB(t) + ctx := context.Background() + + tenantID := be5SeedTenant(t, pool, "s4ks") + be5SeedScope(t, pool, "s4ks:main", tenantID) + if _, err := pool.Exec(ctx, `INSERT INTO context_tenant_quota (scope, daily_calls) VALUES ('s4ks:main', 0)`); err != nil { + t.Fatalf("seed quota: %v", err) + } + acc := backends.NewQuotaAccountant(pool, time.Hour) // no TTL refresh inside the test + if err := acc.RefreshNow(ctx); err != nil { + t.Fatalf("refresh: %v", err) + } + h := NewManageHandler(pool, nil, nil, nil, nil, nil, acc, nil) + + rec := be5ScopeManageAs(t, h, be5TenantAdmin(tenantID), map[string]any{ + "action": "keyset-provision", "data": map[string]any{ + "scopes": []string{"members"}, + "keys": []map[string]any{{"label": "s4ks-members", "home_scope": "members", "allowed_scopes": []string{"main"}, + "write_scopes": []string{}, "scope_narrowing": "required"}}, + }, + }) + if rec.Code != http.StatusOK { + t.Fatalf("keyset-provision: status %d, body %s", rec.Code, rec.Body.String()) + } + _, err := acc.Gate("s4ks:members", []backends.Backend{{ID: "x", Name: "local", Locality: "local"}}) + var qe *backends.ErrQuotaExceeded + if err == nil || !errors.As(err, &qe) || qe.Reason != "daily_calls" { + t.Fatalf("the set's new scope must be gated by the tenant's quota right after keyset-provision, Gate err=%v", err) + } +} diff --git a/go/internal/handler/keyset_provision_test.go b/go/internal/handler/keyset_provision_test.go new file mode 100644 index 000000000..a860c90f0 --- /dev/null +++ b/go/internal/handler/keyset_provision_test.go @@ -0,0 +1,96 @@ +package handler + +// Achse 02 C-3: the parts of keyset-provision that need no database — the +// shape of a set (size bounds, one label per key) and the resolution of +// its scope names to the tenant's full scope names. +// +// go test -short -run 'TestKeyset' ./internal/handler/ + +import ( + "fmt" + "strings" + "testing" + + "github.com/GottZ/ctx/internal/auth" +) + +func ksSpecKey(label, home string, allowed, write []string) keysetKeySpec { + return keysetKeySpec{Label: label, HomeScope: home, AllowedScopes: allowed, WriteScopes: write} +} + +func TestKeysetShapeBoundsAndLabels(t *testing.T) { + keys := func(n int) []keysetKeySpec { + out := make([]keysetKeySpec, n) + for i := range out { + out[i] = ksSpecKey(fmt.Sprintf("k%02d", i), "a", nil, nil) + } + return out + } + names := func(n int) []string { + out := make([]string, n) + for i := range out { + out[i] = fmt.Sprintf("s%02d", i) + } + return out + } + for _, tc := range []struct { + what string + spec keysetProvisionSpec + want string // substring of the refusal; "" = accepted + }{ + {"64 keys", keysetProvisionSpec{Keys: keys(64)}, ""}, + {"65 keys", keysetProvisionSpec{Keys: keys(65)}, "at most 64 keys"}, + {"64 scopes", keysetProvisionSpec{Scopes: names(64)}, ""}, + {"65 scopes", keysetProvisionSpec{Scopes: names(65)}, "at most 64 scopes"}, + {"empty", keysetProvisionSpec{}, "scopes or keys"}, + {"no label", keysetProvisionSpec{Keys: []keysetKeySpec{ksSpecKey("", "a", nil, nil)}}, "label is required"}, + {"label twice", keysetProvisionSpec{Keys: []keysetKeySpec{ksSpecKey("x", "a", nil, nil), ksSpecKey("x", "b", nil, nil)}}, "named twice"}, + } { + got := checkKeysetShape(tc.spec) + if (tc.want == "") != (got == "") || !strings.Contains(got, tc.want) { + t.Errorf("%s: %q, want %q", tc.what, got, tc.want) + } + } +} + +func TestKeysetNamesResolveToTheTenantsScopes(t *testing.T) { + spec := keysetProvisionSpec{ + Scopes: []string{"k", "members"}, + Keys: []keysetKeySpec{ + ksSpecKey("m", "members", []string{"k", "acme:main"}, []string{"k"}), + {Label: "o", HomeScope: "acme:mods", AllowedScopes: []string{"other:x"}, ScopeNarrowing: auth.ScopeNarrowingRequired, ReplaceLabel: true}, + }, + } + scopes, keys, msg := resolveKeysetNames("acme", spec) + if msg != "" { + t.Fatalf("refused: %s", msg) + } + if got := fmt.Sprint(scopes); got != "[acme:k acme:members]" { + t.Errorf("scopes %s", got) + } + got := fmt.Sprintf("%+v", keys) + want := "[{Label:m HomeScope:acme:members AllowedScopes:[acme:k acme:main] WriteScopes:[acme:k] ScopeNarrowing:optional ReplaceLabel:false} " + + "{Label:o HomeScope:acme:mods AllowedScopes:[other:x] WriteScopes:[] ScopeNarrowing:required ReplaceLabel:true}]" + if got != want { + t.Errorf("keys\n got %s\nwant %s", got, want) + } + + for _, tc := range []struct { + what string + spec keysetProvisionSpec + want string + }{ + {"full name in the scope list", keysetProvisionSpec{Scopes: []string{"acme:k"}}, "scopes[0]"}, + {"scope twice", keysetProvisionSpec{Scopes: []string{"k", "k"}}, "named twice"}, + {"upper case", keysetProvisionSpec{Scopes: []string{"K"}}, "scopes[0]"}, + {"underscore", keysetProvisionSpec{Keys: []keysetKeySpec{ksSpecKey("x", "a_b", nil, nil)}}, "keys[0]"}, + {"no home", keysetProvisionSpec{Keys: []keysetKeySpec{ksSpecKey("x", "", nil, nil)}}, "keys[0]"}, + {"reserved", keysetProvisionSpec{Keys: []keysetKeySpec{ksSpecKey("x", "_global", nil, nil)}}, "keys[0]"}, + {"bad allowed", keysetProvisionSpec{Keys: []keysetKeySpec{ksSpecKey("x", "a", []string{"B"}, nil)}}, "keys[0]"}, + {"bad write", keysetProvisionSpec{Keys: []keysetKeySpec{ksSpecKey("x", "a", []string{"a"}, []string{"-a"})}}, "keys[0]"}, + } { + if _, _, msg := resolveKeysetNames("acme", tc.spec); !strings.Contains(msg, tc.want) || msg == "" { + t.Errorf("%s: %q, want a refusal naming %q", tc.what, msg, tc.want) + } + } +} diff --git a/go/internal/handler/manage_action_fixture_test.go b/go/internal/handler/manage_action_fixture_test.go index e8d9b3944..7828e0b3c 100644 --- a/go/internal/handler/manage_action_fixture_test.go +++ b/go/internal/handler/manage_action_fixture_test.go @@ -110,6 +110,9 @@ var manageActionFixture = []manageActionFixtureRow{ {"issue-link-delete", "", tierOpen, "handleIssueLinkDelete"}, {"issue-list", "", tierOpen, "handleIssueList"}, {"issue-update", "", tierOpen, "handleIssueUpdate"}, + // Achse 02 C-3: a set of scopes and keys in one transaction — NEW surface, + // tenant-admin with scope-create's and api-key-create's tenant gates. + {"keyset-provision", "", tierTenantAdmin, "handleKeysetProvision"}, {"list-categories", "", tierOpen, "handleListCategories"}, {"list-meta", "", tierOpen, "handleListMeta"}, {"mcp-client-create", "", tierServerAdmin, "handleMCPClientCreate"}, @@ -175,12 +178,13 @@ var manageActionFixture = []manageActionFixtureRow{ {"update", "", tierOpen, "handleUpdate"}, } -// fixtureActionNames is the deduplicated enumeration (116 names: the 89 of the +// fixtureActionNames is the deduplicated enumeration (117 names: the 89 of the // pre-table tree plus the four model alias actions of W02-04, the eight model // consumer actions of W01-5, the three gateway limits actions of W06-15, // model-alias-preview of W05-04, purge of #202, stats-reconcile of #266, the // three forge conflict actions of #509, embed-backfill-release of #236 and -// the five model-recording actions of #575, server-admin only; three actions +// the five model-recording actions of #575, server-admin only, and +// keyset-provision of Achse 02 C-3; three actions // carry two rows for their two data shapes). func fixtureActionNames() map[string]struct{} { names := make(map[string]struct{}, len(manageActionFixture)) @@ -190,14 +194,14 @@ func fixtureActionNames() map[string]struct{} { return names } -// TestManageActionFixture_Shape guards the fixture itself: 116 distinct actions -// in 119 rows, alphabetically ordered so a merge conflict is a real conflict. +// TestManageActionFixture_Shape guards the fixture itself: 117 distinct actions +// in 120 rows, alphabetically ordered so a merge conflict is a real conflict. func TestManageActionFixture_Shape(t *testing.T) { - if got := len(manageActionFixture); got != 119 { - t.Fatalf("fixture rows = %d, want 119 (116 actions, three of them twice)", got) + if got := len(manageActionFixture); got != 120 { + t.Fatalf("fixture rows = %d, want 120 (117 actions, three of them twice)", got) } - if got := len(fixtureActionNames()); got != 116 { - t.Fatalf("fixture actions = %d, want 116", got) + if got := len(fixtureActionNames()); got != 117 { + t.Fatalf("fixture actions = %d, want 117", got) } for i := 1; i < len(manageActionFixture); i++ { if manageActionFixture[i-1].action > manageActionFixture[i].action { diff --git a/go/internal/handler/manage_table.go b/go/internal/handler/manage_table.go index ea73930ab..eb9d2638f 100644 --- a/go/internal/handler/manage_table.go +++ b/go/internal/handler/manage_table.go @@ -148,7 +148,7 @@ func gamingModeTier(req manageRequest) adminTier { return tierOpen } -// manageActions is the dispatch table: 116 actions (89 pre-table + the four model alias actions of W02-04 + the eight model consumer actions of W01-5 + the three gateway limits actions of W06-15 + model-alias-preview of W05-04 + purge of #202 + stats-reconcile of #266 + the three forge conflict actions of #509 + embed-backfill-release of #236 + the five model-recording actions of #575), alphabetical, one row each. +// manageActions is the dispatch table: 117 actions (89 pre-table + the four model alias actions of W02-04 + the eight model consumer actions of W01-5 + the three gateway limits actions of W06-15 + model-alias-preview of W05-04 + purge of #202 + stats-reconcile of #266 + the three forge conflict actions of #509 + embed-backfill-release of #236 + the five model-recording actions of #575 + keyset-provision of Achse 02 C-3), alphabetical, one row each. // // The tiers are the pre-table behaviour, action for action — this wave routes // differently, it does not re-cut permissions. @@ -249,6 +249,9 @@ var manageActions = map[string]manageAction{ "issue-link-delete": {tier: tierOpen, handle: (*ManageHandler).handleIssueLinkDelete}, "issue-list": {tier: tierOpen, handle: (*ManageHandler).handleIssueList}, "issue-update": {tier: tierOpen, handle: (*ManageHandler).handleIssueUpdate}, + // keyset-provision (Achse 02 C-3): scope-create and api-key-create for a + // whole set in one transaction, with both actions' tenant gates. + "keyset-provision": {tier: tierTenantAdmin, handle: (*ManageHandler).handleKeysetProvision}, "list-categories": {tier: tierOpen, handle: dropReq((*ManageHandler).handleListCategories)}, "list-meta": {tier: tierOpen, handle: (*ManageHandler).handleListMeta}, "mcp-client-create": {tier: tierServerAdmin, handle: (*ManageHandler).handleMCPClientCreate}, diff --git a/go/internal/store/keyset.go b/go/internal/store/keyset.go new file mode 100644 index 000000000..e227adc04 --- /dev/null +++ b/go/internal/store/keyset.go @@ -0,0 +1,360 @@ +// Keyset provisioning (Achse 02 C-3, manage action keyset-provision): the +// scopes and the keys of one set — say the groups of one community — created +// in ONE transaction under the tenant row's lock, with the checks scope-create +// and api-key-create make one at a time (the tenant owns every scope a key +// names, max_scopes, max_keys, write_scopes ⊆ allowed_scopes ∪ {home_scope}). +// Either the whole set exists afterwards or nothing of it does. +// +// The store knows no community, no bot and no group: labels, scopes and +// rights come from the caller as they are. The handler resolves the request's +// scope names to full '<slug>:<name>' names of the binding tenant first; this +// file decides only what the tenant row and the rows under it say. +package store + +import ( + "context" + "errors" + "fmt" + "sort" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/pgxdb" +) + +// KeysetKey is one key of a set. Its scopes are full scope names of the +// binding tenant. The key is minted with the role member (like +// api-key-create: a provisioned key administers nothing) and with exactly the +// allowed_scopes and write_scopes named — nil is the empty set here, never the +// default tenant's implicit 'shared'. +type KeysetKey struct { + Label string + HomeScope string + AllowedScopes []string + WriteScopes []string + ScopeNarrowing string // auth.ScopeNarrowingOptional or auth.ScopeNarrowingRequired + // ReplaceLabel deactivates, in the same transaction, the tenant's active + // keys that carry Label, before the set's keys are counted and minted. + ReplaceLabel bool +} + +// KeysetScope is one scope of the set's scope list: created by this call, or +// already the tenant's. +type KeysetScope struct { + Scope string + Created bool +} + +// MintedKey is one key of the set and its plaintext — the only place the +// plaintext exists (only its hash is stored). +type MintedKey struct { + Key ApiKey + Plaintext string +} + +// Keyset is what ProvisionKeyset created: the scope list and the keys, both in +// the order of the call. +type Keyset struct { + Scopes []KeysetScope + Keys []MintedKey +} + +// ErrKeysetScopeOutsideTenant: a scope of the set — in the scope list or +// named by a key — belongs to another tenant, or a key names a scope the +// tenant does not own and the set does not create. Foreign and unknown are +// one answer, so the call is no oracle for other tenants' scopes. +var ErrKeysetScopeOutsideTenant = errors.New("store: not a scope of this tenant") + +// ErrKeysetLabelProtected: replace_label names a label an active owner, admin +// or server-admin key of the tenant carries. The set's keys are member keys; +// replacing such a key would revoke it past the owner rules of api-key-delete +// (only an owner revokes an owner key, never the last one; only a +// server-admin revokes a server-admin key). Refused, whoever calls. +var ErrKeysetLabelProtected = errors.New("store: replace_label names an active key that is not a member key") + +// KeysetRefusal carries which scope or label a refusal is about +// (ErrKeysetScopeOutsideTenant, ErrKeysetLabelProtected) — the caller's own +// input, never another tenant's row. +type KeysetRefusal struct { + Err error + Subject string +} + +func (e *KeysetRefusal) Error() string { return e.Err.Error() + ": " + e.Subject } +func (e *KeysetRefusal) Unwrap() error { return e.Err } + +// KeysetQuotaError: the set would take the tenant past max_scopes or +// max_keys. It unwraps to ErrScopeQuotaExceeded or ErrKeyQuotaExceeded. +// Count is the tenant's count before the set (keys: its active keys after the +// set's replacements), Requested what the set adds. +type KeysetQuotaError struct { + Keys bool // false: max_scopes, true: max_keys + Limit int + Count int + Requested int +} + +func (e *KeysetQuotaError) Error() string { + return fmt.Sprintf("%v: limit %d, count %d, requested %d", e.Unwrap(), e.Limit, e.Count, e.Requested) +} + +func (e *KeysetQuotaError) Unwrap() error { + if e.Keys { + return ErrKeyQuotaExceeded + } + return ErrScopeQuotaExceeded +} + +// ProvisionKeyset creates the missing scopes of scopes, then the keys of keys, +// for tenantID in one transaction (Achse 02 C-3): +// +// 1. Lock the tenant row (FOR UPDATE — the lock every scope and key write of +// the tenant takes first: AssignTenantScopeTx, MintKeyWithQuota, +// UpdateApiKey, DeleteApiKey) and read status, max_scopes and max_keys +// from it under the lock. Absent ⇒ ErrTenantNotFound, offboarding ⇒ +// ErrTenantOffboarding. +// 2. Every scope of the list is the tenant's (kept) or nobody's (created); +// every scope a key names is the tenant's or created by the set +// (ErrKeysetScopeOutsideTenant otherwise). The tenant's scope count plus +// the new ones may not pass max_scopes (KeysetQuotaError). The new +// scopes' groups of migration 176 are locked in sorted order before the +// one INSERT of all of them. +// 3. replace_label: the tenant's active keys with a replaced label are +// deactivated — all member keys, or ErrKeysetLabelProtected. +// 4. The tenant's active keys (after 3) plus the set may not pass max_keys. +// 5. Each key through insertApiKeyTx, the one INSERT path of a key: its own +// principal, role member, the audit row of the stamp. +// +// Every value a decision reads is read after the lock, in a statement of its +// own (READ COMMITTED: a write that held the lock is seen). A failure anywhere +// — a refusal of steps 2 to 4, a key insertApiKeyTx refuses (write_scopes ⊄ +// allowed_scopes ∪ {home_scope}, a scope_narrowing other than optional and +// required), a database error — rolls the whole set back. +func ProvisionKeyset(ctx context.Context, pool *pgxpool.Pool, tenantID string, scopes []string, keys []KeysetKey, stamp AuditStamp) (Keyset, error) { + var out Keyset + err := pgxdb.Write(ctx, pool, + pgxdb.Stages{Begin: "store: keyset begin", Commit: "store: keyset commit"}, + func(tx pgx.Tx) error { + maxScopes, maxKeys, err := lockKeysetTenant(ctx, tx, tenantID) + if err != nil { + return err + } + if err := stampAudit(ctx, tx, stamp); err != nil { + return err + } + listed, err := keysetScopesTx(ctx, tx, tenantID, scopes, keys, maxScopes) + if err != nil { + return err + } + if err := keysetReplaceTx(ctx, tx, tenantID, keys); err != nil { + return err + } + if err := keysetKeyQuotaTx(ctx, tx, tenantID, len(keys), maxKeys); err != nil { + return err + } + minted := make([]MintedKey, 0, len(keys)) + for i, k := range keys { + key, plain, err := insertApiKeyTx(ctx, tx, k.Label, k.HomeScope, + nonNilScopes(k.AllowedScopes), nonNilScopes(k.WriteScopes), tenantID, "member", k.ScopeNarrowing) + if err != nil { + // The index, not the label: a failure line names no + // value of the request (adminWriteFailed). + return fmt.Errorf("keys[%d]: %w", i, err) + } + minted = append(minted, MintedKey{Key: key, Plaintext: plain}) + } + out = Keyset{Scopes: listed, Keys: minted} + return nil + }) + if err != nil { + return Keyset{}, err + } + return out, nil +} + +// nonNilScopes turns nil into the empty set, so insertApiKeyTx stores exactly +// what the set names (its nil means "the default tenant's {shared}"). +func nonNilScopes(s []string) []string { + if s == nil { + return []string{} + } + return s +} + +// lockKeysetTenant takes the tenant row's lock and reads, under it, what the +// set is decided on: the status and both structural limits (nil = unlimited). +func lockKeysetTenant(ctx context.Context, tx pgx.Tx, tenantID string) (maxScopes, maxKeys *int, err error) { + var status string + if err = tx.QueryRow(ctx, + `SELECT status, max_scopes, max_keys FROM context_tenants WHERE id = $1::uuid FOR UPDATE`, + tenantID).Scan(&status, &maxScopes, &maxKeys); err != nil { + if pgxdb.AbsentOrMalformed(err) { + return nil, nil, ErrTenantNotFound + } + return nil, nil, fmt.Errorf("store: keyset tenant lock: %w", err) + } + // A tenant whose delete has begun takes no scope and no key (issue #555, + // the rule of AssignTenantScopeTx): the row lock waits for the delete's + // mark, so this is the status the delete acts on. + if status == tenantStatusOffboarding { + return nil, nil, ErrTenantOffboarding + } + return maxScopes, maxKeys, nil +} + +// embedExcludedGroupLockSQL is the exclusive advisory lock of one embed_excluded +// group, the key migration 176 hashes ('ctx:embed_excluded:grp:' || group). +const embedExcludedGroupLockSQL = `SELECT pg_advisory_xact_lock(hashtext('ctx:embed_excluded:grp:' || $1::text))` + +// keysetScopesTx decides the set's scopes under the tenant lock and creates +// the missing ones of the list: one lookup of every scope the set names, one +// count against max_scopes when the set adds any, one INSERT of all new ones. +func keysetScopesTx(ctx context.Context, tx pgx.Tx, tenantID string, scopes []string, keys []KeysetKey, maxScopes *int) ([]KeysetScope, error) { + named := append([]string(nil), scopes...) + for _, k := range keys { + named = append(named, k.HomeScope) + named = append(named, k.AllowedScopes...) + named = append(named, k.WriteScopes...) + } + owner := make(map[string]bool, len(named)) // scope → owned by tenantID + rows, err := tx.Query(ctx, + `SELECT scope, tenant_id = $2::uuid FROM context_tenant_scopes WHERE scope = ANY($1::text[])`, + named, tenantID) + if err != nil { + return nil, fmt.Errorf("store: keyset scope lookup: %w", err) + } + for rows.Next() { + var ( + s string + own bool + ) + if err := rows.Scan(&s, &own); err != nil { + rows.Close() + return nil, fmt.Errorf("store: keyset scope lookup: %w", err) + } + owner[s] = own + } + rows.Close() + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("store: keyset scope lookup: %w", err) + } + + listed := make([]KeysetScope, 0, len(scopes)) + var create []string + creates := make(map[string]bool, len(scopes)) + for _, s := range scopes { + own, exists := owner[s] + switch { + case exists && own: + listed = append(listed, KeysetScope{Scope: s}) + case exists: + return nil, &KeysetRefusal{Err: ErrKeysetScopeOutsideTenant, Subject: s} + default: + listed = append(listed, KeysetScope{Scope: s, Created: true}) + create = append(create, s) + creates[s] = true + } + } + for _, s := range named[len(scopes):] { + if !owner[s] && !creates[s] { + return nil, &KeysetRefusal{Err: ErrKeysetScopeOutsideTenant, Subject: s} + } + } + if len(create) == 0 { + return listed, nil + } + if maxScopes != nil { + var cnt int + if err := tx.QueryRow(ctx, + `SELECT count(*) FROM context_tenant_scopes WHERE tenant_id = $1::uuid`, tenantID).Scan(&cnt); err != nil { + return nil, fmt.Errorf("store: keyset scope count: %w", err) + } + if cnt+len(create) > *maxScopes { + return nil, &KeysetQuotaError{Limit: *maxScopes, Count: cnt, Requested: len(create)} + } + } + // Assigning a scope fires the trigger of migration 176 + // (context_tenant_scopes_embed_excluded), which takes the advisory locks + // of the row's groups — 's:<scope>' and 't:<tenant>' — in sorted order, + // the one order every writer of these groups keeps. Row by row, a set + // would take 's:<second scope>' after 't:<tenant>', against that order, + // and deadlock with a transaction that holds 's:<second scope>' and waits + // for 't:<tenant>' (40P01, TestKeysetTakesTheScopeGroupsInOrder). So the + // groups of all new scopes are taken here first, in sorted order; the + // trigger finds them held and takes 't:<tenant>' after them. + groups := make([]string, len(create)) + for i, s := range create { + groups[i] = "s:" + s + } + sort.Strings(groups) + b := &pgx.Batch{} + for _, g := range groups { + b.Queue(embedExcludedGroupLockSQL, g) + } + if err := tx.SendBatch(ctx, b).Close(); err != nil { + return nil, fmt.Errorf("store: keyset scope group locks: %w", err) + } + if _, err := tx.Exec(ctx, + `INSERT INTO context_tenant_scopes (scope, tenant_id) SELECT s, $2::uuid FROM unnest($1::text[]) AS s`, + create, tenantID); err != nil { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "23505" { + return nil, ErrScopeExists // unreachable under the lock but for a scope of no tenant's prefix + } + return nil, fmt.Errorf("store: keyset scope insert: %w", err) + } + return listed, nil +} + +// keysetReplaceTx deactivates the tenant's active keys whose label a key of +// the set replaces (replace_label), after checking under the tenant lock that +// each of them is a member key that is no server-admin key. +func keysetReplaceTx(ctx context.Context, tx pgx.Tx, tenantID string, keys []KeysetKey) error { + var labels []string + for _, k := range keys { + if k.ReplaceLabel { + labels = append(labels, k.Label) + } + } + if len(labels) == 0 { + return nil + } + var protected *string + if err := tx.QueryRow(ctx, + `SELECT min(label) FROM context_api_keys + WHERE tenant_id = $1::uuid AND active AND label = ANY($2::text[]) + AND (tenant_role <> 'member' OR is_admin)`, + tenantID, labels).Scan(&protected); err != nil { + return fmt.Errorf("store: keyset replace check: %w", err) + } + if protected != nil { + return &KeysetRefusal{Err: ErrKeysetLabelProtected, Subject: *protected} + } + if _, err := tx.Exec(ctx, + `UPDATE context_api_keys SET active = false, updated_at = now() + WHERE tenant_id = $1::uuid AND active AND label = ANY($2::text[])`, + tenantID, labels); err != nil { + return fmt.Errorf("store: keyset replace: %w", err) + } + return nil +} + +// keysetKeyQuotaTx counts the tenant's active keys under the lock (after the +// set's replacements, which it sees in this statement's snapshot) and refuses +// a set that would pass max_keys — the active-only count of MintKeyWithQuota. +func keysetKeyQuotaTx(ctx context.Context, tx pgx.Tx, tenantID string, n int, maxKeys *int) error { + if maxKeys == nil || n == 0 { + return nil + } + var cnt int + if err := tx.QueryRow(ctx, + `SELECT count(*) FROM context_api_keys WHERE tenant_id = $1::uuid AND active = true`, tenantID).Scan(&cnt); err != nil { + return fmt.Errorf("store: keyset key count: %w", err) + } + if cnt+n > *maxKeys { + return &KeysetQuotaError{Keys: true, Limit: *maxKeys, Count: cnt, Requested: n} + } + return nil +} diff --git a/go/internal/store/keyset_integration_test.go b/go/internal/store/keyset_integration_test.go new file mode 100644 index 000000000..4d7b51a81 --- /dev/null +++ b/go/internal/store/keyset_integration_test.go @@ -0,0 +1,372 @@ +//go:build integration + +// ProvisionKeyset (Achse 02 C-3) under concurrent writes of the same tenant +// (Präambel 9a): every value the set is decided on — max_scopes, max_keys, +// the tenant's scopes, the role of a key replace_label would deactivate — is +// read after the tenant row lock that every scope and key write of the tenant +// takes first. Each interleaving test holds that lock on a second connection, +// changes the value there, starts ProvisionKeyset (which waits for the +// lock), commits, and checks the set was decided on the committed value. Two +// concurrent sets with replace_label on one label end with one active key. +// The cost test logs what a set of 64 scopes and 64 keys takes. +// +// go test -tags=integration -p 1 -count=1 -v -run 'TestKeyset' ./internal/store/ +package store_test + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" +) + +func ksScope(t *testing.T, pool *pgxpool.Pool, scope, tid string) { + t.Helper() + if _, err := pool.Exec(context.Background(), `INSERT INTO context_tenant_scopes (scope, tenant_id) VALUES ($1, $2::uuid)`, scope, tid); err != nil { + t.Fatalf("seed scope %s: %v", scope, err) + } +} + +func ksActive(t *testing.T, pool *pgxpool.Pool, tid, label string) int { + t.Helper() + var n int + if err := pool.QueryRow(context.Background(), + `SELECT count(*) FROM context_api_keys WHERE tenant_id = $1::uuid AND label = $2 AND active`, tid, label).Scan(&n); err != nil { + t.Fatal(err) + } + return n +} + +func ksKey(label, home string, replace bool) store.KeysetKey { + return store.KeysetKey{Label: label, HomeScope: home, ScopeNarrowing: "required", ReplaceLabel: replace} +} + +// TestKeysetReadsTheLimitUnderTheLock: max_keys drops to 0 while the set +// waits for the tenant lock. Read before the lock, the old limit (50) would +// let the key through; read under it, the set is refused and nothing exists. +func TestKeysetReadsTheLimitUnderTheLock(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + tid := freshTenant(t, ctx, pool, "ks-lim") + err := ownerInterleave(ctx, t, pool, tid, + func(tx pgx.Tx) { + if _, err := tx.Exec(ctx, `UPDATE context_tenants SET max_keys = 0 WHERE id = $1::uuid`, tid); err != nil { + t.Fatal(err) + } + }, + func() error { + _, err := store.ProvisionKeyset(ctx, pool, tid, []string{"ks-lim:a"}, []store.KeysetKey{ksKey("ks-lim-k", "ks-lim:a", false)}, store.AuditStamp{}) + return err + }) + var qe *store.KeysetQuotaError + if !errors.As(err, &qe) || !qe.Keys || qe.Limit != 0 || !errors.Is(err, store.ErrKeyQuotaExceeded) { + t.Errorf("max_keys 0 committed while the set waited: err %v, want the key quota refusal with limit 0", err) + } + var scopes int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM context_tenant_scopes WHERE tenant_id = $1::uuid`, tid).Scan(&scopes); err != nil || scopes != 0 { + t.Errorf("the refused set left %d scope(s) (err %v)", scopes, err) + } + if n := ksActive(t, pool, tid, "ks-lim-k"); n != 0 { + t.Errorf("the refused set left %d key(s)", n) + } +} + +// TestKeysetReplaceDecidesOnTheRoleUnderTheLock: the member key that +// replace_label names is promoted to admin while the set waits for the lock. +// Read before the lock it is a member key and would be deactivated; read under +// it, it is an admin key and the set is refused. +func TestKeysetReplaceDecidesOnTheRoleUnderTheLock(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + tid := freshTenant(t, ctx, pool, "ks-rol") + ksScope(t, pool, "ks-rol:a", tid) + id := seedKeyRole(t, pool, "ks-rol-label", tid, "member", true) + err := ownerInterleave(ctx, t, pool, tid, + func(tx pgx.Tx) { + if _, err := tx.Exec(ctx, `UPDATE context_api_keys SET tenant_role = 'admin' WHERE id = $1::uuid`, id); err != nil { + t.Fatal(err) + } + }, + func() error { + _, err := store.ProvisionKeyset(ctx, pool, tid, nil, []store.KeysetKey{ksKey("ks-rol-label", "ks-rol:a", true)}, store.AuditStamp{}) + return err + }) + var ref *store.KeysetRefusal + if !errors.Is(err, store.ErrKeysetLabelProtected) || !errors.As(err, &ref) || ref.Subject != "ks-rol-label" { + t.Errorf("replace_label on a key promoted to admin while the set waited: err %v, want ErrKeysetLabelProtected naming the label", err) + } + if role, active := keyRoleActive(t, pool, id); role != "admin" || !active { + t.Errorf("the admin key: role %s active %v, want admin and active", role, active) + } + if n := ksActive(t, pool, tid, "ks-rol-label"); n != 1 { + t.Errorf("%d active key(s) with the label, want the admin key alone", n) + } +} + +// TestKeysetSeesAScopeCreatedMeanwhile: a scope-create of the same tenant +// commits the set's scope while the set waits for the lock. Looked up under +// the lock, the scope is the tenant's and kept (created=false); looked up +// before it, the set would insert it again and fail. +func TestKeysetSeesAScopeCreatedMeanwhile(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + tid := freshTenant(t, ctx, pool, "ks-mw") + var set store.Keyset + err := ownerInterleave(ctx, t, pool, tid, + func(tx pgx.Tx) { + if _, err := tx.Exec(ctx, `INSERT INTO context_tenant_scopes (scope, tenant_id) VALUES ('ks-mw:a', $1::uuid)`, tid); err != nil { + t.Fatal(err) + } + }, + func() error { + var err error + set, err = store.ProvisionKeyset(ctx, pool, tid, []string{"ks-mw:a", "ks-mw:b"}, []store.KeysetKey{ksKey("ks-mw-k", "ks-mw:a", false)}, store.AuditStamp{}) + return err + }) + if err != nil { + t.Fatalf("set after a concurrent scope-create of one of its scopes: %v", err) + } + if got := fmt.Sprint(set.Scopes); got != "[{ks-mw:a false} {ks-mw:b true}]" { + t.Errorf("scopes %s, want ks-mw:a kept and ks-mw:b created", got) + } +} + +// TestKeysetRefusesWhatIsNotTheTenants: the scope list names a scope another +// tenant holds (a row with this tenant's prefix assigned elsewhere — no API +// writes one, a hand edit or an old deployment can), and replace_label names +// the label of a server-admin key that holds the member role. Both refuse +// the whole set; the foreign scope keeps its tenant, the server-admin key +// stays active, and nothing of the set exists. +func TestKeysetRefusesWhatIsNotTheTenants(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + tid := freshTenant(t, ctx, pool, "ks-own") + other := freshTenant(t, ctx, pool, "ks-other") + ksScope(t, pool, "ks-own:main", tid) + ksScope(t, pool, "ks-own:legacy", other) + + _, err := store.ProvisionKeyset(ctx, pool, tid, []string{"ks-own:new", "ks-own:legacy"}, nil, store.AuditStamp{}) + var ref *store.KeysetRefusal + if !errors.Is(err, store.ErrKeysetScopeOutsideTenant) || !errors.As(err, &ref) || ref.Subject != "ks-own:legacy" { + t.Errorf("scope list with another tenant's scope: err %v, want ErrKeysetScopeOutsideTenant naming it", err) + } + var owner string + if err := pool.QueryRow(ctx, `SELECT tenant_id::text FROM context_tenant_scopes WHERE scope = 'ks-own:legacy'`).Scan(&owner); err != nil || owner != other { + t.Errorf("ks-own:legacy belongs to %s (err %v), want the other tenant", owner, err) + } + + // A key naming a scope no tenant holds — another prefix, or the tenant's + // own prefix that the set does not create — gets the same refusal as a + // foreign one: such a key would read the scope once someone registers it. + for _, unknown := range []string{"ks-nobody:main", "ks-own:ghost"} { + _, err = store.ProvisionKeyset(ctx, pool, tid, []string{"ks-own:new"}, + []store.KeysetKey{{Label: "ks-own-unknown", HomeScope: "ks-own:new", AllowedScopes: []string{unknown}, ScopeNarrowing: "required"}}, store.AuditStamp{}) + if !errors.Is(err, store.ErrKeysetScopeOutsideTenant) || !errors.As(err, &ref) || ref.Subject != unknown { + t.Errorf("a key naming %s, a scope no tenant holds: err %v, want ErrKeysetScopeOutsideTenant naming it", unknown, err) + } + } + + admin := seedKeyRole(t, pool, "ks-own-srv", tid, "member", true) + if _, err := pool.Exec(ctx, `UPDATE context_api_keys SET is_admin = true WHERE id = $1::uuid`, admin); err != nil { + t.Fatal(err) + } + _, err = store.ProvisionKeyset(ctx, pool, tid, []string{"ks-own:new"}, []store.KeysetKey{ksKey("ks-own-srv", "ks-own:new", true)}, store.AuditStamp{}) + if !errors.Is(err, store.ErrKeysetLabelProtected) { + t.Errorf("replace_label on a server-admin key with the member role: err %v, want ErrKeysetLabelProtected", err) + } + if _, active := keyRoleActive(t, pool, admin); !active { + t.Error("the server-admin key was deactivated") + } + var n int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM context_tenant_scopes WHERE scope = 'ks-own:new'`).Scan(&n); err != nil || n != 0 { + t.Errorf("the refused sets left ks-own:new behind (%d, err %v)", n, err) + } + + if _, err := store.ProvisionKeyset(ctx, pool, tid, []string{"ks-own:new"}, []store.KeysetKey{ksKey("ks-own-k", "ks-own:new", true)}, store.AuditStamp{}); err != nil { + t.Errorf("control: a set of the tenant's own: %v", err) + } +} + +// TestKeysetTakesTheScopeGroupsInOrder: assigning a scope fires the trigger +// of migration 176, which takes the advisory locks of the row's groups +// ('s:<scope>', 't:<tenant>') in sorted order — the one order every writer +// of these groups keeps. A set assigns several scopes in one transaction. +// Here another transaction holds the group of the set's second scope and, +// while the set waits for it, asks for the tenant's group: taken in row +// order the set would already hold 't:<tenant>' and the two would deadlock +// (40P01 for one of them); taken all in sorted order first, the set waits for +// 's:' before it takes 't:' and both commit. +func TestKeysetTakesTheScopeGroupsInOrder(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + tid := freshTenant(t, ctx, pool, "ks-grp") + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock_shared(hashtext('ctx:embed_excluded:grp:' || $1))`, "s:ks-grp:b"); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + _, err := store.ProvisionKeyset(ctx, pool, tid, []string{"ks-grp:a", "ks-grp:b"}, nil, store.AuditStamp{}) + done <- err + }() + deadline := time.Now().Add(5 * time.Second) + for { + var waiting int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM pg_stat_activity + WHERE datname = current_database() AND wait_event = 'advisory' AND pid <> pg_backend_pid()`).Scan(&waiting); err != nil { + t.Fatal(err) + } + if waiting > 0 { + break + } + if time.Now().After(deadline) { + t.Fatal("the set never waited for the group the other transaction holds") + } + time.Sleep(10 * time.Millisecond) + } + if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock_shared(hashtext('ctx:embed_excluded:grp:' || $1))`, "t:"+tid); err != nil { + t.Errorf("the other transaction asks for the tenant's group while the set waits: %v, want it granted", err) + } + if err := tx.Commit(ctx); err != nil { + t.Errorf("commit of the other transaction: %v", err) + } + if err := <-done; err != nil { + t.Errorf("the set: %v, want it committed after the other transaction", err) + } +} + +// TestKeysetDefaultTenantKeyHasNoImplicitShared: insertApiKeyTx gives a key +// of the default tenant without allowed_scopes the 'shared' scope; a set's +// key with none named gets none, and no write scope either. +func TestKeysetDefaultTenantKeyHasNoImplicitShared(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + set, err := store.ProvisionKeyset(ctx, pool, store.DefaultTenantID, []string{"default:ks-grp"}, + []store.KeysetKey{ksKey("ks-default-grp", "default:ks-grp", false)}, store.AuditStamp{}) + if err != nil { + t.Fatalf("set in the default tenant: %v", err) + } + var allowed, write []string + if err := pool.QueryRow(ctx, `SELECT allowed_scopes, write_scopes FROM context_api_keys WHERE id = $1::uuid`, set.Keys[0].Key.ID).Scan(&allowed, &write); err != nil { + t.Fatal(err) + } + if len(allowed) != 0 || len(write) != 0 { + t.Errorf("the set's key: allowed_scopes %v write_scopes %v, want both empty", allowed, write) + } +} + +// TestKeysetConcurrentReplacementsLeaveOneActiveKey: two callers provision +// the same label with replace_label at the same time, round after round. +// Serialised by the tenant lock, every round ends with exactly one active key +// of that label — the promise access provision's retry rests on (E4 takes +// any active key of its label). Without the lock the second UPDATE would not +// see the first set's new key and both would stay active. +func TestKeysetConcurrentReplacementsLeaveOneActiveKey(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + tid := freshTenant(t, ctx, pool, "ks-race") + ksScope(t, pool, "ks-race:a", tid) + if _, err := pool.Exec(ctx, `UPDATE context_tenants SET max_keys = NULL WHERE id = $1::uuid`, tid); err != nil { + t.Fatal(err) + } + const label = "ks-race-label" + for round := range 12 { + var wg sync.WaitGroup + start := make(chan struct{}) + errs := make([]error, 2) + for i := range errs { + wg.Add(1) + go func() { + defer wg.Done() + <-start + _, errs[i] = store.ProvisionKeyset(ctx, pool, tid, nil, []store.KeysetKey{ksKey(label, "ks-race:a", true)}, store.AuditStamp{}) + }() + } + close(start) + wg.Wait() + for i, err := range errs { + if err != nil { + t.Fatalf("round %d caller %d: %v", round, i, err) + } + } + if n := ksActive(t, pool, tid, label); n != 1 { + t.Fatalf("round %d: %d active key(s) with the label, want 1", round, n) + } + } +} + +// TestKeysetSixtyFourCost logs what the largest set costs (64 new scopes, 64 +// keys with replace_label) in a tenant that already holds many keys and +// scopes (the scope trigger of migration 176 reads the tenant's scopes per +// assigned row), and the same set again (64 replacements): the time the +// tenant lock is held, and the plan of the replacement. A measurement, not a +// pin. +func TestKeysetSixtyFourCost(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + tid := freshTenant(t, ctx, pool, "ks-cost") + if _, err := pool.Exec(ctx, `UPDATE context_tenants SET max_scopes = NULL, max_keys = NULL WHERE id = $1::uuid`, tid); err != nil { + t.Fatal(err) + } + ksScope(t, pool, "ks-cost:main", tid) + const others = 20000 + if _, err := pool.Exec(ctx, ` + WITH p AS (INSERT INTO context_principals (display_name) + SELECT 'ks-cost-other-' || g FROM generate_series(1, $2::int) g RETURNING id, display_name) + INSERT INTO context_api_keys (key_hash, label, home_scope, tenant_id, principal_id) + SELECT 'ks-cost-hash-' || p.display_name, p.display_name, 'ks-cost:main', $1::uuid, p.id FROM p`, tid, others); err != nil { + t.Fatalf("seed %d keys: %v", others, err) + } + const otherScopes = 2000 + if _, err := pool.Exec(ctx, `INSERT INTO context_tenant_scopes (scope, tenant_id) + SELECT 'ks-cost:o' || g, $1::uuid FROM generate_series(1, $2::int) g`, tid, otherScopes); err != nil { + t.Fatalf("seed %d scopes: %v", otherScopes, err) + } + if _, err := pool.Exec(ctx, `ANALYZE context_api_keys; ANALYZE context_tenant_scopes`); err != nil { + t.Fatal(err) + } + rows, err := pool.Query(ctx, `EXPLAIN UPDATE context_api_keys SET active = false, updated_at = now() + WHERE tenant_id = $1::uuid AND active AND label = ANY($2::text[])`, tid, []string{"hermes:discord:1000:g00"}) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var line string + if err := rows.Scan(&line); err != nil { + t.Fatal(err) + } + t.Logf("plan of the replacement: %s", line) + } + rows.Close() + scopes := make([]string, 64) + keys := make([]store.KeysetKey, 64) + for i := range scopes { + scopes[i] = fmt.Sprintf("ks-cost:g%02d", i) + keys[i] = store.KeysetKey{Label: fmt.Sprintf("hermes:discord:%d:g%02d", 1000+i, i), HomeScope: scopes[i], + AllowedScopes: []string{"ks-cost:main"}, ScopeNarrowing: "required", ReplaceLabel: true} + } + for _, run := range []string{"first (64 scopes created, nothing replaced)", "again (64 scopes kept, 64 keys replaced)"} { + t0 := time.Now() + set, err := store.ProvisionKeyset(ctx, pool, tid, scopes, keys, store.AuditStamp{}) + if err != nil { + t.Fatalf("%s: %v", run, err) + } + t.Logf("keyset of 64 scopes and 64 keys, tenant with %d other keys and %d other scopes, %s: %v (%d keys)", others, otherScopes, run, time.Since(t0), len(set.Keys)) + } + var active int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM context_api_keys WHERE tenant_id = $1::uuid AND active AND label LIKE 'hermes:%'`, tid).Scan(&active); err != nil || active != 64 { + t.Errorf("%d active set keys after the second run (err %v), want 64", active, err) + } +} From 94a5288304efc2cdf8ad97786dc912864122c822 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 05:09:33 +0100 Subject: [PATCH 07/15] feat(auth): keyset-provision mints its keys with required scope narrowing unless the call names optional MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The action exists for the keys of restricted groups (design §7.3 C-3: keys with required and a label), so a key whose scope_narrowing the call leaves out — absent or empty — is now minted required: unnarrowed it answers nothing but whoami. optional is minted only when the call names it; api-key-create keeps optional as its default. The set's keys are member keys, so the owner rule of migration 198 (required on an owner key takes its administration) does not apply to them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/api.md | 2 +- docs/multi-tenancy.md | 4 +- ...yset_provision_c3_more_integration_test.go | 41 +++++++++++++++---- go/internal/handler/keyset_provision.go | 7 +++- go/internal/handler/keyset_provision_test.go | 2 +- 5 files changed, 43 insertions(+), 13 deletions(-) diff --git a/docs/api.md b/docs/api.md index 565d3eace..91d8b621f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -87,7 +87,7 @@ PostgreSQL stores a NUL character (U+0000) neither in text nor in JSON, so no va - **Backfill memo release (issue #236):** `embed-backfill-release` (tierTenantAdmin) drops regular embed-backfill failure memos (`context_embed_failures` rows with `migration_id` NULL) so the backfill takes their blocks again — after `embed_backfill.max_tokens` was raised, the embed backend moved to a larger context, or a backend outage ended; without it a parked block came back only through a change of its title or content. `data`: exactly one of `block_id` (a UUID) or `class` (`wire` or `oversize`), optional `limit` (the page size, at most and by default `1000`; a larger value is clamped), and `confirm_memos` together with `as_of`; unknown fields, a second selector, another class, a malformed id, a negative number and a `confirm_memos` without `as_of` (or the reverse) are `400`. A `caller_timeout` memo is never taken, not even by `block_id`: it is no park — the background arm takes such a block at once, and with the arm off the query path retries it after its hold —, and deleting it would hand the block back to the requests' `sync_budget` with its attempts restarted. A tenant-admin reaches the memos of blocks in its own tenant's scopes (a scope or a block granted to the tenant is not its own) — another tenant's block and an unknown one answer the same `counted: 0`; a server-admin reaches every memo; a key without an admin role is `403`. A re-embed migration's memos are never touched. **Without `confirm_memos` the call is a dry run** answering `{action, success, dry_run: true, as_of, counted, confirm_memos, held}` (and `held_until` when `held` is above 0); the real call sends `confirm_memos` and `as_of` of that answer, takes only the memos that were there when the dry run counted (a memo written after `as_of` — a released block that was parked again, a new park — is neither counted nor released, so paging ends), counts them again and releases only when the number is unchanged (otherwise `409` with the fresh `counted` and `confirm_memos`, and the `as_of` the call sent), releases at most `limit` of them — the count and the release decide which memos the reader may release at one instant (one transaction, issue #536), so a hold that ends between the two neither counts nor releases its memo in that call — and answers `{action, success, dry_run: false, as_of, counted, released, remaining, confirm_memos, held}` — `remaining` (and `confirm_memos`, the number to confirm for the next page with the same `as_of`) is what is left of them, including a memo another transaction held at that moment, which the release skips instead of waiting for. Two releases of the same memos at once each count what both may take: one of them releases fewer than it counted and answers a `remaining` the other has already released, and its next page answers `409` with the fresh count. Only memos that keep a block out of the pick (`next_attempt_at` in the future) count. **A server-admin's release deletes the memo; a tenant-admin's keeps it and makes it due**, with its attempts and with the time of the release in `first_seen`, so a block the backend still cannot take is parked again on the same row. A tenant-admin releases such an `oversize` memo again (more than one attempt) only once `embed_backfill.release_hold` × 2^(attempts − 2) has passed since that release, at most `embed_backfill.backoff_cap` (defaults 1 h and 24 h; a cap of 0 sets none; the hold must be above 0, V70); until then it is answered in `held`, with the earliest end in `held_until`. Without the hold a tenant-admin releasing its blocks in a loop while they kept not fitting took one turn of the background arm in every round of the tenants for good, where its way back without the action, an edit per block, costs a write each. The first release of every memo is not held, a `wire` memo is not held (its failure holds the tenant in the arm for `embed_backfill.interval`, and its next failure backs off longer, since the attempts stay), and a server-admin's release and a change of the block's title or content (which deletes the memo) start the count again. For a tenant-admin the count and the page of a class read the tenant's own scopes and their pending blocks, so their cost grows with the tenant's pending blocks, not with other tenants' memos. The next backfill pick of each released block embeds it when it fits now and parks it again after one attempt when it does not. CLI: `ctx admin embed-backfill release --class oversize`, then the same with `--confirm N --as-of T`; `--limit N` is sent as given, so a negative one is answered with the `400` (until issue #536 the CLI left a `--limit` of 0 or below out of the request and the server paged by its maximum). Operator notes in [operations](operations.md#embedding-backend-tuning-cpu-llamacpp), paragraph "Backfill failure memo". - **Block counters (issue #266):** `stats`, `guard-stats` and `list-categories` read per-scope counters that triggers on `context_blocks` keep with every write (migration 170), and so do the per-scope block counts of `scope-overview` (issue #271); the answers are unchanged. `guard-stats`' `pending_count` and `dirty_since` are counted on demand since migration 181: the blocks of the caller's read scopes the guard still has to check, and the oldest `updated_at` among them (`null` when none waits) — before 181 a global count of block writes since the last guard run, the same for every key ([operations](operations.md#migration-181-no-block-writer-waits-on-the-guards-state-row-guard-stats-counts-the-waiting-blocks)). `stats-reconcile` (server-admin) recounts and corrects them: `data` `{}` reconciles every scope, `{"scope": "<scope>"}` one; any other field is a `400`. It answers `{action, success, scopes, corrections, corrections_total, pruned, failed}` — `corrections` lists the corrected keys as `{scope, category, is_archived, guard_status, counted, actual}`, at most the first 1 000 of the pass, and `corrections_total` counts all of them (every one is corrected and logged; issue #271), `pruned` the folded counter rows at 0 it removed, `failed` the scopes whose reconcile failed (the pass goes on with the others; then `success` is `false` and the status `500`). The scheduler runs the same pass on `scheduler.block_count_reconcile_interval` — see [operations](operations.md#migration-170-block-counters-behind-stats-guard-stats-and-list-categories). - **Keys/clients:** `api-key-create` requires `home_scope`; key + MCP-client management and mutating `dream-mode` require an **admin key** since migration 052 (see [security](security.md#admin-tier)). `api-key-create`/`api-key-update` accept optional `write_scopes` (078, E4b) — explicit per-key write scopes that must be ⊆ `allowed_scopes ∪ {home_scope}` (else 400); the effective block-write gate and its double enforcement are in [multi-tenancy](multi-tenancy.md#per-key-write-scopes-e4b-migration-078). They also accept `scope_narrowing` (migration 198): `required` makes the key answer every request without a [narrowing](#scope-narrowing-per-request) with `403 scope_narrowing_required`, `GET /api/whoami` excepted; `optional` (every existing key, the default) keeps today's behaviour; any other value is 400. Both answers carry the value; `api-key-list` lists it. Per-tenant scoping of the `api-key-*` actions and the tenant lifecycle (`tenant-*`, `tenant-grant-*`, `scope-*`, `tenant-limit-set`, `tenant-usage-get`, `tenant-quota-*`, `block-grant-*`) are in [multi-tenancy](multi-tenancy.md). -- **Key sets:** `keyset-provision` (tenant-admin, in the caller's own tenant; a server-admin may name `tenant_id`, anyone else naming it gets 403) creates the scopes and the keys of one set — say the groups of one community — in one transaction: either the whole set exists afterwards or nothing of it does. `data`: `scopes` (at most 64 bare scope names, scope-create's rule; the server puts the tenant's `<slug>:` in front; a scope the tenant already has is kept) and `keys` (at most 64, each `{label, home_scope, allowed_scopes, write_scopes, scope_narrowing, replace_label}`; a key's scope is a bare name or a full `<slug>:<name>` and must be the tenant's own or one the set creates; a name without `:` always gets the prefix, so scopes outside that form — the default tenant's `private`, `work` and `shared` — cannot be named). The answer lists `scopes` as `{scope, created}` and `keys` as `{id, label, home_scope, allowed_scopes, write_scopes, scope_narrowing, api_key}`, both in the order of the call; each `api_key` (the plaintext) is in this answer only. Every key is a `member` key with exactly the scopes it names (no implicit `shared`, also in the default tenant) and its own principal; `scope_narrowing` left out is `optional`. `replace_label: true` deactivates the tenant's active keys with that label in the same transaction, before `max_keys` is counted, so a repeated call leaves one active key per label; on a label an owner, admin or server-admin key carries it refuses the set with `409`. Refusals: a scope of another tenant, or one the tenant neither has nor creates, `403`; `write_scopes ⊄ allowed_scopes ∪ {home_scope}`, a malformed scope name, an unknown field, a label missing or named twice in the set, a value the column cannot hold, a `scope_narrowing` other than `optional`/`required`, more than 64 scopes or keys, `400`; past `max_scopes` or `max_keys`, `429` with `limit`, `count` (the tenant's count before the set; for keys after its replacements) and `requested`; a tenant being deleted, or a scope registered meanwhile past the tenant lock (only a hand edit can), `409`; a top-level `id`, `400` (the target tenant is `data.tenant_id`). A narrowed request never reaches it ([above](#scope-narrowing-per-request)). How it serialises with the other key and scope writes: [multi-tenancy](multi-tenancy.md#key-sets-keyset-provision). +- **Key sets:** `keyset-provision` (tenant-admin, in the caller's own tenant; a server-admin may name `tenant_id`, anyone else naming it gets 403) creates the scopes and the keys of one set — say the groups of one community — in one transaction: either the whole set exists afterwards or nothing of it does. `data`: `scopes` (at most 64 bare scope names, scope-create's rule; the server puts the tenant's `<slug>:` in front; a scope the tenant already has is kept) and `keys` (at most 64, each `{label, home_scope, allowed_scopes, write_scopes, scope_narrowing, replace_label}`; a key's scope is a bare name or a full `<slug>:<name>` and must be the tenant's own or one the set creates; a name without `:` always gets the prefix, so scopes outside that form — the default tenant's `private`, `work` and `shared` — cannot be named). The answer lists `scopes` as `{scope, created}` and `keys` as `{id, label, home_scope, allowed_scopes, write_scopes, scope_narrowing, api_key}`, both in the order of the call; each `api_key` (the plaintext) is in this answer only. Every key is a `member` key with exactly the scopes it names (no implicit `shared`, also in the default tenant) and its own principal; `scope_narrowing` left out is `required` — the set's keys answer nothing without a [narrowing](#scope-narrowing-per-request) but `GET /api/whoami`, and a key without that requirement is minted only when the call names `optional` (unlike `api-key-create`, whose default stays `optional`). `replace_label: true` deactivates the tenant's active keys with that label in the same transaction, before `max_keys` is counted, so a repeated call leaves one active key per label; on a label an owner, admin or server-admin key carries it refuses the set with `409`. Refusals: a scope of another tenant, or one the tenant neither has nor creates, `403`; `write_scopes ⊄ allowed_scopes ∪ {home_scope}`, a malformed scope name, an unknown field, a label missing or named twice in the set, a value the column cannot hold, a `scope_narrowing` other than `optional`/`required`, more than 64 scopes or keys, `400`; past `max_scopes` or `max_keys`, `429` with `limit`, `count` (the tenant's count before the set; for keys after its replacements) and `requested`; a tenant being deleted, or a scope registered meanwhile past the tenant lock (only a hand edit can), `409`; a top-level `id`, `400` (the target tenant is `data.tenant_id`). A narrowed request never reaches it ([above](#scope-narrowing-per-request)). How it serialises with the other key and scope writes: [multi-tenancy](multi-tenancy.md#key-sets-keyset-provision). - **Block-type registry:** `type-list`/`type-get` are open reads; `type-create`/`type-update`/`type-delete` are the **operator transport** (server-admin, `_global` namespace) of the same store logic the REST `PUT/DELETE /api/types/{name}` surface uses — kept functional for MCP/CLI consumers, not superseded (see [Block-type registry](#block-type-registry)). `manage update` accepts a registry-validated `type` field; `list-meta` accepts the `types`/`types_exclude` filters. - **Issue corpus:** `issue-create`/`issue-update`/`issue-get`/`issue-list`/`issue-comment-create`/`issue-link-create`/`issue-link-delete` are the **operator transport** (all tierOpen; isolation is store-layer scope filtering, not an admin tier) over the same store issue logic the REST `/api/project` issue surface (W6/W7) uses — kept reachable for MCP/CLI operators, not the primary UI surface (see [Issue corpus](#issue-corpus)). - **Backend pool:** `backend-list`/`create`/`update`/`delete`/`test` — see [Backend pool](#backend-pool). diff --git a/docs/multi-tenancy.md b/docs/multi-tenancy.md index 1cd844e5a..f828dfdfc 100644 --- a/docs/multi-tenancy.md +++ b/docs/multi-tenancy.md @@ -147,7 +147,7 @@ The `whoami` endpoint carries this on the wire: alongside the server-global `adm ### Key sets (`keyset-provision`) -`keyset-provision` is `scope-create` plus `api-key-create` for a whole set — the scopes and keys of the groups of one community, for instance — in **one** transaction ([api](api.md#manage-actions) has the wire form). It knows no community, bot or group: labels, scopes and rights come from the call. `store.ProvisionKeyset` takes the tenant row lock first (`FOR UPDATE` — the row lock `scope-create` and `api-key-create` take first and `api-key-update`/`api-key-delete` take before their decisive read of the key, and which `tenant-limit-set` and the tenant delete's mark, both an `UPDATE` of the row, wait for) and reads everything it decides on under it, each in a statement of its own: the tenant's status and both limits from the locked row, the owners of every scope the set names, the scope count, the roles of the keys `replace_label` would deactivate, the active key count after those replacements. A concurrent `tenant-limit-set`, `scope-create` or role change of the same tenant is therefore seen, not raced, and two sets that replace the same label one after the other leave one active key of it. Order inside the lock: scopes (refused when one belongs to another tenant, or when a key names a scope the tenant neither has nor creates — foreign and unknown answer alike, and a key never names a scope it could read only once someone registers it; the new scopes counted against `max_scopes`, their groups of migration 176 locked in sorted order — the order the scope trigger keeps, which a row-by-row assignment of several scopes would break — and then one `INSERT`), then `replace_label` (member keys only — a label an owner, admin or server-admin key carries refuses the set, so it can never take a key past the owner rules of `api-key-delete`), then `max_keys` (active keys after the replacements), then each key through `insertApiKeyTx`, the one INSERT path of a key: role `member`, a fresh principal, exactly the scopes named, the audit row (`create`, or `revoke` for a replaced key) attributed to the calling key `via=api`. A failure anywhere rolls the set back. A tenant whose delete has begun takes no set (409), the rule `scope-create` follows since issue #555. When the set created a scope the handler refreshes the quota accountant, as `scope-create` does, so a key homed there is under the tenant's quota from its first call. Cost: one statement per step plus one INSERT per key while the tenant lock is held — measured 41 ms for 64 new scopes and 64 keys and 34 ms for the same set again with 64 replacements, in a tenant holding 20 000 other keys and 2 000 other scopes (`TestKeysetSixtyFourCost`); the replacement, its check and the key count read the tenant's keys (there is no index on the label; a tenant with many keys pays a scan of its own keys, three times per set). Until the commit, other scope and key writes of the same tenant wait, so do inserts that reference the tenant row, block writes of never-embedded types into the tenant's scopes when the set creates a scope (they take the tenant's group of migration 176, which the scope trigger then holds), and the authentication of a key the set replaces (its row is locked by the replacement); the authentication of every other key does not wait (it takes no tenant lock). +`keyset-provision` is `scope-create` plus `api-key-create` for a whole set — the scopes and keys of the groups of one community, for instance — in **one** transaction ([api](api.md#manage-actions) has the wire form). It knows no community, bot or group: labels, scopes and rights come from the call. `store.ProvisionKeyset` takes the tenant row lock first (`FOR UPDATE` — the row lock `scope-create` and `api-key-create` take first and `api-key-update`/`api-key-delete` take before their decisive read of the key, and which `tenant-limit-set` and the tenant delete's mark, both an `UPDATE` of the row, wait for) and reads everything it decides on under it, each in a statement of its own: the tenant's status and both limits from the locked row, the owners of every scope the set names, the scope count, the roles of the keys `replace_label` would deactivate, the active key count after those replacements. A concurrent `tenant-limit-set`, `scope-create` or role change of the same tenant is therefore seen, not raced, and two sets that replace the same label one after the other leave one active key of it. Order inside the lock: scopes (refused when one belongs to another tenant, or when a key names a scope the tenant neither has nor creates — foreign and unknown answer alike, and a key never names a scope it could read only once someone registers it; the new scopes counted against `max_scopes`, their groups of migration 176 locked in sorted order — the order the scope trigger keeps, which a row-by-row assignment of several scopes would break — and then one `INSERT`), then `replace_label` (member keys only — a label an owner, admin or server-admin key carries refuses the set, so it can never take a key past the owner rules of `api-key-delete`), then `max_keys` (active keys after the replacements), then each key through `insertApiKeyTx`, the one INSERT path of a key: role `member`, `scope_narrowing` `required` unless the call names `optional` ([required narrowing](#required-narrowing-migration-198); as member keys they never touch the owner rules that count `required` on an owner key as taking its administration), a fresh principal, exactly the scopes named, the audit row (`create`, or `revoke` for a replaced key) attributed to the calling key `via=api`. A failure anywhere rolls the set back. A tenant whose delete has begun takes no set (409), the rule `scope-create` follows since issue #555. When the set created a scope the handler refreshes the quota accountant, as `scope-create` does, so a key homed there is under the tenant's quota from its first call. Cost: one statement per step plus one INSERT per key while the tenant lock is held — measured 41 ms for 64 new scopes and 64 keys and 34 ms for the same set again with 64 replacements, in a tenant holding 20 000 other keys and 2 000 other scopes (`TestKeysetSixtyFourCost`); the replacement, its check and the key count read the tenant's keys (there is no index on the label; a tenant with many keys pays a scan of its own keys, three times per set). Until the commit, other scope and key writes of the same tenant wait, so do inserts that reference the tenant row, block writes of never-embedded types into the tenant's scopes when the set creates a scope (they take the tenant's group of migration 176, which the scope trigger then holds), and the authentication of a key the set replaces (its row is locked by the replacement); the authentication of every other key does not wait (it takes no tenant lock). ## Per-tenant settings & secrets @@ -265,7 +265,7 @@ Migration 069 adds structural per-tenant count-limits on `context_tenants`: `max | `tenant-usage-get` | tenant-admin (own) | Scope/key counts vs limits; a server-admin may target any. | | `api-key-create` | tenant-admin | Enforces `max_keys` transactionally (429, active-only count); a server-admin may mint into another tenant via `tenant_id` (foreign-target T22 — the new key's scopes must belong to the target; a non-server-admin's `tenant_id` → 403, AM2). New keys are always `member` (a smuggled `tenant_role` is ignored, AM3). Optional `write_scopes` (078, E4b) must be ⊆ `allowed_scopes ∪ {home_scope}` else 400 (see [Per-key write scopes](#per-key-write-scopes-e4b-migration-078)). | | `api-key-update` | tenant-admin | Role delegation (`{tenant_role?, active?, write_scopes?}`): only an owner (or server-admin) may change a key's role — a non-owner tenant-admin → 403, so admin→owner self-elevation is structurally impossible (no `is_admin` field means the server-global tier can never be set here). Demoting/deactivating the last active owner → 409 (last-owner invariant); an admin cannot neutralize an owner key → 403 (enforced at both update and the `api-key-delete` revoke path). A server-admin key (`is_admin`) is managed by server-admins only: any tenant-owner/-admin patch or revoke of it → 403, so a default-tenant admin cannot disable the operator's key. `write_scopes` (078, E4b) is validated ⊆ the key's existing `allowed_scopes ∪ {home_scope}` → 400 on a blind-writer; `[]` clears, absent leaves unchanged. `scope_narrowing` (198): switching an owner key to `required` takes its administration away, so it counts as neutralizing it (admin → 403) and the last-owner invariant counts only owners that are active **and** `optional` (409 for the last one, also on `api-key-delete`). Both actions decide the owner rules on the target as it is under the tenant row lock every key write takes, so a concurrent change of its role, `active` or `scope_narrowing` is seen, not raced. | -| `keyset-provision` | tenant-admin | `scope-create` and `api-key-create` for a set of up to 64 scopes and 64 keys in one transaction under the tenant row lock: all or nothing, `max_scopes`/`max_keys` counted for the whole set (429 with `limit`, `count`, `requested`), member keys with their own principal, `replace_label` deactivates the tenant's active member keys of a label in the same transaction (409 on a label an owner, admin or server-admin key carries); a server-admin may target another tenant via `tenant_id` (a non-server-admin's `tenant_id` → 403). See [Key sets](#key-sets-keyset-provision). | +| `keyset-provision` | tenant-admin | `scope-create` and `api-key-create` for a set of up to 64 scopes and 64 keys in one transaction under the tenant row lock: all or nothing, `max_scopes`/`max_keys` counted for the whole set (429 with `limit`, `count`, `requested`), member keys with their own principal and `scope_narrowing` `required` unless the call names `optional`, `replace_label` deactivates the tenant's active member keys of a label in the same transaction (409 on a label an owner, admin or server-admin key carries); a server-admin may target another tenant via `tenant_id` (a non-server-admin's `tenant_id` → 403). See [Key sets](#key-sets-keyset-provision). | | `gateway-limits-get` | tenant-admin (own) | Reads the limits rows of an own consumer or the own tenant with the ceiling and the effective values ([api](api.md#gateway-limits-gateway-limits-)); instance and envelope values stay server-admin. | | `gateway-limits-set` | tenant-admin (own) | Writes the caller's **tenant-tier** row of an own consumer or the own tenant — narrowing only (each value at or under the ceiling of the levels above, else 400 with the field; `allow_external` only `false`). A server-admin writes the server tier freely, including `instance` and `tenant_envelope`. | | `gateway-limits-delete` | tenant-admin (own) | Removes the caller's tier row; the dimension inherits again. | diff --git a/go/cmd/ctxd/keyset_provision_c3_more_integration_test.go b/go/cmd/ctxd/keyset_provision_c3_more_integration_test.go index 11f354992..1ae7132e7 100644 --- a/go/cmd/ctxd/keyset_provision_c3_more_integration_test.go +++ b/go/cmd/ctxd/keyset_provision_c3_more_integration_test.go @@ -253,13 +253,40 @@ func TestC3MalformedSetsCreateNothing(t *testing.T) { } } w.wantUnchanged(t, "after the top-level id", scopes, labels) - r := w.provision(t, w.owner, []string{"members"}, c3Key(strings.Repeat("l", 100), "members", nil, nil, "")) - r.must(t, "control: a label of 100 characters, scope_narrowing left out") - if _, _, plains := c3KeysOf(r); len(plains) == 1 { - for _, p := range plains { - if b := w.whoami(t, p); b["scope_narrowing"] != "optional" { - t.Errorf("scope_narrowing left out: whoami %v, want optional (api-key-create's default)", b["scope_narrowing"]) - } + w.provision(t, w.owner, []string{"members"}, c3Key(strings.Repeat("l", 100), "members", nil, nil, "required")).must(t, "control: a label of 100 characters") +} + +// TestC3ScopeNarrowingDefaultsToRequired: the action exists for the keys of +// restricted groups (design §7.3 C-3: keys "with required and label"), so a +// key whose scope_narrowing the call leaves out — absent or empty — is minted +// required: unnarrowed it answers nothing but whoami. optional is minted only +// when the call names it; api-key-create keeps optional as its default. +func TestC3ScopeNarrowingDefaultsToRequired(t *testing.T) { + w := c3Setup(t) + absent := c3Key("c3-default-absent", "members", nil, nil, "") + delete(absent, "scope_narrowing") + empty := c3Key("c3-default-empty", "members", nil, nil, "") + named := c3Key("c3-default-optional", "members", nil, nil, "optional") + r := w.provision(t, w.owner, []string{"members"}, absent, empty, named).must(t, "keyset-provision") + answered := map[string]any{} + list, _ := r.body["keys"].([]any) + for _, e := range list { + m, _ := e.(map[string]any) + l, _ := m["label"].(string) + answered[l] = m["scope_narrowing"] + } + _, _, plains := c3KeysOf(r) + for label, want := range map[string]string{"c3-default-absent": "required", "c3-default-empty": "required", "c3-default-optional": "optional"} { + if answered[label] != want { + t.Errorf("%s: the answer says scope_narrowing %v, want %s", label, answered[label], want) + } + if b := w.whoami(t, plains[label]); b["scope_narrowing"] != want { + t.Errorf("%s: whoami scope_narrowing %v, want %s", label, b["scope_narrowing"], want) + } + q := w.do(t, http.MethodPost, "/api/query", plains[label], map[string]any{"query": "c3 default narrowing"}) + refused := q.status == http.StatusForbidden && q.body["code"] == "scope_narrowing_required" + if refused != (want == "required") { + t.Errorf("%s: an unnarrowed /api/query answers HTTP %d %s, want refused=%v (scope_narrowing_required)", label, q.status, q.raw, want == "required") } } } diff --git a/go/internal/handler/keyset_provision.go b/go/internal/handler/keyset_provision.go index bb63033dd..bd0e1b60e 100644 --- a/go/internal/handler/keyset_provision.go +++ b/go/internal/handler/keyset_provision.go @@ -48,7 +48,10 @@ type keysetProvisionSpec struct { } // keysetKeySpec is one key of the set as the call names it. scope_narrowing -// empty means optional, as on api-key-create; the role is always member. +// left out (absent or empty) means required — the action mints the keys of +// restricted groups (design §7.3 C-3), so a key without per-request narrowing +// is minted only when the call names optional; api-key-create keeps optional +// as its default. The role is always member. type keysetKeySpec struct { Label string `json:"label"` HomeScope string `json:"home_scope"` @@ -195,7 +198,7 @@ func resolveKeysetNames(slug string, spec keysetProvisionSpec) (scopes []string, } narrowing := k.ScopeNarrowing if narrowing == "" { - narrowing = auth.ScopeNarrowingOptional + narrowing = auth.ScopeNarrowingRequired } nAllowed := len(k.AllowedScopes) keys = append(keys, store.KeysetKey{ diff --git a/go/internal/handler/keyset_provision_test.go b/go/internal/handler/keyset_provision_test.go index a860c90f0..7415c98a6 100644 --- a/go/internal/handler/keyset_provision_test.go +++ b/go/internal/handler/keyset_provision_test.go @@ -69,7 +69,7 @@ func TestKeysetNamesResolveToTheTenantsScopes(t *testing.T) { t.Errorf("scopes %s", got) } got := fmt.Sprintf("%+v", keys) - want := "[{Label:m HomeScope:acme:members AllowedScopes:[acme:k acme:main] WriteScopes:[acme:k] ScopeNarrowing:optional ReplaceLabel:false} " + + want := "[{Label:m HomeScope:acme:members AllowedScopes:[acme:k acme:main] WriteScopes:[acme:k] ScopeNarrowing:required ReplaceLabel:false} " + "{Label:o HomeScope:acme:mods AllowedScopes:[other:x] WriteScopes:[] ScopeNarrowing:required ReplaceLabel:true}]" if got != want { t.Errorf("keys\n got %s\nwant %s", got, want) From e29f8888332b2419b1f58bf74cc813f82a4234cc Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 06:13:52 +0100 Subject: [PATCH 08/15] =?UTF-8?q?chore:=20the=20server=20branch=20carries?= =?UTF-8?q?=20no=20plugin=20file=20=E2=80=94=20the=20ctx=5Fcheckpoint=20co?= =?UTF-8?q?ntract=20stubs=20land=20with=20the=20plugin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/access.py | 299 ----------- .../ctx_checkpoint/memory/access_cli.py | 51 -- .../ctx_checkpoint/memory/base_blocks.py | 82 --- .../ctx_checkpoint/memory/checkpoint.py | 14 - .../plugin/ctx_checkpoint/memory/client.py | 14 - .../plugin/ctx_checkpoint/memory/narrowing.py | 130 ----- .../plugin/ctx_checkpoint/memory/status.py | 21 +- .../plugin/ctx_checkpoint/tests/conftest.py | 47 -- .../ctx_checkpoint/tests/fakes/__init__.py | 3 - .../ctx_checkpoint/tests/fakes/access_host.py | 363 -------------- .../ctx_checkpoint/tests/fakes/ctx_server.py | 474 ------------------ .../ctx_checkpoint/tests/fakes/s1_pending.py | 15 - .../tests/test_access_pa_client.py | 256 ---------- .../tests/test_access_pb_decide.py | 291 ----------- .../tests/test_access_pc_binding.py | 176 ------- .../tests/test_access_pd_base_blocks.py | 235 --------- .../tests/test_access_pe_tools.py | 111 ---- .../tests/test_access_pf_docs.py | 30 -- .../tests/test_access_pg_window.py | 29 -- 19 files changed, 1 insertion(+), 2640 deletions(-) delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/memory/access.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/__init__.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/access_host.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_decide.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pf_docs.py delete mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py deleted file mode 100644 index 11654f786..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py +++ /dev/null @@ -1,299 +0,0 @@ -"""Access groups: the fields ctx_checkpoint adds to them and the binding decision (contract, S1). - -Hermes' access groups (``gateway.access_groups``) run each sender of a governed server in the -profile of the first group that matches. A plugin adds fields to those groups -(``PluginContext.register_access_fields``) and is told, per agent build, which group the turn serves -(``initialize(scope_id=, access_group=, access_group_restricted=, access_fields=, -restricted_profile=)``) and, inside a turn, through ``gateway.access_groups.current_access()``. - -This module holds the schema of ctx_checkpoint's twelve fields, the detection of that host surface -and the pure decision which connection a session gets (``off``, the profile's own, or a group -binding). S1 state: the data forms are final, the functions are inert stubs; nothing in the plugin -calls them yet, so the plugin behaves as 0.19.1. The decision cluster (P-B) fills them in. -""" - -from __future__ import annotations - -from collections.abc import Mapping -from dataclasses import dataclass, field -from types import MappingProxyType -from typing import Any, Literal - -# The namespace is the plugin id ``memory.provider`` selects the provider by. -NAMESPACE = "ctx_checkpoint" -# The hook the core fires before a governed server's turn (gateway/access_prompt.py). -HOOK_NAME = "access_group_fields" - -# Platforms of a local, interactive session (``ungoverned: local`` admits them; forks only when -# their parent session was local). -# The profile's markers (``read_markers``, ``raise_markers``, ``reset_markers``), under the home. -MARKERS_FILE = "ctx_state/access-mode.json" - -LOCAL_PLATFORMS = frozenset({"cli", "tui", "desktop", "local", "codex", "acp", "gui"}) - -# ``memory.ctx_checkpoint.*`` keys of config.yaml this axis reads (never from ctx.json), with defaults. -SETTINGS_DEFAULTS: Mapping[str, Any] = MappingProxyType( - { - "ungoverned": "auto", # auto | profile | local | off - "governed_unbound": "off", # profile | off - "restricted_allow": (), # subset of ("recall", "capture") - "base_cache_s": 900, # 60 .. 86400 - "base_cache_entries": 2048, # 64 .. 65536 - "base_timeout_s": 4, # 1 .. 10 - "base_workers": 4, # 1 .. 32 - "verify_timeout_s": 3, # 1 .. 10 - } -) - - -def _spec(kind: str, description: str) -> Mapping[str, str]: - return MappingProxyType({"type": kind, "description": description}) - - -# The twelve fields (registered without ``default``: the values that apply when a field is not set -# depend on whether the group is restricted, and the core's profile check must judge set values). -# The list only grows: no field changes its type or meaning, none is renamed (the core's registry is -# process-wide, profiles may carry different plugin versions). -SCHEMA: Mapping[str, Mapping[str, str]] = MappingProxyType( - { - "key": _spec( - "env_name", - "Variable in the serving profile's .env holding the ctx key: CTX_KEY, CTX_API_KEY or CTX_KEY_<...>;" - " restricted groups only CTX_KEY_<server id>_<...>. Not set: restricted groups get no ctx," - " others follow memory.ctx_checkpoint.governed_unbound.", - ), - "base_url": _spec( - "env_name", - "Variable holding the https URL of this group's ctx server: CTX_BASE_URL or CTX_BASE_URL_<...>." - " Not set: the profile's ctx URL.", - ), - "tenant": _spec( - "str", - "Expected tenant slug of the key; the group binds only when the key belongs to it." - " Not set: not checked (restricted groups need it).", - ), - "read": _spec( - "list", - "ctx scopes (<slug>:<name>, 1 to 8) recall, read tools and base blocks read." - " Not set: the key's read set without 'write' (restricted groups need it).", - ), - "write": _spec( - "str", - "ctx scope the chain, facts, digests and mirror write to; must be the key's home scope." - " Not set: the key's home scope (restricted groups need it).", - ), - "store": _spec( - "str", - "ctx scope the ctx_store tool writes to; unrestricted groups only, within the key's write set." - " Not set: 'write'.", - ), - "recall": _spec( - "bool", - "Recall before each turn. Not set: on for unrestricted groups, off for restricted ones;" - " restricted groups need memory.ctx_checkpoint.restricted_allow to list recall.", - ), - "capture": _spec( - "bool", - "Chain, facts, digests and mirror are written. Not set: on for unrestricted groups, off for" - " restricted ones; restricted groups need memory.ctx_checkpoint.restricted_allow to list capture.", - ), - "base_blocks": _spec( - "list", - "ctx block ids (up to 16) whose content joins the group's prompt. Not set: no base blocks.", - ), - "base_max_chars": _spec( - "int", - "Most characters the base blocks add to the group's prompt (256 to 8000). Not set: 4000.", - ), - "base_rev": _spec( - "int", - "Raise it to reload the base blocks in every session of the group. Not set: 0.", - ), - "enabled": _spec( - "bool", - "false: this group gets no ctx (counts as set for the core's profile check). Not set: true.", - ), - } -) - - -@dataclass(frozen=True) -class AccessContext: - """The access group a session serves, in ctx_checkpoint's terms: from ``initialize``'s access - kwargs or from ``gateway.access_groups.current_access()``. ``restricted``: the group's (``None`` - = unknown, which counts as restricted). ``fields``: this plugin's namespace only.""" - - platform: str - scope_id: str - group: str - profile: str | None - restricted: bool | None - admin: bool = False - fields: Mapping[str, Any] = field(default_factory=lambda: MappingProxyType({}), compare=False) - - -@dataclass(frozen=True) -class GroupFields: - """The group's fields, parsed and with their forms checked (``parse_fields``); defaults applied - for the group's strictness.""" - - key: str - base_url: str - tenant: str - read: tuple[str, ...] - write: str - store: str - recall: bool | None - capture: bool | None - base_blocks: tuple[str, ...] - base_max_chars: int - base_rev: int - enabled: bool - - -@dataclass(frozen=True) -class FieldError: - """Why the fields do not bind: the field and the rule it breaks, never its value.""" - - field: str - reason: str - - -@dataclass(frozen=True) -class Markers: - """The profile's monotone markers (``<home>/ctx_state/access-mode.json``).""" - - restricted_seen: bool = False - governed_seen: bool = False - - -@dataclass(frozen=True) -class Decision: - """What ``initialize`` binds: ``off`` (no ctx at all), ``profile`` (the profile's own connection, - as 0.19.1) or ``group`` (a group binding from ``fields``). ``reason`` names the row of the - decision table and the cause; ``strict``: the group counts as restricted.""" - - kind: Literal["off", "profile", "group"] - reason: str - context: AccessContext | None = None - fields: GroupFields | None = None - strict: bool = False - - -def access_supported() -> bool: - """V8b: the host has the core's access-group fields and hook, read on the public class - ``hermes_cli.plugins.PluginContext`` (a memory provider's ``ctx`` answers every ``register_*``). - S1 stub: ``False``.""" - return False - - -def current_access() -> AccessContext | None: - """V8a/V6a: the access group serving the current turn, through the published - ``gateway.access_groups.current_access`` (imported at call time; ``None`` when the host lacks it, - outside a turn, or for a server that is not governed), with this plugin's namespace only. - S1 stub: ``None``.""" - return None - - -def session_parent_platform() -> str | None: - """The platform of the session a fork was built in: ``HERMES_SESSION_PLATFORM`` through the - published ``gateway.session_context.get_session_env``, and only when the name is not in - ``os.environ`` (else ``get_session_env`` answers with the process value, which says nothing about - the session); ``None`` when unknown. The ``parent_platform`` of ``decide``. S1 stub: ``None``.""" - return None - - -def context_from_init(init_kwargs: Mapping[str, Any]) -> AccessContext | None: - """The access group ``initialize`` was told about (``platform``, ``scope_id``, ``access_group``, - ``access_group_restricted``, ``access_fields``, ``agent_identity``); ``None`` without - ``access_group``. S1 stub: ``None``.""" - return None - - -def is_strict(context: AccessContext | None, *, restricted_profile: bool | None, markers: Markers) -> bool: - """The one definition of "restricted" (design 02 §3.3): the group's ``restricted``; unknown counts - as restricted when the profile is restricted or the marker ``restricted_seen`` is set; in the hook - (no profile knowledge) unknown counts as restricted. S1 stub: ``True``.""" - return True - - -def parse_fields(raw: Mapping[str, Any], *, scope_id: str, strict: bool) -> GroupFields | FieldError: - """The group's fields with their forms checked before any secret is read or request sent: ``key`` - and ``base_url`` name ctx variables (restricted: ``CTX_KEY_<scope_id>_...``), scopes match the ctx - scope pattern, bounds hold; with ``strict`` the rules of E1. S1 stub: a ``FieldError``.""" - return FieldError(field="*", reason="access groups are not available") - - -def load_settings(hermes_home: str) -> Mapping[str, Any]: - """``memory.ctx_checkpoint.*`` of this axis from the home's config.yaml only (``ctx.json`` never - sets them), bounded, unknown values replaced by the defaults. S1 stub: the defaults.""" - return SETTINGS_DEFAULTS - - -def read_markers(hermes_home: str) -> Markers: - """The markers of ``<home>/ctx_state/access-mode.json``; a missing file is no marker, an - unreadable one counts as both set. S1 stub: no marker.""" - return Markers() - - -def raise_markers(hermes_home: str, **flags: bool) -> None: - """Set the named markers (``restricted_seen=True``, ``governed_seen=True``), only from false to - true, atomically; ``False`` never lowers one (only ``access reset-marker`` does). S1 stub: no-op.""" - return None - - -def reset_markers(hermes_home: str, *, restricted: bool = False, governed: bool = False) -> None: - """Lower the named markers (``access reset-marker``, the only way down), atomically; the other - marker stays. File: ``MARKERS_FILE`` under the home, JSON ``{"restricted_seen": bool, - "governed_seen": bool, "since": "<ISO 8601 UTC of the last change>"}``. S1 stub: no-op.""" - return None - - -def e7_inputs(hermes_home: str, platform: str) -> tuple[tuple[str, ...], tuple[str, ...]] | None: - """What rule E7 judges, read without network from the profile at *hermes_home*: the variable - NAMES in its ``.env`` (never a value) and the toolset list ``platform_toolsets.<platform>`` of its - config.yaml, exactly as configured. ``None`` when either cannot be read, which fails E7 (the one - reader P-C, P-D and P-E share). S1 stub: ``None``.""" - return None - - -def decide( - init_kwargs: Mapping[str, Any], - current: AccessContext | None, - parent_platform: str | None, - settings: Mapping[str, Any], - markers: Markers, - v8: bool, -) -> Decision: - """The decision table of design 02 §4.2 (first matching row): pure, no network, no files. - ``current``: ``current_access()`` at the build; ``parent_platform``: the copied session variable - ``HERMES_SESSION_PLATFORM`` of a fork (only when it is not in ``os.environ``). S1 stub: the - profile's own connection, as 0.19.1.""" - return Decision(kind="profile", reason="access groups are not available") - - -__all__ = [ - "HOOK_NAME", - "LOCAL_PLATFORMS", - "MARKERS_FILE", - "NAMESPACE", - "SCHEMA", - "SETTINGS_DEFAULTS", - "AccessContext", - "Decision", - "FieldError", - "GroupFields", - "Markers", - "access_supported", - "context_from_init", - "current_access", - "decide", - "e7_inputs", - "is_strict", - "load_settings", - "parse_fields", - "raise_markers", - "read_markers", - "reset_markers", - "session_parent_platform", -] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py deleted file mode 100644 index 9455de6aa..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ /dev/null @@ -1,51 +0,0 @@ -"""``hermes ctx_checkpoint access <status|check|provision|reset-marker>`` (contract, S1). - -Operator tools for access-group bindings (design 02 §4.7): ``status`` reads the per-binding status -files without network; ``check`` proves a group's fields (E1 to E7) and names every broken rule with -the expected value; ``provision`` computes scope names and the label, calls ctx's -``keyset-provision`` with ``replace_label`` and a tenant-admin key read from a named variable (never -stored), adds the new key to the target profile's ``.env`` and prints the ``/policy field`` lines -(``--emit-yaml``: the whole group entry); ``reset-marker`` lowers the profile's markers. - -Naming (design 02 §3.4): a ctx scope name is 1 to 24 characters of lowercase letters, digits and -inner hyphens (ctx ``scopeNamePattern``). Group names may hold ``_`` and 32 characters: ``_`` becomes -``-``, the edges are cleaned, the text is cut; when the name was changed or cut, its last four -characters are a hash of the original. Collisions are refused. One tenant per operator: -``d<server id in base 36>-k`` and ``d<server id in base 36>-<group part of at most 9>``; one tenant -per community: ``k`` and ``<group>``. The key variable is ``CTX_KEY_<server id>_<PROFILE>`` (profile -upper-cased, ``-`` as ``_``), at most 64 characters (a hash suffix replaces the rest). - -S1 state: the forms are final, the functions are inert stubs, and ``memory/cli.py`` does not offer -``access`` yet. The tools cluster (P-E) fills them in and wires the subcommand. -""" - -from __future__ import annotations - -import re -from collections.abc import Mapping, Sequence - -# ctx: go/internal/handler/tenant_manage.go scopeNamePattern (name part of <slug>:<name>). -SCOPE_NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,22}[a-z0-9])?$") -# Hermes: hermes_cli/access_fields.py ENV_NAME. -ENV_NAME = re.compile(r"^[A-Z][A-Z0-9_]{0,63}$") -KNOWLEDGE = "k" - - -def scope_layout(scope_id: str, groups: Sequence[str], *, per_community: bool = False) -> Mapping[str, str]: - """The ctx scope name (name part, no slug) for the server's knowledge scope (key ``"k"``) and for - each group in *groups*; ``ValueError`` when two map to the same name. S1 stub: ``{}``.""" - return {} - - -def key_env_name(scope_id: str, profile: str) -> str: - """The ``.env`` variable holding a restricted group's key on server *scope_id* served by - *profile*. S1 stub: ``""``.""" - return "" - - -def run_access(argv: Sequence[str], *, hermes_home: str) -> int: - """Run ``access <argv...>`` for the home; the exit code. S1 stub: 2 (not available).""" - return 2 - - -__all__ = ["ENV_NAME", "KNOWLEDGE", "SCOPE_NAME", "key_env_name", "run_access", "scope_layout"] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py deleted file mode 100644 index 865d80d08..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py +++ /dev/null @@ -1,82 +0,0 @@ -"""Base blocks: ctx blocks whose content joins an access group's prompt (contract, S1). - -The core fires the hook ``access_group_fields`` before a governed server's turn, in the serving -profile (its secrets are readable), once per session, group and digest of the group's fields and -prompt; it keeps answers (``None`` too) and asks again after a callback that raised or timed out. -The callback is an ``async def`` (the core awaits it on the gateway loop under -``plugins.hook_callback_timeout``); the blocking work runs on this module's own thread pool, so a -slow ctx server holds neither the loop nor its default executor. Only whole answers: a transient -failure or the end of ``base_timeout_s`` raises ``BaseBlocksUnavailable``, never a partial text. -The callback takes every value from its arguments or ``current_access()``, never from a provider -instance (the active provider's hooks hang on an instance that is never initialized). - -S1 state: the forms are final, the functions are inert stubs, and nothing registers the hook yet. -The base-block cluster (P-D) fills them in. -""" - -from __future__ import annotations - -from collections.abc import Mapping, Sequence -from dataclasses import dataclass -from typing import Any - -# The heading the rendered text starts with (part of the deterministic form). -HEADING = "## Knowledge for this conversation (ctx)" -TRUNCATED_MARK = "…[truncated]" - - -class BaseBlocksUnavailable(Exception): - """A base block could not be fetched now (network, time, 429) or the budget ran out: the hook - gives no partial text, the core keeps the group's prompt and asks again on a later turn.""" - - -@dataclass(frozen=True) -class BaseBlock: - """One fetched base block: its id, title, content and the ctx scope it lives in.""" - - id: str - title: str - content: str - scope: str - - -async def on_access_group_fields( - *, - platform: str, - scope_id: str, - group: str, - restricted: bool | None = None, - profile: str, - fields: Mapping[str, Mapping[str, Any]], - session_key: str, - user_id: str, - **kwargs: Any, -) -> dict | None: - """The hook callback: ``{"prompt": text}`` from the group's base blocks, or ``None``. - ``restricted``: the group's (``None`` = unknown = restricted); ``fields``: every valid namespace - of the group (this plugin reads ``fields["ctx_checkpoint"]``). S1 stub: ``None``.""" - return None - - -def render(blocks: Sequence[BaseBlock], max_chars: int, *, redact: Sequence[str] = ()) -> str: - """The deterministic text of *blocks* (heading, then ``### <title>`` and content per block, in - list order), every value of *redact* removed, filled up to *max_chars*: the block that overflows - is cut with ``…[truncated]``, the rest dropped. S1 stub: ``""``.""" - return "" - - -def reset_state() -> None: - """Drop the render cache, the joined in-flight fetches and the thread pool (tests). S1 stub: - no-op.""" - return None - - -__all__ = [ - "HEADING", - "TRUNCATED_MARK", - "BaseBlock", - "BaseBlocksUnavailable", - "on_access_group_fields", - "render", - "reset_state", -] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py index 578378cdb..07c38b0fb 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py @@ -102,17 +102,6 @@ # would cut recall, the agent's ctx tools and other sessions' checkpoints of the profile off for a # minute. MAX_RATE_REFUSALS = 2 - - -def window_writes(max_parts: int, rate_limit_write: int | None = None) -> int: - """Writes one chain plans inside one rate window: ``max_parts`` parts (at most - ``MAX_PARTS_CEILING``) plus manifest and head. ``rate_limit_write``: the write limit per 60 s the - server reports for the key (``whoami``; ctx with per-request narrowing), which the chain is to - follow (contract, S1: the chain cluster P-G makes it count and wires ``ChainWriter`` to it; - until then the reported limit is ignored).""" - return max(1, min(int(max_parts), MAX_PARTS_CEILING)) + 2 - - # How long (real seconds) a call waits for the answer of another call of the same entry before it # looks at its deadline again (EntryState.admit: the answer in flight decides whether it may go). ENTRY_WAIT_POLL_S = 0.05 @@ -1630,9 +1619,6 @@ class ChainWriter: # The process-wide state of the server entry the client writes to (entry_state; the provider # binds it before each checkpoint). None: every chain keeps a state of its own (before 0.17.0). entry: EntryState | None = field(default=None, repr=False) - # The write limit per 60 s the server reports for the bound key (``whoami.rate_limit_write``; - # the binding sets it, ``window_writes`` follows it). S1 contract: kept, not yet read. - rate_limit_write: int | None = None _tool_evidence_warned: bool = field(default=False, init=False) def _notify(self, message: str) -> None: diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py index d1c08651d..450ef0cdd 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py @@ -33,11 +33,8 @@ import urllib.error import urllib.parse import urllib.request -from collections.abc import Mapping, Sequence from typing import Any -from .narrowing import Narrowing - logger = logging.getLogger(__name__) @@ -381,7 +378,6 @@ def __init__( api_key: str, timeout: float = 10.0, synthesis_timeout: float = 90.0, - narrowing: Narrowing | None = None, ): parsed = urllib.parse.urlsplit(str(base_url or "").strip()) if parsed.scheme not in ("http", "https") or not parsed.netloc: @@ -397,9 +393,6 @@ def __init__( self._key = api_key self._timeout = timeout self._synthesis_timeout = synthesis_timeout - # Per-request scope narrowing (access groups): sent with every call and checked against the - # server's echo on every answer (CtxApiError code "narrowing_lost"). S1: kept, not yet sent. - self._narrowing = narrowing # The server registry's type names (``query_types``), read once per client. self._type_names: frozenset[str] | None = None @@ -639,10 +632,3 @@ def get_block(self, block_id: str, timeout: float | None = None) -> dict[str, An if left <= 0: raise CtxApiError("connection error: timed out") # what the bound ends a call with return self._request("POST", "/api/manage", {"action": "get", "data": {"id": block_id}}, timeout=left) - - def get_blocks(self, ids: Sequence[str], timeout: float | None = None) -> list[Mapping[str, Any]]: - """The blocks *ids* (1 to 16), in order, with one ``get`` carrying ``ids`` (ctx with the - multi-id get); against a server that answers that with 400, one ``get`` per id within the - same bound. A block that cannot be had is an entry with ``error`` (and ``code``), never an - exception for the whole call; a transient failure raises. S1 stub: no blocks.""" - return [] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py deleted file mode 100644 index cb727351b..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Per-request scope narrowing on the client side and the proof of a group binding (contract, S1). - -A narrowed client sends ``X-Context-Read-Scopes`` (and ``X-Context-Write-Scope``) on every call and -expects the server's echo ``X-Context-Narrowed: <read,...>;<write>`` on every answer. A binding is -proven by ``whoami`` answers: one narrowed, and for restricted groups one unnarrowed of the same key. -Only the raw answers are remembered (per base URL, key digest and header set: 60 s after success, -15 s after failure); every binding evaluates the rules E2 to E5 and E7 itself, so a proof for one -group never satisfies another's stricter expectation. - -S1 state: the data forms are final, the functions are inert stubs (nothing calls them yet). The -client cluster (P-A) fills them in. -""" - -from __future__ import annotations - -import hashlib -from collections.abc import Mapping -from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any - -if TYPE_CHECKING: # pragma: no cover - typing only - from .client import CtxClient - -HEADER_READ_SCOPES = "X-Context-Read-Scopes" -HEADER_WRITE_SCOPE = "X-Context-Write-Scope" -HEADER_NARROWED = "X-Context-Narrowed" - -# Raw whoami answers are kept this long (seconds) after a success and after a failure. -PROOF_TTL_OK_S = 60.0 -PROOF_TTL_FAILED_S = 15.0 -# The ctx label column is VARCHAR(100); a longer label hashes the profile part. -LABEL_MAX = 100 - - -@dataclass(frozen=True) -class Narrowing: - """The narrowing a client sends: ``read`` = the request's read set, in order (1 to 8 scopes); - ``write`` = its write scope (``None``: the client writes nothing).""" - - read: tuple[str, ...] - write: str | None = None - - def headers(self) -> dict[str, str]: - """The request headers of this narrowing.""" - out = {HEADER_READ_SCOPES: ",".join(self.read)} - if self.write: - out[HEADER_WRITE_SCOPE] = self.write - return out - - def echo(self) -> str: - """The ``X-Context-Narrowed`` value a server answers this narrowing with.""" - return f"{','.join(self.read)};{self.write or ''}" - - -@dataclass(frozen=True) -class Expect: - """What a binding expects of the key (design 02 §3.3). ``strict``: the group is restricted (E2 - to E4 apply in full); ``tenant``/``label``: expected values or ``None``; ``env_names``: the - variable names in the profile's ``.env`` and ``platform_toolsets``: the toolset list of the - platform in the profile (both for E7); ``scope_id``: the server the binding is for; ``write``: - the group's write scope (E3: the key's home scope, its write set exactly ``{write}``, its - unnarrowed read set exactly ``read ∪ {write}``) — the narrowing of a read client carries no write - scope, so it is named here (``None``: the key's home scope, unrestricted groups only).""" - - narrowing: Narrowing - strict: bool - tenant: str | None - label: str | None - env_names: tuple[str, ...] - platform_toolsets: tuple[str, ...] - scope_id: str - write: str | None = None - - -@dataclass(frozen=True) -class VerifyResult: - """The outcome of ``evaluate``: ``ok`` and, when not, the rules broken (``"E2"`` ...) with the - expected value per rule (no key value ever).""" - - ok: bool - failed: tuple[str, ...] = () - detail: Mapping[str, str] = field(default_factory=dict) - - -def key_digest(api_key: str) -> str: - """The first 16 hex characters of SHA-256 of a key: the only form of a key in caches, status - files and logs.""" - return hashlib.sha256(str(api_key or "").encode("utf-8")).hexdigest()[:16] - - -def expected_label(platform: str, scope_id: str, profile: str) -> str: - """The label a restricted group's key carries (E4): ``hermes:<platform>:<scope_id>:<profile>``; - past 100 characters ``#`` and 16 hex characters of SHA-256 of the profile name replace the - profile part. S1 stub: ``""``.""" - return "" - - -def whoami_raw(client: CtxClient, *, narrowed: bool, budget_s: float) -> Mapping[str, Any]: - """The raw ``whoami`` answer of *client* (narrowed: with its headers; else the same key without - them), from the proof store or the server within *budget_s*; a failure is remembered 15 s and - raised as ``CtxApiError``. S1 stub: an empty answer.""" - return {} - - -def evaluate(raw_narrowed: Mapping[str, Any], raw_unnarrowed: Mapping[str, Any] | None, expect: Expect) -> VerifyResult: - """E2 to E5 and E7 over raw answers, pure, without network. S1 stub: not proven.""" - return VerifyResult(ok=False, failed=("E5",), detail={"E5": "narrowing is not available"}) - - -def reset_proofs() -> None: - """Forget every remembered ``whoami`` answer (tests, ``access check``). S1 stub: no-op.""" - return None - - -__all__ = [ - "HEADER_NARROWED", - "HEADER_READ_SCOPES", - "HEADER_WRITE_SCOPE", - "LABEL_MAX", - "PROOF_TTL_FAILED_S", - "PROOF_TTL_OK_S", - "Expect", - "Narrowing", - "VerifyResult", - "evaluate", - "expected_label", - "key_digest", - "reset_proofs", - "whoami_raw", -] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/status.py b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py index 72569d56b..34a7dae22 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/status.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py @@ -17,7 +17,7 @@ import tempfile import threading import time -from collections.abc import Callable, Iterable, Iterator, Mapping +from collections.abc import Callable, Iterable, Iterator from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime, timezone @@ -749,22 +749,3 @@ def mcp_report(hermes_home: str) -> dict[str, Any]: secrets=profile_ctx_keys(name), servers=servers if isinstance(servers, dict) else {}, ) - - -# -- access groups (contract, S1) --------------------------------------------------------------- -# One small file per binding under <home>/ctx_state/access/<platform>-<scope_id>-<profile>.json, -# written atomically and only when the state changes: ``bound`` or ``off: <reason>``, the rules -# checked (E1-E7), the key digest (16 hex), tenant slug, read, write, time, base blocks loaded and -# skipped with reason. Display only (``hermes memory status``, ``access status``): never read to -# bind, never a key value. The binding cluster (P-C) writes through ``record_access``; the tools -# cluster (P-E) owns the rest. - - -def record_access(hermes_home: str, platform: str, scope_id: str, profile: str, result: Mapping[str, Any]) -> None: - """Record the state of one binding (see above). S1 stub: no-op.""" - return None - - -def read_access(hermes_home: str) -> list[Mapping[str, Any]]: - """Every recorded binding of the home, sorted by platform, server and profile. S1 stub: none.""" - return [] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py b/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py index 9c12acdec..b1728fcd1 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py @@ -7,11 +7,9 @@ from __future__ import annotations -import os import sys import pytest -from fakes.s1_pending import S1_PENDING @pytest.fixture(autouse=True) @@ -37,48 +35,3 @@ def reset() -> None: reset() yield reset() - - -# -- access groups (S1): cluster shield and shared fakes ----------------------------------------- -# Red S1 tests carry ``pytestmark = pytest.mark.access_cluster("<P-x>")``. While their cluster is -# listed in ``fakes/s1_pending.py`` each test gets a strict xfail that only an assertion about the -# missing behaviour satisfies (a TypeError or an import error stays an error); ``s1_green`` marks a -# guard that already holds on the stubs. ``CTX_S1_UNSHIELD=1`` lifts the shield (the red proof). - - -def pytest_configure(config): - config.addinivalue_line("markers", "access_cluster(name): red S1 test of an access-group plugin cluster") - config.addinivalue_line("markers", "s1_green: S1 guard that already holds on the stubs") - - -def pytest_collection_modifyitems(config, items): - if os.environ.get("CTX_S1_UNSHIELD") == "1": - return - for item in items: - marker = item.get_closest_marker("access_cluster") - if marker is None or item.get_closest_marker("s1_green") is not None: - continue - cluster = marker.args[0] if marker.args else "" - if cluster in S1_PENDING: - item.add_marker( - pytest.mark.xfail( - strict=True, - raises=(AssertionError, pytest.fail.Exception), - reason=f"S1 red: {cluster} not built yet", - ) - ) - - -@pytest.fixture -def fake_ctx(monkeypatch): - """A running fake ctx server (``fakes/ctx_server.py``); requests to it on 127.0.0.1 never go - through a proxy of the environment.""" - from fakes.ctx_server import FakeCtx - - monkeypatch.setenv("no_proxy", "127.0.0.1,localhost") - monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost") - server = FakeCtx().start() - try: - yield server - finally: - server.stop() diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/__init__.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/__init__.py deleted file mode 100644 index 441862ecb..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Test fakes of the access-group surfaces (S1): a local ctx server with per-request narrowing -(``ctx_server``) and the Hermes surface of the access-groups core PR over the pinned Hermes -(``access_host``). They belong to no cluster; every plugin cluster tests against them.""" diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/access_host.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/access_host.py deleted file mode 100644 index 2c0999f32..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/access_host.py +++ /dev/null @@ -1,363 +0,0 @@ -"""The Hermes surface of the access-groups core PR (NousResearch/hermes-agent#164604, head -``0b613f2fdf``) over the pinned Hermes the CI runs (``26cd2e6d83``, without the PR), through -``monkeypatch`` only. Forms as the PR's code has them: - -- V8b: ``register_access_fields`` on the class ``hermes_cli.plugins.PluginContext`` - (``hermes_cli/plugins_context.py:825``); a memory provider's ``ctx`` is the collector, which - answers ``register_access_fields`` itself (``plugins/memory/__init__.py:562-564``) and every other - ``register_*`` through ``__getattr__`` (``FakeCollector``). -- V8a/V6a: a module ``gateway.access_groups`` with ``AccessContext(platform, scope_id, group, - profile, restricted: bool, admin=False, fields)`` and ``fields_for`` (``gateway/access_groups.py:131-148``) - and ``current_access()`` read from a ContextVar, so copied contexts (threads, ``/background``) - see it and a cron run sees ``None`` (``:949-980``). -- V4: ``ainvoke_hook_callback`` (``hermes_cli/plugins_dispatch.py:684-729``): an ``async def`` - callback is awaited on the loop under ``asyncio.wait_for(timeout)`` and cancelled when it passes; - any other runs on a daemon thread of its own; a raise or a timeout is ``(False, None)``. The - kwargs of ``gateway/access_prompt.py:46-60`` (``hook_kwargs``), ``fields`` deep-copied per call. -- Secrets: ``agent.secret_scope.get_secret`` reads a ContextVar mapping and counts reads. -- V5: ``initialize`` always gets ``scope_id``, ``access_group``, ``access_group_restricted``, - ``access_fields`` and ``restricted_profile`` (``agent/agent_init_memory_provider.py:180-201``); - ``truth_filter=True`` simulates a host that passes only true values (VB-2). -""" - -from __future__ import annotations - -import asyncio -import contextvars -import copy -import importlib -import importlib.util -import inspect -import sys -import threading -import types -from collections import Counter -from collections.abc import Callable, Iterator, Mapping -from contextlib import contextmanager -from dataclasses import dataclass, field -from pathlib import Path -from types import MappingProxyType -from typing import Any - -PLUGIN_DIR = Path(__file__).resolve().parents[2] -_EMPTY: Mapping[str, Any] = MappingProxyType({}) -OBSERVER_SCHEMA_VERSION = 1 - - -def load_plugin(name: str) -> types.ModuleType: - """The plugin package under a name of its own (as ``tests/test_provider_contract.py`` does).""" - if name in sys.modules: - return sys.modules[name] - spec = importlib.util.spec_from_file_location( - name, PLUGIN_DIR / "__init__.py", submodule_search_locations=[str(PLUGIN_DIR)] - ) - assert spec is not None and spec.loader is not None - module = importlib.util.module_from_spec(spec) - sys.modules[name] = module - spec.loader.exec_module(module) - return module - - -def plugin_module(package: types.ModuleType, sub: str) -> types.ModuleType: - """A submodule of a loaded plugin copy (``memory.access`` ...).""" - return importlib.import_module(f"{package.__name__}.{sub}") - - -# -- V6a --------------------------------------------------------------------------------------- - - -@dataclass(frozen=True) -class AccessContext: - """The core's form (``gateway/access_groups.py:131-148``).""" - - platform: str - scope_id: str - group: str - profile: str | None - restricted: bool - admin: bool = False - fields: Mapping[str, Mapping[str, Any]] = field(default=_EMPTY, compare=False) - - def fields_for(self, plugin_id: str) -> Mapping[str, Any]: - return self.fields.get(plugin_id) or _EMPTY - - -_CURRENT: contextvars.ContextVar[AccessContext | None] = contextvars.ContextVar("fake_current_access", default=None) - - -def make_access( - *, - platform: str = "discord", - scope_id: str = "111", - group: str = "members", - profile: str | None = "members", - restricted: bool = True, - admin: bool = False, - fields: Mapping[str, Any] | None = None, - namespace: str = "ctx_checkpoint", -) -> AccessContext: - spaces = {namespace: MappingProxyType(copy.deepcopy(dict(fields)))} if fields else {} - return AccessContext(platform, str(scope_id), group, profile, restricted, admin, MappingProxyType(spaces)) - - -@contextmanager -def turn(access: AccessContext | None) -> Iterator[None]: - """Run the block as a gateway turn whose ``current_access()`` is *access*.""" - token = _CURRENT.set(access) - try: - yield - finally: - _CURRENT.reset(token) - - -# -- secrets ----------------------------------------------------------------------------------- - - -class SecretScope: - """``agent.secret_scope.get_secret`` over a ContextVar mapping, with a read counter.""" - - def __init__(self, base: Mapping[str, str] | None = None) -> None: - self.var: contextvars.ContextVar[Mapping[str, str]] = contextvars.ContextVar( - "fake_secret_scope", default=MappingProxyType(dict(base or {})) - ) - self.reads: Counter[str] = Counter() - self._lock = threading.Lock() - - def get_secret(self, name: str, default: str | None = None) -> str | None: - with self._lock: - self.reads[name] += 1 - return self.var.get().get(name, default) - - def set_base(self, values: Mapping[str, str]) -> None: - self.var.set(MappingProxyType(dict(values))) - - @contextmanager - def scoped(self, values: Mapping[str, str]) -> Iterator[None]: - token = self.var.set(MappingProxyType(dict(values))) - try: - yield - finally: - self.var.reset(token) - - def total_reads(self) -> int: - return sum(self.reads.values()) - - -# -- the collector a memory provider's register(ctx) gets --------------------------------------- - - -class FakeCollector: - """What ``register(ctx)`` of a memory plugin is handed: records every ``register_*`` call. - ``register_access_fields`` exists on the instance only when the host has V8 (the real collector - answers it itself, and only forwards it while the provider is active).""" - - def __init__(self, *, v8: bool, active: bool = True) -> None: - self.calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = [] - self.hooks: dict[str, list[Callable[..., Any]]] = {} - self.providers: list[Any] = [] - self.access_fields: list[Mapping[str, Any]] = [] - self._v8 = v8 - self._active = active - - def register_memory_provider(self, provider: Any) -> None: - self.calls.append(("register_memory_provider", (provider,), {})) - self.providers.append(provider) - - def register_hook(self, name: str, callback: Callable[..., Any], **kwargs: Any) -> None: - self.calls.append(("register_hook", (name, callback), kwargs)) - self.hooks.setdefault(name, []).append(callback) - - def register_access_fields(self, schema: Mapping[str, Any]) -> Any: - self.calls.append(("register_access_fields", (schema,), {})) - if not self._v8: - raise AttributeError("register_access_fields") # a pre-PR host's collector forwards nothing - if self._active: - self.access_fields.append(schema) - return None - - def __getattr__(self, name: str) -> Any: - if name.startswith("register_"): - - def record(*args: Any, **kwargs: Any) -> None: - self.calls.append((name, args, kwargs)) - - return record - raise AttributeError(name) - - def called(self, name: str) -> int: - return sum(1 for call in self.calls if call[0] == name) - - -# -- V5 ---------------------------------------------------------------------------------------- - - -def v5_kwargs( - *, - scope_id: str | None = None, - group: str | None = None, - group_restricted: bool = False, - fields: Mapping[str, Any] | None = None, - restricted_profile: bool = False, - truth_filter: bool = False, -) -> dict[str, Any]: - """The five access kwargs of every ``initialize`` (all of them; ``truth_filter``: only true ones).""" - out: dict[str, Any] = { - "scope_id": scope_id, - "access_group": group, - "access_group_restricted": bool(group_restricted) if group else False, - "access_fields": copy.deepcopy(dict(fields or {})), - "restricted_profile": bool(restricted_profile), - } - if truth_filter: - out = {k: v for k, v in out.items() if v} - return out - - -# -- V4 ---------------------------------------------------------------------------------------- - - -def hook_kwargs( - *, - platform: str = "discord", - scope_id: str = "111", - group: str = "members", - restricted: bool = True, - profile: str = "members", - fields: Mapping[str, Mapping[str, Any]] | None = None, - session_key: str = "agent:main:discord:group:111:222", - user_id: str = "333", -) -> dict[str, Any]: - """The hook's kwargs as ``gateway/access_prompt.py:_payload`` builds them.""" - return { - "platform": platform, - "scope_id": str(scope_id), - "group": group, - "restricted": bool(restricted), - "profile": profile, - "fields": copy.deepcopy(dict(fields or {})), - "session_key": session_key, - "user_id": user_id, - "telemetry_schema_version": OBSERVER_SCHEMA_VERSION, - } - - -@dataclass -class HookOutcome: - answered: bool - result: Any - error: BaseException | None = None - - -async def ainvoke_hook_callback(callback: Callable[..., Any], *, timeout: float = 30.0, **kwargs: Any) -> HookOutcome: - """One callback the way the core's dispatcher runs it (see the module text).""" - kwargs = dict(kwargs, fields=copy.deepcopy(kwargs.get("fields") or {})) - kwargs.setdefault("telemetry_schema_version", OBSERVER_SCHEMA_VERSION) - try: - if inspect.iscoroutinefunction(callback): - try: - return HookOutcome(True, await asyncio.wait_for(callback(**kwargs), timeout)) - except TimeoutError as exc: - return HookOutcome(False, None, exc) - loop = asyncio.get_running_loop() - done: asyncio.Future[Any] = loop.create_future() - ctx = contextvars.copy_context() - - def run() -> None: - try: - value = ctx.run(callback, **kwargs) - except BaseException as exc: # reported as the callback's failure - loop.call_soon_threadsafe(_settle, done, None, exc) - else: - loop.call_soon_threadsafe(_settle, done, value, None) - - threading.Thread(target=run, name="hermes-hook-access_group_fields", daemon=True).start() - return HookOutcome(True, await done) - except asyncio.CancelledError as exc: - task = asyncio.current_task() - if task is not None and task.cancelling(): - raise - return HookOutcome(False, None, exc) - except BaseException as exc: - return HookOutcome(False, None, exc) - - -def _settle(future: asyncio.Future[Any], value: Any, exc: BaseException | None) -> None: - if future.done(): - return - if exc is not None: - future.set_exception(exc) - else: - future.set_result(value) - - -# -- installation ------------------------------------------------------------------------------ - - -@dataclass -class Host: - """The installed surface; ``v8`` says whether the class carries ``register_access_fields``.""" - - v8: bool - secrets: SecretScope - module: types.ModuleType - - def collector(self, *, active: bool = True) -> FakeCollector: - return FakeCollector(v8=self.v8, active=active) - - -def install(monkeypatch: Any, *, v8: bool = True, secrets: Mapping[str, str] | None = None) -> Host: - """Patch the pinned Hermes with the PR's surface (``v8=False``: the pinned Hermes as it is, but - with the fake secret scope).""" - import agent.secret_scope as secret_scope - import hermes_cli.plugins as plugins - - scope = SecretScope(secrets) - monkeypatch.setattr(secret_scope, "get_secret", scope.get_secret) - module = types.ModuleType("gateway.access_groups") - module.AccessContext = AccessContext # type: ignore[attr-defined] - module.current_access = _CURRENT.get # type: ignore[attr-defined] - if v8: - - def register_access_fields(self: Any, schema: Mapping[str, Any]) -> None: - return None - - monkeypatch.setattr(plugins.PluginContext, "register_access_fields", register_access_fields, raising=False) - monkeypatch.setitem(sys.modules, "gateway.access_groups", module) - import gateway - - monkeypatch.setattr(gateway, "access_groups", module, raising=False) - else: - monkeypatch.delattr(plugins.PluginContext, "register_access_fields", raising=False) - monkeypatch.delitem(sys.modules, "gateway.access_groups", raising=False) - return Host(v8=v8, secrets=scope, module=module) - - -# -- the core's field schema rules (hermes_cli/access_fields.py), for schema checks -------------- - -FIELD_TYPES = frozenset({"str", "int", "float", "bool", "list", "env_name"}) -SPEC_KEYS = frozenset({"type", "description", "default"}) -MAX_FIELDS = 16 -FIELD_NAME = r"^[a-z][a-z0-9_]{0,63}$" -ENV_NAME = r"^[A-Z][A-Z0-9_]{0,63}$" - - -__all__ = [ - "ENV_NAME", - "FIELD_NAME", - "FIELD_TYPES", - "MAX_FIELDS", - "SPEC_KEYS", - "AccessContext", - "FakeCollector", - "HookOutcome", - "Host", - "SecretScope", - "ainvoke_hook_callback", - "hook_kwargs", - "install", - "load_plugin", - "make_access", - "plugin_module", - "turn", - "v5_kwargs", -] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py deleted file mode 100644 index b702a7cce..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py +++ /dev/null @@ -1,474 +0,0 @@ -"""A local ctx server with the target semantics of per-request narrowing (design 02 §3.5 C-1 to -C-4), stdlib only: one thread, ``127.0.0.1``, port 0. - -Keys carry tenant (slug), home, ``allowed_scopes``, tenant grants, ``write_scopes``, -``scope_narrowing``, label, role, admin and ``confirm_writes``. Narrowing headers follow C-1 -(subset rule, write scope rules, closed route list, ``get``/``type-list`` only on ``/api/manage``), -C-2 (``required`` keys refuse every unnarrowed request but ``whoami``), C-3 (``keyset-provision``) -and C-4 (``get`` with ``ids``). Every request is counted per route and header set. Faults are -switches on the server object: echo missing or wrong, latency per route, 429 per route, a server -without C-1 (headers ignored, ``whoami`` without the new fields) and without C-4 (``ids`` refused). - -Answer forms follow what ``memory/client.py`` and ``memory/provider.py`` read today: -``/api/query`` ``{"success", "answer", "sources"}``, ``/api/search`` ``{"success", "results"}``, -``/api/store`` ``{"block": {...}}``, ``/api/manage`` ``get`` as ctx answers it today -(``{"action": "get", "success": true, "block": {...}}``; a miss is 200 with ``{"success": false, -"error": "Block not found"}``). The multi-id form (C-4) is the S1 contract, the same the Go test of -C-4 pins: ``{"success": true, "blocks": [block | {"id", "error", "code": "not_found"}]}``. -""" - -from __future__ import annotations - -import hashlib -import json -import threading -import time -import uuid -from collections.abc import Iterable, Mapping -from dataclasses import dataclass, field -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from typing import Any - -HEADER_READ = "X-Context-Read-Scopes" -HEADER_WRITE = "X-Context-Write-Scope" -HEADER_NARROWED = "X-Context-Narrowed" -# C-1: the closed list of routes a narrowed request may take. -NARROWED_ROUTES = frozenset( - { - ("POST", "/api/query"), - ("POST", "/api/search"), - ("POST", "/api/store"), - ("GET", "/api/whoami"), - ("POST", "/api/manage"), - } -) -NARROWED_ACTIONS = frozenset({"get", "type-list"}) -MAX_READ_SCOPES = 8 -MAX_IDS = 16 -TYPE_NAMES = ("knowledge", "checkpoint", "session-digest", "fact") - - -@dataclass -class FakeKey: - """One API key of the fake (the secret is what ``X-Context-Key`` carries).""" - - secret: str - tenant: str - home: str - allowed: tuple[str, ...] = () - grants: tuple[str, ...] = () # tenant grants: readable, never writable - write_scopes: tuple[str, ...] = () - scope_narrowing: str = "optional" - label: str = "" - role: str = "member" - admin: bool = False - confirm_writes: bool = False - active: bool = True - - @property - def read_scopes(self) -> list[str]: - out: list[str] = [] - for scope in (self.home, *self.allowed, *self.grants): - if scope not in out: - out.append(scope) - return out - - @property - def writable(self) -> list[str]: - return [self.home, *[s for s in self.write_scopes if s != self.home]] - - -@dataclass -class Seen: - """One request as the fake saw it.""" - - method: str - path: str - action: str - key_digest: str - read_header: str | None - write_header: str | None - status: int - body: Mapping[str, Any] = field(default_factory=dict) - - -def digest(secret: str) -> str: - return hashlib.sha256(secret.encode("utf-8")).hexdigest()[:16] - - -class FakeCtx: - """The fake server: keys, blocks per scope, counters and fault switches.""" - - def __init__(self) -> None: - self.keys: dict[str, FakeKey] = {} - self.blocks: dict[str, dict[str, Any]] = {} - self.scopes: set[str] = set() # scopes keyset-provision created or found (C-3) - self.seen: list[Seen] = [] - self.lock = threading.Lock() - # Fault switches. - self.echo_missing = False - self.echo_wrong = False - self.without_c1 = False - self.without_c4 = False - self.leak_on_get = False # get answers blocks outside the request's read set (E6 is the client's too) - self.latency: dict[str, float] = {} # route key ("/api/whoami", "manage:get", ...) -> seconds - self.throttle: dict[str, int] = {} # route key -> number of 429 answers still to give - self.rate_limit_write = 97 - self.max_keys = 50 - self._server: ThreadingHTTPServer | None = None - self._thread: threading.Thread | None = None - - # -- set-up ------------------------------------------------------------------------------ - - def add_key(self, **kwargs: Any) -> FakeKey: - key = FakeKey(**kwargs) - self.keys[key.secret] = key - return key - - def add_block(self, scope: str, title: str, content: str, *, block_id: str = "", **extra: Any) -> str: - block_id = block_id or str(uuid.uuid4()) - self.blocks[block_id] = { - "id": block_id, - "title": title, - "content": content, - "category": extra.pop("category", "reference"), - "type": extra.pop("type", "knowledge"), - "scope": scope, - "tags": list(extra.pop("tags", [])), - "metadata": dict(extra.pop("metadata", {})), - "archived": bool(extra.pop("archived", False)), - } - return block_id - - # -- counters ---------------------------------------------------------------------------- - - def count(self, path: str | None = None, action: str | None = None, *, narrowed: bool | None = None) -> int: - with self.lock: - rows = list(self.seen) - return sum( - 1 - for row in rows - if (path is None or row.path == path) - and (action is None or row.action == action) - and (narrowed is None or (row.read_header is not None) == narrowed) - ) - - def requests(self, path: str | None = None) -> list[Seen]: - with self.lock: - return [row for row in self.seen if path is None or row.path == path] - - def reset_counters(self) -> None: - with self.lock: - self.seen.clear() - - # -- life cycle -------------------------------------------------------------------------- - - @property - def url(self) -> str: - assert self._server is not None - return f"http://127.0.0.1:{self._server.server_port}" - - def start(self) -> FakeCtx: - fake = self - - class Handler(BaseHTTPRequestHandler): - def log_message(self, *args: Any) -> None: - return None - - def do_GET(self) -> None: - fake._handle(self, "GET") - - def do_POST(self) -> None: - fake._handle(self, "POST") - - self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) - self._server.daemon_threads = True - self._thread = threading.Thread(target=self._server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True) - self._thread.start() - return self - - def stop(self) -> None: - if self._server is not None: - self._server.shutdown() - self._server.server_close() - self._server = None - - # -- request handling -------------------------------------------------------------------- - - def _handle(self, h: BaseHTTPRequestHandler, method: str) -> None: - path = h.path.split("?", 1)[0] - length = int(h.headers.get("Content-Length") or 0) - raw = h.rfile.read(length) if length else b"" - try: - body = json.loads(raw.decode("utf-8")) if raw else {} - except ValueError: - body = {} - if not isinstance(body, dict): - body = {} - action = str(body.get("action") or "") if path == "/api/manage" else "" - secret = h.headers.get("X-Context-Key") or "" - read_values = h.headers.get_all(HEADER_READ) or [] - write_values = h.headers.get_all(HEADER_WRITE) or [] - route = f"manage:{action}" if action else path - status, payload, echo = self._answer(method, path, action, body, secret, read_values, write_values) - with self.lock: - self.seen.append( - Seen( - method=method, - path=path, - action=action, - key_digest=digest(secret), - read_header=",".join(read_values) if read_values else None, - write_header=",".join(write_values) if write_values else None, - status=status, - body=body, - ) - ) - delay = self.latency.get(route, self.latency.get(path, 0.0)) - if delay: - time.sleep(delay) - data = json.dumps(payload).encode("utf-8") - try: - h.send_response(status) - h.send_header("Content-Type", "application/json") - h.send_header("Content-Length", str(len(data))) - if echo is not None and not self.echo_missing: - h.send_header(HEADER_NARROWED, "x;y" if self.echo_wrong else echo) - h.end_headers() - h.wfile.write(data) - except OSError: - pass # the client gave up (its deadline); nothing to answer - - def _answer( - self, - method: str, - path: str, - action: str, - body: Mapping[str, Any], - secret: str, - read_values: list[str], - write_values: list[str], - ) -> tuple[int, dict[str, Any], str | None]: - key = self.keys.get(secret) - if key is None or not key.active: - return 401, {"success": False, "error": "unauthorized", "code": "unauthorized"}, None - route = f"manage:{action}" if action else path - with self.lock: - left = self.throttle.get(route, self.throttle.get(path, 0)) - if left > 0: - self.throttle[route if route in self.throttle else path] = left - 1 - return 429, {"success": False, "error": "rate limited", "code": "rate_limit"}, None - narrowed: tuple[list[str], str] | None = None - if not self.without_c1 and (read_values or write_values): - if not read_values: - return 400, _err("write scope without read scopes", "scope_narrowing_invalid"), None - if len(read_values) > 1 or len(write_values) > 1: - return 400, _err("narrowing header repeated", "scope_narrowing_invalid"), None - read = [s.strip() for s in read_values[0].split(",")] - if not read_values[0].strip() or any(not s for s in read) or len(read) != len(set(read)): - return 400, _err("empty or doubled narrowing", "scope_narrowing_invalid"), None - if len(read) > MAX_READ_SCOPES: - return 400, _err("too many read scopes", "scope_narrowing_invalid"), None - write = write_values[0].strip() if write_values else "" - if write_values and not write: - return 400, _err("empty write scope", "scope_narrowing_invalid"), None - if any(s not in key.read_scopes for s in read): - return 403, _err("scope outside the key", "scope_denied"), None - if write and (write not in key.writable or write not in read): - return 403, _err("write scope outside the key", "scope_denied"), None - if (method, path) not in NARROWED_ROUTES: - return 403, _err("route not open to narrowing", "scope_narrowing_route"), None - narrowed = (read, write) - elif not self.without_c1 and key.scope_narrowing == "required" and (method, path) != ("GET", "/api/whoami"): - return 403, _err("this key requires narrowing", "scope_narrowing_required"), None - echo = f"{','.join(narrowed[0])};{narrowed[1]}" if narrowed else None - read_set = narrowed[0] if narrowed else key.read_scopes - if (method, path) == ("GET", "/api/whoami"): - return 200, self._whoami(key, narrowed), echo - if (method, path) == ("POST", "/api/query"): - hits = self._visible(read_set, body.get("types_exclude")) - return 200, {"success": True, "answer": "", "sources": hits}, echo - if (method, path) == ("POST", "/api/search"): - hits = self._visible(read_set, body.get("types_exclude")) - return 200, {"success": True, "results": hits}, echo - if (method, path) == ("POST", "/api/store"): - if narrowed is not None: - if not narrowed[1]: - return 403, _err("no write scope on a narrowed request", "scope_denied"), echo - scope = narrowed[1] - else: - scope = key.home - block_id = self.add_block( - scope, - str(body.get("title") or ""), - str(body.get("content") or ""), - category=str(body.get("category") or "reference"), - type=str(body.get("type") or "knowledge"), - tags=list(body.get("tags") or []), - metadata=dict(body.get("metadata") or {}), - ) - now = "2026-12-06T00:00:00Z" - block = dict(self.blocks[block_id], created_at=now, updated_at=now) - return 200, {"block": block}, echo - if (method, path) == ("POST", "/api/manage"): - if narrowed is not None and (action not in NARROWED_ACTIONS or _shadowed_action(body)): - return 403, _err("action not open to narrowing", "scope_narrowing_route"), echo - return self._manage(key, action, body, read_set, echo) - if narrowed is not None: # unreachable: other routes were refused above - return 403, _err("route not open to narrowing", "scope_narrowing_route"), echo - return 200, {"success": True}, echo - - def whoami_answer(self, secret: str, read: Iterable[str] | None = None, write: str = "") -> dict[str, Any]: - """The ``whoami`` body this server gives *secret* (narrowed to *read*/*write* when given), - without a request: raw answers for the pure rule checks.""" - return self._whoami(self.keys[secret], (list(read), write) if read is not None else None) - - def _whoami(self, key: FakeKey, narrowed: tuple[list[str], str] | None) -> dict[str, Any]: - out: dict[str, Any] = { - "success": True, - "home_scope": key.home, - "read_scopes": list(key.read_scopes), - "tenant_slug": key.tenant, - "label": key.label, - "role": key.role, - "admin": key.admin, - } - if self.without_c1: - return out - out.update( - { - "write_scopes": [narrowed[1]] if narrowed and narrowed[1] else ([] if narrowed else key.writable), - "confirm_writes": key.confirm_writes, - "narrowed": {"read": list(narrowed[0]), "write": narrowed[1]} if narrowed else None, - "scope_narrowing": key.scope_narrowing, - "rate_limit_write": self.rate_limit_write, - } - ) - if narrowed: - out["read_scopes"] = list(narrowed[0]) - out["admin"] = False - out["role"] = "member" - return out - - def _visible(self, read_set: Iterable[str], types_exclude: Any) -> list[dict[str, Any]]: - excluded = {str(t) for t in types_exclude} if isinstance(types_exclude, list) else set() - scopes = set(read_set) - return [ - {k: v for k, v in block.items() if k != "archived"} - for block in self.blocks.values() - if block["scope"] in scopes and not block["archived"] and block["type"] not in excluded - ] - - def _manage( - self, key: FakeKey, action: str, body: Mapping[str, Any], read_set: list[str], echo: str | None - ) -> tuple[int, dict[str, Any], str | None]: - if action == "type-list": - return 200, {"success": True, "types": [{"name": name} for name in TYPE_NAMES]}, echo - if action == "get": - if "ids" in body: - ids = body.get("ids") - if self.without_c4: - return 400, _err("Missing required field: id", "missing_fields"), echo - if not isinstance(ids, list) or not 1 <= len(ids) <= MAX_IDS: - return 400, _err("ids: 1 to 16", "invalid_body"), echo - return 200, {"success": True, "blocks": [self._get_one(str(i), read_set) for i in ids]}, echo - block_id = str(body.get("id") or "") - if not block_id: - return 400, _err("Missing required field: id", "missing_fields"), echo - # The single get answers as ctx does today (go/internal/handler/context_manage.go handleGet): - # 200 with {"action": "get", "success": true, "block": ...}; a miss is 200 with - # {"success": false, "error": "Block not found"}. - one = self._get_one(block_id, read_set) - if "error" in one: - return 200, {"success": False, "error": "Block not found"}, echo - return 200, {"action": "get", "success": True, "block": one}, echo - if action == "keyset-provision": - return self._keyset_provision(key, body, echo) - return 200, {"success": True}, echo - - def _get_one(self, block_id: str, read_set: list[str]) -> dict[str, Any]: - block = self.blocks.get(block_id) - if block is None or block["archived"] or (block["scope"] not in read_set and not self.leak_on_get): - return {"id": block_id, "error": "block not found", "code": "not_found"} - return {k: v for k, v in block.items() if k != "archived"} - - def _keyset_provision( - self, admin: FakeKey, body: Mapping[str, Any], echo: str | None - ) -> tuple[int, dict[str, Any], str | None]: - # Wire form of the S1 contract, the same the Go test of C-3 pins - # (go/cmd/ctxd/keyset_provision_c3_integration_test.go): tenant owner or admin (or a ctx server - # admin); data.scopes = bare scope names, created when missing; the answer lists the scopes as - # {"scope", "created"} and the keys as {"id", "label", "home_scope", "allowed_scopes", - # "write_scopes", "scope_narrowing", "api_key"}, both in request order. - if admin.role not in ("owner", "admin") and not admin.admin: - return 403, _err("tenant admin required", "scope_denied"), echo - data = body.get("data") if isinstance(body.get("data"), dict) else {} - keys = data.get("keys") if isinstance(data.get("keys"), list) else [] - names = data.get("scopes") if isinstance(data.get("scopes"), list) else [] - if len(names) > 64: - return 400, _err("at most 64 scopes", "invalid_body"), echo - if len(keys) > 64: - return 400, _err("at most 64 keys", "invalid_body"), echo - active = [k for k in self.keys.values() if k.tenant == admin.tenant and k.active] - replaced = {str(spec.get("label")) for spec in keys if isinstance(spec, dict) and spec.get("replace_label")} - after = len([k for k in active if k.label not in replaced]) + len(keys) - if after > self.max_keys: - return ( - 429, - { - "success": False, - "error": "max_keys", - "code": "rate_limit", - "limit": self.max_keys, - "count": len(active), - }, - echo, - ) - scopes_out = [] - for name in names: - full = f"{admin.tenant}:{name}" - created = full not in self.scopes - self.scopes.add(full) - scopes_out.append({"scope": full, "created": created}) - out = [] - for spec in keys: - label = str(spec.get("label") or "") - if spec.get("replace_label"): - for other in active: - if other.label == label: - other.active = False - secret = "ctx_" + uuid.uuid4().hex - scope = lambda name: name if ":" in name else f"{admin.tenant}:{name}" # noqa: E731 - made = self.add_key( - secret=secret, - tenant=admin.tenant, - home=scope(str(spec.get("home_scope") or "")), - allowed=tuple(scope(str(s)) for s in spec.get("allowed_scopes") or ()), - write_scopes=tuple(scope(str(s)) for s in spec.get("write_scopes") or ()), - scope_narrowing=str(spec.get("scope_narrowing") or "optional"), - label=label, - ) - out.append( - { - "id": str(uuid.uuid4()), - "label": label, - "home_scope": made.home, - "allowed_scopes": list(made.allowed), - "write_scopes": list(made.write_scopes), - "scope_narrowing": made.scope_narrowing, - "api_key": secret, - } - ) - return 200, {"success": True, "scopes": scopes_out, "keys": out}, echo - - -def _shadowed_action(body: Mapping[str, Any]) -> bool: - """A second spelling of ``action`` (``{"action":"get","ACTION":"purge"}``) counts as another action.""" - return any(k.lower() == "action" and k != "action" for k in body) - - -def _err(text: str, code: str) -> dict[str, Any]: - return {"success": False, "error": text, "code": code} - - -__all__ = ["HEADER_NARROWED", "HEADER_READ", "HEADER_WRITE", "FakeCtx", "FakeKey", "Seen", "digest"] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py deleted file mode 100644 index fc032c8d1..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Clusters whose red S1 tests are still shielded (``tests/conftest.py`` gives each test marked -``access_cluster(<c>)`` with ``c`` listed here a strict xfail). Switching a cluster on = deleting -its line. ``CTX_S1_UNSHIELD=1`` lifts the shield for every cluster (the red proof).""" - -S1_PENDING = frozenset( - { - "P-A", - "P-B", - "P-C", - "P-D", - "P-E", - "P-F", - "P-G", - } -) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py deleted file mode 100644 index 3f7d2a70f..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py +++ /dev/null @@ -1,256 +0,0 @@ -"""P-A (design 02 §4.5, §7.3): the client narrows every call, checks the server's echo, proves a -binding by raw ``whoami`` answers and fetches base blocks with one multi-id ``get``. Red on S1: -``CtxClient`` keeps the narrowing but sends nothing, ``whoami_raw``/``evaluate``/``get_blocks`` are -stubs. Real ``CtxClient`` against the fake ctx server (``fakes/ctx_server.py``).""" - -from __future__ import annotations - -import time - -import pytest -from fakes.access_host import load_plugin, plugin_module - -pytestmark = pytest.mark.access_cluster("P-A") - -_PKG = load_plugin("ctx_checkpoint_access_pa") -_client = plugin_module(_PKG, "memory.client") -_nar = plugin_module(_PKG, "memory.narrowing") -CtxClient, CtxApiError = _client.CtxClient, _client.CtxApiError -Narrowing, Expect = _nar.Narrowing, _nar.Expect - -K, M, B = "t:d111-k", "t:d111-members", "t:d222-k" -LABEL = "hermes:discord:111:members" -MEMBER_KEY = "ctx_member_111" -OPS_KEY = "ctx_ops" - - -@pytest.fixture(autouse=True) -def _fresh_proofs(): - _nar.reset_proofs() - yield - _nar.reset_proofs() - - -def _keys(fake, *, narrowing="optional"): - fake.add_key( - secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing=narrowing, label=LABEL, role="member" - ) - fake.add_key(secret=OPS_KEY, tenant="t", home="t:d111-ops", allowed=(K, M, B), write_scopes=(K,), role="admin") - - -def _expect(**overrides): - values = { - "narrowing": Narrowing(read=(K,)), - "strict": True, - "tenant": "t", - "label": LABEL, - "env_names": ("CTX_KEY_111_MEMBERS",), - "platform_toolsets": ("web",), - "scope_id": "111", - "write": M, - } - values.update(overrides) - return Expect(**values) - - -def _raws(fake, secret=MEMBER_KEY, read=(K,), write=""): - return fake.whoami_answer(secret, read, write), fake.whoami_answer(secret) - - -def _baseline_ok(fake): - narrowed, unnarrowed = _raws(fake) - result = _nar.evaluate(narrowed, unnarrowed, _expect()) - assert result.ok, f"a key that fits the restricted layout proves the binding: {result}" - return narrowed, unnarrowed - - -# -- headers and echo --------------------------------------------------------------------------- - - -def test_narrowed_client_sends_read_scopes_on_search_store_get_and_type_list(fake_ctx): - _keys(fake_ctx) - block = fake_ctx.add_block(K, "rules", "be kind") - client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K, M), write=M)) - client.search("rules") - client.store("reference", "note", "text") - client.get_block(block) - client.query_types("rules", ["knowledge"], limit=3) - seen = fake_ctx.requests() - assert {(r.path, r.action) for r in seen} >= { - ("/api/search", ""), - ("/api/store", ""), - ("/api/manage", "get"), - ("/api/manage", "type-list"), - } - assert all(r.read_header == f"{K},{M}" for r in seen), [(r.path, r.read_header) for r in seen] - assert all(r.write_header == M for r in seen), [(r.path, r.write_header) for r in seen] - - -@pytest.mark.parametrize("fault", ["echo_missing", "echo_wrong"]) -def test_answer_without_the_right_echo_is_narrowing_lost(fake_ctx, fault): - _keys(fake_ctx) - setattr(fake_ctx, fault, True) - client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) - with pytest.raises(CtxApiError) as caught: - client.search("rules") - assert caught.value.code == "narrowing_lost" - - -@pytest.mark.s1_green -def test_client_without_narrowing_sends_no_narrowing_header(fake_ctx): - """Guard: a client built without ``narrowing`` stays as 0.19.1 (no header, no echo check).""" - _keys(fake_ctx) - fake_ctx.echo_missing = True - CtxClient(fake_ctx.url, OPS_KEY, timeout=5).search("rules") - assert [r.read_header for r in fake_ctx.requests()] == [None] - - -# -- proof: raw whoami answers, rules evaluated per binding -------------------------------------- - - -def test_whoami_raw_returns_the_narrowed_and_the_unnarrowed_answer(fake_ctx): - _keys(fake_ctx, narrowing="required") - client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) - narrowed = _nar.whoami_raw(client, narrowed=True, budget_s=3) - unnarrowed = _nar.whoami_raw(client, narrowed=False, budget_s=3) - assert narrowed.get("narrowed") == {"read": [K], "write": ""} - assert unnarrowed.get("narrowed") is None - assert unnarrowed.get("home_scope") == M - assert fake_ctx.count("/api/whoami", narrowed=True) == 1 - assert fake_ctx.count("/api/whoami", narrowed=False) == 1 - - -def test_server_without_narrowed_in_whoami_fails_e5(fake_ctx): - _keys(fake_ctx, narrowing="required") - _baseline_ok(fake_ctx) - fake_ctx.without_c1 = True - narrowed, unnarrowed = _raws(fake_ctx) - result = _nar.evaluate(narrowed, unnarrowed, _expect()) - assert not result.ok and "E5" in result.failed - - -def test_other_narrowed_list_fails_e5(fake_ctx): - _keys(fake_ctx, narrowing="required") - _baseline_ok(fake_ctx) - narrowed, unnarrowed = _raws(fake_ctx, read=(K, M)) - result = _nar.evaluate(narrowed, unnarrowed, _expect()) - assert not result.ok and "E5" in result.failed - - -@pytest.mark.parametrize( - ("change", "rule"), - [ - ("grant", "E3"), - ("write_not_home", "E3"), - ("admin", "E2"), - ("role", "E2"), - ("optional", "E2"), - ("tenant", "E2"), - ("label", "E4"), - ("toolset", "E7"), - ], -) -def test_strict_expectation_names_the_broken_rule(fake_ctx, change, rule): - _keys(fake_ctx, narrowing="required") - narrowed, unnarrowed = _baseline_ok(fake_ctx) - unnarrowed = dict(unnarrowed) - expect = _expect() - if change == "grant": - unnarrowed["read_scopes"] = [*unnarrowed["read_scopes"], "u:shared"] - elif change == "write_not_home": - expect = _expect(write="t:d111-mods") - elif change == "admin": - unnarrowed["admin"] = True - elif change == "role": - unnarrowed["role"] = "admin" - elif change == "optional": - unnarrowed["scope_narrowing"] = "optional" - elif change == "tenant": - expect = _expect(tenant="other") - elif change == "label": - expect = _expect(label="hermes:discord:111:mods") - elif change == "toolset": - expect = _expect(env_names=("CTX_KEY_111_MEMBERS", "CTX_KEY_222_MEMBERS"), platform_toolsets=("web", "file")) - result = _nar.evaluate(narrowed, unnarrowed, expect) - assert not result.ok - assert rule in result.failed, result - assert rule in result.detail and MEMBER_KEY not in str(result.detail) - - -def test_other_label_within_the_proof_ttl_is_off(fake_ctx): - """BP-21: the remembered answers are raw; a second binding with the same key and scopes but - another label is evaluated anew and fails E4.""" - _keys(fake_ctx, narrowing="required") - client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) - first = _nar.evaluate( - _nar.whoami_raw(client, narrowed=True, budget_s=3), - _nar.whoami_raw(client, narrowed=False, budget_s=3), - _expect(), - ) - assert first.ok, first - second = _nar.evaluate( - _nar.whoami_raw(client, narrowed=True, budget_s=3), - _nar.whoami_raw(client, narrowed=False, budget_s=3), - _expect(label="hermes:discord:111:other-profile"), - ) - assert fake_ctx.count("/api/whoami") == 2, "the second binding reads the remembered answers" - assert not second.ok and "E4" in second.failed - - -def test_failed_proof_is_remembered_15_s_then_asked_again(fake_ctx, monkeypatch): - _keys(fake_ctx, narrowing="required") - fake_ctx.throttle["/api/whoami"] = 2 # the first answer and its one retry are 429 - client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) - clock = [time.monotonic()] - monkeypatch.setattr(time, "monotonic", lambda: clock[0]) - with pytest.raises(CtxApiError): - _nar.whoami_raw(client, narrowed=True, budget_s=3) - asked = fake_ctx.count("/api/whoami") - with pytest.raises(CtxApiError): - _nar.whoami_raw(client, narrowed=True, budget_s=3) - assert fake_ctx.count("/api/whoami") == asked, "a failure is remembered" - clock[0] += _nar.PROOF_TTL_FAILED_S + 1 - assert _nar.whoami_raw(client, narrowed=True, budget_s=3).get("narrowed") == {"read": [K], "write": ""} - assert fake_ctx.count("/api/whoami") == asked + 1 - - -def test_proof_holds_its_budget(fake_ctx): - _keys(fake_ctx, narrowing="required") - fake_ctx.latency["/api/whoami"] = 4.0 - client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=10, narrowing=Narrowing(read=(K,))) - started = time.monotonic() - with pytest.raises(CtxApiError): - _nar.whoami_raw(client, narrowed=True, budget_s=1.0) - assert time.monotonic() - started < 2.0 - - -def test_expected_label_and_its_hash_past_100_characters(): - assert _nar.expected_label("discord", "111", "members") == LABEL - long_profile = "p" * 120 - label = _nar.expected_label("discord", "111", long_profile) - assert len(label) <= _nar.LABEL_MAX - assert label.startswith("hermes:discord:111:#") and len(label.rsplit("#", 1)[1]) == 16 - - -# -- multi-id get (C-4) and its fallback --------------------------------------------------------- - - -def test_get_blocks_is_one_request_with_ids(fake_ctx): - _keys(fake_ctx) - first = fake_ctx.add_block(K, "one", "1") - second = fake_ctx.add_block(K, "two", "2") - client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) - blocks = client.get_blocks([second, "missing-id", first]) - assert [b.get("id") for b in blocks] == [second, "missing-id", first] - assert blocks[1].get("code") == "not_found" and "error" in blocks[1] - assert fake_ctx.count("/api/manage", "get") == 1 - - -def test_get_blocks_falls_back_to_one_get_per_id_on_400(fake_ctx): - _keys(fake_ctx) - fake_ctx.without_c4 = True - ids = [fake_ctx.add_block(K, f"b{i}", str(i)) for i in range(3)] - client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) - blocks = client.get_blocks(ids) - assert [b.get("title") for b in blocks] == ["b0", "b1", "b2"] - assert fake_ctx.count("/api/manage", "get") == 1 + len(ids) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_decide.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_decide.py deleted file mode 100644 index 0336898b8..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_decide.py +++ /dev/null @@ -1,291 +0,0 @@ -"""P-B (design 02 §3.1, §3.2, §3.6, §4.1 steps 1-2, §4.2 table): detection, the field schema, the -decision table and the markers. Red on S1: ``access_supported``/``decide``/``parse_fields``/markers -are stubs and ``register`` registers no fields. Aligned to the core PR's code: ``initialize`` always -gets the five access kwargs, ``access_group_restricted`` is the group's (the draft had no -restriction in V5, VB-11).""" - -from __future__ import annotations - -import json -import logging -import re - -import pytest -from fakes import access_host as ah - -pytestmark = pytest.mark.access_cluster("P-B") - -_PKG = ah.load_plugin("ctx_checkpoint_access_pb") -acc = ah.plugin_module(_PKG, "memory.access") - -K, M = "t:d111-k", "t:d111-members" -RESTRICTED_FIELDS = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [K], "write": M, "base_blocks": ["b1"]} -OPS_FIELDS = {"key": "CTX_KEY_OPS", "read": [K], "write": "t:d111-ops"} - - -def _settings(**overrides): - return {**dict(acc.SETTINGS_DEFAULTS), **overrides} - - -def _init(platform="discord", agent_context="primary", **v5): - return {"platform": platform, "agent_context": agent_context, "hermes_home": "/h/profiles/members", **v5} - - -def _decide(init, *, current=None, parent=None, markers=None, v8=True, **settings): - return acc.decide(init, current, parent, _settings(**settings), markers or acc.Markers(), v8) - - -def _group_init(fields, *, restricted=True, truth_filter=False): - return _init( - **ah.v5_kwargs( - scope_id="111", group="members", group_restricted=restricted, fields=fields, truth_filter=truth_filter - ) - ) - - -# -- register(ctx): detection (V8b), fields (V3) ------------------------------------------------- - - -def test_register_on_a_host_with_v8_registers_the_schema(monkeypatch): - host = ah.install(monkeypatch, v8=True) - collector = host.collector() - _PKG.register(collector) - assert collector.access_fields == [acc.SCHEMA] - assert collector.called("register_memory_provider") == 1 - - -@pytest.mark.s1_green -def test_register_on_a_host_without_v8_calls_nothing_new_and_warns_nothing(monkeypatch, caplog): - """Guard: the collector answers every ``register_*``; detection reads the class, so a pre-PR - host sees no call and no WARNING.""" - host = ah.install(monkeypatch, v8=False) - collector = host.collector() - with caplog.at_level(logging.WARNING): - _PKG.register(collector) - assert collector.called("register_access_fields") == 0 - assert collector.called("register_hook") == 0 - assert collector.called("register_memory_provider") == 1 - assert not [r for r in caplog.records if r.levelno >= logging.WARNING] - - -def test_access_supported_reads_the_public_class(monkeypatch): - ah.install(monkeypatch, v8=True) - assert acc.access_supported() is True - ah.install(monkeypatch, v8=False) - assert acc.access_supported() is False - - -@pytest.mark.s1_green -def test_schema_fits_the_core_rules(): - assert 0 < len(acc.SCHEMA) <= ah.MAX_FIELDS - for name, spec in acc.SCHEMA.items(): - assert re.match(ah.FIELD_NAME, name), name - assert set(spec) <= ah.SPEC_KEYS - {"default"}, (name, spec) - assert spec["type"] in ah.FIELD_TYPES, (name, spec) - assert "Not set" in spec.get("description", ""), name - - -# -- current_access (V6a) and the init kwargs (V5) ----------------------------------------------- - - -def test_current_access_gives_this_plugins_namespace(monkeypatch): - ah.install(monkeypatch, v8=True) - access = ah.make_access(fields=RESTRICTED_FIELDS) - with ah.turn(access): - got = acc.current_access() - assert got is not None - assert (got.platform, got.scope_id, got.group, got.profile, got.restricted) == ( - "discord", - "111", - "members", - "members", - True, - ) - assert dict(got.fields) == RESTRICTED_FIELDS - - -@pytest.mark.s1_green -def test_current_access_is_none_outside_a_turn_and_without_the_core(monkeypatch): - ah.install(monkeypatch, v8=True) - assert acc.current_access() is None - ah.install(monkeypatch, v8=False) - assert acc.current_access() is None - - -def test_context_from_init_takes_the_groups_restriction(): - ctx = acc.context_from_init(_group_init(RESTRICTED_FIELDS, restricted=False)) - assert ctx is not None - assert (ctx.scope_id, ctx.group, ctx.restricted) == ("111", "members", False) - assert dict(ctx.fields) == RESTRICTED_FIELDS - assert acc.context_from_init(_init(**ah.v5_kwargs())) is None - - -def test_is_strict_follows_the_group_then_profile_then_marker(): - open_group = acc.AccessContext("discord", "111", "ops", "ops", False) - unknown = acc.AccessContext("discord", "111", "ops", "ops", None) - assert acc.is_strict(open_group, restricted_profile=False, markers=acc.Markers()) is False - assert acc.is_strict(unknown, restricted_profile=True, markers=acc.Markers()) is True - assert acc.is_strict(unknown, restricted_profile=False, markers=acc.Markers(restricted_seen=True)) is True - - -# -- the decision table (§4.2), one case per row -------------------------------------------------- - - -def test_row1_v8_false_with_restricted_seen_is_off(): - decision = _decide(_init(platform="cli"), v8=False, markers=acc.Markers(restricted_seen=True)) - assert decision.kind == "off" - - -@pytest.mark.s1_green -def test_row1_v8_false_without_marker_is_the_profile_connection(): - assert _decide(_init(platform="cli"), v8=False).kind == "profile" - - -def test_row2_group_with_fields_binds_the_group(): - decision = _decide(_group_init(RESTRICTED_FIELDS)) - assert decision.kind == "group" - assert decision.strict is True - assert decision.fields is not None - assert (decision.fields.read, decision.fields.write, decision.fields.tenant) == ((K,), M, "t") - - -def test_row2_enabled_false_is_off(): - assert _decide(_group_init({**RESTRICTED_FIELDS, "enabled": False})).kind == "off" - - -def test_row2_without_key_restricted_off_unrestricted_governed_unbound(): - no_key = {k: v for k, v in OPS_FIELDS.items() if k != "key"} - restricted_no_key = {k: v for k, v in RESTRICTED_FIELDS.items() if k != "key"} - assert _decide(_group_init(restricted_no_key, restricted=True)).kind == "off" - assert _decide(_group_init(no_key, restricted=False)).kind == "off" - assert _decide(_group_init(no_key, restricted=False), governed_unbound="profile").kind == "profile" - - -def test_row3_group_without_fields_restricted_off_unrestricted_governed_unbound(): - assert _decide(_group_init({}, restricted=True)).kind == "off" - assert _decide(_group_init({}, restricted=False)).kind == "off" - assert _decide(_group_init({}, restricted=False), governed_unbound="profile").kind == "profile" - - -@pytest.mark.parametrize("profile", ["members", None]) -def test_row4_background_with_a_turn_context_binds_its_group(profile): - current = acc.AccessContext("discord", "111", "members", profile, True, fields=RESTRICTED_FIELDS) - decision = _decide(_init(platform="discord", agent_context="primary", **ah.v5_kwargs()), current=current) - assert decision.kind == "group" and decision.strict is True - - -def test_row5_restricted_profile_is_off(): - assert _decide(_init(platform="cli", **ah.v5_kwargs(restricted_profile=True))).kind == "off" - - -def test_row6_restricted_seen_is_off_even_when_the_host_drops_false_values(): - init = _init(platform="cli", **ah.v5_kwargs(restricted_profile=False, truth_filter=True)) - assert "restricted_profile" not in init - assert _decide(init, markers=acc.Markers(restricted_seen=True)).kind == "off" - - -def test_row7_messaging_session_without_context_after_governed_seen_is_off(): - init = _init(platform="discord", **ah.v5_kwargs()) - assert _decide(init, markers=acc.Markers(governed_seen=True), ungoverned="profile").kind == "off" - - -def test_parent_platform_comes_from_the_session_never_from_the_process_env(monkeypatch): - """Row 7 and ``ungoverned: local`` for forks read the copied ``HERMES_SESSION_PLATFORM`` only - through ``get_session_env`` and only while the name is not in ``os.environ`` (where - ``get_session_env`` would answer with the process value).""" - import gateway.session_context as session_context - - def session_env(name, default=""): - return "discord" if name == "HERMES_SESSION_PLATFORM" else default - - monkeypatch.setattr(session_context, "get_session_env", session_env) - monkeypatch.delenv("HERMES_SESSION_PLATFORM", raising=False) - assert acc.session_parent_platform() == "discord" - monkeypatch.setenv("HERMES_SESSION_PLATFORM", "discord") - assert acc.session_parent_platform() is None - - -def test_row8_auto_is_profile_before_and_local_after_governed_seen(): - discord = _init(platform="discord", **ah.v5_kwargs()) - cli = _init(platform="cli", **ah.v5_kwargs()) - assert _decide(discord).kind == "profile" - assert _decide(discord, markers=acc.Markers(governed_seen=True)).kind == "off" - assert _decide(cli, markers=acc.Markers(governed_seen=True)).kind == "profile" - - -@pytest.mark.parametrize( - ("platform", "agent_context", "parent", "kind"), - [ - ("cli", "primary", None, "profile"), - ("tui", "primary", None, "profile"), - ("cron", "cron", None, "off"), - ("api_server", "primary", None, "off"), - ("discord", "primary", None, "off"), - ("cli", "subagent", "cli", "profile"), - ("discord", "subagent", "discord", "off"), - ], -) -def test_ungoverned_local_admits_local_sessions_only(platform, agent_context, parent, kind): - init = _init(platform=platform, agent_context=agent_context, **ah.v5_kwargs()) - assert _decide(init, parent=parent, ungoverned="local").kind == kind - assert _decide(init, parent=parent, ungoverned="off").kind == "off" - - -# -- fields: forms before any secret -------------------------------------------------------------- - - -def test_parse_fields_accepts_the_restricted_layout(): - parsed = acc.parse_fields(RESTRICTED_FIELDS, scope_id="111", strict=True) - assert isinstance(parsed, acc.GroupFields), parsed - assert parsed.recall is None or parsed.recall is False - assert parsed.base_blocks == ("b1",) and parsed.base_max_chars == 4000 and parsed.enabled is True - - -@pytest.mark.parametrize( - ("change", "field", "strict"), - [ - ({"key": "OPENAI_API_KEY"}, "key", False), - ({"key": "CTX_KEY_222_MEMBERS"}, "key", True), - ({"base_url": "HOME_URL"}, "base_url", False), - ({"read": ["no scope"]}, "read", False), - ({"read": [f"t:s{i}" for i in range(9)]}, "read", False), - ({"write": "t:d111-k"}, "write", True), - ({"tenant": "Bad_Slug"}, "tenant", False), - ({"base_blocks": [f"b{i}" for i in range(17)]}, "base_blocks", False), - ({"base_max_chars": 100}, "base_max_chars", False), - ], -) -def test_parse_fields_names_the_broken_field(change, field, strict): - assert isinstance(acc.parse_fields(RESTRICTED_FIELDS, scope_id="111", strict=True), acc.GroupFields) - parsed = acc.parse_fields({**RESTRICTED_FIELDS, **change}, scope_id="111", strict=strict) - assert isinstance(parsed, acc.FieldError) and parsed.field == field, parsed - assert str(change[field]) not in parsed.reason - - -# -- settings and markers (§3.2, §3.6) ------------------------------------------------------------ - - -def test_settings_come_from_config_yaml_never_from_ctx_json(tmp_path): - (tmp_path / "config.yaml").write_text( - "memory:\n ctx_checkpoint:\n governed_unbound: profile\n base_timeout_s: 99\n", encoding="utf-8" - ) - (tmp_path / "ctx.json").write_text(json.dumps({"ungoverned": "off"}), encoding="utf-8") - settings = acc.load_settings(str(tmp_path)) - assert settings["governed_unbound"] == "profile" - assert settings["ungoverned"] == "auto" - assert settings["base_timeout_s"] == 10 - - -def test_markers_only_rise(tmp_path): - home = str(tmp_path) - acc.raise_markers(home, restricted_seen=True) - assert acc.read_markers(home).restricted_seen is True - acc.raise_markers(home, restricted_seen=False, governed_seen=True) - assert acc.read_markers(home) == acc.Markers(restricted_seen=True, governed_seen=True) - - -def test_unreadable_marker_file_counts_as_both_set(tmp_path): - state = tmp_path / "ctx_state" - state.mkdir() - (state / "access-mode.json").write_text("{not json", encoding="utf-8") - assert acc.read_markers(str(tmp_path)) == acc.Markers(restricted_seen=True, governed_seen=True) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py deleted file mode 100644 index 05fc79e9d..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py +++ /dev/null @@ -1,176 +0,0 @@ -"""P-C (design 02 §4.2 steps 0, 3-9, §4.6): the provider binds a group, or nothing, from the access -kwargs every ``initialize`` gets (V5) and drops a binding whose group changed under it (V6a). Red on -S1: the provider ignores the access kwargs and connects as 0.19.1 with the profile's key. Real -``CtxCheckpointMemoryProvider`` over REST against the fake ctx server, secrets from the fake -secret scope.""" - -from __future__ import annotations - -import pytest -from fakes import access_host as ah -from fakes.ctx_server import digest - -pytestmark = pytest.mark.access_cluster("P-C") - -_PKG = ah.load_plugin("ctx_checkpoint_access_pc") -_cfg = ah.plugin_module(_PKG, "memory.config") -Provider = _PKG.CtxCheckpointMemoryProvider - -A_K, A_OPS, B_K = "t:d111-k", "t:d111-ops", "t:d222-k" -A_MEMBERS = "t:d111-members" -PROFILE_KEY = "ctx_profile_operator" -OPS_A_KEY = "ctx_ops_a" -MEMBER_KEY = "ctx_member_111" -MEMBER_LABEL = "hermes:discord:111:members" -OPS_FIELDS = {"key": "CTX_KEY_111_OPS", "read": [A_K], "write": A_OPS} -MEMBER_FIELDS = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [A_K], "write": A_MEMBERS} - - -@pytest.fixture -def world(fake_ctx, monkeypatch, tmp_path): - fake_ctx.add_key(secret=PROFILE_KEY, tenant="t", home="t:main", allowed=(A_K, B_K, A_OPS, A_MEMBERS)) - fake_ctx.add_key(secret=OPS_A_KEY, tenant="t", home=A_OPS, allowed=(A_K,), write_scopes=(A_K,)) - fake_ctx.add_key( - secret=MEMBER_KEY, tenant="t", home=A_MEMBERS, allowed=(A_K,), scope_narrowing="required", label=MEMBER_LABEL - ) - fake_ctx.add_block(A_K, "Server A rules", "alpha knowledge") - fake_ctx.add_block(B_K, "Server B secret plans", "bravo knowledge") - fake_ctx.add_block(A_MEMBERS, "member transcript", "what another member said") - host = ah.install( - monkeypatch, - v8=True, - secrets={ - "CTX_KEY": PROFILE_KEY, - "CTX_BASE_URL": fake_ctx.url, - "CTX_KEY_111_OPS": OPS_A_KEY, - "CTX_KEY_111_MEMBERS": MEMBER_KEY, - }, - ) - home = tmp_path / "profiles" / "members" - home.mkdir(parents=True) - return fake_ctx, host, home - - -def _write_settings(home, text): - (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n" + text, encoding="utf-8") - - -def _provider(home, *, platform="discord", **v5): - provider = Provider(config={"transport": "rest", "memory": True}) - provider.initialize("s-1", hermes_home=str(home), platform=platform, agent_context="primary", **v5) - return provider - - -def test_restricted_profile_group_without_fields_sends_nothing(world): - fake, _host, home = world - provider = _provider( - home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, restricted_profile=True) - ) - text = provider.prefetch("what are the plans?") - assert fake.count() == 0, [(r.path, r.action) for r in fake.requests()] - assert text == "" and provider.get_tool_schemas() == [] and provider.system_prompt_block() == "" - - -def test_session_in_server_a_never_reads_server_b(world): - fake, _host, home = world - provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) - text = provider.prefetch("what are the plans?") - assert "bravo knowledge" not in text - assert "alpha knowledge" in text - assert all(r.read_header == A_K for r in fake.requests() if r.path != "/api/whoami") - assert {r.key_digest for r in fake.requests()} == {digest(OPS_A_KEY)} - - -def test_changed_fields_under_a_cached_agent_turn_the_binding_off(world): - fake, _host, home = world - provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) - changed = ah.make_access(group="ops", profile="members", restricted=False, fields={**OPS_FIELDS, "read": [B_K]}) - fake.reset_counters() - with ah.turn(changed): - text = provider.prefetch("what are the plans?") - assert text == "" and fake.count() == 0 - with ah.turn(None): - assert provider.prefetch("what are the plans?") == "", "the trip wire turns the instance off for good" - - -def test_member_layout_binds_and_recall_never_reads_the_write_scope(world): - _fake, _host, home = world - _write_settings(home, " restricted_allow: [recall]\n") - fields = {**MEMBER_FIELDS, "recall": True} - provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields)) - text = provider.prefetch("rules?") - assert "alpha knowledge" in text - assert "what another member said" not in text - names = [s.get("name") for s in provider.get_tool_schemas()] - assert "ctx_store" not in names and "ctx_query" in names - - -def test_swapped_fields_are_off_e3(world): - fake, _host, home = world - swapped = {**MEMBER_FIELDS, "read": [A_MEMBERS], "write": A_K, "recall": True} - _write_settings(home, " restricted_allow: [recall]\n") - provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=swapped)) - assert fake.count("/api/whoami") >= 1, "the proof asked the server" - fake.reset_counters() - assert provider.prefetch("rules?") == "" and fake.count() == 0 - - -def test_restricted_recall_without_restricted_allow_stays_off(world): - fake, _host, home = world - fields = {**MEMBER_FIELDS, "recall": True} - provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields)) - assert fake.count("/api/whoami", narrowed=True) == 1, "the group is proven" - fake.reset_counters() - assert provider.prefetch("rules?") == "" and fake.count() == 0 - - -def test_foreign_key_in_env_with_file_toolset_is_off_e7(world): - fake, _host, home = world - _write_settings(home, " restricted_allow: [recall]\n") - (home / ".env").write_text("CTX_KEY_111_MEMBERS=x\nCTX_KEY_222_MEMBERS=y\n", encoding="utf-8") - (home / "config.yaml").write_text( - "platform_toolsets:\n discord: [web, file]\nmemory:\n ctx_checkpoint:\n restricted_allow: [recall]\n", - encoding="utf-8", - ) - fields = {**MEMBER_FIELDS, "recall": True} - provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields)) - assert fake.count("/api/whoami") >= 1, "E7 is evaluated with the proof" - fake.reset_counters() - assert provider.prefetch("rules?") == "" and fake.count() == 0 - - -def test_invalid_key_name_reads_no_secret_and_sends_nothing(world): - fake, host, home = world - bad = {**OPS_FIELDS, "key": "OPENAI_API_KEY"} - host.secrets.reads.clear() - _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=bad)) - assert host.secrets.reads["OPENAI_API_KEY"] == 0 - assert fake.count() == 0 - - -def test_reinit_that_fails_validation_reads_nothing_after(world): - fake, _host, home = world - provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) - assert "alpha knowledge" in provider.prefetch("plans?") - provider.initialize( - "s-2", - hermes_home=str(home), - platform="discord", - **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields={**OPS_FIELDS, "read": ["bad"]}), - ) - fake.reset_counters() - assert provider.prefetch("plans?") == "" and fake.count() == 0 - - -def test_profile_without_default_key_is_available_with_ungoverned_local(world, monkeypatch): - fake, host, home = world - host.secrets.set_base({"CTX_BASE_URL": fake.url}) - _write_settings(home, " ungoverned: local\n") - monkeypatch.setenv("HERMES_HOME", str(home)) - assert Provider(config={"transport": "rest"}).is_available() is True - - -def test_group_and_server_tags_are_reserved_for_the_plugin(): - tags = _cfg.merge_tags(["server:discord:999", "group:admins", "topic"], "members", "tool") - assert "topic" in tags - assert not [t for t in tags if t.startswith(("server:", "group:"))] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py deleted file mode 100644 index 6c66188bc..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py +++ /dev/null @@ -1,235 +0,0 @@ -"""P-D (design 02 §4.1 step 3, §4.4): the hook ``access_group_fields`` puts the group's base blocks -into its prompt, whole or not at all, without holding the gateway loop. Red on S1: ``register`` -registers no hook and the callback returns ``None``. Driven through the core's dispatcher form -(``fakes.access_host.ainvoke_hook_callback``) against the fake ctx server. - -Aligned to the core PR's code, not the draft: the core passes ``restricted`` (the group's) to the -hook, so "unknown" is only the absence of that kwarg (an older core); a plain callback would run on a -daemon thread of its own, not inline on the loop (the draft's reason for ``async def`` is now the -bounded ``wait_for`` and the cancellation, not a blocked loop).""" - -from __future__ import annotations - -import asyncio -import inspect -import time - -import pytest -from fakes import access_host as ah - -pytestmark = pytest.mark.access_cluster("P-D") - -_PKG = ah.load_plugin("ctx_checkpoint_access_pd") -bb = ah.plugin_module(_PKG, "memory.base_blocks") -_nar = ah.plugin_module(_PKG, "memory.narrowing") - -K, M, B = "t:d111-k", "t:d111-members", "t:d222-k" -MEMBER_KEY = "ctx_member_111_secret_value" -LABEL = "hermes:discord:111:members" - - -@pytest.fixture -def world(fake_ctx, monkeypatch, _isolated_hermes_home): - bb.reset_state() - _nar.reset_proofs() - fake_ctx.add_key( - secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=LABEL, role="member" - ) - ids = { - "one": fake_ctx.add_block(K, "House rules", "Be kind to each other."), - "two": fake_ctx.add_block(K, "FAQ", "Ask in #help."), - "other_server": fake_ctx.add_block(B, "Server B notes", "bravo"), - "own_write": fake_ctx.add_block(M, "Member chatter", "said by a member"), - } - host = ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) - yield fake_ctx, host, ids, _isolated_hermes_home - bb.reset_state() - _nar.reset_proofs() - - -def _fields(ids, *names, **extra): - own = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [K], "write": M} - own["base_blocks"] = [ids.get(n, n) for n in names] - own.update(extra) - return {"ctx_checkpoint": own} - - -def _call(fields, **overrides): - kwargs = ah.hook_kwargs(fields=fields, **overrides) - return asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs)) - - -def _prompt(outcome): - assert outcome.answered, f"the hook failed: {outcome.error!r}" - assert isinstance(outcome.result, dict) and isinstance(outcome.result.get("prompt"), str), outcome.result - return outcome.result["prompt"] - - -def test_hook_gives_the_prompt_of_two_base_blocks(world): - _fake, _host, ids, _home = world - text = _prompt(_call(_fields(ids, "one", "two"))) - assert text.startswith(bb.HEADING) - assert text.index("### House rules") < text.index("### FAQ") - assert "Be kind to each other." in text and "Ask in #help." in text - - -def test_register_on_v8_registers_the_async_hook(monkeypatch): - host = ah.install(monkeypatch, v8=True) - collector = host.collector() - _PKG.register(collector) - callbacks = collector.hooks.get("access_group_fields") or [] - assert len(callbacks) == 1 and inspect.iscoroutinefunction(callbacks[0]) - - -@pytest.mark.s1_green -def test_restricted_group_without_fields_is_none_with_no_request_and_no_secret(world): - fake, host, _ids, _home = world - host.secrets.reads.clear() - outcome = _call({}) - assert outcome.answered and outcome.result is None - assert fake.count() == 0 and host.secrets.total_reads() == 0 - - -@pytest.mark.s1_green -def test_enabled_false_is_none_with_no_request_and_no_secret(world): - fake, host, ids, _home = world - host.secrets.reads.clear() - outcome = _call(_fields(ids, "one", enabled=False)) - assert outcome.answered and outcome.result is None - assert fake.count() == 0 and host.secrets.total_reads() == 0 - - -def test_unknown_strictness_counts_as_restricted(world): - fake, _host, ids, _home = world - no_tenant = _fields(ids, "one") - del no_tenant["ctx_checkpoint"]["tenant"] - kwargs = ah.hook_kwargs(fields=no_tenant) - del kwargs["restricted"] # an older core: the group's restriction is not told - outcome = asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs)) - assert outcome.answered and outcome.result is None and fake.count() == 0 - assert "House rules" in _prompt(_call(no_tenant, restricted=False)) - - -def test_swapped_fields_are_none_without_get(world): - fake, _host, ids, _home = world - assert "House rules" in _prompt(_call(_fields(ids, "one"))) - bb.reset_state() - fake.reset_counters() - swapped = _fields(ids, "one", read=[M], write=K) - outcome = _call(swapped) - assert outcome.answered and outcome.result is None - assert fake.count("/api/manage", "get") == 0 - - -def test_block_outside_read_is_skipped(world): - _fake, _host, ids, _home = world - text = _prompt(_call(_fields(ids, "one", "other_server"))) - assert "House rules" in text and "bravo" not in text - - -def test_block_of_the_write_scope_is_refused_e6(world): - fake, _host, ids, _home = world - fake.leak_on_get = True # a server that answers outside the narrowing: E6 holds on the client too - text = _prompt(_call(_fields(ids, "one", "own_write"))) - assert "House rules" in text and "said by a member" not in text - - -def test_render_is_deterministic_and_cut_with_a_marker(): - blocks = [bb.BaseBlock("1", "First", "a" * 300, K), bb.BaseBlock("2", "Second", "b" * 300, K)] - once, twice = bb.render(blocks, 4000), bb.render(blocks, 4000) - assert once == twice and once.startswith(bb.HEADING) and "### First" in once and "### Second" in once - short = bb.render(blocks, 200) - assert len(short) <= 200 and short.endswith(bb.TRUNCATED_MARK) and "### Second" not in short - - -def test_key_value_in_a_block_is_redacted(world): - fake, _host, ids, _home = world - leaked = fake.add_block(K, "Leaky", f"the key is {MEMBER_KEY} here") - text = _prompt(_call(_fields(ids, leaked))) - assert "Leaky" in text and MEMBER_KEY not in text - - -def test_base_rev_changes_the_cache_key(world): - fake, _host, ids, _home = world - _prompt(_call(_fields(ids, "one"))) - _prompt(_call(_fields(ids, "one"))) - assert fake.count("/api/manage", "get") == 1, "the second call is a cache hit" - _prompt(_call(_fields(ids, "one", base_rev=1))) - assert fake.count("/api/manage", "get") == 2 - - -def test_loop_stays_free_while_a_fetch_hangs(world): - fake, _host, ids, _home = world - fake.latency["manage:get"] = 3.0 - kwargs = ah.hook_kwargs(fields=_fields(ids, "one")) - ticks = [] - - async def ticker(stop): - while not stop.is_set(): - ticks.append(time.monotonic()) - await asyncio.sleep(0.1) - - async def main(): - stop = asyncio.Event() - tick = asyncio.create_task(ticker(stop)) - outcome = await ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs) - stop.set() - await tick - return outcome - - text = _prompt(asyncio.run(main())) - assert "House rules" in text - assert len(ticks) >= 15, f"the loop ran only {len(ticks)} ticks during a 3 s fetch" - - -def test_budget_ends_in_unavailable_never_a_partial_text(world): - fake, _host, ids, home = world - (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n base_timeout_s: 1\n", encoding="utf-8") - fake.latency["manage:get"] = 5.0 - started = time.monotonic() - outcome = _call(_fields(ids, "one", "two")) - assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome - assert time.monotonic() - started < 1.5 - - -def test_transient_failure_of_one_block_is_unavailable(world): - fake, _host, ids, _home = world - fake.without_c4 = True - fake.throttle["manage:get"] = 4 # the multi-id get is refused (400 without C-4); per-id gets meet 429s - outcome = _call(_fields(ids, "one", "two")) - assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome - - -def test_one_request_with_c4_one_per_id_without(world): - fake, _host, ids, _home = world - _prompt(_call(_fields(ids, "one", "two"))) - assert fake.count("/api/manage", "get") == 1 - bb.reset_state() - fake.reset_counters() - fake.without_c4 = True - _prompt(_call(_fields(ids, "one", "two"))) - assert fake.count("/api/manage", "get") == 3 - - -def test_concurrent_calls_with_the_same_key_fetch_once(world): - fake, _host, ids, _home = world - fake.latency["manage:get"] = 0.5 - kwargs = ah.hook_kwargs(fields=_fields(ids, "one")) - - async def main(): - return await asyncio.gather( - ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs), - ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs), - ) - - first, second = asyncio.run(main()) - assert _prompt(first) == _prompt(second) - assert fake.count("/api/manage", "get") == 1 - - -def test_secret_of_the_turn_scope_is_read_in_the_hook(world): - fake, host, ids, _home = world - host.secrets.set_base({"CTX_BASE_URL": fake.url}) - with host.secrets.scoped({"CTX_BASE_URL": fake.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}): - text = _prompt(_call(_fields(ids, "one"))) - assert "House rules" in text and host.secrets.reads["CTX_KEY_111_MEMBERS"] >= 1 diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py deleted file mode 100644 index f374805d6..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py +++ /dev/null @@ -1,111 +0,0 @@ -"""P-E (design 02 §3.6, §4.7): per-binding status files and ``hermes ctx_checkpoint access ...``. -Red on S1: ``record_access``/``read_access`` and ``access_cli`` are stubs. ``provision`` runs against -the fake ctx server's ``keyset-provision`` (C-3).""" - -from __future__ import annotations - -import re - -import pytest -from fakes import access_host as ah - -pytestmark = pytest.mark.access_cluster("P-E") - -_PKG = ah.load_plugin("ctx_checkpoint_access_pe") -st = ah.plugin_module(_PKG, "memory.status") -cli = ah.plugin_module(_PKG, "memory.access_cli") -acc = ah.plugin_module(_PKG, "memory.access") - -ADMIN_KEY = "ctx_admin_MARKED_FAKE_KEY_do_not_store" -OFF_RESULT = { - "state": "off: E4", - "rules": {"E4": "label hermes:discord:111:members"}, - "key_digest": "0123456789abcdef", - "tenant_slug": "t", - "read": ["t:d111-k"], - "write": "t:d111-members", -} - - -def _files_text(root): - return "\n".join(p.read_text(encoding="utf-8", errors="replace") for p in root.rglob("*") if p.is_file()) - - -def test_record_access_is_read_back_without_a_key_value(tmp_path): - st.record_access(str(tmp_path), "discord", "111", "members", {**OFF_RESULT, "key": "ctx_secret_value"}) - rows = st.read_access(str(tmp_path)) - assert len(rows) == 1 and rows[0].get("state") == "off: E4" - assert (tmp_path / "ctx_state" / "access" / "discord-111-members.json").is_file() - assert "ctx_secret_value" not in _files_text(tmp_path) - - -def test_access_status_names_an_off_binding(tmp_path, capsys): - st.record_access(str(tmp_path), "discord", "111", "members", OFF_RESULT) - assert cli.run_access(["status"], hermes_home=str(tmp_path)) == 0 - out = capsys.readouterr().out - assert "111" in out and "off: E4" in out and "api-key-update" in out - - -def test_reset_marker_lowers_the_markers(tmp_path): - home = str(tmp_path) - acc.raise_markers(home, restricted_seen=True, governed_seen=True) - assert acc.read_markers(home) == acc.Markers(True, True) - assert cli.run_access(["reset-marker", "--profile", "members", "--restricted"], hermes_home=home) == 0 - assert acc.read_markers(home) == acc.Markers(False, True) - - -def test_scope_names_fit_the_ctx_pattern_and_refuse_collisions(): - layout = cli.scope_layout("1234567890123456789", ["members", "Mod_Team_With_A_Long_Name"]) - assert layout.get(cli.KNOWLEDGE, "").endswith("-k") - assert set(layout) == {cli.KNOWLEDGE, "members", "Mod_Team_With_A_Long_Name"} - for name in layout.values(): - assert cli.SCOPE_NAME.match(name) and "_" not in name, name - assert layout["members"].startswith("d") and len(layout["members"]) <= 24 - with pytest.raises(ValueError): - cli.scope_layout("111", ["a_b", "a-b"]) - - -def test_key_variable_name_is_bounded(): - name = cli.key_env_name("1234567890123456789", "members-eu") - assert name == "CTX_KEY_1234567890123456789_MEMBERS_EU" - long_name = cli.key_env_name("1234567890123456789", "p" * 80) - assert ( - len(long_name) <= 64 and cli.ENV_NAME.match(long_name) and long_name.startswith("CTX_KEY_1234567890123456789_") - ) - - -def _provision_world(fake_ctx, monkeypatch, home): - fake_ctx.add_key(secret=ADMIN_KEY, tenant="t", home="t:main", role="admin") - host = ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_ADMIN": ADMIN_KEY}) - monkeypatch.setenv("CTX_ADMIN", ADMIN_KEY) - monkeypatch.setenv("CTX_BASE_URL", fake_ctx.url) - return host - - -def _provision(home, *extra): - argv = ["provision", "--server", "discord:111", "--profile", "members", "--group", "members"] - return cli.run_access([*argv, "--admin-key-env", "CTX_ADMIN", *extra], hermes_home=str(home)) - - -def test_provision_at_the_key_limit_writes_no_env_line(fake_ctx, monkeypatch, tmp_path, caplog, capsys): - _provision_world(fake_ctx, monkeypatch, tmp_path) - fake_ctx.max_keys = 1 - assert _provision(tmp_path) != 0 - assert fake_ctx.count("/api/manage", "keyset-provision") == 1 - env = tmp_path / ".env" - assert not env.exists() or "CTX_KEY_111" not in env.read_text(encoding="utf-8") - assert ADMIN_KEY not in caplog.text + capsys.readouterr().out + _files_text(tmp_path) - - -def test_provision_twice_leaves_one_active_key_per_label(fake_ctx, monkeypatch, tmp_path, capsys): - _provision_world(fake_ctx, monkeypatch, tmp_path) - assert _provision(tmp_path, "--emit-yaml") == 0 - assert _provision(tmp_path) == 0 - calls = [r.body for r in fake_ctx.requests("/api/manage") if r.action == "keyset-provision"] - assert len(calls) == 2 and all(k.get("replace_label") for c in calls for k in c["data"]["keys"]) - labels = [k.label for k in fake_ctx.keys.values() if k.active and k.label.startswith("hermes:")] - assert labels == ["hermes:discord:111:members"] - out = capsys.readouterr().out - assert "members" in out and "ctx_checkpoint" in out - assert ADMIN_KEY not in out + _files_text(tmp_path) - assert re.search(r"^CTX_KEY_111_MEMBERS=", (tmp_path / ".env").read_text(encoding="utf-8"), re.M) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pf_docs.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pf_docs.py deleted file mode 100644 index efb6f86cc..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pf_docs.py +++ /dev/null @@ -1,30 +0,0 @@ -"""P-F (design 02 §7.3): the README names every access-group field and every setting of this axis. -Red on S1: the README predates both.""" - -from __future__ import annotations - -import pytest -from fakes import access_host as ah - -pytestmark = pytest.mark.access_cluster("P-F") - -_PKG = ah.load_plugin("ctx_checkpoint_access_pf") -acc = ah.plugin_module(_PKG, "memory.access") -README = (ah.PLUGIN_DIR / "README.md").read_text(encoding="utf-8") - - -@pytest.mark.parametrize("name", sorted(acc.SCHEMA)) -def test_readme_names_every_field(name): - assert f"`{name}`" in README and "Access groups" in README - - -@pytest.mark.parametrize("name", sorted(acc.SETTINGS_DEFAULTS)) -def test_readme_names_every_setting(name): - assert f"`{name}`" in README and "Access groups" in README - - -@pytest.mark.parametrize( - "heading", ["Access groups", "Base blocks", "Recipe for restricted profiles", "What this does not promise"] -) -def test_readme_has_the_sections(heading): - assert heading in README diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py deleted file mode 100644 index 8e99e7c79..000000000 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py +++ /dev/null @@ -1,29 +0,0 @@ -"""P-G (design 02 §7.3, CC-7): the chain's writes per rate window follow the write limit the -server reports for the key (``whoami.rate_limit_write``). Red on S1: ``window_writes`` ignores it.""" - -from __future__ import annotations - -import pytest -from fakes import access_host as ah - -pytestmark = pytest.mark.access_cluster("P-G") - -_PKG = ah.load_plugin("ctx_checkpoint_access_pg") -cp = ah.plugin_module(_PKG, "memory.checkpoint") - - -def test_reported_limit_bounds_the_window(): - assert cp.window_writes(cp.MAX_PARTS_CEILING, 40) <= 40 - assert cp.window_writes(10, 40) == 12 - - -@pytest.mark.s1_green -def test_server_without_the_field_keeps_todays_window(): - assert cp.window_writes(cp.MAX_PARTS_CEILING, None) == cp.MAX_PARTS_CEILING + 2 - assert cp.window_writes(10) == 12 - - -@pytest.mark.s1_green -def test_reported_limit_over_100_never_raises_the_window(): - assert cp.window_writes(500, 1000) == min(500, cp.MAX_PARTS_CEILING) + 2 - assert cp.window_writes(cp.MAX_PARTS_CEILING, 101) == cp.MAX_PARTS_CEILING + 2 From 6f5c0574607d1a0b289ad6aefc682de43cf994b4 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 06:24:34 +0100 Subject: [PATCH 09/15] =?UTF-8?q?docs(api):=20whoami=20names=20the=20overl?= =?UTF-8?q?ay=20rate=5Flimit=5Fwrite=20comes=20from=20=E2=80=94=20the=20ke?= =?UTF-8?q?y's=20home=20scope,=20not=20the=20tenant?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A run of the Hermes plugin against a server built from this branch showed that an override an owner sets on their own scope does not reach keys whose home scope is another scope of the tenant. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api.md b/docs/api.md index c207601d1..43ba16af0 100644 --- a/docs/api.md +++ b/docs/api.md @@ -23,7 +23,7 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. | `GET /api/graph/overview` | Scope-pure Louvain cluster supergraph ("landkarte"); reads precomputed scope-partitioned aggregates, gated on `graph_overview.enabled` (off → 404). Read-only, no LLM. | | `GET /api/graph/cluster` | Cluster ego: the members + neighbour topics of ONE topic handle (see [Cluster ego](#cluster-ego-get-apigraphcluster)). Double-gated on `graph_overview.enabled` **and** `cluster.route_enabled` (both default off → 404, indistinguishable from an absent route). | | `POST /api/synthesize/daily` | Manual trigger of the daily synthesis (Tagesbericht) for the caller's `home_scope` — the same `GenerateDailyReport` path the 03:00 scheduler iteration runs (digest role, constant internal). Concurrency cap 1 per principal (429 fail-fast), dispatch-interactive (429 + `Retry-After` on capacity rejection). Optional `?date=YYYY-MM-DD` (M103) re-synthesizes the report titled that day over its historical window `[date-1 03:00 UTC, date 03:00 UTC)` — the backfill path; the `(category, title, scope)` upsert replaces the old report in place (same block id, embedding regenerates). A malformed date, a window that has not closed yet, or — with `scheduler.writelog_retention_days` set — a window that starts before the write-log horizon or before the eviction boundary the retention recorded on any earlier run, whatever the setting is now (its guard and dream decisions are deleted, and the replacement would lack them; issue #277) ⇒ 400; a boundary the server cannot read ⇒ 500. `{ok, block_id, scope[, date][, reason:"no_activity"]}`. The report language follows the hot `dream.language` setting, read per request: empty (default) keeps the German surface this row describes, any other tag localizes **title and tag together** (`Daily Report <date>` / `daily-report`) — so a change **starts a new series** instead of continuing the old one, and a backfill after the switch writes a second block for a day that already has a `Tagesbericht`. Deliberate and operator-triggered; see [`CTX_DREAM_LANGUAGE`](operations.md#environment-variables). | -| `GET /api/whoami` | Calling key's identity: `label`, `home_scope`, `read_scopes`, the server-global `admin` tier flag, plus the Model-C tenant identity `tenant_id` + per-tenant `role` (`owner`/`admin`/`member`), and the feature-flag bag `capabilities` (`{workflow: true}` since v4.3.0 — switches the SPA's issues/board surface visible; the field is data, so a later per-tenant gate only changes the value, not the SPA). `capabilities.model_api` carries the gateway policy as data, read per request from the `_global` settings: `{enabled, self_service, key_max_lifetime_s, rotation_grace_s, expiry_warn_s}` = `gateway.enabled`, `gateway.tenant_self_service`, `gateway.key_max_lifetime_app`, `gateway.key_rotation_grace`, `gateway.key_expiry_warn` (durations in whole seconds; the peer lifetime is not carried). Every authenticated caller receives it — server policy, no secret; the SPA derives two capabilities from it, `viewModelApi` and `mintModelKeys`, for the gateway administration surface ([multi-tenancy](multi-tenancy.md#admin-tiers)), while the manage actions enforce their own tiers ([Model consumer administration](#model-consumer-administration)). The SPA login gate probes it, derives its read-only degradation from `admin`, and tells server-admin from tenant-admin. Four fields describe the write side and a narrowing: `write_scopes` (the effective write set, home scope first — under a narrowing its write scope alone, or `[]`), `confirm_writes`, `narrowed` (`{read, write}` of a [narrowed request](#scope-narrowing-per-request), `null` otherwise; under a narrowing `read_scopes` is that read set, `admin` is `false` and `role` is `member`) `rate_limit_write` (the write budget per key and 60 s that applies to this key: `query.rate_limit_write` after its tenant's overlay, `0` = unlimited) and `scope_narrowing` (`optional` or `required`, the key's column; a key with `required` answers nothing unnarrowed but this route). | +| `GET /api/whoami` | Calling key's identity: `label`, `home_scope`, `read_scopes`, the server-global `admin` tier flag, plus the Model-C tenant identity `tenant_id` + per-tenant `role` (`owner`/`admin`/`member`), and the feature-flag bag `capabilities` (`{workflow: true}` since v4.3.0 — switches the SPA's issues/board surface visible; the field is data, so a later per-tenant gate only changes the value, not the SPA). `capabilities.model_api` carries the gateway policy as data, read per request from the `_global` settings: `{enabled, self_service, key_max_lifetime_s, rotation_grace_s, expiry_warn_s}` = `gateway.enabled`, `gateway.tenant_self_service`, `gateway.key_max_lifetime_app`, `gateway.key_rotation_grace`, `gateway.key_expiry_warn` (durations in whole seconds; the peer lifetime is not carried). Every authenticated caller receives it — server policy, no secret; the SPA derives two capabilities from it, `viewModelApi` and `mintModelKeys`, for the gateway administration surface ([multi-tenancy](multi-tenancy.md#admin-tiers)), while the manage actions enforce their own tiers ([Model consumer administration](#model-consumer-administration)). The SPA login gate probes it, derives its read-only degradation from `admin`, and tells server-admin from tenant-admin. Four fields describe the write side and a narrowing: `write_scopes` (the effective write set, home scope first — under a narrowing its write scope alone, or `[]`), `confirm_writes`, `narrowed` (`{read, write}` of a [narrowed request](#scope-narrowing-per-request), `null` otherwise; under a narrowing `read_scopes` is that read set, `admin` is `false` and `role` is `member`), `rate_limit_write` (the write budget per key and 60 s that applies to this key: `query.rate_limit_write` after the settings overlay of the key's home scope, `0` = unlimited; an override set on another scope of the same tenant does not reach this key) and `scope_narrowing` (`optional` or `required`, the key's column; a key with `required` answers nothing unnarrowed but this route). | | `POST /api/manage` | CRUD, Guard API, stats, API-key management, block-type registry (see [manage actions](#manage-actions)). | | `GET /api/types[/{name}]` | Block-type registry reads: effective type list (`_global` ∪ your tenant) and single-type policy config, **member-gated** (any valid key) (see [Block-type registry](#block-type-registry)). | | `PUT\|DELETE /api/types/{name}` | Block-type registry writes (upsert/delete), **admin-or-tenant-admin-gated**: a tenant-admin writes its own tenant namespace, `_global` types are operator-only; DELETE 409s while referenced or on a builtin (see [Block-type registry](#block-type-registry)). | From 068f9d5b2c0f6f6f64125d05a6344359ea3ac818 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 06:34:30 +0100 Subject: [PATCH 10/15] docs: the comments on rate_limit_write name the overlay of the key's home scope, as docs/api.md does Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- go/internal/handler/whoami.go | 2 +- go/web/src/lib/api/types.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/go/internal/handler/whoami.go b/go/internal/handler/whoami.go index 7dc3a9157..e69a89b7c 100644 --- a/go/internal/handler/whoami.go +++ b/go/internal/handler/whoami.go @@ -84,7 +84,7 @@ type whoamiResponse struct { // member — a client binding a group reads both answers, narrowed and not. Narrowed *whoamiNarrowed `json:"narrowed"` // RateLimitWrite is the write budget per key and 60 s that applies to - // this key: query.rate_limit_write after the overlay of the key's tenant + // this key: query.rate_limit_write after the settings overlay of the key's home scope // (0 = unlimited). A client that paces its writes reads it here instead // of planning with the default. RateLimitWrite int `json:"rate_limit_write"` diff --git a/go/web/src/lib/api/types.ts b/go/web/src/lib/api/types.ts index 094e2db59..cdf031b93 100644 --- a/go/web/src/lib/api/types.ts +++ b/go/web/src/lib/api/types.ts @@ -77,7 +77,7 @@ export interface WhoamiResponse { confirm_writes?: boolean /** The request's narrowing (X-Context-Read-Scopes / X-Context-Write-Scope), null when unnarrowed. */ narrowed?: { read: string[]; write: string } | null - /** query.rate_limit_write after the key's tenant overlay; 0 = unlimited. */ + /** query.rate_limit_write after the settings overlay of the key's home scope; 0 = unlimited. */ rate_limit_write?: number /** The key's scope_narrowing (migration 198): 'optional' | 'required'. Bare string for forward-compat. */ scope_narrowing?: string From aba04857ccc0e0bee14623f0d4be4d286ec82d79 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 07:17:35 +0100 Subject: [PATCH 11/15] =?UTF-8?q?fix(store):=20an=20answer=20drops=20the?= =?UTF-8?q?=20guard=20verdict=20of=20a=20match=20outside=20the=20request's?= =?UTF-8?q?=20read=20scopes=20=E2=80=94=20the=20/api/store=20and=20/api/st?= =?UTF-8?q?ore/batch=20answers=20too,=20and=20similarity=20and=20cross-sco?= =?UTF-8?q?pe=20flag=20with=20the=20id?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The duplicate guard matches a block across the scopes of its tenant, and its verdict in the block's metadata names (guard_matched_id) and describes (guard_similarity, guard_is_cross_scope) the matched block. The read paths dropped only guard_matched_id when that block lay outside the caller's scopes; the answers of /api/store and /api/store/batch dropped nothing — an overwrite keeps the stored verdict and the upsert RETURNING read it raw, so the answer named a block of another scope, also to a key that cannot read it and, since #595 lists /api/store for narrowed requests, outside a narrowing. One predicate now (guardMatchReadableSQL): the read paths' SQL expression drops all three keys, and the write answers of /api/store and /api/store/batch go through store.RedactGuardVerdicts against the request's read scopes (the narrowed ones under a narrowing), one statement per answer, fail-closed when it fails. A caller that reads the matched block's scope gets the verdict as before. guard_status and the guard list's similarity column stay (documented). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/api.md | 2 + docs/mcp.md | 5 +- .../guard_verdict_answers_integration_test.go | 226 ++++++++++++++++++ go/internal/handler/context_store.go | 16 ++ go/internal/handler/store_batch.go | 7 + go/internal/store/blocks.go | 15 +- .../store/guard_redact_integration_test.go | 19 +- go/internal/store/guard_verdict.go | 117 +++++++++ go/internal/store/guard_verdict_test.go | 51 ++++ 9 files changed, 445 insertions(+), 13 deletions(-) create mode 100644 go/cmd/ctxd/guard_verdict_answers_integration_test.go create mode 100644 go/internal/store/guard_verdict.go create mode 100644 go/internal/store/guard_verdict_test.go diff --git a/docs/api.md b/docs/api.md index 43ba16af0..959766b93 100644 --- a/docs/api.md +++ b/docs/api.md @@ -107,6 +107,8 @@ PostgreSQL stores a NUL character (U+0000) neither in text nor in JSON, so no va **The duplicate guard's metadata keys are server-owned (issue #238).** Every metadata key with the prefix `guard_` is the guard's record about a block: its verdict (`guard_status`, `guard_checked_at`, `guard_similarity`, `guard_matched_id`, `guard_is_cross_scope`, the thresholds), a person's `guard-resolve` trace (`guard_resolution`, `guard_resolved_at`) and the repair marks of migrations 121/156/157 (`guard_repair`). A client write cannot set, overwrite or remove one: on every surface that takes a caller's metadata — `POST /api/store` and `/api/store/batch`, `POST /api/ingest` (blocks and chunks), `manage update` (`metadata` and `metadata_merge`, a `null` included), the issue domain's writes, the MCP `store`, `store_batch`, `update` and issue tools, and the `confirm` of a staged card — such keys are **dropped from the request, not refused**, and the block keeps the ones it has. A replacement `metadata` document keeps the stored `guard_*` keys, a merge does not touch them, and a content change drops only `guard_checked_at`, which puts the block up for a check of its new text (a chunk, which the guard never checks, keeps it). A staged card shows the request as it was sent; its `confirm` drops the keys. A client that writes back the metadata it read (`get`, then `update`) keeps working and changes none of them. Before, a caller could write any value there: a `guard_similarity` that is not a number made `guard-list` answer an empty list to every reader of the scope, a `guard_checked_at` lifted the block out of the guard's queue or set the queue's age. `guard-list` now orders by `guard_similarity` only where the value is a JSON number (since issue #536; before #536, where it read as a number, a string such as `"0.97"` or `"NaN"` included) and sorts any other value last, as it sorts a missing one, and a fault of its statement is an error, not an empty list. To count the blocks whose `guard_*` keys no server writer produced (values written before this change), see [operations](operations.md#guard-keys-written-by-a-caller). +**The guard verdict in an answer follows the read scopes (review #595).** The duplicate guard matches a block against the blocks of every scope of its tenant, so its verdict can name a block the caller cannot read. Every answer that returns a block's `metadata` — `get` (one id or `ids`), `search` and `list` with full rows, the MCP `get` and `search` with content, the issue reads, the `manage update` answer, and the write answers of `POST /api/store` and `/api/store/batch` — drops the three keys that name or describe the match, `guard_matched_id`, `guard_similarity` and `guard_is_cross_scope`, when the matched block lies outside the request's read scopes (under a [narrowing](#scope-narrowing-per-request), the named ones). A caller that reads the matched block's scope gets them as stored. The `manage update` and issue-update answers judge against the key's write scopes, a subset of its read scopes, as before. Before, only `guard_matched_id` was dropped, and the write answers of `/api/store` and `/api/store/batch` dropped nothing: an overwrite answered with the stored verdict, the id of a block in another scope included. What remains readable on purpose: the block's own `guard_status` (its review state, not the match's), and `guard-list`, whose rows keep `similarity` for a partner shown `[redacted]` — the review page orders and shows the queue by it. A caller of `guard-list` therefore still learns that a block of its scopes has a near-duplicate somewhere in its tenant and how similar it is, not which block or in which scope. `guard-list` is no route a narrowed request may take. + **The derived layer is not client-claimable (I7).** The block types of the derived layer — `insight` and `catalog` — plus the categories they write into (`session-insights`, `catalog`), the metadata key `provenance`, and any block that already carries such a `provenance` object are **server-reserved on every write surface**: `POST /api/store`, `POST /api/ingest`, `manage update`, `manage delete`, `manage guard-resolve` (`archive`), the whole issue domain (`manage issue-create` / `issue-update` / `issue-comment-create`, their `/api/project/{id}/issues…` REST twins and the MCP `issue_create` / `issue_comment` tools), the MCP `store` / `update` tools, the chat write and update tools, and the `confirm` of a staged card on any of them. The refusals: * naming such a `type` ⇒ **422** `reserved_type` (the type exists — it is simply not the client's to claim, which is why it is not `unknown_type`); diff --git a/docs/mcp.md b/docs/mcp.md index c73b22e50..d82b8bb92 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -316,8 +316,9 @@ non-empty `query` is an error: the full-text path answers its top matches and ha next page. **Content (`include_content`).** The rows are those of `POST /api/search` with -`compact: false`: `content` and `metadata` (with the guard's `guard_matched_id` dropped -when the block it names lies outside the key's read scopes, as on `get`) instead of `content_preview` +`compact: false`: `content` and `metadata` (with the guard's verdict — `guard_matched_id`, +`guard_similarity`, `guard_is_cross_scope` — dropped when the block it names lies outside the key's +read scopes, as on `get`) instead of `content_preview` and `content_length`, through the same scope, grant and type rules, with `untrusted` on foreign-text rows. The rows of one answer are bounded at 64 KiB of JSON, content, metadata and escaping included: the page ends before the first row that would cross diff --git a/go/cmd/ctxd/guard_verdict_answers_integration_test.go b/go/cmd/ctxd/guard_verdict_answers_integration_test.go new file mode 100644 index 000000000..2215456d7 --- /dev/null +++ b/go/cmd/ctxd/guard_verdict_answers_integration_test.go @@ -0,0 +1,226 @@ +//go:build integration + +// The guard verdict a block carries in its metadata — guard_matched_id, +// guard_similarity, guard_is_cross_scope — names, or describes, the block the +// duplicate guard matched it with. The guard matches across the scopes of one +// tenant, so that block can lie in a scope the caller does not read. Every +// answer that returns a block's metadata, a read or a write, drops the three +// keys when the matched block lies outside the request's read scopes (under a +// narrowing the named ones): the read paths in SQL (guardRedactedMetadataSQL), +// the write answers of /api/store and /api/store/batch through +// store.RedactGuardVerdicts. A caller that reads the matched block's scope +// gets the verdict whole, as before. +// +// The verdict comes from a real guard run (guard.RunGuardBatch) over vectors +// the query backfill wrote: an embed stub gives the twin block a vector at +// cosine 0.95 from every other text, between the review threshold (0.92) and +// the archive threshold (0.98), so both blocks are flagged needs_review and +// neither is archived. +// +// go test -tags=integration -p 1 -count=1 -run '^TestGuardVerdict' ./cmd/ctxd/ +package main + +import ( + "context" + "encoding/json" + "io" + "math" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/blocktype" + "github.com/GottZ/ctx/internal/guard" +) + +// gwTwinWord marks the text of the twin block; the stub embeds it apart. +const gwTwinWord = "gwtwinbeta" + +// gwVerdictKeys are the guard verdict keys an answer keeps or drops together. +var gwVerdictKeys = []string{"guard_matched_id", "guard_similarity", "guard_is_cross_scope"} + +// gwEmbedHost serves /api/embed: the twin's text gets (0.95, √(1-0.95²), 0…), +// every other text (1, 0, 0…) — cosine 0.95. +func gwEmbedHost(t *testing.T) string { + t.Helper() + base := make([]float64, 1024) + base[0] = 1 + twin := make([]float64, 1024) + twin[0], twin[1] = 0.95, math.Sqrt(1-0.95*0.95) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path != "/api/embed" { + _, _ = io.Copy(io.Discard, r.Body) + w.WriteHeader(http.StatusNotFound) + return + } + var req struct { + Input any `json:"input"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + var inputs []string + switch in := req.Input.(type) { + case string: + inputs = []string{in} + case []any: + for _, e := range in { + s, _ := e.(string) + inputs = append(inputs, s) + } + } + out := make([][]float64, len(inputs)) + for i, s := range inputs { + out[i] = base + if strings.Contains(s, gwTwinWord) { + out[i] = twin + } + } + _ = json.NewEncoder(w).Encode(map[string]any{"embeddings": out}) + })) + t.Cleanup(srv.Close) + return srv.URL +} + +// gwWorld: default tenant with scope default:k; block A in work, its twin B in +// default:k, both flagged by a guard run; key w reads work and default:k, key +// wo reads work only. +type gwWorld struct { + *c1World + a, b string +} + +func gwSetup(t *testing.T) *gwWorld { + t.Helper() + pool, router := c1Router(t, backends.Backend{ID: "gw-embed", Name: "gw-embed", Scope: "_global", Host: gwEmbedHost(t), + Protocol: backends.ProtocolOllama, Model: "gw-embed-model", Trust: backends.TrustFull, Enabled: true, + Priority: 9, Roles: []string{backends.RoleEmbed}}) + w := &gwWorld{c1World: &c1World{pool: pool, router: router, keys: map[string]string{}, blocks: map[string]string{}}} + w.manage(t, c1AdminKey, nil, map[string]any{"action": "scope-create", "data": map[string]any{"name": "k"}}).must(t, "scope-create k") + w.keys["w"] = w.mintKey(t, map[string]any{"label": "gw-w", "home_scope": "work", "allowed_scopes": []string{"default:k"}}) + w.keys["wo"] = w.mintKey(t, map[string]any{"label": "gw-wo", "home_scope": "work", "allowed_scopes": []string{}}) + w.keys["kw"] = w.mintKey(t, map[string]any{"label": "gw-kw", "home_scope": "default:k"}) + + w.b = w.storeBlock(t, w.keys["kw"], "", "gw twin "+gwTwinWord) + w.a = w.storeBlock(t, w.keys["w"], "", "gw target") + + // The query backfill embeds the pending blocks of key w's read scopes. + w.do(t, http.MethodPost, "/api/query", w.keys["w"], nil, map[string]any{"query": "gw fixture", "synthesize": false}).must(t, "query backfill") + var embedded int + if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM context_blocks WHERE id = ANY($1::uuid[]) AND embedding IS NOT NULL`, + []string{w.a, w.b}).Scan(&embedded); err != nil || embedded != 2 { + t.Fatalf("fixture: %d of the 2 blocks embedded (err %v)", embedded, err) + } + if _, err := guard.RunGuardBatch(context.Background(), pool, blocktype.NewRegistry().Snapshot(), 100, + guard.Search{EfSearch: 800, ExactMaxCandidates: 400}); err != nil { + t.Fatalf("fixture: guard run: %v", err) + } + var matched, status string + var cross bool + if err := pool.QueryRow(context.Background(), `SELECT coalesce(metadata->>'guard_matched_id',''), coalesce(guard_status,''), + coalesce((metadata->>'guard_is_cross_scope')::bool, false) FROM context_blocks WHERE id = $1::uuid AND NOT is_archived`, w.a). + Scan(&matched, &status, &cross); err != nil { + t.Fatalf("fixture: read block A: %v", err) + } + if matched != w.b || status != "needs_review" || !cross { + t.Fatalf("fixture: the guard run left block A with matched %q status %q cross %v, want %s needs_review true", matched, status, cross, w.b) + } + return w +} + +// gwVerdict reports which verdict keys a block answer carries. +func gwVerdict(t *testing.T, blk any) map[string]bool { + t.Helper() + b, _ := blk.(map[string]any) + md, _ := b["metadata"].(map[string]any) + got := map[string]bool{} + for _, k := range gwVerdictKeys { + _, got[k] = md[k] + } + return got +} + +// gwWant fails unless the answer carries all verdict keys (whole) or none. +func gwWant(t *testing.T, what string, blk any, whole bool) { + t.Helper() + for k, has := range gwVerdict(t, blk) { + if has != whole { + t.Errorf("%s: metadata.%s present %v, want %v", what, k, has, whole) + } + } +} + +// TestGuardVerdictOfTheStoreAnswerFollowsTheReadScopes: /api/store overwriting +// block A answers A with its verdict only when the request reads B's scope. +func TestGuardVerdictOfTheStoreAnswerFollowsTheReadScopes(t *testing.T) { + w := gwSetup(t) + write := func(key string, h http.Header, content string) any { + t.Helper() + r := w.do(t, http.MethodPost, "/api/store", key, h, + map[string]any{"category": "learnings", "title": "gw target", "content": content + " " + c1Probe}) + if r.status != http.StatusOK { + t.Fatalf("store %s: HTTP %d %s", content, r.status, r.raw) + } + blk, _ := r.body["block"].(map[string]any) + if id, _ := blk["id"].(string); id != w.a { + t.Fatalf("store %s overwrote %v, want block A %s", content, blk["id"], w.a) + } + return blk + } + gwWant(t, "key w unnarrowed (reads default:k)", write(w.keys["w"], nil, "one"), true) + gwWant(t, "key w narrowed to work,default:k", write(w.keys["w"], c1Narrow("work,default:k", "work"), "two"), true) + gwWant(t, "key wo (reads work only)", write(w.keys["wo"], nil, "three"), false) + gwWant(t, "key w narrowed to work", write(w.keys["w"], c1Narrow("work", "work"), "four"), false) +} + +// TestGuardVerdictOfTheBatchAnswerFollowsTheReadScopes: the same for a store +// item of /api/store/batch (not a narrowed route). +func TestGuardVerdictOfTheBatchAnswerFollowsTheReadScopes(t *testing.T) { + w := gwSetup(t) + write := func(key, content string) any { + t.Helper() + r := w.do(t, http.MethodPost, "/api/store/batch", key, nil, map[string]any{"items": []any{ + map[string]any{"category": "learnings", "title": "gw target", "content": content + " " + c1Probe}}}) + if r.status != http.StatusOK { + t.Fatalf("batch %s: HTTP %d %s", content, r.status, r.raw) + } + items, _ := r.body["items"].([]any) + if len(items) != 1 { + t.Fatalf("batch %s: %d items", content, len(items)) + } + it, _ := items[0].(map[string]any) + return it["block"] + } + gwWant(t, "batch, key w (reads default:k)", write(w.keys["w"], "one"), true) + gwWant(t, "batch, key wo (reads work only)", write(w.keys["wo"], "two"), false) +} + +// TestGuardVerdictOfTheReadAndUpdateAnswersDropsAllThreeKeys: the read paths +// and the update answer drop the whole verdict, not only the id, when the +// matched block lies outside the request's view. +func TestGuardVerdictOfTheReadAndUpdateAnswersDropsAllThreeKeys(t *testing.T) { + w := gwSetup(t) + get := func(key string, h http.Header) any { + t.Helper() + r := w.manage(t, key, h, map[string]any{"action": "get", "id": w.a}).must(t, "get") + return r.body["block"] + } + gwWant(t, "get, key w", get(w.keys["w"], nil), true) + gwWant(t, "get, key wo", get(w.keys["wo"], nil), false) + gwWant(t, "get, key w narrowed to work", get(w.keys["w"], c1Narrow("work")), false) + + s := w.do(t, http.MethodPost, "/api/search", w.keys["wo"], nil, map[string]any{"query": "gw target", "compact": false}).must(t, "search") + for _, e := range s.body["results"].([]any) { + if m, _ := e.(map[string]any); m["id"] == w.a { + gwWant(t, "search (full), key wo", m, false) + } + } + + upd := func(key, content string) any { + t.Helper() + r := w.manage(t, key, nil, map[string]any{"action": "update", "id": w.a, "data": map[string]any{"content": content}}).must(t, "update") + return r.body["block"] + } + gwWant(t, "update, key wo", upd(w.keys["wo"], "upd one"), false) +} diff --git a/go/internal/handler/context_store.go b/go/internal/handler/context_store.go index c92a94a3a..58027e005 100644 --- a/go/internal/handler/context_store.go +++ b/go/internal/handler/context_store.go @@ -261,6 +261,11 @@ func (h *StoreHandler) HandleStore(w http.ResponseWriter, r *http.Request) { } }() + // The answer shows the block's guard verdict as the read paths do: only + // when the matched block lies in the request's read scopes (an overwrite + // keeps the stored verdict, and the upsert RETURNING reads it raw). + redactWrittenGuardVerdicts(ctx, h.pool, authResult, block) + // Embedding generated async by scheduler backfill loop. resp := map[string]any{ "success": true, @@ -500,6 +505,17 @@ func resolveWriteScope(ar *auth.AuthResult, requested string) (scope string, exp return requested, true, nil } +// redactWrittenGuardVerdicts is the guard redaction of a write answer +// (store.RedactGuardVerdicts) against the request's read scopes — under a +// narrowing the named ones. A failure is logged; the redaction has then +// dropped every verdict (fail-closed), and the committed write is answered. +func redactWrittenGuardVerdicts(ctx context.Context, pool *pgxpool.Pool, ar *auth.AuthResult, blocks ...*store.Block) { + if err := store.RedactGuardVerdicts(ctx, pool, ar.ReadScopes, blocks...); err != nil { + logRequestError(ctx, "write answer: guard verdict redaction failed, verdicts dropped", "error", err, + "request_id", RequestIDFromContext(ctx)) + } +} + // writeJSON writes a JSON response with the given status code. func writeJSON(w http.ResponseWriter, status int, data any) { w.Header().Set("Content-Type", "application/json") diff --git a/go/internal/handler/store_batch.go b/go/internal/handler/store_batch.go index 5bf299981..9cbe37969 100644 --- a/go/internal/handler/store_batch.go +++ b/go/internal/handler/store_batch.go @@ -801,6 +801,13 @@ func (h *StoreHandler) HandleStoreBatch(w http.ResponseWriter, r *http.Request) writeJSONReject(w, rej) return } + // Each answered block shows its guard verdict as the read paths do (the + // /api/store rule; update items are redacted by their statement already). + written := make([]*store.Block, len(results)) + for i := range results { + written[i] = results[i].Block + } + redactWrittenGuardVerdicts(ctx, h.pool, ar, written...) answers := make([]map[string]any, len(results)) for i, it := range results { answers[i] = storeBatchItemAnswer(it) diff --git a/go/internal/store/blocks.go b/go/internal/store/blocks.go index 44fb6228d..5860b5317 100644 --- a/go/internal/store/blocks.go +++ b/go/internal/store/blocks.go @@ -1563,8 +1563,11 @@ func ResolveBlockID(ctx context.Context, pool *pgxpool.Pool, idOrPrefix string, // guardRedactedMetadataSQL is the `metadata` select expression of the raw read // paths (GetBlock, non-compact SearchBlocks, the UpdateBlock RETURNING and the -// issue projection issueScanColsRedacted): the guard's guard_matched_id is -// dropped when the matched block does not lie in the caller's scopes — +// issue projection issueScanColsRedacted): the guard verdict — guard_matched_id +// and the two keys that describe the match, guard_similarity and +// guard_is_cross_scope (guardVerdictKeys) — is dropped when the matched block +// does not lie in the caller's scopes (guardMatchReadableSQL, the predicate the +// write answers share through RedactGuardVerdicts) — // the rule GuardList applies to matched_id/matched_title, now on every path // that returns metadata verbatim (GHSA 2026-10-31 §2: the key named a block // the caller could not read, a UUIDv7 with its creation time). scopesParam is @@ -1576,11 +1579,9 @@ func ResolveBlockID(ctx context.Context, pool *pgxpool.Pool, idOrPrefix string, // matched-block lookup is a primary-key probe (one row per returned block; // guardMatchedIDSQL, which the guard list reads the key with as well). func guardRedactedMetadataSQL(scopesParam string) string { - return `CASE WHEN context_blocks.metadata ? 'guard_matched_id' AND NOT EXISTS ( - SELECT 1 FROM context_blocks mb - WHERE mb.id = ` + guardMatchedIDSQL("context_blocks.metadata") + ` - AND mb.scope = ANY(` + scopesParam + `::text[])) - THEN context_blocks.metadata - 'guard_matched_id' ELSE context_blocks.metadata END AS metadata` + return `CASE WHEN context_blocks.metadata ? 'guard_matched_id' AND NOT ` + + guardMatchReadableSQL("context_blocks.metadata", scopesParam) + ` + THEN context_blocks.metadata - ` + guardVerdictKeysSQL + ` ELSE context_blocks.metadata END AS metadata` } // GetBlock retrieves a single block by ID, filtered by allowed scopes plus the diff --git a/go/internal/store/guard_redact_integration_test.go b/go/internal/store/guard_redact_integration_test.go index b08aa6624..0108ca1dc 100644 --- a/go/internal/store/guard_redact_integration_test.go +++ b/go/internal/store/guard_redact_integration_test.go @@ -3,8 +3,10 @@ // GHSA 2026-10-31 §2 — raw read paths redact the guard's matched-block key: // GetBlock and non-compact SearchBlocks drop metadata.guard_matched_id when // the matched block lies outside the caller's read scopes (the rule GuardList -// applies to matched_id). The similarity and the cross-scope flag stay, as on -// GuardList. §F-§2 extends the rule to the paths that still returned the key +// applies to matched_id). Since review #595 L1 the two keys that describe the +// match, guard_similarity and guard_is_cross_scope, go with it (no reader of +// block metadata needs them for a match it cannot read; the guard list keeps +// its own similarity field). §F-§2 extends the rule to the paths that still returned the key // verbatim: the UpdateBlock RETURNING (both execution paths) and the issue // projection (GetIssue, ListComments, the comment page, the UpdateIssueBlock // RETURNING). @@ -54,9 +56,14 @@ func TestGuardMatchedIDRedacted_Integration(t *testing.T) { if _, has := b.Metadata["guard_matched_id"]; has { t.Errorf("guard_matched_id returned to a caller who cannot read the matched block: %v", b.Metadata) } - if b.Metadata["other"] != "kept" || b.Metadata["guard_similarity"] == nil { + if b.Metadata["other"] != "kept" { t.Errorf("unrelated metadata keys were disturbed: %v", b.Metadata) } + for _, k := range []string{"guard_similarity", "guard_is_cross_scope"} { + if _, has := b.Metadata[k]; has { + t.Errorf("%s returned to a caller who cannot read the matched block: %v", k, b.Metadata) + } + } // Caller can read work too → the key is returned verbatim. b, err = store.GetBlock(ctx, pool, nil, writer, []string{"private", "work"}, nil) @@ -141,9 +148,13 @@ func TestGuardMatchedIDRedacted_WritePathsAndIssues_Integration(t *testing.T) { case !want && has: t.Errorf("%s: guard_matched_id %v returned to a caller who cannot reach the matched block", label, v) } - if meta["other"] != "kept" || meta["guard_similarity"] == nil { + if meta["other"] != "kept" { t.Errorf("%s: unrelated metadata keys were disturbed: %v", label, meta) } + // The similarity goes and comes with the id (review #595 L1). + if _, has := meta["guard_similarity"]; has != want { + t.Errorf("%s: guard_similarity present %v, want %v", label, has, want) + } } // UpdateBlock, plain path: the RETURNING carried the key verbatim. diff --git a/go/internal/store/guard_verdict.go b/go/internal/store/guard_verdict.go new file mode 100644 index 000000000..e539139e4 --- /dev/null +++ b/go/internal/store/guard_verdict.go @@ -0,0 +1,117 @@ +package store + +import ( + "context" + "fmt" + + "github.com/GottZ/ctx/internal/pgxdb" +) + +// guardVerdictKeys are the keys of a guard verdict that name or describe the +// block the duplicate guard matched (guard.applyDecision): which block, how +// similar, whether it lies in another scope. The guard matches across the +// scopes of one tenant, so the matched block can lie in a scope the caller +// does not read; every answer that returns a block's metadata drops the three +// keys together then (guardRedactedMetadataSQL on the read paths, +// RedactGuardVerdicts on the write answers). The block's own guard_status +// stays: it is the state of the caller's block, not of the match. No reader +// of block metadata needs the two describing keys for a match it cannot read +// — the review UI reads the guard list, which carries similarity in a field +// of its own (GuardList). +var guardVerdictKeys = []string{"guard_matched_id", "guard_similarity", "guard_is_cross_scope"} + +// guardVerdictKeysSQL is guardVerdictKeys as a text[] literal for `metadata - …`. +const guardVerdictKeysSQL = `'{guard_matched_id,guard_similarity,guard_is_cross_scope}'::text[]` + +// guardMatchReadableSQL is the one predicate of the redaction: the block the +// guard_matched_id key of the metadata expression names lies in one of the +// scopes scopesParam (a code-owned text[] expression). A malformed or absent +// value names no block and is not readable (guardMatchedIDSQL). The matched +// block's own state does not matter, as on the guard list: an archived match +// in a readable scope stays named. +func guardMatchReadableSQL(metadata, scopesParam string) string { + return `EXISTS (SELECT 1 FROM context_blocks mb + WHERE mb.id = ` + guardMatchedIDSQL(metadata) + ` + AND mb.scope = ANY(` + scopesParam + `::text[]))` +} + +// RedactGuardVerdicts applies the read paths' guard redaction to blocks a +// write path answers with: a block whose metadata carries guard_matched_id +// loses the verdict keys unless the matched block lies in readScopes — the +// request's read scopes, under a narrowing the named ones. An upsert answers +// with the row as its RETURNING read it, and an overwrite keeps the stored +// verdict (keptGuardKeysSQL), so without this the answer named a block in a +// scope the caller cannot read. One statement for all blocks, with the +// predicate of guardRedactedMetadataSQL. Blocks without the key, and nil +// entries, are left alone. +// +// Fail-closed: when the statement fails, every block that carries the key +// loses the verdict keys, and the error is returned for the log — the write +// itself has committed, so the caller answers it anyway. +func RedactGuardVerdicts(ctx context.Context, q pgxdb.Querier, readScopes []string, blocks ...*Block) error { + var idx []int + var matched []*string + for i, b := range blocks { + if b == nil || b.Metadata == nil { + continue + } + v, ok := b.Metadata["guard_matched_id"] + if !ok { + continue + } + idx = append(idx, i) + if v == nil { + matched = append(matched, nil) + continue + } + s, isString := v.(string) + if !isString { + s = fmt.Sprint(v) + } + matched = append(matched, &s) + } + if len(idx) == 0 { + return nil + } + readable := make([]bool, len(idx)) + rows, err := q.Query(ctx, + `SELECT t.n::int, `+guardMatchReadableSQL(`jsonb_build_object('guard_matched_id', t.m)`, "$2")+` + FROM unnest($1::text[]) WITH ORDINALITY AS t(m, n)`, + matched, readScopes) + if err == nil { + for rows.Next() { + var n int + var ok bool + if err = rows.Scan(&n, &ok); err != nil { + break + } + if n >= 1 && n <= len(readable) { + readable[n-1] = ok + } + } + rows.Close() + if err == nil { + err = rows.Err() + } + } + if err != nil { + readable = make([]bool, len(idx)) // fail-closed: nothing counts as readable + } + for j, i := range idx { + if readable[j] { + continue + } + md := make(map[string]any, len(blocks[i].Metadata)) + for k, v := range blocks[i].Metadata { + md[k] = v + } + for _, k := range guardVerdictKeys { + delete(md, k) + } + blocks[i].Metadata = md + } + if err != nil { + return fmt.Errorf("store: redact guard verdicts: %w", err) + } + return nil +} diff --git a/go/internal/store/guard_verdict_test.go b/go/internal/store/guard_verdict_test.go new file mode 100644 index 000000000..50f8c300d --- /dev/null +++ b/go/internal/store/guard_verdict_test.go @@ -0,0 +1,51 @@ +package store + +import ( + "context" + "errors" + "testing" + + "github.com/jackc/pgx/v5" +) + +// failingQuerier answers every query with an error. +type failingQuerier struct{ calls int } + +func (f *failingQuerier) Query(context.Context, string, ...any) (pgx.Rows, error) { + f.calls++ + return nil, errors.New("connection lost") +} + +// TestRedactGuardVerdictsFailsClosed: when the readability probe fails, every +// block that carries a verdict loses all three keys, the rest of its metadata +// stays, the caller's map is not modified, and the error comes back for the +// log. Blocks without a verdict cost no statement. +func TestRedactGuardVerdictsFailsClosed(t *testing.T) { + stored := map[string]any{"guard_matched_id": "019f3310-0000-7000-9000-00000000a001", "guard_similarity": 0.95, + "guard_is_cross_scope": true, "guard_status": "needs_review", "source": "kept"} + flagged := &Block{Metadata: stored} + plain := &Block{Metadata: map[string]any{"source": "plain"}} + q := &failingQuerier{} + if err := RedactGuardVerdicts(context.Background(), q, []string{"work"}, flagged, nil, plain); err == nil { + t.Fatal("a failed probe returned no error") + } + for _, k := range guardVerdictKeys { + if _, has := flagged.Metadata[k]; has { + t.Errorf("after a failed probe the answer still carries %s: %v", k, flagged.Metadata) + } + } + if flagged.Metadata["source"] != "kept" || flagged.Metadata["guard_status"] != "needs_review" { + t.Errorf("the redaction took more than the verdict keys: %v", flagged.Metadata) + } + if _, has := stored["guard_matched_id"]; !has { + t.Error("the redaction modified the caller's metadata map in place") + } + if plain.Metadata["source"] != "plain" { + t.Errorf("a block without a verdict changed: %v", plain.Metadata) + } + + q = &failingQuerier{} + if err := RedactGuardVerdicts(context.Background(), q, []string{"work"}, plain, nil); err != nil || q.calls != 0 { + t.Errorf("blocks without a verdict: err %v, %d statement(s), want none", err, q.calls) + } +} From 579d05ee83256553b56b6270d860a6285fb50316 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 07:20:34 +0100 Subject: [PATCH 12/15] =?UTF-8?q?test(auth):=20credentials=20minted=20from?= =?UTF-8?q?=20a=20key=20that=20requires=20narrowing=20carry=20the=20requir?= =?UTF-8?q?ement,=20and=20an=20escaped=20spelling=20of=20a=20listed=20rout?= =?UTF-8?q?e=20gives=20no=20data=20=E2=80=94=20docs=20name=20what=20such?= =?UTF-8?q?=20a=20key=20reaches=20unnarrowed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POST /auth/login, POST /authorize with /token (and a refresh) take a key with scope_narrowing required unnarrowed and mint a web session, a code and a token pair. The tests run both flows and pin that every credential they mint reaches GET /api/whoami and, narrowed, the routes of a narrowed request — every other request answers 403 scope_narrowing_required (search, query, store, manage, session keys, /mcp). The SSO session is minted through the same path. A listed route spelled with percent escapes answers 404 before Auth, with no block, echo or write. Docs: the exact list of what a required key reaches unnarrowed; the narrowing is the client's choice and the boundary stays the key's scope set (required makes a forgotten narrowing fail closed); the rollback of migration 198 counts and names the required keys first (SQL); the lock wait of the migration (up to lock_timeout 3 s, authentications queue behind it) beside its measured run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/api.md | 6 +- docs/multi-tenancy.md | 2 +- docs/operations.md | 13 +- .../narrowing_c1_more_integration_test.go | 39 ++++ ...g_required_c2_authflow_integration_test.go | 176 ++++++++++++++++++ 5 files changed, 230 insertions(+), 6 deletions(-) create mode 100644 go/cmd/ctxd/scope_narrowing_required_c2_authflow_integration_test.go diff --git a/docs/api.md b/docs/api.md index 959766b93..fc210c4dd 100644 --- a/docs/api.md +++ b/docs/api.md @@ -57,14 +57,14 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. ### Scope narrowing per request -A request can narrow its key's rights to scopes it names, for that one request (multi-tenancy: [Per-request scope narrowing](multi-tenancy.md#per-request-scope-narrowing)). `X-Context-Read-Scopes: <scope>,<scope>,…` names 1 to 8 scopes, each one the key reads; the request reads those and nothing else — no other scope, no block grant —, in that order. `X-Context-Write-Scope: <scope>` names the one scope the request writes: it must be one of the read scopes and one the key may write (`write_scopes` in whoami without a narrowing); without it the request writes nothing (`/api/store` answers `403 scope_denied`). Every answer of an accepted narrowing carries `X-Context-Narrowed: <read scopes, comma-separated>;<write scope or empty>` — the read set as the request ran with it; a client that sent a narrowing and gets a 2xx answer without that header knows the narrowing was lost on the way. +A request can narrow its key's rights to scopes it names, for that one request (multi-tenancy: [Per-request scope narrowing](multi-tenancy.md#per-request-scope-narrowing)). The client chooses the narrowing; it shrinks what one request may do and never widens it — the boundary stays the key's scope set. `X-Context-Read-Scopes: <scope>,<scope>,…` names 1 to 8 scopes, each one the key reads; the request reads those and nothing else — no other scope, no block grant —, in that order. `X-Context-Write-Scope: <scope>` names the one scope the request writes: it must be one of the read scopes and one the key may write (`write_scopes` in whoami without a narrowing); without it the request writes nothing (`/api/store` answers `403 scope_denied`). Every answer of an accepted narrowing carries `X-Context-Narrowed: <read scopes, comma-separated>;<write scope or empty>` — the read set as the request ran with it; a client that sent a narrowing and gets a 2xx answer without that header knows the narrowing was lost on the way. | Refusal | Status, code | |---|---| | `X-Context-Write-Scope` without `X-Context-Read-Scopes`; a header sent twice; an empty header or list element; a scope named twice; more than 8 read scopes | `400 scope_narrowing_invalid` | | a read scope the key does not read; a write scope outside the read scopes or one the key cannot write | `403 scope_denied` | -| any route but `POST /api/query`, `POST /api/search`, `POST /api/store`, `GET /api/whoami`, `POST /api/manage` (method and path exactly, without percent escapes); on `/api/manage` any action but `get` and `type-list` | `403 scope_narrowing_route` | -| a request without a narrowing by a key whose `scope_narrowing` is `required` (migration 198), on any route but `GET /api/whoami` | `403 scope_narrowing_required` | +| any route but `POST /api/query`, `POST /api/search`, `POST /api/store`, `GET /api/whoami`, `POST /api/manage` (method and path exactly); on `/api/manage` any action but `get` and `type-list`. A listed route spelled with percent escapes (`/api/%73earch`) matches no route and answers `404` before the authentication, with no data | `403 scope_narrowing_route` | +| a request without a narrowing by a key whose `scope_narrowing` is `required` (migration 198), on any route behind the API authentication but `GET /api/whoami` (the sign-in flows accept the key and mint credentials that carry the requirement, [multi-tenancy](multi-tenancy.md#required-narrowing-migration-198)) | `403 scope_narrowing_required` | These are decided before the route's handler runs (the `manage` action after the body is decoded, on the one action the dispatcher runs). A narrowed request is never an administration request: it runs as a `member` without the server-admin tier. The key's home scope stays its own — the backend chain, the quota and the settings overlay of a narrowed request are the key's, whatever scope the narrowing names first. A request without the headers runs as before. diff --git a/docs/multi-tenancy.md b/docs/multi-tenancy.md index ddb6eda56..2d0642099 100644 --- a/docs/multi-tenancy.md +++ b/docs/multi-tenancy.md @@ -76,7 +76,7 @@ What it is for: a client that serves several groups of people with one server na ### Required narrowing (migration 198) -Migration 198 adds `context_api_keys.scope_narrowing TEXT NOT NULL DEFAULT 'optional' CHECK (optional | required)` and rebuilds `ctx_auth_by_id` and `ctx_auth` with it as the **12th** return column (appended after `principal_id`, the 078/090/095 convention). A key with `required` answers every request **without** a narrowing with `403 scope_narrowing_required` — reads, writes, `/mcp`, the session surface —, `GET /api/whoami` excepted, which reports `scope_narrowing`. The check sits in `narrowAuth`, beside the narrowing it demands. A key that belongs to one group of people is minted `required` (`ctx keys create … --require-narrowing`, or `scope_narrowing: "required"` on `api-key-create`): then the key itself is the boundary, not the care of its client — an old client, a client that forgets the headers, or another tool holding the same key reaches nothing, and with a narrowing it may only shrink the key's rights. Every existing key is `optional` and behaves as before; `api-key-update {scope_narrowing}` switches it (tenant-admin, like `write_scopes`; a server-admin key only by a server-admin). The switch applies from the next request: `ctx_auth_by_id` reads the column from the key row it locks for `last_used_at`, and nothing caches an authentication. Turning it on or off writes an `api_key` audit row like any other key change ([security](security.md)). On an owner key the requirement is owner power: a key that requires narrowing administers nothing (unnarrowed it gets only whoami, narrowed it runs as a `member`), so only an owner or a server-admin switches an owner key to `required`, and never the last owner that can still administer the tenant — an owner counts for the last-owner invariant only while it is active and `optional`. The two event streams (`/api/project/events`, `/api/events`) re-authenticate their key periodically and end once it requires narrowing (they are never narrowed); `/register` in admin mode, which resolves its key outside the Auth middleware, applies the same rules (a key that requires narrowing, or a narrowed request, registers nothing). +Migration 198 adds `context_api_keys.scope_narrowing TEXT NOT NULL DEFAULT 'optional' CHECK (optional | required)` and rebuilds `ctx_auth_by_id` and `ctx_auth` with it as the **12th** return column (appended after `principal_id`, the 078/090/095 convention). A key with `required` answers every request **without** a narrowing with `403 scope_narrowing_required` on every route behind the API authentication — reads, writes, `/mcp`, the session surface, the event streams —, `GET /api/whoami` excepted, which reports `scope_narrowing`. Unnarrowed, such a key reaches exactly these: `GET /api/whoami`; the sign-in flows `POST /auth/login`, `POST /authorize` (with the consent) and the SSO key selection, which accept the key and mint a web session, a code and the token pair `/token` trades for it (and refreshes); and nothing else. Every credential those flows mint resolves through `ctx_auth_by_id` and carries the requirement: the session and the tokens reach `GET /api/whoami` and, with a narrowing, the routes of a narrowed request — nothing more (executed for the session, the access token and a refreshed one; the SSO session is minted through the same path). `/register` in admin mode refuses the key. The check sits in `narrowAuth`, beside the narrowing it demands. A key that belongs to one group of people is minted `required` (`ctx keys create … --require-narrowing`, or `scope_narrowing: "required"` on `api-key-create`): then an old client, a client that forgets the headers, or another tool that sends none reaches nothing with it. The narrowing itself is the client's choice: whoever holds the key and sends the headers reads, request by request (up to eight scopes each), everything the key may read. The boundary is the key's own scope set — which is why a group's key is minted with exactly the group's scopes (`keyset-provision`); `required` makes a forgotten narrowing fail closed, it does not shrink what the key may do. Every existing key is `optional` and behaves as before; `api-key-update {scope_narrowing}` switches it (tenant-admin, like `write_scopes`; a server-admin key only by a server-admin). The switch applies from the next request: `ctx_auth_by_id` reads the column from the key row it locks for `last_used_at`, and nothing caches an authentication. Turning it on or off writes an `api_key` audit row like any other key change ([security](security.md)). On an owner key the requirement is owner power: a key that requires narrowing administers nothing (unnarrowed it gets only whoami, narrowed it runs as a `member`), so only an owner or a server-admin switches an owner key to `required`, and never the last owner that can still administer the tenant — an owner counts for the last-owner invariant only while it is active and `optional`. The two event streams (`/api/project/events`, `/api/events`) re-authenticate their key periodically and end once it requires narrowing (they are never narrowed); `/register` in admin mode, which resolves its key outside the Auth middleware, applies the same rules (a key that requires narrowing, or a narrowed request, registers nothing). ## Block-level grants (row level) diff --git a/docs/operations.md b/docs/operations.md index f33af6487..4a952af28 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -2398,9 +2398,18 @@ Issue #571. `context_model_consumers.record_bodies BOOLEAN NOT NULL DEFAULT fals `context_api_keys.scope_narrowing TEXT NOT NULL DEFAULT 'optional' CHECK (optional | required)` — every key reads `optional` after the upgrade and behaves as before (the value names no scope: a tenant's offboarding deletes its keys with it as before); a key switched to `required` answers every request without `X-Context-Read-Scopes` with `403 scope_narrowing_required`, `GET /api/whoami` excepted ([multi-tenancy](multi-tenancy.md#required-narrowing-migration-198)). `ctx_auth_by_id` and `ctx_auth` gain the column as their last one; the audit projection `audit_state_api_key` and the trigger `trg_api_keys_audit_upd` gain it, so every switch is an `update` row of `api_key`. -**Locks.** `ADD COLUMN` with a constant default rewrites no row, but its `CHECK` reads every key once, under the `ACCESS EXCLUSIVE` lock on `context_api_keys` that lasts to the commit — while it is held every authentication waits (`ctx_auth_by_id` writes `last_used_at`). Measured with `TestMigration198LockWindow` (`CTX_M198_KEYS=100000,1000000`, a test container on the build host, warm cache): the whole file took 46 ms on 100 000 keys and 215 ms on 1 000 000 keys, where an authentication started 50 ms in answered after 167 ms. The scan grows with the number of keys, not of blocks; a key table of ten million rows would hold authentications for about two seconds by that line (not measured). `CREATE TRIGGER` and the function rebuild add no lock wait of their own; `lock_timeout` 3 s. After the upgrade a switch of `scope_narrowing` applies from the next authentication: `ctx_auth_by_id` reads the column from the key row its `last_used_at` update locks, so an authentication that meets an uncommitted switch waits for it and answers the committed value (executed: `TestMigration198AuthReadsTheLockedRow`, with the switch held open on a second connection). +**Locks.** `ADD COLUMN` with a constant default rewrites no row, but its `CHECK` reads every key once, under the `ACCESS EXCLUSIVE` lock on `context_api_keys` that lasts to the commit — while it is held every authentication waits (`ctx_auth_by_id` writes `last_used_at`). Measured with `TestMigration198LockWindow` (`CTX_M198_KEYS=100000,1000000`, a test container on the build host, warm cache): the whole file took 46 ms on 100 000 keys and 215 ms on 1 000 000 keys, where an authentication started 50 ms in answered after 167 ms. The scan grows with the number of keys, not of blocks; a key table of ten million rows would hold authentications for about two seconds by that line (not measured). `CREATE TRIGGER` and the function rebuild add no lock wait of their own. Before that, `ALTER TABLE` may have to wait for its lock behind a transaction that holds `context_api_keys` (any reader or writer of a key row): up to `lock_timeout` 3 s, and during that wait every authentication queues behind it as well — in the worst case all requests stand for 3 s plus the scan, then the file fails, the boot stops, and the next start retries. After the upgrade a switch of `scope_narrowing` applies from the next authentication: `ctx_auth_by_id` reads the column from the key row its `last_used_at` update locks, so an authentication that meets an uncommitted switch waits for it and answers the committed value (executed: `TestMigration198AuthReadsTheLockedRow`, with the switch held open on a second connection). -**Rolling deploy and way back.** A binary before 198 on a database with 198 selects `ctx_auth`'s columns by name (executed: the eleven-column statement answers at 198, `TestMigration198WayBack`), mints keys that read `optional`, and serves **every** key without the requirement — the check lives in the binary. Before rolling the binary back, deactivate the keys that require narrowing (`api-key-update {active: false}`), or accept that each then reaches everything its own rights allow. The way back of the schema is in the header of `198_api_key_scope_narrowing.sql` and executed by `TestMigration198WayBack`; after it, and after 198 runs again, every key reads `optional` — the requirements are not restored. +**Rolling deploy and way back.** A binary before 198 on a database with 198 selects `ctx_auth`'s columns by name (executed: the eleven-column statement answers at 198, `TestMigration198WayBack`), mints keys that read `optional`, and serves **every** key without the requirement — the check lives in the binary. Before rolling the binary back, count and name the keys that require narrowing: + +```sql +SELECT k.id, k.label, t.slug AS tenant, k.home_scope + FROM context_api_keys k JOIN context_tenants t ON t.id = k.tenant_id + WHERE k.active AND k.scope_narrowing = 'required' + ORDER BY t.slug, k.label; +``` + +Each row is a key the older binary will serve with all its rights and no narrowing: deactivate it (`api-key-update {id, active: false}`; reactivate it after the upgrade again) or accept that it then reaches everything its own scope set allows. No row: the rollback opens nothing. The way back of the schema is in the header of `198_api_key_scope_narrowing.sql` and executed by `TestMigration198WayBack`; after it, and after 198 runs again, every key reads `optional` — the requirements are not restored. ### `graph_overview.csr_loader`: the rebuild's input substrate diff --git a/go/cmd/ctxd/narrowing_c1_more_integration_test.go b/go/cmd/ctxd/narrowing_c1_more_integration_test.go index 9dacc1758..aea7ffaca 100644 --- a/go/cmd/ctxd/narrowing_c1_more_integration_test.go +++ b/go/cmd/ctxd/narrowing_c1_more_integration_test.go @@ -14,9 +14,11 @@ import ( "context" "net/http" "slices" + "strings" "testing" "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/handler" "github.com/GottZ/ctx/internal/llmlog" ) @@ -136,3 +138,40 @@ func TestC1PinGrantScopeFirstUsesTheKeysBackendChain(t *testing.T) { t.Errorf("the question of key w (narrowed to %s first) walked tenant c1two's backend in %d of %d embed(s), want 0 — the chain must stay the key's", w.two, tried, rows) } } + +// TestC1EscapedPathOfAListedRouteGivesNoData (review #595): a narrowed request +// to a listed route spelled with percent escapes never reaches the route — the +// router matches the escaped form, finds no route and answers 404 before Auth +// (narrowAuth would refuse it as well, TestNarrowAuthRefusesAnEscapedPath). +// No block, no echo, no write. +func TestC1EscapedPathOfAListedRouteGivesNoData(t *testing.T) { + w := c1Setup(t) + h := c1Narrow("work") + hw := c1Narrow("work", "work") + for _, c := range []struct { + method, path string + h http.Header + body any + }{ + {http.MethodPost, "/api/%73earch", h, map[string]any{"query": c1Probe}}, + {http.MethodPost, "/api/qu%65ry", h, map[string]any{"query": c1Probe, "synthesize": false}}, + {http.MethodPost, "/api/m%61nage", h, map[string]any{"action": "get", "id": w.blocks["work"]}}, + {http.MethodGet, "/api/who%61mi", h, nil}, + {http.MethodPost, "/api/st%6Fre", hw, map[string]any{"category": "learnings", "title": "c1 escaped write", "content": "x"}}, + } { + r := w.do(t, c.method, c.path, w.keys["w"], c.h, c.body) + t.Logf("%s %s narrowed: HTTP %d", c.method, c.path, r.status) + if r.status >= 200 && r.status < 300 { + t.Errorf("%s %s narrowed: HTTP %d, want no success", c.method, c.path, r.status) + } + if strings.Contains(r.raw, c1Probe) || strings.Contains(r.raw, "c1-w") { + t.Errorf("%s %s narrowed: the answer carries data: %s", c.method, c.path, r.raw) + } + if len(r.header.Values(handler.HeaderNarrowed)) != 0 { + t.Errorf("%s %s narrowed: an echo %v — the request reached Auth", c.method, c.path, r.header.Values(handler.HeaderNarrowed)) + } + } + if n := w.c1Count(t, "c1 escaped write"); n != 0 { + t.Errorf("the escaped store wrote %d block(s)", n) + } +} diff --git a/go/cmd/ctxd/scope_narrowing_required_c2_authflow_integration_test.go b/go/cmd/ctxd/scope_narrowing_required_c2_authflow_integration_test.go new file mode 100644 index 000000000..1682dc5a4 --- /dev/null +++ b/go/cmd/ctxd/scope_narrowing_required_c2_authflow_integration_test.go @@ -0,0 +1,176 @@ +//go:build integration + +// Achse 02 C-2, review #595 L2: the auth flows take a key that requires +// narrowing without one — POST /auth/login mints a web session, POST +// /authorize a code that /token trades for an access and a refresh token — +// and every credential they mint resolves through ctx_auth_by_id, so it +// carries the requirement: without a narrowing it reaches GET /api/whoami +// and nothing else, with one it reads its named scopes. +// +// go test -tags=integration -p 1 -count=1 -run '^TestC2RequiredKeyThrough' ./cmd/ctxd/ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/GottZ/ctx/internal/handler" + "github.com/GottZ/ctx/internal/store" +) + +// c2afSend runs one request with the credential set by cred. +func c2afSend(t *testing.T, router http.Handler, method, path string, body any, h http.Header, cred func(*http.Request)) *httptest.ResponseRecorder { + t.Helper() + var rd *bytes.Reader + if body != nil { + b, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + rd = bytes.NewReader(b) + } else { + rd = bytes.NewReader(nil) + } + req := httptest.NewRequest(method, path, rd) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + req.Header.Set("Accept", "application/json, text/event-stream") + for k, vs := range h { + for _, v := range vs { + req.Header.Add(k, v) + } + } + cred(req) + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + return rec +} + +// c2afWantRequired checks what a credential minted from the required key +// reaches: whoami (reporting the requirement), and nothing else unnarrowed; +// narrowed, a search of the key's home scope. +func c2afWantRequired(t *testing.T, router http.Handler, who string, cred func(*http.Request)) { + t.Helper() + who200 := c2afSend(t, router, http.MethodGet, "/api/whoami", nil, nil, cred) + var wb map[string]any + _ = json.Unmarshal(who200.Body.Bytes(), &wb) + if who200.Code != http.StatusOK || wb["scope_narrowing"] != "required" { + t.Errorf("%s: whoami HTTP %d scope_narrowing %v, want 200 required", who, who200.Code, wb["scope_narrowing"]) + } + for _, c := range []struct { + method, path string + body any + }{ + {http.MethodPost, "/api/search", map[string]any{"query": c1Probe}}, + {http.MethodPost, "/api/query", map[string]any{"query": c1Probe, "synthesize": false}}, + {http.MethodPost, "/api/store", map[string]any{"category": "learnings", "title": "c2af refused " + who, "content": "x"}}, + {http.MethodPost, "/api/manage", map[string]any{"action": "type-list"}}, + {http.MethodGet, "/api/session/keys", nil}, + {http.MethodPost, "/mcp", map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}}, + } { + rec := c2afSend(t, router, c.method, c.path, c.body, nil, cred) + var b map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &b) + if rec.Code != http.StatusForbidden || b["code"] != "scope_narrowing_required" { + t.Errorf("%s: unnarrowed %s %s: HTTP %d %s, want 403 scope_narrowing_required", who, c.method, c.path, rec.Code, strings.TrimSpace(rec.Body.String())) + } + } + h := http.Header{} + h.Set(handler.HeaderReadScopes, "work") + if rec := c2afSend(t, router, http.MethodPost, "/api/search", map[string]any{"query": c1Probe}, h, cred); rec.Code != http.StatusOK || rec.Header().Get(handler.HeaderNarrowed) != "work;" { + t.Errorf("%s: narrowed search: HTTP %d echo %q, want 200 work;", who, rec.Code, rec.Header().Get(handler.HeaderNarrowed)) + } +} + +// TestC2RequiredKeyThroughLoginCarriesTheRequirement: the login answers the +// required key, and its web session (cookie + CSRF token) carries the +// requirement. +func TestC2RequiredKeyThroughLoginCarriesTheRequirement(t *testing.T) { + w := c1Setup(t) + key := w.mintKey(t, map[string]any{"label": "c2af-login", "home_scope": "work", "scope_narrowing": "required"}) + login := c2afSend(t, w.router, http.MethodPost, "/auth/login", map[string]any{"api_key": key}, nil, func(*http.Request) {}) + if login.Code != http.StatusOK { + t.Fatalf("fixture: login of the required key: HTTP %d %s", login.Code, login.Body.String()) + } + var lr struct { + CSRF string `json:"csrf_token"` + } + _ = json.Unmarshal(login.Body.Bytes(), &lr) + cookies := login.Result().Cookies() + if len(cookies) == 0 { + t.Fatal("fixture: the login set no cookie") + } + c2afWantRequired(t, w.router, "web session", func(r *http.Request) { + for _, c := range cookies { + r.AddCookie(c) + } + r.Header.Set("X-CSRF-Token", lr.CSRF) + }) +} + +// TestC2RequiredKeyThroughOAuthCarriesTheRequirement: /authorize answers the +// required key with a code, /token trades it for a token pair, and the access +// token — as the one a refresh mints — carries the requirement. +func TestC2RequiredKeyThroughOAuthCarriesTheRequirement(t *testing.T) { + w := c1Setup(t) + key := w.mintKey(t, map[string]any{"label": "c2af-oauth", "home_scope": "work", "scope_narrowing": "required"}) + const callback = "https://c2af.example/cb" + client, _, err := store.RegisterOAuthClient(context.Background(), w.pool, store.RegisterOAuthClientSpec{ + Label: "c2af", RedirectURIs: []string{callback}, TokenEndpointAuthMethod: "none", Source: "admin", + }) + if err != nil { + t.Fatal(err) + } + verifier := strings.Repeat("c", 64) + sum := sha256.Sum256([]byte(verifier)) + form := url.Values{ + "response_type": {"code"}, "client_id": {client.ClientID}, "redirect_uri": {callback}, + "code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])}, "code_challenge_method": {"S256"}, + "state": {"c2af"}, "consent": {"yes"}, "api_key": {key}, + } + post := func(path string, f url.Values) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(f.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + rec := httptest.NewRecorder() + w.router.ServeHTTP(rec, req) + return rec + } + authz := post("/authorize", form) + loc, err := url.Parse(authz.Header().Get("Location")) + if authz.Code != http.StatusFound || err != nil || loc.Query().Get("code") == "" { + t.Fatalf("fixture: /authorize of the required key: HTTP %d location %q", authz.Code, authz.Header().Get("Location")) + } + tok := post("/token", url.Values{"grant_type": {"authorization_code"}, "code": {loc.Query().Get("code")}, + "code_verifier": {verifier}, "client_id": {client.ClientID}, "redirect_uri": {callback}}) + var pair struct { + Access string `json:"access_token"` + Refresh string `json:"refresh_token"` + } + _ = json.Unmarshal(tok.Body.Bytes(), &pair) + if tok.Code != http.StatusOK || pair.Access == "" || pair.Refresh == "" { + t.Fatalf("fixture: /token: HTTP %d %s", tok.Code, tok.Body.String()) + } + bearer := func(token string) func(*http.Request) { + return func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+token) } + } + c2afWantRequired(t, w.router, "access token", bearer(pair.Access)) + + ref := post("/token", url.Values{"grant_type": {"refresh_token"}, "refresh_token": {pair.Refresh}, "client_id": {client.ClientID}}) + var next struct { + Access string `json:"access_token"` + } + _ = json.Unmarshal(ref.Body.Bytes(), &next) + if ref.Code != http.StatusOK || next.Access == "" { + t.Fatalf("fixture: refresh: HTTP %d %s", ref.Code, ref.Body.String()) + } + c2afWantRequired(t, w.router, "refreshed access token", bearer(next.Access)) +} From 8e91a3d7f5ff592136529c2c31b29b354c6fcbd9 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 07:50:34 +0100 Subject: [PATCH 13/15] =?UTF-8?q?test(handler):=20the=20column=20probe=20o?= =?UTF-8?q?f=20get=20reads=20the=20guard=20redaction=20by=20its=20new=20te?= =?UTF-8?q?xt=20=E2=80=94=20the=20three=20verdict=20keys=20go=20as=20one?= =?UTF-8?q?=20text[]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TestGetOptionsLeaveColumnsUnread tells a by-id read that reads metadata from one that skips it by the SQL text of guardRedactedMetadataSQL. That expression drops guard_matched_id, guard_similarity and guard_is_cross_scope together since the previous commit, as "metadata - '{guard_matched_id,…}'::text[]"; the probe now looks for that text. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- go/internal/handler/get_fields_integration_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/go/internal/handler/get_fields_integration_test.go b/go/internal/handler/get_fields_integration_test.go index 6003f7ab4..9ff81317d 100644 --- a/go/internal/handler/get_fields_integration_test.go +++ b/go/internal/handler/get_fields_integration_test.go @@ -736,7 +736,9 @@ func TestGetOptionsLeaveColumnsUnread(t *testing.T) { for _, s := range reads { readsContent := strings.Contains(s, "title, content, ") skipsContent := strings.Contains(s, "''::text AS content") - readsMetadata := strings.Contains(s, "context_blocks.metadata - 'guard_matched_id'") + // The guard redaction of the metadata column (guardRedactedMetadataSQL): + // since review #595 it drops the three verdict keys as one text[]. + readsMetadata := strings.Contains(s, "context_blocks.metadata - '{guard_matched_id,") skipsMetadata := strings.Contains(s, "NULL::jsonb AS metadata") if readsContent != c.content || skipsContent == c.content || readsMetadata != c.metadata || skipsMetadata == c.metadata { t.Errorf("statement reads content %t (skips %t), metadata %t (skips %t); want content %t, metadata %t:\n%s", From 508eea77f9bacb1877b26d55b428b7083cc317d4 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 09:01:58 +0100 Subject: [PATCH 14/15] =?UTF-8?q?fix(auth):=20keyset-provision=20refuses?= =?UTF-8?q?=20a=20set=20whose=20label=20an=20active=20key=20already=20carr?= =?UTF-8?q?ies=20=E2=80=94=20one=20active=20key=20per=20label=20also=20wit?= =?UTF-8?q?hout=20replace=5Flabel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Without replace_label the action minted a key of a label an active key of the tenant already carried: two runs of the same set — two machines, or a repeated first run — left two active keys of one label, and a client that binds a key by its label (whoami.label) would take either. The label is not unique in the schema, so only the action can decide it. Now a key without replace_label whose label an active key of the tenant carries refuses the whole set with 409 before anything is written, no scope either; the answer names the labels concerned (sorted) and no key value. The check reads under the tenant lock every key write takes first, so of two concurrent sets one goes through and the other is refused. A deactivated key of the label does not count (a set after a revoke goes through); replace_label replaces as before, and its refusal of an administrative key's label now carries the same labels field. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/api.md | 2 +- docs/multi-tenancy.md | 4 +- ...keyset_provision_label_integration_test.go | 67 ++++++++++ go/internal/handler/keyset_provision.go | 18 ++- go/internal/store/keyset.go | 70 ++++++++++- go/internal/store/keyset_integration_test.go | 116 ++++++++++++++++++ 6 files changed, 268 insertions(+), 9 deletions(-) create mode 100644 go/cmd/ctxd/keyset_provision_label_integration_test.go diff --git a/docs/api.md b/docs/api.md index fc210c4dd..4807cb9c1 100644 --- a/docs/api.md +++ b/docs/api.md @@ -88,7 +88,7 @@ PostgreSQL stores a NUL character (U+0000) neither in text nor in JSON, so no va - **Backfill memo release (issue #236):** `embed-backfill-release` (tierTenantAdmin) drops regular embed-backfill failure memos (`context_embed_failures` rows with `migration_id` NULL) so the backfill takes their blocks again — after `embed_backfill.max_tokens` was raised, the embed backend moved to a larger context, or a backend outage ended; without it a parked block came back only through a change of its title or content. `data`: exactly one of `block_id` (a UUID) or `class` (`wire` or `oversize`), optional `limit` (the page size, at most and by default `1000`; a larger value is clamped), and `confirm_memos` together with `as_of`; unknown fields, a second selector, another class, a malformed id, a negative number and a `confirm_memos` without `as_of` (or the reverse) are `400`. A `caller_timeout` memo is never taken, not even by `block_id`: it is no park — the background arm takes such a block at once, and with the arm off the query path retries it after its hold —, and deleting it would hand the block back to the requests' `sync_budget` with its attempts restarted. A tenant-admin reaches the memos of blocks in its own tenant's scopes (a scope or a block granted to the tenant is not its own) — another tenant's block and an unknown one answer the same `counted: 0`; a server-admin reaches every memo; a key without an admin role is `403`. A re-embed migration's memos are never touched. **Without `confirm_memos` the call is a dry run** answering `{action, success, dry_run: true, as_of, counted, confirm_memos, held}` (and `held_until` when `held` is above 0); the real call sends `confirm_memos` and `as_of` of that answer, takes only the memos that were there when the dry run counted (a memo written after `as_of` — a released block that was parked again, a new park — is neither counted nor released, so paging ends), counts them again and releases only when the number is unchanged (otherwise `409` with the fresh `counted` and `confirm_memos`, and the `as_of` the call sent), releases at most `limit` of them — the count and the release decide which memos the reader may release at one instant (one transaction, issue #536), so a hold that ends between the two neither counts nor releases its memo in that call — and answers `{action, success, dry_run: false, as_of, counted, released, remaining, confirm_memos, held}` — `remaining` (and `confirm_memos`, the number to confirm for the next page with the same `as_of`) is what is left of them, including a memo another transaction held at that moment, which the release skips instead of waiting for. Two releases of the same memos at once each count what both may take: one of them releases fewer than it counted and answers a `remaining` the other has already released, and its next page answers `409` with the fresh count. Only memos that keep a block out of the pick (`next_attempt_at` in the future) count. **A server-admin's release deletes the memo; a tenant-admin's keeps it and makes it due**, with its attempts and with the time of the release in `first_seen`, so a block the backend still cannot take is parked again on the same row. A tenant-admin releases such an `oversize` memo again (more than one attempt) only once `embed_backfill.release_hold` × 2^(attempts − 2) has passed since that release, at most `embed_backfill.backoff_cap` (defaults 1 h and 24 h; a cap of 0 sets none; the hold must be above 0, V70); until then it is answered in `held`, with the earliest end in `held_until`. Without the hold a tenant-admin releasing its blocks in a loop while they kept not fitting took one turn of the background arm in every round of the tenants for good, where its way back without the action, an edit per block, costs a write each. The first release of every memo is not held, a `wire` memo is not held (its failure holds the tenant in the arm for `embed_backfill.interval`, and its next failure backs off longer, since the attempts stay), and a server-admin's release and a change of the block's title or content (which deletes the memo) start the count again. For a tenant-admin the count and the page of a class read the tenant's own scopes and their pending blocks, so their cost grows with the tenant's pending blocks, not with other tenants' memos. The next backfill pick of each released block embeds it when it fits now and parks it again after one attempt when it does not. CLI: `ctx admin embed-backfill release --class oversize`, then the same with `--confirm N --as-of T`; `--limit N` is sent as given, so a negative one is answered with the `400` (until issue #536 the CLI left a `--limit` of 0 or below out of the request and the server paged by its maximum). Operator notes in [operations](operations.md#embedding-backend-tuning-cpu-llamacpp), paragraph "Backfill failure memo". - **Block counters (issue #266):** `stats`, `guard-stats` and `list-categories` read per-scope counters that triggers on `context_blocks` keep with every write (migration 170), and so do the per-scope block counts of `scope-overview` (issue #271); the answers are unchanged. `guard-stats`' `pending_count` and `dirty_since` are counted on demand since migration 181: the blocks of the caller's read scopes the guard still has to check, and the oldest `updated_at` among them (`null` when none waits) — before 181 a global count of block writes since the last guard run, the same for every key ([operations](operations.md#migration-181-no-block-writer-waits-on-the-guards-state-row-guard-stats-counts-the-waiting-blocks)). `stats-reconcile` (server-admin) recounts and corrects them: `data` `{}` reconciles every scope, `{"scope": "<scope>"}` one; any other field is a `400`. It answers `{action, success, scopes, corrections, corrections_total, pruned, failed}` — `corrections` lists the corrected keys as `{scope, category, is_archived, guard_status, counted, actual}`, at most the first 1 000 of the pass, and `corrections_total` counts all of them (every one is corrected and logged; issue #271), `pruned` the folded counter rows at 0 it removed, `failed` the scopes whose reconcile failed (the pass goes on with the others; then `success` is `false` and the status `500`). The scheduler runs the same pass on `scheduler.block_count_reconcile_interval` — see [operations](operations.md#migration-170-block-counters-behind-stats-guard-stats-and-list-categories). - **Keys/clients:** `api-key-create` requires `home_scope`; key + MCP-client management and mutating `dream-mode` require an **admin key** since migration 052 (see [security](security.md#admin-tier)). `api-key-create`/`api-key-update` accept optional `write_scopes` (078, E4b) — explicit per-key write scopes that must be ⊆ `allowed_scopes ∪ {home_scope}` (else 400); the effective block-write gate and its double enforcement are in [multi-tenancy](multi-tenancy.md#per-key-write-scopes-e4b-migration-078). They also accept `scope_narrowing` (migration 198): `required` makes the key answer every request without a [narrowing](#scope-narrowing-per-request) with `403 scope_narrowing_required`, `GET /api/whoami` excepted; `optional` (every existing key, the default) keeps today's behaviour; any other value is 400. Both answers carry the value; `api-key-list` lists it. Per-tenant scoping of the `api-key-*` actions and the tenant lifecycle (`tenant-*`, `tenant-grant-*`, `scope-*`, `tenant-limit-set`, `tenant-usage-get`, `tenant-quota-*`, `block-grant-*`) are in [multi-tenancy](multi-tenancy.md). -- **Key sets:** `keyset-provision` (tenant-admin, in the caller's own tenant; a server-admin may name `tenant_id`, anyone else naming it gets 403) creates the scopes and the keys of one set — say the groups of one community — in one transaction: either the whole set exists afterwards or nothing of it does. `data`: `scopes` (at most 64 bare scope names, scope-create's rule; the server puts the tenant's `<slug>:` in front; a scope the tenant already has is kept) and `keys` (at most 64, each `{label, home_scope, allowed_scopes, write_scopes, scope_narrowing, replace_label}`; a key's scope is a bare name or a full `<slug>:<name>` and must be the tenant's own or one the set creates; a name without `:` always gets the prefix, so scopes outside that form — the default tenant's `private`, `work` and `shared` — cannot be named). The answer lists `scopes` as `{scope, created}` and `keys` as `{id, label, home_scope, allowed_scopes, write_scopes, scope_narrowing, api_key}`, both in the order of the call; each `api_key` (the plaintext) is in this answer only. Every key is a `member` key with exactly the scopes it names (no implicit `shared`, also in the default tenant) and its own principal; `scope_narrowing` left out is `required` — the set's keys answer nothing without a [narrowing](#scope-narrowing-per-request) but `GET /api/whoami`, and a key without that requirement is minted only when the call names `optional` (unlike `api-key-create`, whose default stays `optional`). `replace_label: true` deactivates the tenant's active keys with that label in the same transaction, before `max_keys` is counted, so a repeated call leaves one active key per label; on a label an owner, admin or server-admin key carries it refuses the set with `409`. Refusals: a scope of another tenant, or one the tenant neither has nor creates, `403`; `write_scopes ⊄ allowed_scopes ∪ {home_scope}`, a malformed scope name, an unknown field, a label missing or named twice in the set, a value the column cannot hold, a `scope_narrowing` other than `optional`/`required`, more than 64 scopes or keys, `400`; past `max_scopes` or `max_keys`, `429` with `limit`, `count` (the tenant's count before the set; for keys after its replacements) and `requested`; a tenant being deleted, or a scope registered meanwhile past the tenant lock (only a hand edit can), `409`; a top-level `id`, `400` (the target tenant is `data.tenant_id`). A narrowed request never reaches it ([above](#scope-narrowing-per-request)). How it serialises with the other key and scope writes: [multi-tenancy](multi-tenancy.md#key-sets-keyset-provision). +- **Key sets:** `keyset-provision` (tenant-admin, in the caller's own tenant; a server-admin may name `tenant_id`, anyone else naming it gets 403) creates the scopes and the keys of one set — say the groups of one community — in one transaction: either the whole set exists afterwards or nothing of it does. `data`: `scopes` (at most 64 bare scope names, scope-create's rule; the server puts the tenant's `<slug>:` in front; a scope the tenant already has is kept) and `keys` (at most 64, each `{label, home_scope, allowed_scopes, write_scopes, scope_narrowing, replace_label}`; a key's scope is a bare name or a full `<slug>:<name>` and must be the tenant's own or one the set creates; a name without `:` always gets the prefix, so scopes outside that form — the default tenant's `private`, `work` and `shared` — cannot be named). The answer lists `scopes` as `{scope, created}` and `keys` as `{id, label, home_scope, allowed_scopes, write_scopes, scope_narrowing, api_key}`, both in the order of the call; each `api_key` (the plaintext) is in this answer only. Every key is a `member` key with exactly the scopes it names (no implicit `shared`, also in the default tenant) and its own principal; `scope_narrowing` left out is `required` — the set's keys answer nothing without a [narrowing](#scope-narrowing-per-request) but `GET /api/whoami`, and a key without that requirement is minted only when the call names `optional` (unlike `api-key-create`, whose default stays `optional`). `replace_label: true` deactivates the tenant's active keys with that label in the same transaction, before `max_keys` is counted, so a repeated call leaves one active key per label; on a label an owner, admin or server-admin key carries it refuses the set with `409`. Without `replace_label` a key may not take a label an active key of the tenant already carries: the whole set is refused with `409` and nothing of it is created, no scope either — so two runs of the same set (two machines, a repeated first run) never leave two active keys of one label; a deactivated key of the label does not count. Both label refusals answer `{"success": false, "error": "…", "labels": [<the set's labels concerned, sorted>]}` and name no key value. Refusals: a scope of another tenant, or one the tenant neither has nor creates, `403`; `write_scopes ⊄ allowed_scopes ∪ {home_scope}`, a malformed scope name, an unknown field, a label missing or named twice in the set, a value the column cannot hold, a `scope_narrowing` other than `optional`/`required`, more than 64 scopes or keys, `400`; past `max_scopes` or `max_keys`, `429` with `limit`, `count` (the tenant's count before the set; for keys after its replacements) and `requested`; a tenant being deleted, or a scope registered meanwhile past the tenant lock (only a hand edit can), `409`; a top-level `id`, `400` (the target tenant is `data.tenant_id`). A narrowed request never reaches it ([above](#scope-narrowing-per-request)). How it serialises with the other key and scope writes: [multi-tenancy](multi-tenancy.md#key-sets-keyset-provision). - **Block-type registry:** `type-list`/`type-get` are open reads; `type-create`/`type-update`/`type-delete` are the **operator transport** (server-admin, `_global` namespace) of the same store logic the REST `PUT/DELETE /api/types/{name}` surface uses — kept functional for MCP/CLI consumers, not superseded (see [Block-type registry](#block-type-registry)). `manage update` accepts a registry-validated `type` field; `list-meta` accepts the `types`/`types_exclude` filters. - **Issue corpus:** `issue-create`/`issue-update`/`issue-get`/`issue-list`/`issue-comment-create`/`issue-link-create`/`issue-link-delete` are the **operator transport** (all tierOpen; isolation is store-layer scope filtering, not an admin tier) over the same store issue logic the REST `/api/project` issue surface (W6/W7) uses — kept reachable for MCP/CLI operators, not the primary UI surface (see [Issue corpus](#issue-corpus)). - **Backend pool:** `backend-list`/`create`/`update`/`delete`/`test` — see [Backend pool](#backend-pool). diff --git a/docs/multi-tenancy.md b/docs/multi-tenancy.md index 2d0642099..1fc182912 100644 --- a/docs/multi-tenancy.md +++ b/docs/multi-tenancy.md @@ -147,7 +147,7 @@ The `whoami` endpoint carries this on the wire: alongside the server-global `adm ### Key sets (`keyset-provision`) -`keyset-provision` is `scope-create` plus `api-key-create` for a whole set — the scopes and keys of the groups of one community, for instance — in **one** transaction ([api](api.md#manage-actions) has the wire form). It knows no community, bot or group: labels, scopes and rights come from the call. `store.ProvisionKeyset` takes the tenant row lock first (`FOR UPDATE` — the row lock `scope-create` and `api-key-create` take first and `api-key-update`/`api-key-delete` take before their decisive read of the key, and which `tenant-limit-set` and the tenant delete's mark, both an `UPDATE` of the row, wait for) and reads everything it decides on under it, each in a statement of its own: the tenant's status and both limits from the locked row, the owners of every scope the set names, the scope count, the roles of the keys `replace_label` would deactivate, the active key count after those replacements. A concurrent `tenant-limit-set`, `scope-create` or role change of the same tenant is therefore seen, not raced, and two sets that replace the same label one after the other leave one active key of it. Order inside the lock: scopes (refused when one belongs to another tenant, or when a key names a scope the tenant neither has nor creates — foreign and unknown answer alike, and a key never names a scope it could read only once someone registers it; the new scopes counted against `max_scopes`, their groups of migration 176 locked in sorted order — the order the scope trigger keeps, which a row-by-row assignment of several scopes would break — and then one `INSERT`), then `replace_label` (member keys only — a label an owner, admin or server-admin key carries refuses the set, so it can never take a key past the owner rules of `api-key-delete`), then `max_keys` (active keys after the replacements), then each key through `insertApiKeyTx`, the one INSERT path of a key: role `member`, `scope_narrowing` `required` unless the call names `optional` ([required narrowing](#required-narrowing-migration-198); as member keys they never touch the owner rules that count `required` on an owner key as taking its administration), a fresh principal, exactly the scopes named, the audit row (`create`, or `revoke` for a replaced key) attributed to the calling key `via=api`. A failure anywhere rolls the set back. A tenant whose delete has begun takes no set (409), the rule `scope-create` follows since issue #555. When the set created a scope the handler refreshes the quota accountant, as `scope-create` does, so a key homed there is under the tenant's quota from its first call. Cost: one statement per step plus one INSERT per key while the tenant lock is held — measured 41 ms for 64 new scopes and 64 keys and 34 ms for the same set again with 64 replacements, in a tenant holding 20 000 other keys and 2 000 other scopes (`TestKeysetSixtyFourCost`); the replacement, its check and the key count read the tenant's keys (there is no index on the label; a tenant with many keys pays a scan of its own keys, three times per set). Until the commit, other scope and key writes of the same tenant wait, so do inserts that reference the tenant row, block writes of never-embedded types into the tenant's scopes when the set creates a scope (they take the tenant's group of migration 176, which the scope trigger then holds), and the authentication of a key the set replaces (its row is locked by the replacement); the authentication of every other key does not wait (it takes no tenant lock). +`keyset-provision` is `scope-create` plus `api-key-create` for a whole set — the scopes and keys of the groups of one community, for instance — in **one** transaction ([api](api.md#manage-actions) has the wire form). It knows no community, bot or group: labels, scopes and rights come from the call. `store.ProvisionKeyset` takes the tenant row lock first (`FOR UPDATE` — the row lock `scope-create` and `api-key-create` take first and `api-key-update`/`api-key-delete` take before their decisive read of the key, and which `tenant-limit-set` and the tenant delete's mark, both an `UPDATE` of the row, wait for) and reads everything it decides on under it, each in a statement of its own: the tenant's status and both limits from the locked row, the active keys that already carry a label of the set, the owners of every scope the set names, the scope count, the roles of the keys `replace_label` would deactivate, the active key count after those replacements. A concurrent `tenant-limit-set`, `scope-create` or role change of the same tenant is therefore seen, not raced, and two sets that replace the same label one after the other leave one active key of it. Order inside the lock: the labels first — a key without `replace_label` whose label an active key of the tenant already carries refuses the whole set (409, the labels named) before anything is written, so two runs of one set never leave two active keys of one label (a deactivated key does not count; the check reads the tenant's active keys, there is no index on the label — measured 3.9 ms at 20 000 keys); then scopes (refused when one belongs to another tenant, or when a key names a scope the tenant neither has nor creates — foreign and unknown answer alike, and a key never names a scope it could read only once someone registers it; the new scopes counted against `max_scopes`, their groups of migration 176 locked in sorted order — the order the scope trigger keeps, which a row-by-row assignment of several scopes would break — and then one `INSERT`), then `replace_label` (member keys only — a label an owner, admin or server-admin key carries refuses the set, so it can never take a key past the owner rules of `api-key-delete`), then `max_keys` (active keys after the replacements), then each key through `insertApiKeyTx`, the one INSERT path of a key: role `member`, `scope_narrowing` `required` unless the call names `optional` ([required narrowing](#required-narrowing-migration-198); as member keys they never touch the owner rules that count `required` on an owner key as taking its administration), a fresh principal, exactly the scopes named, the audit row (`create`, or `revoke` for a replaced key) attributed to the calling key `via=api`. A failure anywhere rolls the set back. A tenant whose delete has begun takes no set (409), the rule `scope-create` follows since issue #555. When the set created a scope the handler refreshes the quota accountant, as `scope-create` does, so a key homed there is under the tenant's quota from its first call. Cost: one statement per step plus one INSERT per key while the tenant lock is held — measured 41 ms for 64 new scopes and 64 keys and 34 ms for the same set again with 64 replacements, in a tenant holding 20 000 other keys and 2 000 other scopes (`TestKeysetSixtyFourCost`); the replacement, its check and the key count read the tenant's keys (there is no index on the label; a tenant with many keys pays a scan of its own keys, three times per set). Until the commit, other scope and key writes of the same tenant wait, so do inserts that reference the tenant row, block writes of never-embedded types into the tenant's scopes when the set creates a scope (they take the tenant's group of migration 176, which the scope trigger then holds), and the authentication of a key the set replaces (its row is locked by the replacement); the authentication of every other key does not wait (it takes no tenant lock). ## Per-tenant settings & secrets @@ -265,7 +265,7 @@ Migration 069 adds structural per-tenant count-limits on `context_tenants`: `max | `tenant-usage-get` | tenant-admin (own) | Scope/key counts vs limits; a server-admin may target any. | | `api-key-create` | tenant-admin | Enforces `max_keys` transactionally (429, active-only count); a server-admin may mint into another tenant via `tenant_id` (foreign-target T22 — the new key's scopes must belong to the target; a non-server-admin's `tenant_id` → 403, AM2). New keys are always `member` (a smuggled `tenant_role` is ignored, AM3). Optional `write_scopes` (078, E4b) must be ⊆ `allowed_scopes ∪ {home_scope}` else 400 (see [Per-key write scopes](#per-key-write-scopes-e4b-migration-078)). | | `api-key-update` | tenant-admin | Role delegation (`{tenant_role?, active?, write_scopes?}`): only an owner (or server-admin) may change a key's role — a non-owner tenant-admin → 403, so admin→owner self-elevation is structurally impossible (no `is_admin` field means the server-global tier can never be set here). Demoting/deactivating the last active owner → 409 (last-owner invariant); an admin cannot neutralize an owner key → 403 (enforced at both update and the `api-key-delete` revoke path). A server-admin key (`is_admin`) is managed by server-admins only: any tenant-owner/-admin patch or revoke of it → 403, so a default-tenant admin cannot disable the operator's key. `write_scopes` (078, E4b) is validated ⊆ the key's existing `allowed_scopes ∪ {home_scope}` → 400 on a blind-writer; `[]` clears, absent leaves unchanged. `scope_narrowing` (198): switching an owner key to `required` takes its administration away, so it counts as neutralizing it (admin → 403) and the last-owner invariant counts only owners that are active **and** `optional` (409 for the last one, also on `api-key-delete`). Both actions decide the owner rules on the target as it is under the tenant row lock every key write takes, so a concurrent change of its role, `active` or `scope_narrowing` is seen, not raced. | -| `keyset-provision` | tenant-admin | `scope-create` and `api-key-create` for a set of up to 64 scopes and 64 keys in one transaction under the tenant row lock: all or nothing, `max_scopes`/`max_keys` counted for the whole set (429 with `limit`, `count`, `requested`), member keys with their own principal and `scope_narrowing` `required` unless the call names `optional`, `replace_label` deactivates the tenant's active member keys of a label in the same transaction (409 on a label an owner, admin or server-admin key carries); a server-admin may target another tenant via `tenant_id` (a non-server-admin's `tenant_id` → 403). See [Key sets](#key-sets-keyset-provision). | +| `keyset-provision` | tenant-admin | `scope-create` and `api-key-create` for a set of up to 64 scopes and 64 keys in one transaction under the tenant row lock: all or nothing, `max_scopes`/`max_keys` counted for the whole set (429 with `limit`, `count`, `requested`), member keys with their own principal and `scope_narrowing` `required` unless the call names `optional`, `replace_label` deactivates the tenant's active member keys of a label in the same transaction (409 on a label an owner, admin or server-admin key carries), without it a label an active key already carries refuses the set (409); a server-admin may target another tenant via `tenant_id` (a non-server-admin's `tenant_id` → 403). See [Key sets](#key-sets-keyset-provision). | | `gateway-limits-get` | tenant-admin (own) | Reads the limits rows of an own consumer or the own tenant with the ceiling and the effective values ([api](api.md#gateway-limits-gateway-limits-)); instance and envelope values stay server-admin. | | `gateway-limits-set` | tenant-admin (own) | Writes the caller's **tenant-tier** row of an own consumer or the own tenant — narrowing only (each value at or under the ceiling of the levels above, else 400 with the field; `allow_external` only `false`). A server-admin writes the server tier freely, including `instance` and `tenant_envelope`. | | `gateway-limits-delete` | tenant-admin (own) | Removes the caller's tier row; the dimension inherits again. | diff --git a/go/cmd/ctxd/keyset_provision_label_integration_test.go b/go/cmd/ctxd/keyset_provision_label_integration_test.go new file mode 100644 index 000000000..2ce2aac0c --- /dev/null +++ b/go/cmd/ctxd/keyset_provision_label_integration_test.go @@ -0,0 +1,67 @@ +//go:build integration + +// keyset-provision without replace_label and a label an active key of the +// tenant already carries: the whole set is refused (409, naming the labels), +// nothing of it is created — no key, no scope. A deactivated key of the label +// does not count (a set after a revoke goes through); replace_label keeps +// replacing. Without the refusal two runs of the same set — two machines, or a +// repeated first run — would leave two active keys of one label, and a client +// that binds a key by its label (whoami.label) would take either. +// +// go test -tags=integration -p 1 -count=1 -run '^TestC3ALabel' ./cmd/ctxd/ +package main + +import ( + "context" + "fmt" + "net/http" + "regexp" + "testing" +) + +func TestC3ALabelAnActiveKeyCarriesRefusesTheSet(t *testing.T) { + w := c3Setup(t) + const label = "hermes:discord:444:members" + r := w.provision(t, w.owner, []string{"members"}, c3Key(label, "members", nil, nil, "required")).must(t, "first set") + _, ids, _ := c3KeysOf(r) + w.provision(t, w.owner, nil, c3Key("c3-label-b", "members", nil, nil, "required")).must(t, "a second label") + scopes, labels := w.state(t) + + // The same set again — plus a new scope and a key of a free label: the + // whole set is refused, the new scope included. + r = w.provision(t, w.owner, []string{"members", "mods"}, + c3Key(label, "members", nil, nil, "required"), + c3Key("c3-label-free", "mods", nil, nil, "required")) + if r.status != http.StatusConflict { + t.Errorf("a set naming a label an active key carries: HTTP %d %s, want 409", r.status, r.raw) + } + if got := fmt.Sprint(r.body["labels"]); got != "["+label+"]" { + t.Errorf("the refusal names labels %s, want [%s]", got, label) + } + if hex := regexp.MustCompile(`[0-9a-f]{64}`).FindString(r.raw); hex != "" { + t.Errorf("the refusal carries a 64-hex token: %s", r.raw) + } + w.wantUnchanged(t, "after the refused set", scopes, labels) + + // Two taken labels: both named, sorted. + r = w.provision(t, w.owner, nil, c3Key(label, "members", nil, nil, "required"), c3Key("c3-label-b", "members", nil, nil, "required")) + if got := fmt.Sprint(r.body["labels"]); r.status != http.StatusConflict || got != "[c3-label-b "+label+"]" { + t.Errorf("two taken labels: HTTP %d labels %s, want 409 and [c3-label-b %s]", r.status, got, label) + } + w.wantUnchanged(t, "after the second refused set", scopes, labels) + + // A deactivated key of the label does not count: after a revoke the set + // goes through without replace_label (the rerun after a rotation). + w.manage(t, w.owner, map[string]any{"action": "api-key-delete", "data": map[string]any{"id": ids[label]}}).must(t, "revoke the first key") + w.provision(t, w.owner, nil, c3Key(label, "members", nil, nil, "required")).must(t, "control: the label of a revoked key") + + // replace_label keeps replacing the active key of the label. + k := c3Key(label, "members", nil, nil, "required") + k["replace_label"] = true + w.provision(t, w.owner, nil, k).must(t, "control: replace_label") + var n int + if err := w.pool.QueryRow(context.Background(), + `SELECT count(*) FROM context_api_keys WHERE tenant_id = $1::uuid AND label = $2 AND active`, w.tenantID, label).Scan(&n); err != nil || n != 1 { + t.Errorf("%d active key(s) with the label (err %v), want 1", n, err) + } +} diff --git a/go/internal/handler/keyset_provision.go b/go/internal/handler/keyset_provision.go index bd0e1b60e..c95432b61 100644 --- a/go/internal/handler/keyset_provision.go +++ b/go/internal/handler/keyset_provision.go @@ -251,6 +251,7 @@ func writeKeysetError(w http.ResponseWriter, r *http.Request, err error) { var ( quota *store.KeysetQuotaError refusal *store.KeysetRefusal + taken *store.KeysetLabelRefusal ) switch { case errors.As(err, "a): @@ -265,7 +266,13 @@ func writeKeysetError(w http.ResponseWriter, r *http.Request, err error) { "error": "not a scope of this tenant: " + refusal.Subject}) case errors.As(err, &refusal) && errors.Is(refusal.Err, store.ErrKeysetLabelProtected): writeJSON(w, http.StatusConflict, map[string]any{"success": false, - "error": "replace_label: an active key labelled " + fmt.Sprintf("%q", refusal.Subject) + " is not a member key; revoke it with api-key-delete"}) + "error": "replace_label: an active key labelled " + fmt.Sprintf("%q", refusal.Subject) + " is not a member key; revoke it with api-key-delete", + "labels": []string{refusal.Subject}}) + case errors.As(err, &taken): + // The same form as the refusal above: 409, the text, the labels. + writeJSON(w, http.StatusConflict, map[string]any{"success": false, + "error": "an active key of the tenant already carries the label " + quotedLabels(taken.Labels) + "; name replace_label to replace it", + "labels": taken.Labels}) case errors.Is(err, store.ErrWriteScopeNotAllowed): // write_scopes ⊄ allowed_scopes ∪ {home_scope} (078, E4b): a blind writer. writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": err.Error()}) @@ -281,3 +288,12 @@ func writeKeysetError(w http.ResponseWriter, r *http.Request, err error) { writeAdminFailure(w, r, "manage: keyset-provision failed", err, writeOutcome(err), "keyset provision failed") } } + +// quotedLabels lists labels for a refusal's text: quoted, comma-separated. +func quotedLabels(labels []string) string { + q := make([]string, len(labels)) + for i, l := range labels { + q[i] = fmt.Sprintf("%q", l) + } + return strings.Join(q, ", ") +} diff --git a/go/internal/store/keyset.go b/go/internal/store/keyset.go index e227adc04..a8b412529 100644 --- a/go/internal/store/keyset.go +++ b/go/internal/store/keyset.go @@ -16,6 +16,7 @@ import ( "errors" "fmt" "sort" + "strings" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" @@ -74,6 +75,26 @@ var ErrKeysetScopeOutsideTenant = errors.New("store: not a scope of this tenant" // server-admin revokes a server-admin key). Refused, whoever calls. var ErrKeysetLabelProtected = errors.New("store: replace_label names an active key that is not a member key") +// ErrKeysetLabelTaken: a key of the set without replace_label carries a label +// an active key of the tenant already carries. Two active keys of one label +// would leave a client that binds a key by its label (whoami.label) to either +// of them; a set that means to take a label over names replace_label. A +// deactivated key of the label does not count (a set after a revoke goes +// through). Refused, whoever calls; nothing of the set is written. +var ErrKeysetLabelTaken = errors.New("store: an active key of the tenant already carries the label") + +// KeysetLabelRefusal names every label of the set an ErrKeysetLabelTaken is +// about, sorted — the caller's own labels, never a key's value. +type KeysetLabelRefusal struct { + Err error + Labels []string +} + +func (e *KeysetLabelRefusal) Error() string { + return e.Err.Error() + ": " + strings.Join(e.Labels, ", ") +} +func (e *KeysetLabelRefusal) Unwrap() error { return e.Err } + // KeysetRefusal carries which scope or label a refusal is about // (ErrKeysetScopeOutsideTenant, ErrKeysetLabelProtected) — the caller's own // input, never another tenant's row. @@ -115,21 +136,24 @@ func (e *KeysetQuotaError) Unwrap() error { // UpdateApiKey, DeleteApiKey) and read status, max_scopes and max_keys // from it under the lock. Absent ⇒ ErrTenantNotFound, offboarding ⇒ // ErrTenantOffboarding. -// 2. Every scope of the list is the tenant's (kept) or nobody's (created); +// 2. A key without replace_label may not carry a label an active key of the +// tenant carries (KeysetLabelRefusal, ErrKeysetLabelTaken) — checked +// before anything of the set is written; a deactivated key does not count. +// 3. Every scope of the list is the tenant's (kept) or nobody's (created); // every scope a key names is the tenant's or created by the set // (ErrKeysetScopeOutsideTenant otherwise). The tenant's scope count plus // the new ones may not pass max_scopes (KeysetQuotaError). The new // scopes' groups of migration 176 are locked in sorted order before the // one INSERT of all of them. -// 3. replace_label: the tenant's active keys with a replaced label are +// 4. replace_label: the tenant's active keys with a replaced label are // deactivated — all member keys, or ErrKeysetLabelProtected. -// 4. The tenant's active keys (after 3) plus the set may not pass max_keys. -// 5. Each key through insertApiKeyTx, the one INSERT path of a key: its own +// 5. The tenant's active keys (after 4) plus the set may not pass max_keys. +// 6. Each key through insertApiKeyTx, the one INSERT path of a key: its own // principal, role member, the audit row of the stamp. // // Every value a decision reads is read after the lock, in a statement of its // own (READ COMMITTED: a write that held the lock is seen). A failure anywhere -// — a refusal of steps 2 to 4, a key insertApiKeyTx refuses (write_scopes ⊄ +// — a refusal of steps 2 to 5, a key insertApiKeyTx refuses (write_scopes ⊄ // allowed_scopes ∪ {home_scope}, a scope_narrowing other than optional and // required), a database error — rolls the whole set back. func ProvisionKeyset(ctx context.Context, pool *pgxpool.Pool, tenantID string, scopes []string, keys []KeysetKey, stamp AuditStamp) (Keyset, error) { @@ -144,6 +168,9 @@ func ProvisionKeyset(ctx context.Context, pool *pgxpool.Pool, tenantID string, s if err := stampAudit(ctx, tx, stamp); err != nil { return err } + if err := keysetLabelsTakenTx(ctx, tx, tenantID, keys); err != nil { + return err + } listed, err := keysetScopesTx(ctx, tx, tenantID, scopes, keys, maxScopes) if err != nil { return err @@ -308,6 +335,39 @@ func keysetScopesTx(ctx context.Context, tx pgx.Tx, tenantID string, scopes []st return listed, nil } +// keysetLabelsTakenSQL lists, sorted, the labels of a set that an active key +// of the tenant already carries. +const keysetLabelsTakenSQL = `SELECT coalesce(array_agg(DISTINCT label::text ORDER BY label::text), '{}'::text[]) + FROM context_api_keys + WHERE tenant_id = $1::uuid AND active AND label = ANY($2::text[])` + +// keysetLabelsTakenTx refuses the set when a key of it without replace_label +// carries a label an active key of the tenant already carries +// (ErrKeysetLabelTaken, every such label named). It reads under the tenant +// lock, which every key write of the tenant takes first, so a key of the +// label committed by a concurrent set or api-key-create is seen; and it runs +// before the set writes anything. Without it two runs of one set — two +// machines, a repeated first run — would leave two active keys of one label. +func keysetLabelsTakenTx(ctx context.Context, tx pgx.Tx, tenantID string, keys []KeysetKey) error { + var labels []string + for _, k := range keys { + if !k.ReplaceLabel { + labels = append(labels, k.Label) + } + } + if len(labels) == 0 { + return nil + } + var taken []string + if err := tx.QueryRow(ctx, keysetLabelsTakenSQL, tenantID, labels).Scan(&taken); err != nil { + return fmt.Errorf("store: keyset label check: %w", err) + } + if len(taken) > 0 { + return &KeysetLabelRefusal{Err: ErrKeysetLabelTaken, Labels: taken} + } + return nil +} + // keysetReplaceTx deactivates the tenant's active keys whose label a key of // the set replaces (replace_label), after checking under the tenant lock that // each of them is a member key that is no server-admin key. diff --git a/go/internal/store/keyset_integration_test.go b/go/internal/store/keyset_integration_test.go index 4d7b51a81..3d2ed8478 100644 --- a/go/internal/store/keyset_integration_test.go +++ b/go/internal/store/keyset_integration_test.go @@ -267,6 +267,89 @@ func TestKeysetDefaultTenantKeyHasNoImplicitShared(t *testing.T) { } } +// TestKeysetLabelIsCheckedUnderTheLock: another key write of the tenant +// commits an active key of the set's label while the set waits for the +// tenant lock. Checked under the lock, the set (without replace_label) is +// refused and nothing of it exists; checked before it, the set would add a +// second active key of the label. +func TestKeysetLabelIsCheckedUnderTheLock(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + tid := freshTenant(t, ctx, pool, "ks-lbl") + ksScope(t, pool, "ks-lbl:a", tid) + err := ownerInterleave(ctx, t, pool, tid, + func(tx pgx.Tx) { + if _, err := tx.Exec(ctx, `WITH p AS (INSERT INTO context_principals (display_name) VALUES ('ks-lbl-label') RETURNING id) + INSERT INTO context_api_keys (key_hash, label, home_scope, tenant_id, principal_id) + SELECT 'ks-lbl-hash', 'ks-lbl-label', 'ks-lbl:a', $1::uuid, p.id FROM p`, tid); err != nil { + t.Fatal(err) + } + }, + func() error { + _, err := store.ProvisionKeyset(ctx, pool, tid, []string{"ks-lbl:b"}, []store.KeysetKey{ksKey("ks-lbl-label", "ks-lbl:a", false)}, store.AuditStamp{}) + return err + }) + var lr *store.KeysetLabelRefusal + if !errors.Is(err, store.ErrKeysetLabelTaken) || !errors.As(err, &lr) || fmt.Sprint(lr.Labels) != "[ks-lbl-label]" { + t.Errorf("a key of the label committed while the set waited: err %v, want ErrKeysetLabelTaken naming the label", err) + } + if n := ksActive(t, pool, tid, "ks-lbl-label"); n != 1 { + t.Errorf("%d active key(s) with the label, want the committed one alone", n) + } + var scopes int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM context_tenant_scopes WHERE scope = 'ks-lbl:b'`).Scan(&scopes); err != nil || scopes != 0 { + t.Errorf("the refused set left its scope behind (%d, err %v)", scopes, err) + } +} + +// TestKeysetConcurrentFirstRunsLeaveOneActiveKey: two callers provision the +// same label without replace_label at the same time, round after round (two +// machines running the same first set). Serialised by the tenant lock, one +// set goes through and the other is refused — never two active keys of one +// label. +func TestKeysetConcurrentFirstRunsLeaveOneActiveKey(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + tid := freshTenant(t, ctx, pool, "ks-first") + ksScope(t, pool, "ks-first:a", tid) + if _, err := pool.Exec(ctx, `UPDATE context_tenants SET max_keys = NULL WHERE id = $1::uuid`, tid); err != nil { + t.Fatal(err) + } + for round := range 12 { + label := fmt.Sprintf("ks-first-%02d", round) + var wg sync.WaitGroup + start := make(chan struct{}) + errs := make([]error, 2) + for i := range errs { + wg.Add(1) + go func() { + defer wg.Done() + <-start + _, errs[i] = store.ProvisionKeyset(ctx, pool, tid, nil, []store.KeysetKey{ksKey(label, "ks-first:a", false)}, store.AuditStamp{}) + }() + } + close(start) + wg.Wait() + ok, refused := 0, 0 + for i, err := range errs { + switch { + case err == nil: + ok++ + case errors.Is(err, store.ErrKeysetLabelTaken): + refused++ + default: + t.Fatalf("round %d caller %d: %v", round, i, err) + } + } + if ok != 1 || refused != 1 { + t.Fatalf("round %d: %d set(s) through, %d refused, want 1 and 1", round, ok, refused) + } + if n := ksActive(t, pool, tid, label); n != 1 { + t.Fatalf("round %d: %d active key(s) with the label, want 1", round, n) + } + } +} + // TestKeysetConcurrentReplacementsLeaveOneActiveKey: two callers provision // the same label with replace_label at the same time, round after round. // Serialised by the tenant lock, every round ends with exactly one active key @@ -369,4 +452,37 @@ func TestKeysetSixtyFourCost(t *testing.T) { if err := pool.QueryRow(ctx, `SELECT count(*) FROM context_api_keys WHERE tenant_id = $1::uuid AND active AND label LIKE 'hermes:%'`, tid).Scan(&active); err != nil || active != 64 { t.Errorf("%d active set keys after the second run (err %v), want 64", active, err) } + + // Without replace_label the set's labels are checked against the tenant's + // active keys under the lock: 64 free labels (the check finds nothing), + // then the same 64 again (the check finds all of them and refuses). + fresh := make([]store.KeysetKey, 64) + labels := make([]string, 64) + for i := range fresh { + labels[i] = fmt.Sprintf("hermes:discord:%d:g%02d", 2000+i, i) + fresh[i] = store.KeysetKey{Label: labels[i], HomeScope: scopes[i], AllowedScopes: []string{"ks-cost:main"}, ScopeNarrowing: "required"} + } + t0 := time.Now() + if _, err := store.ProvisionKeyset(ctx, pool, tid, scopes, fresh, store.AuditStamp{}); err != nil { + t.Fatalf("64 free labels without replace_label: %v", err) + } + t.Logf("keyset of 64 scopes and 64 keys without replace_label (label check, no conflict): %v", time.Since(t0)) + t0 = time.Now() + if _, err := store.ProvisionKeyset(ctx, pool, tid, scopes, fresh, store.AuditStamp{}); !errors.Is(err, store.ErrKeysetLabelTaken) { + t.Fatalf("the same 64 labels again: err %v, want ErrKeysetLabelTaken", err) + } + t.Logf("the same set again, refused by the label check (64 labels taken): %v", time.Since(t0)) + rows, err = pool.Query(ctx, `EXPLAIN (ANALYZE, BUFFERS) SELECT array_agg(DISTINCT label ORDER BY label) FROM context_api_keys + WHERE tenant_id = $1::uuid AND active AND label = ANY($2::text[])`, tid, labels) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var line string + if err := rows.Scan(&line); err != nil { + t.Fatal(err) + } + t.Logf("plan of the label check: %s", line) + } + rows.Close() } From 98ea987ea3886f46e90860fe9fb4957caee075a0 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 09:12:11 +0100 Subject: [PATCH 15/15] =?UTF-8?q?fix(auth):=20keyset-provision's=20label?= =?UTF-8?q?=20refusal=20sorts=20bytewise=20and=20is=20pinned=20ahead=20of?= =?UTF-8?q?=20the=20scope=20check=20=E2=80=94=20the=20docs=20scope=20the?= =?UTF-8?q?=20rule=20to=20this=20action=20and=20count=20four=20reads=20of?= =?UTF-8?q?=20the=20tenant's=20keys?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From the review of the label refusal: the labels of the 409 are sorted with COLLATE "C", the same order on every database; a test pins that a taken label is refused before the set's scopes and limits are checked (409, not the 403 of a foreign scope), and that the replace_label refusal of an administrative key's label carries the labels field too. The docs say that api-key-create and a reactivation through api-key-update check no label, and that a set reads the tenant's keys up to four times, deactivated ones included. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/api.md | 2 +- docs/multi-tenancy.md | 2 +- .../ctxd/keyset_provision_c3_more_integration_test.go | 4 ++++ .../ctxd/keyset_provision_label_integration_test.go | 11 +++++++++++ go/internal/store/keyset.go | 7 ++++--- go/internal/store/keyset_integration_test.go | 2 +- 6 files changed, 22 insertions(+), 6 deletions(-) diff --git a/docs/api.md b/docs/api.md index 4807cb9c1..b5a933801 100644 --- a/docs/api.md +++ b/docs/api.md @@ -88,7 +88,7 @@ PostgreSQL stores a NUL character (U+0000) neither in text nor in JSON, so no va - **Backfill memo release (issue #236):** `embed-backfill-release` (tierTenantAdmin) drops regular embed-backfill failure memos (`context_embed_failures` rows with `migration_id` NULL) so the backfill takes their blocks again — after `embed_backfill.max_tokens` was raised, the embed backend moved to a larger context, or a backend outage ended; without it a parked block came back only through a change of its title or content. `data`: exactly one of `block_id` (a UUID) or `class` (`wire` or `oversize`), optional `limit` (the page size, at most and by default `1000`; a larger value is clamped), and `confirm_memos` together with `as_of`; unknown fields, a second selector, another class, a malformed id, a negative number and a `confirm_memos` without `as_of` (or the reverse) are `400`. A `caller_timeout` memo is never taken, not even by `block_id`: it is no park — the background arm takes such a block at once, and with the arm off the query path retries it after its hold —, and deleting it would hand the block back to the requests' `sync_budget` with its attempts restarted. A tenant-admin reaches the memos of blocks in its own tenant's scopes (a scope or a block granted to the tenant is not its own) — another tenant's block and an unknown one answer the same `counted: 0`; a server-admin reaches every memo; a key without an admin role is `403`. A re-embed migration's memos are never touched. **Without `confirm_memos` the call is a dry run** answering `{action, success, dry_run: true, as_of, counted, confirm_memos, held}` (and `held_until` when `held` is above 0); the real call sends `confirm_memos` and `as_of` of that answer, takes only the memos that were there when the dry run counted (a memo written after `as_of` — a released block that was parked again, a new park — is neither counted nor released, so paging ends), counts them again and releases only when the number is unchanged (otherwise `409` with the fresh `counted` and `confirm_memos`, and the `as_of` the call sent), releases at most `limit` of them — the count and the release decide which memos the reader may release at one instant (one transaction, issue #536), so a hold that ends between the two neither counts nor releases its memo in that call — and answers `{action, success, dry_run: false, as_of, counted, released, remaining, confirm_memos, held}` — `remaining` (and `confirm_memos`, the number to confirm for the next page with the same `as_of`) is what is left of them, including a memo another transaction held at that moment, which the release skips instead of waiting for. Two releases of the same memos at once each count what both may take: one of them releases fewer than it counted and answers a `remaining` the other has already released, and its next page answers `409` with the fresh count. Only memos that keep a block out of the pick (`next_attempt_at` in the future) count. **A server-admin's release deletes the memo; a tenant-admin's keeps it and makes it due**, with its attempts and with the time of the release in `first_seen`, so a block the backend still cannot take is parked again on the same row. A tenant-admin releases such an `oversize` memo again (more than one attempt) only once `embed_backfill.release_hold` × 2^(attempts − 2) has passed since that release, at most `embed_backfill.backoff_cap` (defaults 1 h and 24 h; a cap of 0 sets none; the hold must be above 0, V70); until then it is answered in `held`, with the earliest end in `held_until`. Without the hold a tenant-admin releasing its blocks in a loop while they kept not fitting took one turn of the background arm in every round of the tenants for good, where its way back without the action, an edit per block, costs a write each. The first release of every memo is not held, a `wire` memo is not held (its failure holds the tenant in the arm for `embed_backfill.interval`, and its next failure backs off longer, since the attempts stay), and a server-admin's release and a change of the block's title or content (which deletes the memo) start the count again. For a tenant-admin the count and the page of a class read the tenant's own scopes and their pending blocks, so their cost grows with the tenant's pending blocks, not with other tenants' memos. The next backfill pick of each released block embeds it when it fits now and parks it again after one attempt when it does not. CLI: `ctx admin embed-backfill release --class oversize`, then the same with `--confirm N --as-of T`; `--limit N` is sent as given, so a negative one is answered with the `400` (until issue #536 the CLI left a `--limit` of 0 or below out of the request and the server paged by its maximum). Operator notes in [operations](operations.md#embedding-backend-tuning-cpu-llamacpp), paragraph "Backfill failure memo". - **Block counters (issue #266):** `stats`, `guard-stats` and `list-categories` read per-scope counters that triggers on `context_blocks` keep with every write (migration 170), and so do the per-scope block counts of `scope-overview` (issue #271); the answers are unchanged. `guard-stats`' `pending_count` and `dirty_since` are counted on demand since migration 181: the blocks of the caller's read scopes the guard still has to check, and the oldest `updated_at` among them (`null` when none waits) — before 181 a global count of block writes since the last guard run, the same for every key ([operations](operations.md#migration-181-no-block-writer-waits-on-the-guards-state-row-guard-stats-counts-the-waiting-blocks)). `stats-reconcile` (server-admin) recounts and corrects them: `data` `{}` reconciles every scope, `{"scope": "<scope>"}` one; any other field is a `400`. It answers `{action, success, scopes, corrections, corrections_total, pruned, failed}` — `corrections` lists the corrected keys as `{scope, category, is_archived, guard_status, counted, actual}`, at most the first 1 000 of the pass, and `corrections_total` counts all of them (every one is corrected and logged; issue #271), `pruned` the folded counter rows at 0 it removed, `failed` the scopes whose reconcile failed (the pass goes on with the others; then `success` is `false` and the status `500`). The scheduler runs the same pass on `scheduler.block_count_reconcile_interval` — see [operations](operations.md#migration-170-block-counters-behind-stats-guard-stats-and-list-categories). - **Keys/clients:** `api-key-create` requires `home_scope`; key + MCP-client management and mutating `dream-mode` require an **admin key** since migration 052 (see [security](security.md#admin-tier)). `api-key-create`/`api-key-update` accept optional `write_scopes` (078, E4b) — explicit per-key write scopes that must be ⊆ `allowed_scopes ∪ {home_scope}` (else 400); the effective block-write gate and its double enforcement are in [multi-tenancy](multi-tenancy.md#per-key-write-scopes-e4b-migration-078). They also accept `scope_narrowing` (migration 198): `required` makes the key answer every request without a [narrowing](#scope-narrowing-per-request) with `403 scope_narrowing_required`, `GET /api/whoami` excepted; `optional` (every existing key, the default) keeps today's behaviour; any other value is 400. Both answers carry the value; `api-key-list` lists it. Per-tenant scoping of the `api-key-*` actions and the tenant lifecycle (`tenant-*`, `tenant-grant-*`, `scope-*`, `tenant-limit-set`, `tenant-usage-get`, `tenant-quota-*`, `block-grant-*`) are in [multi-tenancy](multi-tenancy.md). -- **Key sets:** `keyset-provision` (tenant-admin, in the caller's own tenant; a server-admin may name `tenant_id`, anyone else naming it gets 403) creates the scopes and the keys of one set — say the groups of one community — in one transaction: either the whole set exists afterwards or nothing of it does. `data`: `scopes` (at most 64 bare scope names, scope-create's rule; the server puts the tenant's `<slug>:` in front; a scope the tenant already has is kept) and `keys` (at most 64, each `{label, home_scope, allowed_scopes, write_scopes, scope_narrowing, replace_label}`; a key's scope is a bare name or a full `<slug>:<name>` and must be the tenant's own or one the set creates; a name without `:` always gets the prefix, so scopes outside that form — the default tenant's `private`, `work` and `shared` — cannot be named). The answer lists `scopes` as `{scope, created}` and `keys` as `{id, label, home_scope, allowed_scopes, write_scopes, scope_narrowing, api_key}`, both in the order of the call; each `api_key` (the plaintext) is in this answer only. Every key is a `member` key with exactly the scopes it names (no implicit `shared`, also in the default tenant) and its own principal; `scope_narrowing` left out is `required` — the set's keys answer nothing without a [narrowing](#scope-narrowing-per-request) but `GET /api/whoami`, and a key without that requirement is minted only when the call names `optional` (unlike `api-key-create`, whose default stays `optional`). `replace_label: true` deactivates the tenant's active keys with that label in the same transaction, before `max_keys` is counted, so a repeated call leaves one active key per label; on a label an owner, admin or server-admin key carries it refuses the set with `409`. Without `replace_label` a key may not take a label an active key of the tenant already carries: the whole set is refused with `409` and nothing of it is created, no scope either — so two runs of the same set (two machines, a repeated first run) never leave two active keys of one label; a deactivated key of the label does not count. Both label refusals answer `{"success": false, "error": "…", "labels": [<the set's labels concerned, sorted>]}` and name no key value. Refusals: a scope of another tenant, or one the tenant neither has nor creates, `403`; `write_scopes ⊄ allowed_scopes ∪ {home_scope}`, a malformed scope name, an unknown field, a label missing or named twice in the set, a value the column cannot hold, a `scope_narrowing` other than `optional`/`required`, more than 64 scopes or keys, `400`; past `max_scopes` or `max_keys`, `429` with `limit`, `count` (the tenant's count before the set; for keys after its replacements) and `requested`; a tenant being deleted, or a scope registered meanwhile past the tenant lock (only a hand edit can), `409`; a top-level `id`, `400` (the target tenant is `data.tenant_id`). A narrowed request never reaches it ([above](#scope-narrowing-per-request)). How it serialises with the other key and scope writes: [multi-tenancy](multi-tenancy.md#key-sets-keyset-provision). +- **Key sets:** `keyset-provision` (tenant-admin, in the caller's own tenant; a server-admin may name `tenant_id`, anyone else naming it gets 403) creates the scopes and the keys of one set — say the groups of one community — in one transaction: either the whole set exists afterwards or nothing of it does. `data`: `scopes` (at most 64 bare scope names, scope-create's rule; the server puts the tenant's `<slug>:` in front; a scope the tenant already has is kept) and `keys` (at most 64, each `{label, home_scope, allowed_scopes, write_scopes, scope_narrowing, replace_label}`; a key's scope is a bare name or a full `<slug>:<name>` and must be the tenant's own or one the set creates; a name without `:` always gets the prefix, so scopes outside that form — the default tenant's `private`, `work` and `shared` — cannot be named). The answer lists `scopes` as `{scope, created}` and `keys` as `{id, label, home_scope, allowed_scopes, write_scopes, scope_narrowing, api_key}`, both in the order of the call; each `api_key` (the plaintext) is in this answer only. Every key is a `member` key with exactly the scopes it names (no implicit `shared`, also in the default tenant) and its own principal; `scope_narrowing` left out is `required` — the set's keys answer nothing without a [narrowing](#scope-narrowing-per-request) but `GET /api/whoami`, and a key without that requirement is minted only when the call names `optional` (unlike `api-key-create`, whose default stays `optional`). `replace_label: true` deactivates the tenant's active keys with that label in the same transaction, before `max_keys` is counted, so a repeated call leaves one active key per label; on a label an owner, admin or server-admin key carries it refuses the set with `409`. Without `replace_label` a key may not take a label an active key of the tenant already carries: the whole set is refused with `409` and nothing of it is created, no scope either — so two runs of the same set (two machines, a repeated first run) never leave two active keys of one label; a deactivated key of the label does not count, and the label is checked before the set's scopes and limits. The rule is this action's: `api-key-create` and a reactivation through `api-key-update` check no label. Both label refusals answer `{"success": false, "error": "…", "labels": [<the set's labels concerned, sorted>]}` and name no key value. Refusals: a scope of another tenant, or one the tenant neither has nor creates, `403`; `write_scopes ⊄ allowed_scopes ∪ {home_scope}`, a malformed scope name, an unknown field, a label missing or named twice in the set, a value the column cannot hold, a `scope_narrowing` other than `optional`/`required`, more than 64 scopes or keys, `400`; past `max_scopes` or `max_keys`, `429` with `limit`, `count` (the tenant's count before the set; for keys after its replacements) and `requested`; a tenant being deleted, or a scope registered meanwhile past the tenant lock (only a hand edit can), `409`; a top-level `id`, `400` (the target tenant is `data.tenant_id`). A narrowed request never reaches it ([above](#scope-narrowing-per-request)). How it serialises with the other key and scope writes: [multi-tenancy](multi-tenancy.md#key-sets-keyset-provision). - **Block-type registry:** `type-list`/`type-get` are open reads; `type-create`/`type-update`/`type-delete` are the **operator transport** (server-admin, `_global` namespace) of the same store logic the REST `PUT/DELETE /api/types/{name}` surface uses — kept functional for MCP/CLI consumers, not superseded (see [Block-type registry](#block-type-registry)). `manage update` accepts a registry-validated `type` field; `list-meta` accepts the `types`/`types_exclude` filters. - **Issue corpus:** `issue-create`/`issue-update`/`issue-get`/`issue-list`/`issue-comment-create`/`issue-link-create`/`issue-link-delete` are the **operator transport** (all tierOpen; isolation is store-layer scope filtering, not an admin tier) over the same store issue logic the REST `/api/project` issue surface (W6/W7) uses — kept reachable for MCP/CLI operators, not the primary UI surface (see [Issue corpus](#issue-corpus)). - **Backend pool:** `backend-list`/`create`/`update`/`delete`/`test` — see [Backend pool](#backend-pool). diff --git a/docs/multi-tenancy.md b/docs/multi-tenancy.md index 1fc182912..24f531e5f 100644 --- a/docs/multi-tenancy.md +++ b/docs/multi-tenancy.md @@ -147,7 +147,7 @@ The `whoami` endpoint carries this on the wire: alongside the server-global `adm ### Key sets (`keyset-provision`) -`keyset-provision` is `scope-create` plus `api-key-create` for a whole set — the scopes and keys of the groups of one community, for instance — in **one** transaction ([api](api.md#manage-actions) has the wire form). It knows no community, bot or group: labels, scopes and rights come from the call. `store.ProvisionKeyset` takes the tenant row lock first (`FOR UPDATE` — the row lock `scope-create` and `api-key-create` take first and `api-key-update`/`api-key-delete` take before their decisive read of the key, and which `tenant-limit-set` and the tenant delete's mark, both an `UPDATE` of the row, wait for) and reads everything it decides on under it, each in a statement of its own: the tenant's status and both limits from the locked row, the active keys that already carry a label of the set, the owners of every scope the set names, the scope count, the roles of the keys `replace_label` would deactivate, the active key count after those replacements. A concurrent `tenant-limit-set`, `scope-create` or role change of the same tenant is therefore seen, not raced, and two sets that replace the same label one after the other leave one active key of it. Order inside the lock: the labels first — a key without `replace_label` whose label an active key of the tenant already carries refuses the whole set (409, the labels named) before anything is written, so two runs of one set never leave two active keys of one label (a deactivated key does not count; the check reads the tenant's active keys, there is no index on the label — measured 3.9 ms at 20 000 keys); then scopes (refused when one belongs to another tenant, or when a key names a scope the tenant neither has nor creates — foreign and unknown answer alike, and a key never names a scope it could read only once someone registers it; the new scopes counted against `max_scopes`, their groups of migration 176 locked in sorted order — the order the scope trigger keeps, which a row-by-row assignment of several scopes would break — and then one `INSERT`), then `replace_label` (member keys only — a label an owner, admin or server-admin key carries refuses the set, so it can never take a key past the owner rules of `api-key-delete`), then `max_keys` (active keys after the replacements), then each key through `insertApiKeyTx`, the one INSERT path of a key: role `member`, `scope_narrowing` `required` unless the call names `optional` ([required narrowing](#required-narrowing-migration-198); as member keys they never touch the owner rules that count `required` on an owner key as taking its administration), a fresh principal, exactly the scopes named, the audit row (`create`, or `revoke` for a replaced key) attributed to the calling key `via=api`. A failure anywhere rolls the set back. A tenant whose delete has begun takes no set (409), the rule `scope-create` follows since issue #555. When the set created a scope the handler refreshes the quota accountant, as `scope-create` does, so a key homed there is under the tenant's quota from its first call. Cost: one statement per step plus one INSERT per key while the tenant lock is held — measured 41 ms for 64 new scopes and 64 keys and 34 ms for the same set again with 64 replacements, in a tenant holding 20 000 other keys and 2 000 other scopes (`TestKeysetSixtyFourCost`); the replacement, its check and the key count read the tenant's keys (there is no index on the label; a tenant with many keys pays a scan of its own keys, three times per set). Until the commit, other scope and key writes of the same tenant wait, so do inserts that reference the tenant row, block writes of never-embedded types into the tenant's scopes when the set creates a scope (they take the tenant's group of migration 176, which the scope trigger then holds), and the authentication of a key the set replaces (its row is locked by the replacement); the authentication of every other key does not wait (it takes no tenant lock). +`keyset-provision` is `scope-create` plus `api-key-create` for a whole set — the scopes and keys of the groups of one community, for instance — in **one** transaction ([api](api.md#manage-actions) has the wire form). It knows no community, bot or group: labels, scopes and rights come from the call. `store.ProvisionKeyset` takes the tenant row lock first (`FOR UPDATE` — the row lock `scope-create` and `api-key-create` take first and `api-key-update`/`api-key-delete` take before their decisive read of the key, and which `tenant-limit-set` and the tenant delete's mark, both an `UPDATE` of the row, wait for) and reads everything it decides on under it, each in a statement of its own: the tenant's status and both limits from the locked row, the active keys that already carry a label of the set, the owners of every scope the set names, the scope count, the roles of the keys `replace_label` would deactivate, the active key count after those replacements. A concurrent `tenant-limit-set`, `scope-create` or role change of the same tenant is therefore seen, not raced, and two sets that replace the same label one after the other leave one active key of it. Order inside the lock: the labels first — a key without `replace_label` whose label an active key of the tenant already carries refuses the whole set (409, the labels named) before anything is written, so two runs of one set never leave two active keys of one label (a deactivated key does not count; the check reads the tenant's active keys, there is no index on the label — measured 3.9 ms at 20 000 keys); then scopes (refused when one belongs to another tenant, or when a key names a scope the tenant neither has nor creates — foreign and unknown answer alike, and a key never names a scope it could read only once someone registers it; the new scopes counted against `max_scopes`, their groups of migration 176 locked in sorted order — the order the scope trigger keeps, which a row-by-row assignment of several scopes would break — and then one `INSERT`), then `replace_label` (member keys only — a label an owner, admin or server-admin key carries refuses the set, so it can never take a key past the owner rules of `api-key-delete`), then `max_keys` (active keys after the replacements), then each key through `insertApiKeyTx`, the one INSERT path of a key: role `member`, `scope_narrowing` `required` unless the call names `optional` ([required narrowing](#required-narrowing-migration-198); as member keys they never touch the owner rules that count `required` on an owner key as taking its administration), a fresh principal, exactly the scopes named, the audit row (`create`, or `revoke` for a replaced key) attributed to the calling key `via=api`. A failure anywhere rolls the set back. A tenant whose delete has begun takes no set (409), the rule `scope-create` follows since issue #555. When the set created a scope the handler refreshes the quota accountant, as `scope-create` does, so a key homed there is under the tenant's quota from its first call. Cost: one statement per step plus one INSERT per key while the tenant lock is held — measured 41 ms for 64 new scopes and 64 keys and 34 ms for the same set again with 64 replacements, in a tenant holding 20 000 other keys and 2 000 other scopes (`TestKeysetSixtyFourCost`); the label check, the replacement's check, the replacement and the key count each read the tenant's keys, deactivated ones included (there is no index on the label; a tenant with many keys pays a scan of its own keys up to four times per set). Until the commit, other scope and key writes of the same tenant wait, so do inserts that reference the tenant row, block writes of never-embedded types into the tenant's scopes when the set creates a scope (they take the tenant's group of migration 176, which the scope trigger then holds), and the authentication of a key the set replaces (its row is locked by the replacement); the authentication of every other key does not wait (it takes no tenant lock). ## Per-tenant settings & secrets diff --git a/go/cmd/ctxd/keyset_provision_c3_more_integration_test.go b/go/cmd/ctxd/keyset_provision_c3_more_integration_test.go index 1ae7132e7..ef4c741ae 100644 --- a/go/cmd/ctxd/keyset_provision_c3_more_integration_test.go +++ b/go/cmd/ctxd/keyset_provision_c3_more_integration_test.go @@ -55,6 +55,10 @@ func TestC3ReplaceLabelNeverRevokesAnAdministrativeKey(t *testing.T) { if r.status != http.StatusConflict { t.Errorf("%s: HTTP %d %s, want 409", tc.what, r.status, r.raw) } + // The same form as the refusal of a taken label: the labels named. + if got := fmt.Sprint(r.body["labels"]); got != "["+tc.label+"]" { + t.Errorf("%s: the refusal names labels %s, want [%s]", tc.what, got, tc.label) + } w.wantUnchanged(t, tc.what, scopes, labels) } for key, name := range map[string]string{w.owner: "owner", tadmin: "admin"} { diff --git a/go/cmd/ctxd/keyset_provision_label_integration_test.go b/go/cmd/ctxd/keyset_provision_label_integration_test.go index 2ce2aac0c..d8ccc6e82 100644 --- a/go/cmd/ctxd/keyset_provision_label_integration_test.go +++ b/go/cmd/ctxd/keyset_provision_label_integration_test.go @@ -50,6 +50,17 @@ func TestC3ALabelAnActiveKeyCarriesRefusesTheSet(t *testing.T) { } w.wantUnchanged(t, "after the second refused set", scopes, labels) + // The label is checked before the set's scopes and limits: a set that + // would also fail on another tenant's scope gets the label's 409, not the + // scope's 403. + r = w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3l", "display_name": "C3 other"}}).must(t, "second tenant") + foreign, _ := r.body["scope"].(string) + r = w.provision(t, w.owner, nil, c3Key(label, "members", []string{foreign}, nil, "required")) + if got := fmt.Sprint(r.body["labels"]); r.status != http.StatusConflict || got != "["+label+"]" { + t.Errorf("a taken label and a foreign scope: HTTP %d labels %s, want 409 and [%s] (the label first)", r.status, got, label) + } + w.wantUnchanged(t, "after the label-and-scope refusal", scopes, labels) + // A deactivated key of the label does not count: after a revoke the set // goes through without replace_label (the rerun after a rotation). w.manage(t, w.owner, map[string]any{"action": "api-key-delete", "data": map[string]any{"id": ids[label]}}).must(t, "revoke the first key") diff --git a/go/internal/store/keyset.go b/go/internal/store/keyset.go index a8b412529..a07a0d9e4 100644 --- a/go/internal/store/keyset.go +++ b/go/internal/store/keyset.go @@ -335,9 +335,10 @@ func keysetScopesTx(ctx context.Context, tx pgx.Tx, tenantID string, scopes []st return listed, nil } -// keysetLabelsTakenSQL lists, sorted, the labels of a set that an active key -// of the tenant already carries. -const keysetLabelsTakenSQL = `SELECT coalesce(array_agg(DISTINCT label::text ORDER BY label::text), '{}'::text[]) +// keysetLabelsTakenSQL lists, sorted bytewise (COLLATE "C", the same order on +// every database), the labels of a set that an active key of the tenant +// already carries. +const keysetLabelsTakenSQL = `SELECT coalesce(array_agg(DISTINCT label::text COLLATE "C" ORDER BY label::text COLLATE "C"), '{}'::text[]) FROM context_api_keys WHERE tenant_id = $1::uuid AND active AND label = ANY($2::text[])` diff --git a/go/internal/store/keyset_integration_test.go b/go/internal/store/keyset_integration_test.go index 3d2ed8478..d0e187ca0 100644 --- a/go/internal/store/keyset_integration_test.go +++ b/go/internal/store/keyset_integration_test.go @@ -472,7 +472,7 @@ func TestKeysetSixtyFourCost(t *testing.T) { t.Fatalf("the same 64 labels again: err %v, want ErrKeysetLabelTaken", err) } t.Logf("the same set again, refused by the label check (64 labels taken): %v", time.Since(t0)) - rows, err = pool.Query(ctx, `EXPLAIN (ANALYZE, BUFFERS) SELECT array_agg(DISTINCT label ORDER BY label) FROM context_api_keys + rows, err = pool.Query(ctx, `EXPLAIN (ANALYZE, BUFFERS) SELECT array_agg(DISTINCT label::text COLLATE "C" ORDER BY label::text COLLATE "C") FROM context_api_keys WHERE tenant_id = $1::uuid AND active AND label = ANY($2::text[])`, tid, labels) if err != nil { t.Fatal(err)