Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(server): authenticate REST, MCP HTTP and webhooks to a principal with repo and tool scope (#3725)
Raghav Chamadiya6388c8257b9e
diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.mdindex b751b1b9b..22be2028e 100644--- a/docs/reference/API_REFERENCE.md+++ b/docs/reference/API_REFERENCE.md@@ -141,7 +141,7 @@ Authorization: Bearer <your-key-value>```The comparison is constant-time and the prefix must be exactly `Bearer ` with a-single space (`deps.py`, `verify_api_key` / `bearer_is_valid`; verified: a bare+single space (`auth.py`, `LocalAuthenticator`; verified: a barekey and a double space are both rejected).The key is read once, at import (`deps.py` line 26). Changing the environment of@@ -149,6 +149,19 @@ a running server has no effect; restart it. The webhook secrets are theexception and are read per request (`routers/webhooks.py`), deliberately, so asetting change is picked up without a restart.+Scoped tokens are an optional second credential: list them in+`~/.repowise/tokens.yaml` (or the file named by `REPOWISE_TOKENS_FILE`) as+`{id, sha256, repos?, tools?, expires_at?}` entries, where `sha256` is the hex+digest of the token, `repos`/`tools` narrow what it reaches by repository id or+name and MCP tool name, and `expires_at` is an ISO 8601 time. A token with+`tools` is refused on every REST route except chat, which runs only the tools+in its scope. Every check returns a `Principal`, and the same check guards the+MCP streamable HTTP and SSE transports, which answer a missing bearer with+`401` and `WWW-Authenticate: Bearer resource_metadata="..."` pointing at an RFC+9728 document under `/.well-known/oauth-protected-resource` (set+`REPOWISE_PUBLIC_URL` when serving behind a proxy). With no key and no tokens+file, every surface behaves exactly as described below.+### 2.2 What happens when the header is absent| Server state | Caller | Result |diff --git a/packages/server/src/repowise/server/auth.py b/packages/server/src/repowise/server/auth.pynew file mode 100644index 000000000..80461d53c--- /dev/null+++ b/packages/server/src/repowise/server/auth.py@@ -0,0 +1,323 @@+"""Who is calling, and what they may reach.++``verify_api_key`` (REST), the MCP HTTP transports and the webhooks all ask the+same :class:`Authenticator` for a :class:`Principal`, and the same+:class:`Authorizer` whether that principal may reach a repository or a tool.++The default authenticator is the shared ``REPOWISE_API_KEY`` exactly as before,+plus an optional local scoped-tokens file (``~/.repowise/tokens.yaml``, or the+path in ``REPOWISE_TOKENS_FILE``). With neither configured, loopback callers are+served without a credential and everyone else is refused, as before.++Both are named seams (``authenticator``, ``authorizer``) with ``local`` as the+default. A plugin registers its own implementation from the ``repowise.plugins``+entry point and selects it with ``default=True`` or+``REPOWISE_SEAM_AUTHENTICATOR`` / ``REPOWISE_SEAM_AUTHORIZER``.+"""++from __future__ import annotations++import hashlib+import hmac+import logging+import os+from collections.abc import Iterable+from contextvars import ContextVar+from dataclasses import dataclass+from datetime import UTC, datetime+from pathlib import Path+from typing import Any, Protocol, runtime_checkable++from fastapi import HTTPException, Request++from repowise.core.registry.plugins import SeamRegistry++logger = logging.getLogger(__name__)++TOKENS_FILE_ENV = "REPOWISE_TOKENS_FILE"+#: Declared by a REST route that checks tool scope on each tool it runs (chat);+#: every other route refuses a tool-scoped principal.+PER_CALL_TOOL_SCOPE = "tools:per-call"+++@dataclass(frozen=True)+class Principal:+ """An authenticated caller. ``None`` scopes mean unrestricted."""++ id: str+ kind: str # "local" | "shared-key" | "token" | "webhook", or a plugin's own+ repo_scope: frozenset[str] | None = None+ tool_scope: frozenset[str] | None = None+++#: A loopback caller on a server with no credential configured.+LOCAL_PRINCIPAL = Principal(id="local", kind="local")+#: A caller holding ``REPOWISE_API_KEY``.+SHARED_KEY_PRINCIPAL = Principal(id="shared-key", kind="shared-key")++#: The principal a tool is running for (MCP HTTP and chat), so a tool that+#: lists repos can filter to its scope. None outside an authenticated call.+current_principal: ContextVar[Principal | None] = ContextVar("current_principal", default=None)+++@runtime_checkable+class Authenticator(Protocol):+ """Turns a request or a bearer token into a :class:`Principal`."""++ #: OAuth authorization servers that issue tokens for this server, published+ #: in the RFC 9728 metadata. Empty for static keys.+ authorization_servers: tuple[str, ...]++ def configured(self) -> bool:+ """True when a credential is required (otherwise loopback is open)."""+ ...++ async def verify_token(self, token: str) -> Principal | None:+ """The principal a bearer token stands for, or None. Mirrors the MCP SDK+ ``TokenVerifier.verify_token``."""+ ...++ async def authenticate(self, request: Request) -> Principal:+ """The principal for ``request``; raises ``HTTPException`` 401/403."""+ ...+++@runtime_checkable+class Authorizer(Protocol):+ """Decides what an authenticated principal may reach."""++ def can_access_repo(self, principal: Principal, identifiers: Iterable[str | None]) -> bool:+ """True when any of ``identifiers`` (id, name, alias of one repo) is in scope."""+ ...++ def can_use_tool(self, principal: Principal, tool: str) -> bool: ...+++# ---------------------------------------------------------------------------+# Scoped tokens file+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class ScopedToken:+ id: str+ sha256: str+ repos: frozenset[str] | None+ tools: frozenset[str] | None+ expires_at: datetime | None = None+++_TOKEN_KEYS = frozenset({"id", "sha256", "repos", "tools", "expires_at"})+++def tokens_file_path() -> Path:+ override = os.environ.get(TOKENS_FILE_ENV)+ return Path(override) if override else Path.home() / ".repowise" / "tokens.yaml"+++def hash_token(token: str) -> str:+ """The digest stored in the tokens file. Tokens are random, so a plain+ SHA-256 is enough; no slow KDF is needed."""+ return hashlib.sha256(token.encode("utf-8")).hexdigest()+++_cache: tuple[tuple[str, int, int], tuple[ScopedToken, ...]] | None = None+++def _optional_set(entry: dict[str, Any], key: str) -> frozenset[str] | None:+ value = entry.get(key)+ if value is None:+ return None+ if not isinstance(value, list) or not all(isinstance(v, str) for v in value):+ raise ValueError(f"'{key}' must be a list of strings")+ return frozenset(value)+++def _parse_tokens(raw: Any) -> tuple[ScopedToken, ...]:+ if not isinstance(raw, dict) or not isinstance(raw.get("tokens"), list):+ raise ValueError("expected a top-level 'tokens' list")+ tokens = []+ for entry in raw["tokens"]:+ if not isinstance(entry, dict):+ raise ValueError("each token must be a mapping")+ token_id, digest = entry.get("id"), entry.get("sha256")+ if not isinstance(token_id, str) or not token_id:+ raise ValueError("each token needs an 'id'")+ unknown = set(entry) - _TOKEN_KEYS+ if unknown:+ raise ValueError(f"token '{token_id}' has unknown keys: {sorted(unknown)}")+ if not isinstance(digest, str) or len(digest) != 64:+ raise ValueError(f"token '{token_id}' needs a 64-character 'sha256'")+ tokens.append(+ ScopedToken(+ id=token_id,+ sha256=digest.lower(),+ repos=_optional_set(entry, "repos"),+ tools=_optional_set(entry, "tools"),+ expires_at=_expiry(token_id, entry.get("expires_at")),+ )+ )+ return tuple(tokens)+++def _expiry(token_id: str, value: Any) -> datetime | None:+ """ISO 8601; a time without an offset is read as UTC."""+ if value is None:+ return None+ if isinstance(value, datetime): # YAML parses unquoted timestamps itself+ parsed = value+ elif isinstance(value, str):+ try:+ parsed = datetime.fromisoformat(value)+ except ValueError as exc:+ raise ValueError(f"token '{token_id}' has an invalid 'expires_at'") from exc+ else:+ raise ValueError(f"token '{token_id}' has an invalid 'expires_at'")+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)+++def _tokens_file_present(path: Path) -> bool:+ """True when the file exists or cannot be checked (fail closed)."""+ try:+ path.stat()+ except (FileNotFoundError, NotADirectoryError):+ return False+ except OSError:+ return True+ return True+++def load_scoped_tokens(path: Path | None = None) -> tuple[ScopedToken, ...]:+ """Tokens from the file, re-read when it changes. Raises ``ValueError`` on+ a malformed file so the caller can fail closed."""+ global _cache+ path = path or tokens_file_path()+ try:+ stat = path.stat()+ except (FileNotFoundError, NotADirectoryError):+ return ()+ except OSError as exc:+ raise ValueError(str(exc)) from exc+ key = (str(path), stat.st_mtime_ns, stat.st_size)+ if _cache is not None and _cache[0] == key:+ return _cache[1]+ import yaml++ try:+ tokens = _parse_tokens(yaml.safe_load(path.read_text(encoding="utf-8")))+ except (OSError, yaml.YAMLError) as exc:+ raise ValueError(str(exc)) from exc+ _cache = (key, tokens)+ return tokens+++# ---------------------------------------------------------------------------+# Defaults+# ---------------------------------------------------------------------------+++def _shared_key() -> str | None:+ # Read through deps so the import-time capture (and tests patching it) stay+ # the single source.+ from repowise.server import deps++ return deps._API_KEY+++class LocalAuthenticator:+ """The shared ``REPOWISE_API_KEY`` plus the optional scoped-tokens file."""++ authorization_servers: tuple[str, ...] = ()++ def configured(self) -> bool:+ return _shared_key() is not None or _tokens_file_present(tokens_file_path())++ async def verify_token(self, token: str) -> Principal | None:+ key = _shared_key()+ # Bytes, so a non-ASCII bearer is a mismatch rather than a TypeError.+ if key is not None and hmac.compare_digest(token.encode("utf-8"), key.encode("utf-8")):+ return SHARED_KEY_PRINCIPAL+ try:+ tokens = load_scoped_tokens()+ except ValueError as exc:+ # Fail closed: a broken file grants nothing, the shared key still works.+ logger.error("Ignoring unreadable tokens file %s: %s", tokens_file_path(), exc)+ return None+ if not tokens:+ return None+ digest = hash_token(token)+ for entry in tokens:+ if hmac.compare_digest(digest, entry.sha256):+ if entry.expires_at is not None and entry.expires_at <= datetime.now(UTC):+ return None+ return Principal(+ id=f"token:{entry.id}",+ kind="token",+ repo_scope=entry.repos,+ tool_scope=entry.tools,+ )+ return None++ async def authenticate(self, request: Request) -> Principal:+ from repowise.server.deps import client_is_local++ if not self.configured():+ if not client_is_local(request):+ raise HTTPException(+ status_code=403,+ detail="Server is reachable from the network but REPOWISE_API_KEY "+ "is not set. Set REPOWISE_API_KEY or bind to 127.0.0.1.",+ )+ return LOCAL_PRINCIPAL+ auth = request.headers.get("Authorization")+ if not auth or not auth.startswith("Bearer "):+ raise HTTPException(status_code=401, detail="Missing API key")+ principal = await self.verify_token(auth[7:])+ if principal is None:+ raise HTTPException(status_code=401, detail="Invalid API key")+ return principal+++class ScopeAuthorizer:+ """Checks a principal's own repo and tool scopes."""++ def can_access_repo(self, principal: Principal, identifiers: Iterable[str | None]) -> bool:+ if principal.repo_scope is None:+ return True+ return any(i in principal.repo_scope for i in identifiers if i)++ def can_use_tool(self, principal: Principal, tool: str) -> bool:+ return principal.tool_scope is None or tool in principal.tool_scope+++authenticators: SeamRegistry[Authenticator] = SeamRegistry("authenticator")+authorizers: SeamRegistry[Authorizer] = SeamRegistry("authorizer")+_DEFAULT_AUTHENTICATOR = LocalAuthenticator()+_DEFAULT_AUTHORIZER = ScopeAuthorizer()+authenticators.register("local", _DEFAULT_AUTHENTICATOR, default=True)+authorizers.register("local", _DEFAULT_AUTHORIZER, default=True)+++def get_authenticator() -> Authenticator:+ return authenticators.get()+++def get_authorizer() -> Authorizer:+ return authorizers.get()+++def set_authenticator(authenticator: Authenticator | None) -> None:+ """Select ``authenticator`` in-process (tests, embedders); ``None`` restores+ the local default."""+ if authenticator is None:+ authenticators.register("local", _DEFAULT_AUTHENTICATOR, default=True)+ else:+ authenticators.register("override", authenticator, default=True)+++def set_authorizer(authorizer: Authorizer | None) -> None:+ """Select ``authorizer`` in-process; ``None`` restores the local default."""+ if authorizer is None:+ authorizers.register("local", _DEFAULT_AUTHORIZER, default=True)+ else:+ authorizers.register("override", authorizer, default=True)diff --git a/packages/server/src/repowise/server/chat_tools.py b/packages/server/src/repowise/server/chat_tools.pyindex 5ae939417..678b20bc2 100644--- a/packages/server/src/repowise/server/chat_tools.py+++ b/packages/server/src/repowise/server/chat_tools.py@@ -8,6 +8,7 @@ from dataclasses import dataclassfrom typing import Anyfrom repowise.core.registry import ToolEntry+from repowise.server.auth import Principal, current_principal, get_authorizerfrom repowise.server.mcp_server._tool_selection import (get_registered_tool,selected_tool_entries,@@ -25,10 +26,16 @@ class ChatToolContract:parameters: dict[str, Any]-def get_tool_catalog(repo_path: str | None) -> list[ChatToolContract]:- """Return the repository's configured MCP surface with generated schemas."""+def get_tool_catalog(+ repo_path: str | None, principal: Principal | None = None+) -> list[ChatToolContract]:+ """Return the repository's configured MCP surface with generated schemas,+ narrowed to ``principal``'s tool scope when one is given."""catalog: list[ChatToolContract] = []+ authorizer = get_authorizer()for entry in selected_tool_entries(repo_path):+ if principal is not None and not authorizer.can_use_tool(principal, entry.name):+ continueregistered = get_registered_tool(entry.name)if registered is None:logger.error("Registered MCP entry has no FastMCP contract: %s", entry.name)@@ -43,7 +50,9 @@ def get_tool_catalog(repo_path: str | None) -> list[ChatToolContract]:return catalog-def get_tool_schemas_for_llm(repo_path: str | None) -> list[dict[str, Any]]:+def get_tool_schemas_for_llm(+ repo_path: str | None, principal: Principal | None = None+) -> list[dict[str, Any]]:"""Return OpenAI-format definitions from FastMCP's canonical schemas."""return [{@@ -54,7 +63,7 @@ def get_tool_schemas_for_llm(repo_path: str | None) -> list[dict[str, Any]]:"parameters": tool.parameters,},}- for tool in get_tool_catalog(repo_path)+ for tool in get_tool_catalog(repo_path, principal)]@@ -70,9 +79,20 @@ def _make_json_serializable(obj: Any) -> Any:return str(obj)-def _scope_repo_arg(entry: ToolEntry, arguments: dict[str, Any], repo: str | None) -> None:- """Backstop a model-supplied repo value with the active workspace alias."""- if not repo or "repo" not in inspect.signature(entry.fn).parameters:+def _scope_repo_arg(+ entry: ToolEntry, arguments: dict[str, Any], repo: str | None, pinned: str | None = None+) -> None:+ """Backstop a model-supplied repo value with the active workspace alias.++ ``pinned`` (set for repo-restricted principals) always wins, so neither+ ``"all"`` nor another alias can widen the call.+ """+ if "repo" not in inspect.signature(entry.fn).parameters:+ return+ if pinned is not None:+ arguments["repo"] = pinned+ return+ if not repo:returnimport repowise.server.mcp_server as mcp_mod@@ -93,8 +113,21 @@ async def execute_entry(*,repo: str | None = None,confirmed: bool = False,+ principal: Principal | None = None,+ repo_id: str | None = None,) -> dict[str, Any]:- """Execute one selected registry entry under its safety contract."""+ """Execute one selected registry entry under its safety contract.++ With a ``principal``, the tool must be in its scope, and a repo-restricted+ principal is pinned to ``repo`` (or ``repo_id`` outside a workspace).+ """+ if principal is not None and not get_authorizer().can_use_tool(principal, entry.name):+ return {+ "error": f"Tool is outside this credential's scope: {entry.name}",+ "error_code": "tool_not_in_scope",+ }+ restricted = principal is not None and principal.repo_scope is not None+ pinned = (repo or repo_id) if restricted else Noneif entry.safety == "mutating" and not confirmed:return {"error": f"{entry.name} requires explicit confirmation before it can run",@@ -103,13 +136,16 @@ async def execute_entry("tool_name": entry.name,}+ reset = current_principal.set(principal)try:scoped_arguments = dict(arguments)- _scope_repo_arg(entry, scoped_arguments, repo)+ _scope_repo_arg(entry, scoped_arguments, repo, pinned)return _make_json_serializable(await entry.fn(**scoped_arguments))except Exception as exc:logger.exception("Tool execution failed: %s", entry.name)return {"error": f"{type(exc).__name__}: {exc}", "error_code": "tool_failed"}+ finally:+ current_principal.reset(reset)async def execute_tool(@@ -119,6 +155,8 @@ async def execute_tool(repo_path: str | None = None,repo: str | None = None,confirmed: bool = False,+ principal: Principal | None = None,+ repo_id: str | None = None,) -> dict[str, Any]:"""Execute a tool only when it belongs to the configured MCP surface."""entry = _catalog_entry(name, repo_path)@@ -127,7 +165,9 @@ async def execute_tool("error": f"Tool is not enabled for this repository: {name}","error_code": "tool_not_enabled",}- return await execute_entry(entry, arguments, repo=repo, confirmed=confirmed)+ return await execute_entry(+ entry, arguments, repo=repo, confirmed=confirmed, principal=principal, repo_id=repo_id+ )def _catalog_entry(tool_name: str, repo_path: str | None) -> ToolEntry | None:diff --git a/packages/server/src/repowise/server/deps.py b/packages/server/src/repowise/server/deps.pyindex 24111b808..5800d4d90 100644--- a/packages/server/src/repowise/server/deps.py+++ b/packages/server/src/repowise/server/deps.py@@ -4,22 +4,27 @@ Provides Depends() callables for:- Database sessions (async, auto-commit/rollback)- Vector store access- Full-text search access-- Optional API key authentication+- API key authentication, returning the caller's ``Principal``"""from __future__ import annotations-import hmacimport ipaddressimport loggingimport osfrom collections.abc import AsyncGeneratorfrom fastapi import HTTPException, Request, Security-from fastapi.security import APIKeyHeader+from fastapi.security import APIKeyHeader, SecurityScopesfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.persistence.database import get_session+from repowise.server.auth import (+ PER_CALL_TOOL_SCOPE,+ Principal,+ get_authenticator,+ get_authorizer,+)logger = logging.getLogger(__name__)@@ -124,44 +129,94 @@ def client_is_local(request: Request) -> bool:def auth_is_open(request: Request) -> bool:- """True when no key is required (no ``REPOWISE_API_KEY``, local caller)."""- return _API_KEY is None and client_is_local(request)+ """True when no credential is required (none configured, local caller)."""+ return not get_authenticator().configured() and client_is_local(request)-def bearer_is_valid(auth: str | None) -> bool:- """True iff ``auth`` carries the configured API key as a bearer token.+#: Routes a repo-scoped principal may call without naming a repo, because the+#: handler filters its output to the principal's scope.+_SCOPE_FILTERED_ROUTES = frozenset({("GET", "/api/repos"), ("GET", "/api/repos/summary")})- Returns False (rather than raising) so callers that also accept another- credential — the SSE stream token — can fall through to it. Always False- when no key is configured; the open-access decision is ``auth_is_open``.- """- if _API_KEY is None:- return False- if not auth or not auth.startswith("Bearer "):- return False- return hmac.compare_digest(auth[7:], _API_KEY)++async def _repo_identifiers(request: Request, repo_id: str) -> tuple[str, ...]:+ """The id plus the stored name, so a scope may list either."""+ from repowise.core.persistence import crud++ try:+ factory = resolve_session_factory(request.app.state, repo_id)+ async with get_session(factory) as session:+ repo = await crud.get_repository(session, repo_id)+ except Exception:+ repo = None+ return (repo_id, repo.name) if repo is not None else (repo_id,)+++async def _enforce_repo_scope(request: Request, principal: Principal) -> None:+ """403 unless the route's repo is in scope. A restricted principal is+ refused on routes that name no repo, except the filtered listings."""+ if principal.repo_scope is None:+ return+ authorizer = get_authorizer()+ repo_id = request.path_params.get("repo_id") or request.query_params.get("repo_id")+ if repo_id:+ if authorizer.can_access_repo(principal, (repo_id,)):+ return+ if authorizer.can_access_repo(principal, await _repo_identifiers(request, repo_id)):+ return+ else:+ route = request.scope.get("route")+ if (request.method, getattr(route, "path", None)) in _SCOPE_FILTERED_ROUTES:+ return+ raise HTTPException(status_code=403, detail="Repository is outside this credential's scope")+++def request_principal(request: Request) -> Principal | None:+ """The principal ``verify_api_key`` stored on this request, if any."""+ return getattr(request.state, "principal", None)+++def scoped_repo_id(request: Request) -> str | None:+ """The repo a repo-restricted principal was authorised for on this request;+ None for unrestricted callers. Routes that load an object by its own id+ check it belongs to this repo."""+ principal = request_principal(request)+ if principal is None or principal.repo_scope is None:+ return None+ return request.path_params.get("repo_id") or request.query_params.get("repo_id")async def verify_api_key(+ security_scopes: SecurityScopes,request: Request,auth: str | None = Security(_header_scheme),-) -> None:- """API key verification.+) -> Principal:+ """Authenticate the caller and return its :class:`Principal`.- When REPOWISE_API_KEY is not set, only local callers are served; a request+ With no credential configured only local callers are served; a requestfrom anywhere else is rejected (fail-closed for network-exposed- deployments, however the server was started). When set, requests must- include ``Authorization: Bearer <key>``.+ deployments, however the server was started). Otherwise requests must+ include ``Authorization: Bearer <key>`` carrying ``REPOWISE_API_KEY`` or a+ scoped token. The principal is also stored on ``request.state.principal``.++ ``auth`` is read again by the authenticator; declaring it here keeps the+ bearer scheme in the OpenAPI document. ``Security(verify_api_key,+ scopes=["tool:<name>"])`` additionally requires those tools in scope. A+ tool-scoped principal is refused on any route that declares neither tool+ scopes nor ``PER_CALL_TOOL_SCOPE``."""- if _API_KEY is None:- if not client_is_local(request):+ principal = await get_authenticator().authenticate(request)+ request.state.principal = principal+ await _enforce_repo_scope(request, principal)+ scopes = security_scopes.scopes+ if principal.tool_scope is not None and not any(+ s == PER_CALL_TOOL_SCOPE or s.startswith("tool:") for s in scopes+ ):+ raise HTTPException(status_code=403, detail="This credential is limited to tools")+ authorizer = get_authorizer()+ for scope in scopes:+ tool = scope.removeprefix("tool:")+ if tool != scope and not authorizer.can_use_tool(principal, tool):raise HTTPException(- status_code=403,- detail="Server is reachable from the network but REPOWISE_API_KEY "- "is not set. Set REPOWISE_API_KEY or bind to 127.0.0.1.",+ status_code=403, detail=f"Tool '{tool}' is outside this credential's scope")- return- if not auth or not auth.startswith("Bearer "):- raise HTTPException(status_code=401, detail="Missing API key")- if not hmac.compare_digest(auth[7:], _API_KEY):- raise HTTPException(status_code=401, detail="Invalid API key")+ return principaldiff --git a/packages/server/src/repowise/server/mcp_server/_http_auth.py b/packages/server/src/repowise/server/mcp_server/_http_auth.pynew file mode 100644index 000000000..dc35ee502--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_http_auth.py@@ -0,0 +1,252 @@+"""Bearer auth for the MCP HTTP transports (streamable HTTP and SSE).++Installed only when the server's :class:`~repowise.server.auth.Authenticator`+says a credential is configured; with none, the transports are served exactly+as before. The gate speaks the MCP authorization shape: an SDK ``TokenVerifier``+checks the bearer, a 401 carries ``WWW-Authenticate: Bearer+resource_metadata="..."``, and the RFC 9728 protected-resource document is+served at ``/.well-known/oauth-protected-resource``. An OAuth-backed+authenticator therefore plugs in by listing its ``authorization_servers``.+"""++from __future__ import annotations++import json+import os+import re+import time+from pathlib import Path+from typing import Any+from urllib.parse import urlsplit++from mcp.server.auth.middleware.auth_context import auth_context_var+from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser+from mcp.server.auth.provider import AccessToken, TokenVerifier+from starlette.authentication import AuthCredentials+from starlette.datastructures import Headers+from starlette.requests import Request+from starlette.responses import JSONResponse, Response+from starlette.routing import Route+from starlette.types import ASGIApp, Receive, Scope, Send++from repowise.server.auth import Authenticator, Principal, get_authenticator, get_authorizer++#: Lists repos rather than reading one; it filters its own output to the scope.+_SELF_SCOPED_TOOLS = frozenset({"list_repos"})++WELL_KNOWN = "/.well-known/oauth-protected-resource"+#: Externally visible base URL (``https://host[/prefix]``) for the metadata and+#: the 401 challenge, for servers behind a proxy. Otherwise a validated Host.+PUBLIC_URL_ENV = "REPOWISE_PUBLIC_URL"+_HOST_RE = re.compile(r"^(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::\d{1,5})?$")+_TOOL_PREFIX = "tool:"+_ALL_TOOLS = "tool:*"+++def access_token_for(principal: Principal, token: str) -> AccessToken:+ """Express a principal in the SDK's token shape. Tool scope travels as+ ``tool:<name>`` scopes; repo scope and kind as claims."""+ scopes = (+ [_ALL_TOOLS]+ if principal.tool_scope is None+ else sorted(_TOOL_PREFIX + t for t in principal.tool_scope)+ )+ claims: dict[str, Any] = {"repowise_kind": principal.kind}+ if principal.repo_scope is not None:+ claims["repowise_repos"] = sorted(principal.repo_scope)+ return AccessToken(+ token=token, client_id=principal.id, scopes=scopes, subject=principal.id, claims=claims+ )+++def principal_from_access_token(access: AccessToken) -> Principal:+ """The inverse of :func:`access_token_for`, for any SDK verifier's token.+ No ``tool:`` scopes at all means no tool restriction."""+ claims = access.claims or {}+ tools = [s[len(_TOOL_PREFIX) :] for s in access.scopes if s.startswith(_TOOL_PREFIX)]+ repos = claims.get("repowise_repos")+ return Principal(+ id=access.subject or access.client_id,+ kind=str(claims.get("repowise_kind", "token")),+ repo_scope=frozenset(repos) if isinstance(repos, list) else None,+ tool_scope=None if not tools or "*" in tools else frozenset(tools),+ )+++class PrincipalTokenVerifier(TokenVerifier):+ """An MCP SDK ``TokenVerifier`` backed by the server's Authenticator."""++ def __init__(self, authenticator: Authenticator | None = None) -> None:+ self._authenticator = authenticator++ async def verify_token(self, token: str) -> AccessToken | None:+ principal = await (self._authenticator or get_authenticator()).verify_token(token)+ return access_token_for(principal, token) if principal is not None else None+++def protected_resource_metadata(resource: str, authorization_servers: tuple[str, ...]) -> dict:+ """RFC 9728 document. ``authorization_servers`` is optional there and+ omitted for static keys, which no authorization server issues."""+ doc: dict[str, Any] = {+ "resource": resource,+ "bearer_methods_supported": ["header"],+ "resource_name": "repowise",+ }+ if authorization_servers:+ doc["authorization_servers"] = list(authorization_servers)+ return doc+++def _origin_and_prefix(scope: Scope) -> tuple[str, str]:+ """``scheme://host`` and any path prefix the public URL adds. The Host+ header is used only when it is a plain host[:port]."""+ public = os.environ.get(PUBLIC_URL_ENV, "").strip().rstrip("/")+ if public:+ parts = urlsplit(public)+ return f"{parts.scheme}://{parts.netloc}", parts.path+ scheme = scope.get("scheme") if scope.get("scheme") in ("http", "https") else "http"+ host = Headers(scope=scope).get("host", "")+ if not _HOST_RE.match(host):+ server = scope.get("server")+ host = f"{_bracket(server[0])}:{server[1]}" if server else "localhost"+ return f"{scheme}://{host}", ""+++def _bracket(host: str) -> str:+ return f"[{host}]" if ":" in host and not host.startswith("[") else host+++def _quoted(value: str) -> str:+ return value.replace("\\", "\\\\").replace('"', '\\"')+++def _metadata_doc(scope: Scope, resource_path: str) -> dict:+ origin, prefix = _origin_and_prefix(scope)+ servers = tuple(getattr(get_authenticator(), "authorization_servers", ()))+ return protected_resource_metadata(origin + prefix + resource_path, servers)+++class BearerGate:+ """ASGI wrapper: serves the metadata document, rejects missing or invalid+ bearers with 401, and hands the principal to the MCP app.++ Whether a credential is configured is checked per request, so a tokens+ file created after start-up gates the transport too; with none, requests+ pass straight through as before.+ """++ def __init__(self, app: ASGIApp, endpoint: str) -> None:+ self.app = app+ self.endpoint = endpoint+ self.verifier = PrincipalTokenVerifier()++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ if scope["type"] != "http" or not get_authenticator().configured():+ await self.app(scope, receive, send)+ return+ root = scope.get("root_path", "")+ path = scope["path"]+ relative = path[len(root) :] if root and path.startswith(root) else path+ resource_path = root + self.endpoint+ if relative in (WELL_KNOWN, WELL_KNOWN + self.endpoint) or path == WELL_KNOWN + resource_path:+ await _send_json(send, 200, _metadata_doc(scope, resource_path), [])+ return++ access = None+ auth = Headers(scope=scope).get("authorization", "")+ if auth.lower().startswith("bearer "):+ access = await self.verifier.verify_token(auth[7:])+ if access is not None and access.expires_at and access.expires_at < int(time.time()):+ access = None+ if access is None:+ origin, prefix = _origin_and_prefix(scope)+ # RFC 9728 3.1: the well-known segment goes between host and path.+ metadata_url = f"{origin}{WELL_KNOWN}{prefix}{resource_path}"+ challenge = (+ 'Bearer error="invalid_token", error_description="Authentication required", '+ f'resource_metadata="{_quoted(metadata_url)}"'+ )+ body = {"error": "invalid_token", "error_description": "Authentication required"}+ await _send_json(send, 401, body, [(b"www-authenticate", challenge.encode())])+ return++ user = AuthenticatedUser(access)+ scope["user"] = user+ scope["auth"] = AuthCredentials(access.scopes)+ scope.setdefault("state", {})["principal"] = principal_from_access_token(access)+ reset = auth_context_var.set(user)+ try:+ await self.app(scope, receive, send)+ finally:+ auth_context_var.reset(reset)+++def gate(app: ASGIApp, endpoint: str) -> BearerGate:+ """Wrap an MCP transport app served at ``endpoint`` (``/mcp`` or ``/sse``)."""+ return BearerGate(app, endpoint)+++def metadata_route(resource_path: str) -> Route:+ """The host-root RFC 9728 route for an MCP app mounted under a sub-path,+ e.g. ``metadata_route("/sub/mcp")`` beside ``Mount("/sub", app=...)``."""++ async def endpoint(request: Request) -> Response:+ if not get_authenticator().configured():+ return JSONResponse({"detail": "Not Found"}, status_code=404)+ return JSONResponse(_metadata_doc(request.scope, resource_path))++ return Route(WELL_KNOWN + resource_path, endpoint, methods=["GET"])+++async def _send_json(send: Send, status: int, body: dict, headers: list) -> None:+ raw = json.dumps(body).encode()+ await send(+ {+ "type": "http.response.start",+ "status": status,+ "headers": [+ (b"content-type", b"application/json"),+ (b"content-length", str(len(raw)).encode()),+ *headers,+ ],+ }+ )+ await send({"type": "http.response.body", "body": raw})+++# ---------------------------------------------------------------------------+# Per-call scope+# ---------------------------------------------------------------------------+++def _call_targets(arguments: dict[str, Any]) -> list[tuple[str | None, ...]]:+ """The repos one tool call would read, each as its accepted identifiers."""+ from repowise.server.mcp_server import _state++ repo = arguments.get("repo") or None+ registry = _state._registry+ if registry is not None:+ try:+ resolved = registry.resolve_repo_param(repo)+ except ValueError:+ return [(repo,)]+ aliases = resolved if isinstance(resolved, list) else [resolved]+ return [(alias,) for alias in aliases]+ if repo is not None:+ return [(repo,)]+ name = Path(_state._repo_path).name if _state._repo_path else None+ return [(_state._served_repo_id, name)]+++def call_denial(principal: Principal, tool: str, arguments: dict[str, Any]) -> str | None:+ """Why ``principal`` may not make this call, or None when it may."""+ authorizer = get_authorizer()+ if not authorizer.can_use_tool(principal, tool):+ return f"Tool '{tool}' is outside this credential's scope."+ if principal.repo_scope is not None and tool not in _SELF_SCOPED_TOOLS:+ if arguments.get("repo") == "all":+ return "repo='all' is not available to a repository-scoped credential."+ for identifiers in _call_targets(arguments):+ if not authorizer.can_access_repo(principal, identifiers):+ return "Repository is outside this credential's scope."+ return Nonediff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.pyindex 4c5e72958..17a60f5d1 100644--- a/packages/server/src/repowise/server/mcp_server/_server.py+++ b/packages/server/src/repowise/server/mcp_server/_server.py@@ -745,7 +745,61 @@ async def _lifespan(server: FastMCP):# Create the MCP server# ----------------------------------------------------------------------------mcp = FastMCP(+class _RepowiseMCP(FastMCP):+ """FastMCP plus the HTTP bearer gate and per-call principal scope.++ Both are inert without an authenticated HTTP principal, so stdio and an+ unconfigured HTTP server behave exactly like plain FastMCP.+ """++ def streamable_http_app(self): # type: ignore[override]+ from repowise.server.mcp_server._http_auth import gate++ return gate(super().streamable_http_app(), self.settings.streamable_http_path)++ def sse_app(self, mount_path: str | None = None): # type: ignore[override]+ from repowise.server.mcp_server._http_auth import gate++ return gate(super().sse_app(mount_path), self.settings.sse_path)++ def _request_principal(self) -> Any:+ try:+ request = self._mcp_server.request_context.request+ except LookupError:+ return None+ state = getattr(request, "scope", {}).get("state") or {}+ return state.get("principal")++ async def list_tools(self): # type: ignore[override]+ tools = await super().list_tools()+ principal = self._request_principal()+ if principal is None:+ return tools+ from repowise.server.auth import get_authorizer++ authorizer = get_authorizer()+ return [t for t in tools if authorizer.can_use_tool(principal, t.name)]++ async def call_tool(self, name: str, arguments: dict[str, Any]): # type: ignore[override]+ principal = self._request_principal()+ if principal is not None:+ from mcp.server.fastmcp.exceptions import ToolError++ from repowise.server.mcp_server._http_auth import call_denial++ denial = call_denial(principal, name, arguments)+ if denial is not None:+ raise ToolError(denial)+ from repowise.server.auth import current_principal++ reset = current_principal.set(principal)+ try:+ return await super().call_tool(name, arguments)+ finally:+ current_principal.reset(reset)+++mcp = _RepowiseMCP("repowise",# Hosts that defer tool schemas show the model only tool names and this# string, so it says when to call; tests pin the key lines and a length cap.diff --git a/packages/server/src/repowise/server/mcp_server/tool_repos.py b/packages/server/src/repowise/server/mcp_server/tool_repos.pyindex 279645183..0f5c05b92 100644--- a/packages/server/src/repowise/server/mcp_server/tool_repos.py+++ b/packages/server/src/repowise/server/mcp_server/tool_repos.py@@ -2,9 +2,11 @@from __future__ import annotations+from pathlib import Pathfrom typing import Anyfrom repowise.core.registry import mcp_tool_registry as mcp+from repowise.server.auth import current_principal, get_authorizerfrom repowise.server.mcp_server import _statefrom repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._references import repository_identity@@ -58,6 +60,15 @@ def _workspace_repos(registry: Any) -> list[dict[str, Any]]:return repos+def _in_scope(*identifiers: str | None) -> bool:+ """True unless a repo-restricted principal is calling and none of these+ identifiers (alias, path, id or name of one repo) is in its scope."""+ principal = current_principal.get()+ if principal is None or principal.repo_scope is None:+ return True+ return get_authorizer().can_access_repo(principal, identifiers)++@mcp.tool(tier="utility",requires_workspace=True,@@ -74,11 +85,15 @@ async def list_repos() -> dict[str, Any]:"""registry = _state._registryif registry is not None:+ repos = [r for r in _workspace_repos(registry) if _in_scope(r["alias"], r["path"])]+ default_alias = registry.get_default_alias()+ default_paths = [r["path"] for r in repos if r.get("is_default")]+ default_in_scope = _in_scope(default_alias, *default_paths)return {"workspace": True,"workspace_root": registry.workspace_root.as_posix(),- "default_repo": repository_identity(registry.get_default_alias()),- "repos": _workspace_repos(registry),+ "default_repo": repository_identity(default_alias) if default_in_scope else None,+ "repos": repos,"hint": ("Pass any emitted alias, path, or absolute_path unchanged as repo ""on workspace-aware tools."@@ -86,10 +101,12 @@ async def list_repos() -> dict[str, Any]:"_meta": _build_meta(),}+ served_name = Path(_state._repo_path).name if _state._repo_path else None+ served = _in_scope(_state._served_repo_id, served_name)return {"workspace": False,"workspace_root": None,- "default_repo": "default",+ "default_repo": "default" if served else None,"repos": [{"alias": "default",@@ -97,7 +114,9 @@ async def list_repos() -> dict[str, Any]:"absolute_path": str(_state._repo_path) if _state._repo_path else None,"is_default": True,}- ],+ ]+ if served+ else [],"hint": "This MCP server is serving a single repo; omit repo unless a tool asks for it.","_meta": _build_meta(),}diff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.pyindex 932389343..7842c46a5 100644--- a/packages/server/src/repowise/server/routers/chat.py+++ b/packages/server/src/repowise/server/routers/chat.py@@ -8,13 +8,14 @@ from collections.abc import AsyncIterator, Iteratorfrom pathlib import Pathfrom typing import Any-from fastapi import APIRouter, Depends, HTTPException, Request+from fastapi import APIRouter, Depends, HTTPException, Request, Securityfrom pydantic import ValidationErrorfrom starlette.responses import StreamingResponsefrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.providers.llm.base import ChatProvider, ProviderError+from repowise.server.auth import PER_CALL_TOOL_SCOPEfrom repowise.server.chat_artifacts import (create_artifact_envelope,find_artifact,@@ -46,6 +47,7 @@ from repowise.server.chat_tools import ()from repowise.server.deps import (get_db_session,+ request_principal,resolve_request_session_factory,verify_api_key,)@@ -66,9 +68,10 @@ from repowise.server.schemas.chat import ChatPageContextlogger = logging.getLogger(__name__)+# Chat checks tool scope on every tool it runs, so tool-scoped tokens may use it.router = APIRouter(tags=["chat"],- dependencies=[Depends(verify_api_key)],+ dependencies=[Security(verify_api_key, scopes=[PER_CALL_TOOL_SCOPE])],)_MAX_AGENTIC_LOOPS = 10@@ -192,9 +195,13 @@ class _AgentTurn:repo_alias: str | None,provider: ChatProvider,llm_messages: list[dict[str, Any]],+ principal: Any = None,+ repo_id: str | None = None,) -> None:self.repo_path = repo_pathself.repo_alias = repo_alias+ self.principal = principal+ self.repo_id = repo_idself.provider = providerself.llm_messages = llm_messagesself.text_parts: list[str] = []@@ -205,7 +212,14 @@ class _AgentTurn:async def execute(self, name: str, args: dict) -> dict:"""Run one tool scoped to this repo; also handed to providers that loop internally."""- return await execute_tool(name, args, repo_path=self.repo_path, repo=self.repo_alias)+ return await execute_tool(+ name,+ args,+ repo_path=self.repo_path,+ repo=self.repo_alias,+ principal=self.principal,+ repo_id=self.repo_id,+ )async def ground(self, page_context: Any, tool_catalog: list) -> str | None:"""Make the one read the page already justifies, before the first model turn.@@ -369,6 +383,7 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):# In workspace mode the MCP tools address repos by alias, not by the id# in this URL, so resolve it once and scope every tool call to it.repo_alias = _workspace_alias(request, repo_path, repo_name)+ principal = request_principal(request)# An override (the UI model picker) applies to this request only; without# one the repo's own config and ``.env`` pick the provider, as for update.@@ -403,11 +418,13 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):conv_id, user_msg_id, created = openedllm_messages = await _llm_history(factory, conv_id, body.context)- tool_catalog = get_tool_catalog(repo_path)+ tool_catalog = get_tool_catalog(repo_path, principal)system_prompt = _build_system_prompt(repo_name, repo_path, tool_catalog, body.context)- tool_schemas = get_tool_schemas_for_llm(repo_path)+ tool_schemas = get_tool_schemas_for_llm(repo_path, principal)- turn = _AgentTurn(repo_path, repo_alias, provider, llm_messages)+ turn = _AgentTurn(+ repo_path, repo_alias, provider, llm_messages, principal=principal, repo_id=repo_id+ )grounded = await turn.ground(body.context, tool_catalog)if grounded is not None:yield grounded@@ -491,13 +508,16 @@ async def chat_suggestions(# banner over a composer.return {"suggestions": []}- tool_catalog = get_tool_catalog(repo_path)+ principal = request_principal(request)+ tool_catalog = get_tool_catalog(repo_path, principal)plan = plan_grounding(context, (tool.entry for tool in tool_catalog))if plan is None:return {"suggestions": []}async def _execute(name: str, args: dict) -> dict:- return await execute_tool(name, args, repo_path=repo_path, repo=repo_alias)+ return await execute_tool(+ name, args, repo_path=repo_path, repo=repo_alias, principal=principal, repo_id=repo_id+ )grounding = await run_grounding(plan, _execute)if grounding is None:diff --git a/packages/server/src/repowise/server/routers/code_health/findings_routes.py b/packages/server/src/repowise/server/routers/code_health/findings_routes.pyindex 767431348..531649ced 100644--- a/packages/server/src/repowise/server/routers/code_health/findings_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/findings_routes.py@@ -2,7 +2,7 @@from __future__ import annotations-from fastapi import Depends, HTTPException, Query+from fastapi import Depends, HTTPException, Query, Requestfrom pydantic import BaseModel, Fieldfrom sqlalchemy.ext.asyncio import AsyncSession@@ -11,7 +11,7 @@ from repowise.core.analysis.health.models import split_by_originfrom repowise.core.analysis.health.scope import parse_scopefrom repowise.core.analysis.health.scoring import ZERO_IMPACT_DIMENSIONSfrom repowise.core.persistence import crud-from repowise.server.deps import get_db_session+from repowise.server.deps import get_db_session, scoped_repo_idfrom repowise.server.schemas import (HealthFindingResponse,HealthFindingWithSymbolResponse,@@ -127,12 +127,19 @@ async def update_finding_status(repo_id: str,finding_id: str,payload: FindingStatusUpdate,+ request: Request,session: AsyncSession = Depends(get_db_session),) -> dict:if payload.status not in ALLOWED_STATUSES:raise HTTPException(status_code=400, detail=f"status must be one of {sorted(ALLOWED_STATUSES)}")+ if scoped_repo_id(request) is not None:+ from repowise.core.persistence.models import HealthFinding++ existing = await session.get(HealthFinding, finding_id)+ if existing is None or existing.repository_id != repo_id:+ raise HTTPException(status_code=404, detail="Finding not found")f = await crud.update_health_finding_status(session, finding_id, payload.status)if f is None:raise HTTPException(status_code=404, detail="Finding not found")diff --git a/packages/server/src/repowise/server/routers/jobs.py b/packages/server/src/repowise/server/routers/jobs.pyindex f168b95d2..e3aaf21f4 100644--- a/packages/server/src/repowise/server/routers/jobs.py+++ b/packages/server/src/repowise/server/routers/jobs.py@@ -13,10 +13,10 @@ from starlette.responses import StreamingResponsefrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GenerationJob, LlmCost+from repowise.server.auth import get_authenticatorfrom repowise.server.deps import (_header_scheme,auth_is_open,- bearer_is_valid,resolve_session_factory,verify_api_key,)@@ -44,8 +44,11 @@ async def authorize_job_stream("""if auth_is_open(request):return- if bearer_is_valid(auth):- return+ if auth and auth.startswith("Bearer "):+ principal = await get_authenticator().verify_token(auth[7:])+ # Jobs name no repo, so only an unrestricted principal may use the bearer path.+ if principal is not None and principal.repo_scope is None and principal.tool_scope is None:+ returnif verify_stream_token(token, job_id):returnraise HTTPException(status_code=401, detail="Missing or invalid job stream credentials")diff --git a/packages/server/src/repowise/server/routers/pages.py b/packages/server/src/repowise/server/routers/pages.pyindex 43ebbbc23..f3fec0909 100644--- a/packages/server/src/repowise/server/routers/pages.py+++ b/packages/server/src/repowise/server/routers/pages.py@@ -19,7 +19,7 @@ from repowise.core.generation.page_redirects import ()from repowise.core.persistence import crudfrom repowise.core.persistence.models import _now_utc-from repowise.server.deps import get_db_session, verify_api_key+from repowise.server.deps import get_db_session, scoped_repo_id, verify_api_keyfrom repowise.server.schemas import (JobAcceptedResponse,PageResponse,@@ -170,6 +170,7 @@ async def list_pages(@router.get("/lookup", response_model=PageResponse)async def get_page_by_query(+ request: Request,response: Response,page_id: str = Query(..., description="Page ID (e.g. file_page:src/main.py)"),repo_id: str | None = Query(@@ -194,11 +195,16 @@ async def get_page_by_query(carries ``X-Repowise-Redirected-From``."""page = await _get_page_or_successor(session, page_id, response)- if page is None:+ if page is None or _outside_scope(request, page.repository_id):raise HTTPException(status_code=404, detail="Page not found")return PageResponse.from_orm(page)+def _outside_scope(request: Request, repository_id: str) -> bool:+ scoped = scoped_repo_id(request)+ return scoped is not None and repository_id != scoped++@router.get("/lookup/versions", response_model=list[PageVersionResponse])async def get_page_versions_by_query(page_id: str = Query(..., description="Page ID"),@@ -268,7 +274,7 @@ async def regenerate_page_by_query(from repowise.server.routers.repos import _accepted, _ensure_no_active_job, _launch_job_taskpage = await crud.get_page(session, page_id)- if page is None:+ if page is None or _outside_scope(request, page.repository_id):raise HTTPException(status_code=404, detail="Page not found")if cascade not in ("none", "dependents", "full"):diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.pyindex 6344ce14d..408434b96 100644--- a/packages/server/src/repowise/server/routers/repos.py+++ b/packages/server/src/repowise/server/routers/repos.py@@ -24,7 +24,8 @@ from repowise.core.persistence.models import (Page,Repository,)-from repowise.server.deps import get_db_session, get_fts, verify_api_key+from repowise.server.auth import get_authorizer+from repowise.server.deps import get_db_session, get_fts, request_principal, verify_api_keyfrom repowise.server.job_executor import execute_jobfrom repowise.server.routers._repo_generate import (GenerateRequestBody,@@ -208,12 +209,15 @@ async def list_repos(# app.state, not on the Repository row.ws_config = getattr(app_state, "workspace_config", None)ws_root = getattr(app_state, "workspace_root", None)- if ws_config is None or ws_root is None:- return responses-- ws_root_path = Path(ws_root)- matched = attach_workspace_metadata(responses, ws_config, ws_root_path, indexed_repo_ids)- responses.extend(unregistered_workspace_rows(ws_config, ws_root_path, matched))+ if ws_config is not None and ws_root is not None:+ ws_root_path = Path(ws_root)+ matched = attach_workspace_metadata(responses, ws_config, ws_root_path, indexed_repo_ids)+ responses.extend(unregistered_workspace_rows(ws_config, ws_root_path, matched))++ principal = request_principal(request)+ if principal is not None and principal.repo_scope is not None:+ authorizer = get_authorizer()+ responses = [r for r in responses if authorizer.can_access_repo(principal, (r.id, r.name))]return responsesdiff --git a/packages/server/src/repowise/server/routers/webhooks.py b/packages/server/src/repowise/server/routers/webhooks.pyindex 1ced9cff6..33587784d 100644--- a/packages/server/src/repowise/server/routers/webhooks.py+++ b/packages/server/src/repowise/server/routers/webhooks.py@@ -14,14 +14,38 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.forges import canonical_keyfrom repowise.core.persistence import crudfrom repowise.core.persistence.models import Repository+from repowise.server.auth import LOCAL_PRINCIPAL, Principal, get_authenticator, get_authorizerfrom repowise.server.deps import auth_is_open, get_db_sessionfrom repowise.server.schemas import WebhookResponserouter = APIRouter(prefix="/api/webhooks", tags=["webhooks"])-# Note: no Depends(verify_api_key) here — webhook routes carry their own-# credential (HMAC signature / shared token) issued by the SCM provider.-# Secrets are read per-request (not cached at import) so env changes are-# picked up without a server restart.+# Note: no Depends(verify_api_key) here. A forge delivery carries its own+# credential (HMAC signature / shared token), never a bearer, so the rule is:+# - secret configured: the verified signature is the principal (all repos);+# - no secret, open local server: the local principal, as before;+# - no secret otherwise: a valid bearer (API key or scoped token) is accepted,+# and without one the 403 is unchanged.+# The principal must have the matched repo in scope before a sync job is+# created. Secrets are read per-request (not cached at import) so env changes+# are picked up without a server restart.++_GITHUB_PRINCIPAL = Principal(id="webhook:github", kind="webhook")+_GITLAB_PRINCIPAL = Principal(id="webhook:gitlab", kind="webhook")+++async def _unsigned_principal(request: Request) -> Principal | None:+ """The principal for a delivery when no forge secret is configured."""+ if auth_is_open(request):+ return LOCAL_PRINCIPAL # local caller, dev mode+ auth = request.headers.get("Authorization", "")+ if auth.startswith("Bearer "):+ return await get_authenticator().verify_token(auth[7:])+ return None+++def _require_repo_in_scope(principal: Principal, repo: Repository) -> None:+ if not get_authorizer().can_access_repo(principal, (repo.id, repo.name)):+ raise HTTPException(status_code=403, detail="Repository is outside this credential's scope")def _normalize_scm_url(url: str) -> str:@@ -51,7 +75,9 @@ async def _find_repo_by_scm_url(session: AsyncSession, url: str) -> Repository |return None-def _verify_github_signature(request: Request, body: bytes, signature_header: str) -> None:+async def _verify_github_signature(+ request: Request, body: bytes, signature_header: str+) -> Principal:"""Verify GitHub HMAC-SHA256 webhook signature.Reads REPOWISE_GITHUB_WEBHOOK_SECRET per-call so env changes (e.g.@@ -60,11 +86,13 @@ def _verify_github_signature(request: Request, body: bytes, signature_header: stWhen the secret is not configured:- Local callers (loopback / no network exposure) are accepted — devconvenience, matching the posture of ``verify_api_key`` in deps.py.- - Non-local callers are rejected with 403 (fail-closed).+ - A caller with a valid bearer credential is accepted as that principal.+ - Anyone else is rejected with 403 (fail-closed)."""secret = os.environ.get("REPOWISE_GITHUB_WEBHOOK_SECRET", "")if not secret:- if not auth_is_open(request):+ principal = await _unsigned_principal(request)+ if principal is None:raise HTTPException(status_code=403,detail=(@@ -73,7 +101,7 @@ def _verify_github_signature(request: Request, body: bytes, signature_header: st"to a loopback interface."),)- return # local caller — dev mode+ return principalif not signature_header.startswith("sha256="):raise HTTPException(status_code=401, detail="Missing signature prefix")@@ -86,9 +114,10 @@ def _verify_github_signature(request: Request, body: bytes, signature_header: stif not hmac.compare_digest(expected, signature_header):raise HTTPException(status_code=401, detail="Invalid signature")+ return _GITHUB_PRINCIPAL-def _verify_gitlab_token(request: Request, token_header: str) -> None:+async def _verify_gitlab_token(request: Request, token_header: str) -> Principal:"""Verify GitLab webhook token.Reads REPOWISE_GITLAB_WEBHOOK_TOKEN per-call so env changes are always@@ -96,11 +125,13 @@ def _verify_gitlab_token(request: Request, token_header: str) -> None:When the token is not configured:- Local callers are accepted (dev convenience).- - Non-local callers are rejected with 403 (fail-closed).+ - A caller with a valid bearer credential is accepted as that principal.+ - Anyone else is rejected with 403 (fail-closed)."""configured = os.environ.get("REPOWISE_GITLAB_WEBHOOK_TOKEN", "")if not configured:- if not auth_is_open(request):+ principal = await _unsigned_principal(request)+ if principal is None:raise HTTPException(status_code=403,detail=(@@ -109,10 +140,11 @@ def _verify_gitlab_token(request: Request, token_header: str) -> None:"to a loopback interface."),)- return # local caller — dev mode+ return principalif not hmac.compare_digest(token_header, configured):raise HTTPException(status_code=401, detail="Invalid token")+ return _GITLAB_PRINCIPALdef _launch_webhook_job(request: Request, job_id: str) -> None:@@ -146,7 +178,7 @@ async def github_webhook("""body = await request.body()sig = request.headers.get("X-Hub-Signature-256", "")- _verify_github_signature(request, body, sig)+ principal = await _verify_github_signature(request, body, sig)event_type = request.headers.get("X-GitHub-Event", "unknown")delivery_id = request.headers.get("X-GitHub-Delivery", "")@@ -176,6 +208,7 @@ async def github_webhook(branch = ref[len("refs/heads/") :]repo = await _find_repo_by_scm_url(session, repo_url)if repo and branch == repo.default_branch:+ _require_repo_in_scope(principal, repo)job = await crud.upsert_generation_job(session,repository_id=repo.id,@@ -205,7 +238,7 @@ async def gitlab_webhook(job for push events on the default branch."""token = request.headers.get("X-Gitlab-Token", "")- _verify_gitlab_token(request, token)+ principal = await _verify_gitlab_token(request, token)body = await request.body()payload = json.loads(body)@@ -227,6 +260,7 @@ async def gitlab_webhook(repo = await _find_repo_by_scm_url(session, project_url)if repo and branch == repo.default_branch:+ _require_repo_in_scope(principal, repo)job = await crud.upsert_generation_job(session,repository_id=repo.id,diff --git a/tests/conftest.py b/tests/conftest.pyindex beb0382b9..6d78969e6 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -110,6 +110,13 @@ def _isolate_db_url_env():os.environ[key] = value[email protected](autouse=True)+def _isolate_tokens_file(monkeypatch: pytest.MonkeyPatch, tmp_path_factory: pytest.TempPathFactory):+ """Keep a developer's ``~/.repowise/tokens.yaml`` from turning server auth on."""+ missing = tmp_path_factory.getbasetemp() / "no-tokens.yaml"+ monkeypatch.setenv("REPOWISE_TOKENS_FILE", str(missing))++@pytest.fixture(autouse=True)def _fresh_per_index_caches():"""Drop the MCP server's per-index caches before every test.diff --git a/tests/unit/server/test_auth_principal.py b/tests/unit/server/test_auth_principal.pynew file mode 100644index 000000000..49f29d97b--- /dev/null+++ b/tests/unit/server/test_auth_principal.py@@ -0,0 +1,727 @@+"""Principal, scoped tokens, and the shared auth check on REST, MCP HTTP and webhooks."""++from __future__ import annotations++import json+from pathlib import Path+from unittest.mock import patch++import pytest+from fastapi import FastAPI, Security+from httpx import ASGITransport, AsyncClient+from sqlalchemy import select+from starlette.applications import Starlette+from starlette.responses import PlainTextResponse+from starlette.routing import Mount, Route++import repowise.server.deps as deps+from repowise.core.persistence.models import GenerationJob, Repository+from repowise.server import auth+from repowise.server.auth import (+ LOCAL_PRINCIPAL,+ SHARED_KEY_PRINCIPAL,+ Principal,+ ScopeAuthorizer,+ hash_token,+)+from repowise.server.mcp_server import _http_auth, _state+from repowise.server.mcp_server._http_auth import (+ PrincipalTokenVerifier,+ access_token_for,+ call_denial,+ gate,+ metadata_route,+ principal_from_access_token,+)++KEY = "shared-secret"+SCOPED = "scoped-token-value"+++def _write_tokens(path: Path, *entries: dict) -> None:+ import yaml++ path.write_text(yaml.safe_dump({"tokens": list(entries)}), encoding="utf-8")+++def tokens_file(tmp_path, monkeypatch) -> Path:+ path = tmp_path / "tokens.yaml"+ monkeypatch.setenv(auth.TOKENS_FILE_ENV, str(path))+ return path+++def shared_key(monkeypatch) -> str:+ monkeypatch.setattr(deps, "_API_KEY", KEY)+ return KEY+++async def remote_client(app) -> AsyncClient:+ transport = ASGITransport(app=app, client=("203.0.113.7", 4242))+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ yield c+++# ---------------------------------------------------------------------------+# Principal and authorizer+# ---------------------------------------------------------------------------+++def test_unrestricted_principal_reaches_everything() -> None:+ authz = ScopeAuthorizer()+ assert authz.can_access_repo(SHARED_KEY_PRINCIPAL, ("any",))+ assert authz.can_use_tool(LOCAL_PRINCIPAL, "get_answer")+++def test_scoped_principal_allow_and_deny() -> None:+ authz = ScopeAuthorizer()+ p = Principal("token:ci", "token", frozenset({"alpha"}), frozenset({"get_answer"}))+ assert authz.can_access_repo(p, ("id-1", "alpha"))+ assert not authz.can_access_repo(p, ("id-2", "beta"))+ assert not authz.can_access_repo(p, (None,))+ assert authz.can_use_tool(p, "get_answer")+ assert not authz.can_use_tool(p, "get_context")+++# ---------------------------------------------------------------------------+# Authenticator: shared key and scoped tokens+# ---------------------------------------------------------------------------+++async def test_no_credentials_means_not_configured() -> None:+ authn = auth.LocalAuthenticator()+ assert not authn.configured()+ assert await authn.verify_token("anything") is None+++async def test_shared_key_verifies_to_shared_principal(shared_key) -> None:+ authn = auth.LocalAuthenticator()+ assert authn.configured()+ assert await authn.verify_token(KEY) == SHARED_KEY_PRINCIPAL+ assert await authn.verify_token("wrong") is None+++async def test_scoped_token_carries_its_scopes(tokens_file) -> None:+ _write_tokens(+ tokens_file,+ {"id": "ci", "sha256": hash_token(SCOPED), "repos": ["alpha"], "tools": ["get_answer"]},+ {"id": "ops", "sha256": hash_token("ops-token")},+ )+ authn = auth.LocalAuthenticator()+ assert authn.configured()+ ci = await authn.verify_token(SCOPED)+ assert ci == Principal("token:ci", "token", frozenset({"alpha"}), frozenset({"get_answer"}))+ ops = await authn.verify_token("ops-token")+ assert ops is not None and ops.repo_scope is None and ops.tool_scope is None+ assert await authn.verify_token("not-a-token") is None+++async def test_malformed_tokens_file_fails_closed(tokens_file, shared_key) -> None:+ tokens_file.write_text("tokens:\n - id: x\n sha256: short\n", encoding="utf-8")+ authn = auth.LocalAuthenticator()+ assert authn.configured()+ assert await authn.verify_token(SCOPED) is None+ assert await authn.verify_token(KEY) == SHARED_KEY_PRINCIPAL+++def test_resolver_override_and_restore() -> None:+ class Custom(auth.LocalAuthenticator):+ pass++ custom = Custom()+ auth.set_authenticator(custom)+ try:+ assert auth.get_authenticator() is custom+ finally:+ auth.set_authenticator(None)+ assert isinstance(auth.get_authenticator(), auth.LocalAuthenticator)+ assert not isinstance(auth.get_authenticator(), Custom)+++# ---------------------------------------------------------------------------+# REST+# ---------------------------------------------------------------------------+++async def test_rest_no_key_local_is_open_and_local_principal(client) -> None:+ assert (await client.get("/api/repos")).status_code == 200+ from starlette.requests import Request++ scope = {"type": "http", "method": "GET", "path": "/", "headers": [], "client": ("127.0.0.1", 1)}+ assert await deps.verify_api_key(deps.SecurityScopes(), Request(scope), None) == LOCAL_PRINCIPAL+++async def test_rest_no_key_remote_refused_unchanged(remote_client) -> None:+ resp = await remote_client.get("/api/repos")+ assert resp.status_code == 403+ assert resp.json()["detail"] == (+ "Server is reachable from the network but REPOWISE_API_KEY "+ "is not set. Set REPOWISE_API_KEY or bind to 127.0.0.1."+ )+++async def test_rest_shared_key_unchanged(client, shared_key) -> None:+ assert (await client.get("/api/repos")).json()["detail"] == "Missing API key"+ bad = await client.get("/api/repos", headers={"Authorization": "Bearer nope"})+ assert bad.status_code == 401 and bad.json()["detail"] == "Invalid API key"+ ok = await client.get("/api/repos", headers={"Authorization": f"Bearer {KEY}"})+ assert ok.status_code == 200+++async def test_rest_tokens_file_alone_turns_auth_on(client, tokens_file) -> None:+ _write_tokens(tokens_file, {"id": "ci", "sha256": hash_token(SCOPED)})+ resp = await client.get("/api/repos")+ assert resp.status_code == 401 and resp.json()["detail"] == "Missing API key"+ ok = await client.get("/api/repos", headers={"Authorization": f"Bearer {SCOPED}"})+ assert ok.status_code == 200+++async def _add_repo(session_factory, name: str, url: str = "") -> str:+ async with session_factory() as session:+ repo = Repository(name=name, url=url, local_path=f"/tmp/{name}", default_branch="main")+ session.add(repo)+ await session.commit()+ return repo.id+++async def test_rest_repo_scope(client, session_factory, tokens_file) -> None:+ alpha = await _add_repo(session_factory, "alpha")+ beta = await _add_repo(session_factory, "beta")+ _write_tokens(tokens_file, {"id": "ci", "sha256": hash_token(SCOPED), "repos": ["alpha"]})+ headers = {"Authorization": f"Bearer {SCOPED}"}++ assert (await client.get(f"/api/repos/{alpha}", headers=headers)).status_code == 200+ denied = await client.get(f"/api/repos/{beta}", headers=headers)+ assert denied.status_code == 403+ listed = await client.get("/api/repos", headers=headers)+ assert [r["name"] for r in listed.json()] == ["alpha"]+ # A route that names no repo is refused for a repo-scoped token.+ assert (await client.get("/api/meta/version", headers=headers)).status_code == 403+++async def test_rest_security_scopes_check_tool_scope(tokens_file) -> None:+ _write_tokens(tokens_file, {"id": "ci", "sha256": hash_token(SCOPED), "tools": ["get_answer"]})+ app = FastAPI()++ @app.get("/answer", dependencies=[Security(deps.verify_api_key, scopes=["tool:get_answer"])])+ async def answer():+ return {}++ @app.get("/risk", dependencies=[Security(deps.verify_api_key, scopes=["tool:get_risk"])])+ async def risk():+ return {}++ headers = {"Authorization": f"Bearer {SCOPED}"}+ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://t") as c:+ assert (await c.get("/answer", headers=headers)).status_code == 200+ assert (await c.get("/risk", headers=headers)).status_code == 403+++# ---------------------------------------------------------------------------+# Webhooks+# ---------------------------------------------------------------------------++_PUSH = {+ "ref": "refs/heads/main",+ "repository": {"clone_url": "https://github.com/org/alpha.git"},+}+_GH_HEADERS = {"X-GitHub-Event": "push", "Content-Type": "application/json"}+++async def test_webhook_no_key_local_unchanged(client, session_factory, monkeypatch) -> None:+ monkeypatch.delenv("REPOWISE_GITHUB_WEBHOOK_SECRET", raising=False)+ await _add_repo(session_factory, "alpha", "https://github.com/org/alpha")+ with patch("repowise.server.routers.webhooks._launch_webhook_job"):+ resp = await client.post("/api/webhooks/github", content=json.dumps(_PUSH), headers=_GH_HEADERS)+ assert resp.status_code == 200+ async with session_factory() as session:+ assert (await session.execute(select(GenerationJob))).scalar_one() is not None+++async def test_webhook_no_secret_remote_needs_bearer(remote_client, monkeypatch, shared_key) -> None:+ monkeypatch.delenv("REPOWISE_GITHUB_WEBHOOK_SECRET", raising=False)+ body = json.dumps(_PUSH)+ refused = await remote_client.post("/api/webhooks/github", content=body, headers=_GH_HEADERS)+ assert refused.status_code == 403+ assert refused.json()["detail"].startswith("Webhook secret not configured.")+ ok = await remote_client.post(+ "/api/webhooks/github",+ content=body,+ headers={**_GH_HEADERS, "Authorization": f"Bearer {KEY}"},+ )+ assert ok.status_code == 200+++async def test_webhook_scoped_token_out_of_scope(client, session_factory, tokens_file, monkeypatch) -> None:+ monkeypatch.delenv("REPOWISE_GITHUB_WEBHOOK_SECRET", raising=False)+ await _add_repo(session_factory, "alpha", "https://github.com/org/alpha")+ _write_tokens(tokens_file, {"id": "ci", "sha256": hash_token(SCOPED), "repos": ["beta"]})+ with patch("repowise.server.routers.webhooks._launch_webhook_job"):+ resp = await client.post(+ "/api/webhooks/github",+ content=json.dumps(_PUSH),+ headers={**_GH_HEADERS, "Authorization": f"Bearer {SCOPED}"},+ )+ assert resp.status_code == 403+ async with session_factory() as session:+ assert (await session.execute(select(GenerationJob))).first() is None+++async def test_webhook_signed_delivery_needs_no_bearer(client, monkeypatch, shared_key) -> None:+ import hashlib+ import hmac++ monkeypatch.setenv("REPOWISE_GITHUB_WEBHOOK_SECRET", "s3cret")+ body = json.dumps(_PUSH).encode()+ sig = "sha256=" + hmac.new(b"s3cret", body, hashlib.sha256).hexdigest()+ resp = await client.post(+ "/api/webhooks/github", content=body, headers={**_GH_HEADERS, "X-Hub-Signature-256": sig}+ )+ assert resp.status_code == 200+++# ---------------------------------------------------------------------------+# MCP HTTP+# ---------------------------------------------------------------------------+++def _inner_app() -> Starlette:+ async def echo(request):+ principal = request.scope.get("state", {}).get("principal")+ return PlainTextResponse(principal.id if principal else "served")++ return Starlette(+ routes=[+ Route("/mcp", echo, methods=["GET", "POST"]),+ Route("/messages/", echo, methods=["POST"]),+ ]+ )+++async def _get(app, path: str, headers: dict | None = None, method: str = "GET"):+ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://127.0.0.1:7338") as c:+ return await c.request(method, path, headers=headers or {})+++async def test_mcp_no_key_passes_straight_through() -> None:+ gated = gate(_inner_app(), "/mcp")+ assert (await _get(gated, "/mcp")).text == "served"+ assert (await _get(gated, "/.well-known/oauth-protected-resource")).status_code == 404+ from repowise.server.mcp_server._server import mcp++ transport = ASGITransport(app=mcp.sse_app())+ async with AsyncClient(transport=transport, base_url="http://127.0.0.1:7338") as c:+ # The SDK's own answer (no session id), not an auth refusal.+ assert (await c.post("/messages/", content=b"{}")).status_code == 400+ assert (await c.get("/.well-known/oauth-protected-resource")).status_code == 404+++async def test_mcp_key_requires_bearer_with_rfc9728_challenge(shared_key) -> None:+ gated = gate(_inner_app(), "/mcp")+ resp = await _get(gated, "/mcp")+ assert resp.status_code == 401+ challenge = resp.headers["www-authenticate"]+ assert challenge.startswith("Bearer ")+ url = "http://127.0.0.1:7338/.well-known/oauth-protected-resource/mcp"+ assert f'resource_metadata="{url}"' in challenge+ assert (await _get(gated, "/mcp", {"Authorization": "Bearer nope"})).status_code == 401+ ok = await _get(gated, "/mcp", {"Authorization": f"Bearer {KEY}"})+ assert ok.status_code == 200 and ok.text == "shared-key"+++async def test_mcp_gate_follows_config_per_request(tokens_file) -> None:+ gated = gate(_inner_app(), "/mcp")+ assert (await _get(gated, "/mcp")).text == "served"+ _write_tokens(tokens_file, {"id": "ci", "sha256": hash_token(SCOPED)})+ assert (await _get(gated, "/mcp")).status_code == 401+++async def test_mcp_sse_messages_carry_the_principal(tokens_file) -> None:+ _write_tokens(tokens_file, {"id": "ci", "sha256": hash_token(SCOPED), "tools": ["get_answer"]})+ gated = gate(_inner_app(), "/sse")+ headers = {"Authorization": f"Bearer {SCOPED}"}+ resp = await _get(gated, "/messages/", headers, method="POST")+ assert resp.status_code == 200 and resp.text == "token:ci"+ assert (await _get(gated, "/messages/", method="POST")).status_code == 401+++async def test_mcp_metadata_document(shared_key) -> None:+ gated = gate(_inner_app(), "/mcp")+ for path in (+ "/.well-known/oauth-protected-resource",+ "/.well-known/oauth-protected-resource/mcp",+ ):+ doc = (await _get(gated, path)).json()+ assert doc["resource"] == "http://127.0.0.1:7338/mcp"+ assert doc["bearer_methods_supported"] == ["header"]+ assert "authorization_servers" not in doc+++async def test_mcp_metadata_lists_plugged_in_authorization_server(shared_key) -> None:+ class OAuthBacked(auth.LocalAuthenticator):+ authorization_servers = ("https://idp.example.com",)++ auth.set_authenticator(OAuthBacked())+ try:+ gated = gate(_inner_app(), "/mcp")+ doc = (await _get(gated, "/.well-known/oauth-protected-resource")).json()+ finally:+ auth.set_authenticator(None)+ assert doc["authorization_servers"] == ["https://idp.example.com"]+++async def test_mcp_hostile_host_header_is_not_reflected(shared_key) -> None:+ gated = gate(_inner_app(), "/mcp")+ resp = await _get(gated, "/mcp", {"Host": 'evil"x, foo="bar'})+ challenge = resp.headers["www-authenticate"]+ assert "evil" not in challenge and challenge.count('"') == 6+ doc = (await _get(gated, "/.well-known/oauth-protected-resource", {"Host": 'a"b'})).json()+ assert '"' not in doc["resource"]+++async def test_mcp_public_url_wins(shared_key, monkeypatch) -> None:+ monkeypatch.setenv(_http_auth.PUBLIC_URL_ENV, "https://code.example.com/rw/")+ gated = gate(_inner_app(), "/mcp")+ challenge = (await _get(gated, "/mcp")).headers["www-authenticate"]+ url = "https://code.example.com/.well-known/oauth-protected-resource/rw/mcp"+ assert f'resource_metadata="{url}"' in challenge+ doc = (await _get(gated, "/.well-known/oauth-protected-resource")).json()+ assert doc["resource"] == "https://code.example.com/rw/mcp"+++async def test_mcp_under_a_sub_path_discovers_at_host_root(shared_key) -> None:+ host = Starlette(+ routes=[metadata_route("/sub/mcp"), Mount("/sub", app=gate(_inner_app(), "/mcp"))]+ )+ challenge = (await _get(host, "/sub/mcp")).headers["www-authenticate"]+ url = "http://127.0.0.1:7338/.well-known/oauth-protected-resource/sub/mcp"+ assert f'resource_metadata="{url}"' in challenge+ doc = (await _get(host, "/.well-known/oauth-protected-resource/sub/mcp")).json()+ assert doc["resource"] == "http://127.0.0.1:7338/sub/mcp"+ ok = await _get(host, "/sub/mcp", {"Authorization": f"Bearer {KEY}"})+ assert ok.text == "shared-key"+++async def test_mcp_real_transports_are_gated(shared_key) -> None:+ from repowise.server.mcp_server._server import mcp++ sse = mcp.sse_app()+ async with AsyncClient(transport=ASGITransport(app=sse), base_url="http://127.0.0.1:7338") as c:+ assert (await c.post("/messages/", content=b"{}")).status_code == 401+ headers = {"Authorization": f"Bearer {KEY}"}+ authed = await c.post("/messages/", content=b"{}", headers=headers)+ assert authed.status_code == 400 # past the gate, into the SDK+ assert isinstance(mcp.streamable_http_app(), _http_auth.BearerGate)+++async def test_token_verifier_round_trips_principal(tokens_file) -> None:+ _write_tokens(+ tokens_file,+ {"id": "ci", "sha256": hash_token(SCOPED), "repos": ["alpha"], "tools": ["get_answer"]},+ )+ access = await PrincipalTokenVerifier().verify_token(SCOPED)+ assert access is not None and access.client_id == "token:ci"+ assert access.scopes == ["tool:get_answer"]+ expected = await auth.get_authenticator().verify_token(SCOPED)+ assert principal_from_access_token(access) == expected+ assert await PrincipalTokenVerifier().verify_token("nope") is None+ unrestricted = principal_from_access_token(access_token_for(SHARED_KEY_PRINCIPAL, KEY))+ assert unrestricted.tool_scope is None and unrestricted.repo_scope is None+++def test_mcp_call_denial_tool_and_repo_scope(monkeypatch) -> None:+ monkeypatch.setattr(_state, "_registry", None)+ monkeypatch.setattr(_state, "_repo_path", "/work/alpha")+ monkeypatch.setattr(_state, "_served_repo_id", "id-alpha")+ p = Principal("token:ci", "token", frozenset({"alpha"}), frozenset({"get_answer"}))+ assert call_denial(p, "get_answer", {}) is None+ assert "Tool" in call_denial(p, "get_context", {})+ assert "Repository" in call_denial(p, "get_answer", {"repo": "beta"})+ assert "all" in call_denial(p, "get_answer", {"repo": "all"})+ assert call_denial(SHARED_KEY_PRINCIPAL, "get_context", {"repo": "beta"}) is None+++class _Workspace:+ workspace_root = Path(".")++ def get_all_aliases(self):+ return ["alpha", "beta"]++ def get_default_alias(self):+ return "alpha"++ def resolve_repo_param(self, repo):+ if repo is None:+ return "alpha"+ if repo == "all":+ return ["alpha", "beta"]+ if repo in ("alpha", "beta"):+ return repo+ raise ValueError(repo)+++def test_mcp_workspace_aliases_and_all_refused_outside_scope(monkeypatch) -> None:+ monkeypatch.setattr(_state, "_registry", _Workspace())+ p = Principal("token:ci", "token", frozenset({"alpha"}), None)+ assert call_denial(p, "get_answer", {"repo": "alpha"}) is None+ assert call_denial(p, "get_answer", {"repo": "beta"}) is not None+ assert call_denial(p, "get_answer", {"repo": "all"}) is not None+ assert call_denial(p, "get_answer", {"repo": "unknown"}) is not None+ assert call_denial(p, "list_repos", {}) is None+++async def test_mcp_list_repos_filters_to_scope(monkeypatch) -> None:+ from repowise.server.mcp_server import tool_repos++ monkeypatch.setattr(_state, "_registry", _Workspace())+ monkeypatch.setattr(+ tool_repos,+ "_workspace_repos",+ lambda _r: [+ {"alias": "alpha", "path": "alpha", "is_default": True},+ {"alias": "beta", "path": "beta", "is_default": False},+ ],+ )+ async def listed(scope):+ principal = Principal("token:ci", "token", frozenset(scope), None)+ reset = auth.current_principal.set(principal)+ try:+ return await tool_repos.list_repos()+ finally:+ auth.current_principal.reset(reset)++ beta_only = await listed({"beta"})+ assert [r["alias"] for r in beta_only["repos"]] == ["beta"]+ assert beta_only["default_repo"] is None+ alpha_only = await listed({"alpha"})+ assert alpha_only["default_repo"] == "alpha"+ nothing = await listed({"gamma"})+ assert nothing["repos"] == [] and nothing["default_repo"] is None+ unrestricted = await tool_repos.list_repos()+ assert len(unrestricted["repos"]) == 2 and unrestricted["default_repo"] == "alpha"+++async def test_mcp_list_repos_single_repo_respects_scope(monkeypatch) -> None:+ from repowise.server.mcp_server import tool_repos++ monkeypatch.setattr(_state, "_registry", None)+ monkeypatch.setattr(_state, "_repo_path", "/work/alpha")+ monkeypatch.setattr(_state, "_served_repo_id", "id-alpha")++ async def listed(principal):+ reset = auth.current_principal.set(principal)+ try:+ return await tool_repos.list_repos()+ finally:+ auth.current_principal.reset(reset)++ out_of_scope = await listed(Principal("token:ci", "token", frozenset({"beta"}), None))+ assert out_of_scope["repos"] == [] and out_of_scope["default_repo"] is None+ by_name = await listed(Principal("token:ci", "token", frozenset({"alpha"}), None))+ assert len(by_name["repos"]) == 1 and by_name["default_repo"] == "default"+ by_id = await listed(Principal("token:ci", "token", frozenset({"id-alpha"}), None))+ assert len(by_id["repos"]) == 1+ unrestricted = await tool_repos.list_repos()+ assert unrestricted["default_repo"] == "default" and len(unrestricted["repos"]) == 1+++# ---------------------------------------------------------------------------+# Tool-scoped tokens on REST and chat+# ---------------------------------------------------------------------------+++async def test_rest_refuses_tool_scoped_token_outside_chat(+ app, client, session_factory, tokens_file+) -> None:+ from repowise.server.routers import chat as chat_router++ app.include_router(chat_router.router)+ alpha = await _add_repo(session_factory, "alpha")+ _write_tokens(tokens_file, {"id": "ci", "sha256": hash_token(SCOPED), "tools": ["get_answer"]})+ headers = {"Authorization": f"Bearer {SCOPED}"}+ assert (await client.get("/api/repos", headers=headers)).status_code == 403+ assert (await client.get(f"/api/repos/{alpha}", headers=headers)).status_code == 403+ patched = await client.patch(f"/api/repos/{alpha}", json={"name": "x"}, headers=headers)+ assert patched.status_code == 403+ chat = await client.get(f"/api/repos/{alpha}/chat/conversations", headers=headers)+ assert chat.status_code == 200+++def _fake_entry(name: str, seen: dict):+ from types import SimpleNamespace++ async def fn(repo: str | None = None):+ seen["repo"] = repo+ seen["principal"] = auth.current_principal.get()+ return {"ok": True}++ return SimpleNamespace(name=name, safety="read_only", fn=fn)+++async def test_chat_execution_enforces_tool_scope_and_pins_repo() -> None:+ from repowise.server.chat_tools import execute_entry++ seen: dict = {}+ tools_only = Principal("token:t", "token", None, frozenset({"get_answer"}))+ refused = await execute_entry(_fake_entry("get_context", seen), {}, principal=tools_only)+ assert refused["error_code"] == "tool_not_in_scope" and not seen++ repo_scoped = Principal("token:r", "token", frozenset({"alpha"}), None)+ entry = _fake_entry("get_answer", seen)+ await execute_entry(entry, {"repo": "all"}, repo="alpha", principal=repo_scoped)+ assert seen["repo"] == "alpha" and seen["principal"] is repo_scoped+ await execute_entry(entry, {"repo": "beta"}, repo=None, principal=repo_scoped, repo_id="id-1")+ assert seen["repo"] == "id-1"+ # Unrestricted callers keep the model's choice, as before.+ await execute_entry(entry, {"repo": "beta"}, repo=None, principal=LOCAL_PRINCIPAL)+ assert seen["repo"] == "beta"+++def test_chat_catalog_follows_tool_scope() -> None:+ from repowise.server.chat_tools import get_tool_catalog, get_tool_schemas_for_llm++ full = {t.entry.name for t in get_tool_catalog(None)}+ assert "get_answer" in full and len(full) > 1+ tools_only = Principal("token:t", "token", None, frozenset({"get_answer"}))+ assert [t.entry.name for t in get_tool_catalog(None, tools_only)] == ["get_answer"]+ schemas = get_tool_schemas_for_llm(None, tools_only)+ assert [s["function"]["name"] for s in schemas] == ["get_answer"]+ assert {t.entry.name for t in get_tool_catalog(None, LOCAL_PRINCIPAL)} == full+++# ---------------------------------------------------------------------------+# Tokens file edge cases, objects outside the scope, job stream+# ---------------------------------------------------------------------------+++async def test_unknown_token_key_fails_closed(tokens_file, shared_key) -> None:+ _write_tokens(tokens_file, {"id": "ci", "sha256": hash_token(SCOPED), "repo": ["alpha"]})+ authn = auth.LocalAuthenticator()+ assert await authn.verify_token(SCOPED) is None+ assert await authn.verify_token(KEY) == SHARED_KEY_PRINCIPAL+++async def test_token_expiry(client, tokens_file) -> None:+ _write_tokens(+ tokens_file,+ {"id": "old", "sha256": hash_token("old-token"), "expires_at": "2020-01-01T00:00:00Z"},+ {"id": "new", "sha256": hash_token(SCOPED), "expires_at": "2999-01-01T00:00:00+00:00"},+ )+ old = {"Authorization": "Bearer old-token"}+ assert (await client.get("/api/repos", headers=old)).status_code == 401+ new = {"Authorization": f"Bearer {SCOPED}"}+ assert (await client.get("/api/repos", headers=new)).status_code == 200+ assert (await _get(gate(_inner_app(), "/mcp"), "/mcp", old)).status_code == 401+++async def test_unreadable_tokens_file_fails_closed(tokens_file, monkeypatch) -> None:+ real_stat = Path.stat++ def stat(self, *args, **kwargs):+ if self == tokens_file:+ raise PermissionError("denied")+ return real_stat(self, *args, **kwargs)++ monkeypatch.setattr(Path, "stat", stat)+ authn = auth.LocalAuthenticator()+ assert authn.configured()+ assert await authn.verify_token(SCOPED) is None+++async def test_non_ascii_bearer_is_401_not_500(client, shared_key) -> None:+ headers = {"Authorization": "Bearer café".encode("latin-1")}+ resp = await client.get("/api/repos", headers=headers)+ assert resp.status_code == 401+++async def test_page_lookup_outside_scope_is_404(client, session_factory, tokens_file) -> None:+ from repowise.core.persistence import crud++ alpha = await _add_repo(session_factory, "alpha")+ beta = await _add_repo(session_factory, "beta")+ async with session_factory() as session:+ await crud.upsert_page(+ session,+ page_id="file_page:b.py",+ repository_id=beta,+ page_type="file_page",+ title="b",+ content="b",+ target_path="b.py",+ source_hash="h",+ model_name="m",+ provider_name="p",+ )+ await session.commit()+ _write_tokens(+ tokens_file,+ {"id": "ci", "sha256": hash_token(SCOPED), "repos": ["alpha"]},+ {"id": "ops", "sha256": hash_token("ops-token")},+ )+ url = f"/api/pages/lookup?page_id=file_page:b.py&repo_id={alpha}"+ scoped = await client.get(url, headers={"Authorization": f"Bearer {SCOPED}"})+ assert scoped.status_code == 404+ # Unrestricted callers are unchanged.+ assert (await client.get(url, headers={"Authorization": "Bearer ops-token"})).status_code == 200+++async def test_job_stream_refuses_tool_scoped_bearer(client, session_factory, tokens_file) -> None:+ from repowise.core.persistence import crud++ alpha = await _add_repo(session_factory, "alpha")+ async with session_factory() as session:+ job = await crud.upsert_generation_job(+ session, repository_id=alpha, status="completed", config={}+ )+ await session.commit()+ job_id = job.id+ _write_tokens(+ tokens_file,+ {"id": "ci", "sha256": hash_token(SCOPED), "tools": ["get_answer"]},+ {"id": "ops", "sha256": hash_token("ops-token")},+ )+ url = f"/api/jobs/{job_id}/stream"+ refused = await client.get(url, headers={"Authorization": f"Bearer {SCOPED}"})+ assert refused.status_code == 401+ assert (await client.get(url, headers={"Authorization": "Bearer ops-token"})).status_code == 200+++# ---------------------------------------------------------------------------+# Seam registry+# ---------------------------------------------------------------------------+++def test_default_authenticator_and_authorizer_are_local(monkeypatch) -> None:+ monkeypatch.delenv("REPOWISE_SEAM_AUTHENTICATOR", raising=False)+ monkeypatch.delenv("REPOWISE_SEAM_AUTHORIZER", raising=False)+ assert auth.authenticators.default == "local"+ assert type(auth.get_authenticator()) is auth.LocalAuthenticator+ assert type(auth.get_authorizer()) is ScopeAuthorizer+++def test_plugin_authenticator_selected_by_env_var(tmp_path, monkeypatch) -> None:+ from repowise.core.registry import plugins++ (tmp_path / "acme_auth_plugin.py").write_text(+ "from repowise.server import auth\n"+ "class Acme(auth.LocalAuthenticator):\n"+ " authorization_servers = ('https://idp.acme.test',)\n"+ "def register():\n"+ " auth.authenticators.register('acme', Acme())\n",+ encoding="utf-8",+ )+ monkeypatch.syspath_prepend(str(tmp_path))+ monkeypatch.setenv("REPOWISE_PLUGINS", "acme_auth_plugin:register")+ plugins.reset()+ try:+ assert type(auth.get_authenticator()) is auth.LocalAuthenticator+ monkeypatch.setenv("REPOWISE_SEAM_AUTHENTICATOR", "acme")+ assert type(auth.get_authenticator()).__name__ == "Acme"+ monkeypatch.setenv("REPOWISE_SEAM_AUTHENTICATOR", "nope")+ with pytest.raises(KeyError, match="nope"):+ auth.get_authenticator()+ finally:+ monkeypatch.delenv("REPOWISE_SEAM_AUTHENTICATOR")+ plugins.reset()diff --git a/tests/unit/server/test_chat_router.py b/tests/unit/server/test_chat_router.pyindex a30ad14e1..d6232b043 100644--- a/tests/unit/server/test_chat_router.py+++ b/tests/unit/server/test_chat_router.py@@ -351,8 +351,15 @@ async def test_a_page_with_findings_gets_chips_that_name_them():texts = [entry["text"] for entry in body["suggestions"]]assert "Explain the 28 bug fixes in a.py" in textsassert all(entry["source"] == "page" for entry in body["suggestions"])+ from repowise.server.auth import LOCAL_PRINCIPAL+execute.assert_awaited_once_with(- "get_risk", {"targets": ["src/a.py"]}, repo_path="/tmp/repo", repo=None+ "get_risk",+ {"targets": ["src/a.py"]},+ repo_path="/tmp/repo",+ repo=None,+ principal=LOCAL_PRINCIPAL,+ repo_id="repo-1",)