Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(auth): reject implicit root fallback on tenant APIs (#716)

AstroHane4a5f4f2db2d
diff --git a/openviking/server/auth.py b/openviking/server/auth.py
index 06aad25e8..0abd7117e 100644
--- a/openviking/server/auth.py
+++ b/openviking/server/auth.py
@@ -7,9 +7,37 @@ from typing import Optional
from fastapi import Depends, Header, Request
from openviking.server.identity import RequestContext, ResolvedIdentity, Role
-from openviking_cli.exceptions import PermissionDeniedError, UnauthenticatedError
+from openviking_cli.exceptions import (
+ InvalidArgumentError,
+ PermissionDeniedError,
+ UnauthenticatedError,
+)
from openviking_cli.session.user_id import UserIdentifier
+_ROOT_IMPLICIT_TENANT_ALLOWED_PATHS = {
+ "/api/v1/system/status",
+ "/api/v1/system/wait",
+ "/api/v1/debug/health",
+}
+_ROOT_IMPLICIT_TENANT_ALLOWED_PREFIXES = (
+ "/api/v1/admin",
+ "/api/v1/observer",
+)
+
+
+def _root_request_requires_explicit_tenant(path: str) -> bool:
+ """Return True when a ROOT request targets tenant-scoped data APIs.
+
+ Root still needs access to admin and monitoring endpoints without a tenant
+ context. For data APIs, implicit fallback to default/default is misleading,
+ so callers must provide explicit account and user headers.
+ """
+ if path in _ROOT_IMPLICIT_TENANT_ALLOWED_PATHS:
+ return False
+ if path.startswith(_ROOT_IMPLICIT_TENANT_ALLOWED_PREFIXES):
+ return False
+ return True
+
async def resolve_identity(
request: Request,
@@ -53,9 +81,25 @@ async def resolve_identity(
async def get_request_context(
+ request: Request,
identity: ResolvedIdentity = Depends(resolve_identity),
) -> RequestContext:
"""Convert ResolvedIdentity to RequestContext."""
+ path = request.url.path
+ api_key_manager = getattr(request.app.state, "api_key_manager", None)
+ if (
+ api_key_manager is not None
+ and identity.role == Role.ROOT
+ and _root_request_requires_explicit_tenant(path)
+ ):
+ account_header = request.headers.get("X-OpenViking-Account")
+ user_header = request.headers.get("X-OpenViking-User")
+ if not account_header or not user_header:
+ raise InvalidArgumentError(
+ "ROOT requests to tenant-scoped APIs must include X-OpenViking-Account "
+ "and X-OpenViking-User headers. Use a user key for regular data access."
+ )
+
return RequestContext(
user=UserIdentifier(
identity.account_id or "default",
diff --git a/tests/server/test_auth.py b/tests/server/test_auth.py
index 70dbc6e8f..559131225 100644
--- a/tests/server/test_auth.py
+++ b/tests/server/test_auth.py
@@ -8,11 +8,19 @@ import uuid
import httpx
import pytest
import pytest_asyncio
+from fastapi import Depends, FastAPI
+from fastapi import Request as FastAPIRequest
+from fastapi.responses import JSONResponse
+from starlette.requests import Request
from openviking.server.app import create_app
+from openviking.server.auth import get_request_context, resolve_identity
from openviking.server.config import ServerConfig, _is_localhost, validate_server_config
from openviking.server.dependencies import set_service
+from openviking.server.identity import ResolvedIdentity, Role
+from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Response
from openviking.service.core import OpenVikingService
+from openviking_cli.exceptions import InvalidArgumentError, OpenVikingError
from openviking_cli.session.user_id import UserIdentifier
@@ -23,6 +31,93 @@ def _uid() -> str:
ROOT_KEY = "root-secret-key-for-testing-only-1234567890abcdef"
+def _make_request(
+ path: str,
+ headers: dict[str, str] | None = None,
+ auth_enabled: bool = True,
+) -> Request:
+ """Create a minimal Starlette request for auth dependency tests."""
+ raw_headers = []
+ for key, value in (headers or {}).items():
+ raw_headers.append((key.lower().encode("latin-1"), value.encode("latin-1")))
+ app = FastAPI()
+ if auth_enabled:
+ # Non-empty api_key_manager means the server is in authenticated mode.
+ app.state.api_key_manager = object()
+ scope = {
+ "type": "http",
+ "path": path,
+ "headers": raw_headers,
+ "app": app,
+ }
+ return Request(scope)
+
+
+def _build_auth_http_test_app(
+ identity: ResolvedIdentity,
+ auth_enabled: bool = True,
+) -> FastAPI:
+ """Create a lightweight app that exercises auth dependency wiring.
+
+ The full server fixture depends on AGFS native libraries. This helper keeps
+ the test focused on request auth behavior and the structured HTTP error body.
+ """
+ app = FastAPI()
+ if auth_enabled:
+ # Match production auth mode so get_request_context enters the guard path.
+ app.state.api_key_manager = object()
+
+ @app.exception_handler(OpenVikingError)
+ async def openviking_error_handler(request: FastAPIRequest, exc: OpenVikingError):
+ """Mirror the server's JSON error envelope for auth failures."""
+ http_status = ERROR_CODE_TO_HTTP_STATUS.get(exc.code, 500)
+ return JSONResponse(
+ status_code=http_status,
+ content=Response(
+ status="error",
+ error=ErrorInfo(
+ code=exc.code,
+ message=exc.message,
+ details=exc.details,
+ ),
+ ).model_dump(),
+ )
+
+ async def _resolve_identity_override() -> ResolvedIdentity:
+ """Return a fixed identity so tests can isolate request header behavior."""
+ return identity
+
+ app.dependency_overrides[resolve_identity] = _resolve_identity_override
+
+ @app.get("/api/v1/fs/ls")
+ async def fs_ls(ctx=Depends(get_request_context)):
+ """Expose a tenant-scoped route for auth regression tests."""
+ return {
+ "status": "ok",
+ "result": {
+ "account_id": ctx.user.account_id,
+ "user_id": ctx.user.user_id,
+ },
+ }
+
+ @app.get("/api/v1/observer/system")
+ async def observer_system(ctx=Depends(get_request_context)):
+ """Expose a monitoring route that should keep implicit ROOT behavior."""
+ return {"status": "ok", "result": {"role": ctx.role.value}}
+
+ @app.post("/api/v1/system/wait")
+ async def system_wait(ctx=Depends(get_request_context)):
+ """Expose a non-tenant system route for auth regression tests."""
+ return {"status": "ok", "result": {"role": ctx.role.value}}
+
+ @app.get("/api/v1/debug/vector/scroll")
+ async def debug_vector_scroll(ctx=Depends(get_request_context)):
+ """Expose a tenant-scoped debug route for auth regression tests."""
+ return {"status": "ok", "result": {"role": ctx.role.value}}
+
+ return app
+
+
@pytest_asyncio.fixture(scope="function")
async def auth_service(temp_dir):
"""Service for auth tests."""
@@ -138,21 +233,38 @@ async def test_dev_mode_no_auth(client: httpx.AsyncClient):
async def test_auth_on_multiple_endpoints(auth_client: httpx.AsyncClient):
- """Multiple protected endpoints should require auth."""
+ """Protected endpoints should require auth before any role-specific checks."""
endpoints = [
("GET", "/api/v1/system/status"),
- ("GET", "/api/v1/fs/ls?uri=viking://"),
("GET", "/api/v1/observer/system"),
("GET", "/api/v1/debug/health"),
+ ("GET", "/api/v1/fs/ls?uri=viking://"),
]
for method, url in endpoints:
resp = await auth_client.request(method, url)
assert resp.status_code == 401, f"{method} {url} should require auth"
- for method, url in endpoints:
+ for method, url in endpoints[:3]:
resp = await auth_client.request(method, url, headers={"X-API-Key": ROOT_KEY})
assert resp.status_code == 200, f"{method} {url} should succeed with root key"
+ tenant_resp = await auth_client.get(
+ "/api/v1/fs/ls?uri=viking://",
+ headers={"X-API-Key": ROOT_KEY},
+ )
+ assert tenant_resp.status_code == 400
+ assert tenant_resp.json()["error"]["code"] == "INVALID_ARGUMENT"
+
+ tenant_resp = await auth_client.get(
+ "/api/v1/fs/ls?uri=viking://",
+ headers={
+ "X-API-Key": ROOT_KEY,
+ "X-OpenViking-Account": "default",
+ "X-OpenViking-User": "default",
+ },
+ )
+ assert tenant_resp.status_code == 200
+
# ---- Role-based access tests ----
@@ -209,6 +321,165 @@ async def test_cross_tenant_session_get_returns_not_found(auth_client: httpx.Asy
assert cross_get.json()["error"]["code"] == "NOT_FOUND"
+async def test_root_tenant_scoped_requests_require_explicit_identity():
+ """ROOT must specify account/user headers on tenant-scoped APIs."""
+ request = _make_request("/api/v1/resources", auth_enabled=True)
+ identity = ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default")
+
+ with pytest.raises(InvalidArgumentError, match="X-OpenViking-Account"):
+ await get_request_context(request, identity)
+
+
+async def test_root_system_status_allows_implicit_default_identity():
+ """ROOT may call status endpoints without explicit tenant headers."""
+ request = _make_request("/api/v1/system/status", auth_enabled=True)
+ identity = ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default")
+
+ ctx = await get_request_context(request, identity)
+
+ assert ctx.role == Role.ROOT
+ assert ctx.user.account_id == "default"
+ assert ctx.user.user_id == "default"
+
+
+async def test_root_tenant_scoped_requests_allow_explicit_identity():
+ """ROOT can access tenant-scoped APIs when account/user headers are present."""
+ request = _make_request(
+ "/api/v1/resources",
+ headers={
+ "X-OpenViking-Account": "acme",
+ "X-OpenViking-User": "alice",
+ },
+ auth_enabled=True,
+ )
+ identity = ResolvedIdentity(role=Role.ROOT, account_id="acme", user_id="alice")
+
+ ctx = await get_request_context(request, identity)
+
+ assert ctx.role == Role.ROOT
+ assert ctx.user.account_id == "acme"
+ assert ctx.user.user_id == "alice"
+
+
+async def test_root_monitoring_requests_allow_implicit_default_identity():
+ """Observer/debug endpoints keep the existing ROOT monitoring flow."""
+ observer_request = _make_request("/api/v1/observer/system", auth_enabled=True)
+ debug_request = _make_request("/api/v1/debug/health", auth_enabled=True)
+ identity = ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default")
+
+ observer_ctx = await get_request_context(observer_request, identity)
+ debug_ctx = await get_request_context(debug_request, identity)
+
+ assert observer_ctx.role == Role.ROOT
+ assert debug_ctx.role == Role.ROOT
+
+
+async def test_root_system_wait_allows_implicit_default_identity():
+ """ROOT may call system wait without explicit tenant headers."""
+ request = _make_request("/api/v1/system/wait", auth_enabled=True)
+ identity = ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default")
+
+ ctx = await get_request_context(request, identity)
+
+ assert ctx.role == Role.ROOT
+
+
+async def test_root_debug_vector_requests_require_explicit_identity():
+ """Tenant-scoped debug routes must not bypass explicit tenant checks."""
+ request = _make_request("/api/v1/debug/vector/scroll", auth_enabled=True)
+ identity = ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default")
+
+ with pytest.raises(InvalidArgumentError, match="X-OpenViking-Account"):
+ await get_request_context(request, identity)
+
+
+async def test_dev_mode_root_tenant_scoped_requests_allow_implicit_identity():
+ """Dev mode should keep the existing implicit ROOT/default behavior."""
+ request = _make_request("/api/v1/resources", auth_enabled=False)
+ identity = ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default")
+
+ ctx = await get_request_context(request, identity)
+
+ assert ctx.role == Role.ROOT
+ assert ctx.user.account_id == "default"
+ assert ctx.user.user_id == "default"
+
+
+async def test_root_tenant_scoped_requests_return_structured_400_via_http():
+ """Tenant-scoped HTTP routes should reject implicit ROOT tenant fallback."""
+ app = _build_auth_http_test_app(
+ ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default"),
+ auth_enabled=True,
+ )
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.get("/api/v1/fs/ls")
+
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "INVALID_ARGUMENT"
+
+
+async def test_root_monitoring_requests_keep_200_via_http():
+ """Monitoring HTTP routes should still work with implicit ROOT identity."""
+ app = _build_auth_http_test_app(
+ ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default"),
+ auth_enabled=True,
+ )
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.get("/api/v1/observer/system")
+
+ assert response.status_code == 200
+ assert response.json()["status"] == "ok"
+
+
+async def test_root_system_wait_keeps_200_via_http():
+ """System wait should keep working for ROOT without tenant headers."""
+ app = _build_auth_http_test_app(
+ ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default"),
+ auth_enabled=True,
+ )
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.post("/api/v1/system/wait")
+
+ assert response.status_code == 200
+ assert response.json()["status"] == "ok"
+
+
+async def test_root_debug_vector_requests_return_structured_400_via_http():
+ """Tenant-scoped debug routes should reject implicit ROOT tenant fallback."""
+ app = _build_auth_http_test_app(
+ ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default"),
+ auth_enabled=True,
+ )
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.get("/api/v1/debug/vector/scroll")
+
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "INVALID_ARGUMENT"
+
+
+async def test_dev_mode_root_tenant_scoped_requests_keep_200_via_http():
+ """Dev mode HTTP routes should keep the existing implicit ROOT/default behavior."""
+ app = _build_auth_http_test_app(
+ ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default"),
+ auth_enabled=False,
+ )
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.get("/api/v1/fs/ls")
+
+ assert response.status_code == 200
+ assert response.json()["status"] == "ok"
+
+
# ---- _is_localhost tests ----