Add Settings -> Database viewer (Adminer) for local devs and any admin
Local dev gets an unauthenticated Adminer instance bound to loopback only. In production, any account with is_admin=true can open it - the app mints a short-lived token from a live admin session, which Nginx's new db.ciagent.org block exchanges for a session cookie that re-checks admin status on every request, instead of a shared static password that wouldn't scale to multiple admins or revoke live. Co-Authored-By: Claude Sonnet 5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
"""Settings -> Database viewer: lets any admin open a web-based Postgres
|
||||
client (Adminer, at db.<domain>) without a separate, shared credential.
|
||||
|
||||
The app's own JWT lives only in the browser's localStorage
|
||||
(apps/web/lib/api-client.ts) - never a cookie, never sent on a plain
|
||||
cross-subdomain navigation - so it can't gate a link to a different
|
||||
subdomain the way an in-app API call is gated. Instead: an admin mints a
|
||||
short-lived DB_VIEWER_BOOTSTRAP token from their real (live-checked) admin
|
||||
session; Nginx's db.<domain> /_auth route exchanges that, one-time, for a
|
||||
longer-lived DB_VIEWER_SESSION cookie scoped to that subdomain; Nginx's
|
||||
`auth_request` then re-validates that cookie - including a fresh `is_admin`
|
||||
check against the database - on every subsequent request. See
|
||||
infrastructure/nginx/nginx.conf's db.<domain> server block and
|
||||
DEPLOYMENT.md.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status
|
||||
from fastapi.responses import RedirectResponse
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.auth.dependencies import require_admin
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.core.security import (
|
||||
InvalidTokenError,
|
||||
TokenType,
|
||||
create_db_viewer_bootstrap_token,
|
||||
create_db_viewer_session_token,
|
||||
decode_token,
|
||||
get_client_ip,
|
||||
)
|
||||
from app.db.session import get_db
|
||||
from app.models.enums import SecurityEventType
|
||||
from app.models.user import User
|
||||
from app.repositories.user_repository import UserRepository
|
||||
from app.repositories.user_security_event_repository import UserSecurityEventRepository
|
||||
|
||||
router = APIRouter(prefix="/db-viewer", tags=["db-viewer"])
|
||||
|
||||
SESSION_COOKIE_NAME = "db_viewer_session"
|
||||
|
||||
|
||||
class DbViewerSessionResponse(BaseModel):
|
||||
token: str
|
||||
|
||||
|
||||
@router.post("/session", response_model=DbViewerSessionResponse)
|
||||
async def create_db_viewer_session(
|
||||
request: Request,
|
||||
settings: Settings = Depends(get_settings),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
) -> DbViewerSessionResponse:
|
||||
"""Mints a 2-minute bootstrap token the frontend embeds in a link to
|
||||
https://<db-viewer-host>/_auth?token=... - Nginx proxies that path
|
||||
straight to `bootstrap` below, which exchanges it for a session cookie."""
|
||||
token = create_db_viewer_bootstrap_token(admin.id, settings)
|
||||
await UserSecurityEventRepository(db).create(
|
||||
user_id=admin.id,
|
||||
event_type=SecurityEventType.DB_VIEWER_SESSION_CREATED,
|
||||
ip_address=get_client_ip(request, settings),
|
||||
)
|
||||
await db.commit()
|
||||
return DbViewerSessionResponse(token=token)
|
||||
|
||||
|
||||
@router.get("/bootstrap")
|
||||
async def bootstrap_db_viewer_session(
|
||||
token: str = Query(...),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> RedirectResponse:
|
||||
"""Reached only via Nginx's db.<domain> /_auth location - never called
|
||||
directly by the frontend. No `require_admin` dependency: the bootstrap
|
||||
token itself, freshly minted by `create_db_viewer_session` above, is the
|
||||
credential here."""
|
||||
try:
|
||||
decoded = decode_token(token, settings, TokenType.DB_VIEWER_BOOTSTRAP)
|
||||
except InvalidTokenError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="Invalid or expired token"
|
||||
) from exc
|
||||
|
||||
session_token = create_db_viewer_session_token(decoded.user_id, settings)
|
||||
response = RedirectResponse(url="/", status_code=status.HTTP_302_FOUND)
|
||||
response.set_cookie(
|
||||
SESSION_COOKIE_NAME,
|
||||
session_token,
|
||||
max_age=60 * 60,
|
||||
httponly=True,
|
||||
secure=True,
|
||||
samesite="lax",
|
||||
# No `domain=` - defaults to the exact host (db.<domain>), not
|
||||
# shared with ciagent.org/api.ciagent.org/git.ciagent.org.
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/verify")
|
||||
async def verify_db_viewer_session(
|
||||
request: Request,
|
||||
settings: Settings = Depends(get_settings),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> Response:
|
||||
"""Reached only via Nginx's `auth_request` subrequest (internal `/_verify`
|
||||
location) - carries just the forwarded Cookie header, no Authorization.
|
||||
Re-checks `is_admin` fresh from the database on every call, not just at
|
||||
token-mint time, so revoking an admin takes effect on their very next
|
||||
request here - same live-check behavior as `require_admin` elsewhere."""
|
||||
token = request.cookies.get(SESSION_COOKIE_NAME)
|
||||
if token is None:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="No session")
|
||||
|
||||
try:
|
||||
decoded = decode_token(token, settings, TokenType.DB_VIEWER_SESSION)
|
||||
except InvalidTokenError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or expired session"
|
||||
) from exc
|
||||
|
||||
user = await UserRepository(db).get_by_id(decoded.user_id)
|
||||
if user is None or not user.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Admin privileges required"
|
||||
)
|
||||
|
||||
return Response(status_code=status.HTTP_200_OK)
|
||||
@@ -11,6 +11,7 @@ from app.api.v1 import (
|
||||
auth,
|
||||
companies,
|
||||
dashboard,
|
||||
db_viewer,
|
||||
monitoring,
|
||||
notification_destinations,
|
||||
reports,
|
||||
@@ -24,6 +25,7 @@ api_v1_router = APIRouter(prefix="/api/v1")
|
||||
api_v1_router.include_router(system.router)
|
||||
api_v1_router.include_router(auth.router)
|
||||
api_v1_router.include_router(admin.router)
|
||||
api_v1_router.include_router(db_viewer.router)
|
||||
api_v1_router.include_router(user_api_keys.router)
|
||||
api_v1_router.include_router(companies.router)
|
||||
api_v1_router.include_router(notification_destinations.router)
|
||||
|
||||
@@ -75,6 +75,11 @@ def verify_password(raw_password: str, password_hash: str) -> bool:
|
||||
class TokenType(StrEnum):
|
||||
ACCESS = "access"
|
||||
REFRESH = "refresh"
|
||||
# Settings -> Database viewer: a short-lived token minted from a live
|
||||
# admin session, exchanged (via Nginx's db.ciagent.org /_auth route) for
|
||||
# a longer-lived DB_VIEWER_SESSION cookie. See app/api/v1/db_viewer.py.
|
||||
DB_VIEWER_BOOTSTRAP = "db_viewer_bootstrap"
|
||||
DB_VIEWER_SESSION = "db_viewer_session"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -105,6 +110,14 @@ def create_refresh_token(user_id: uuid.UUID, settings: Settings) -> tuple[str, s
|
||||
return token, jti, expires_at
|
||||
|
||||
|
||||
def create_db_viewer_bootstrap_token(user_id: uuid.UUID, settings: Settings) -> str:
|
||||
return _encode_token(user_id, TokenType.DB_VIEWER_BOOTSTRAP, timedelta(minutes=2), settings)
|
||||
|
||||
|
||||
def create_db_viewer_session_token(user_id: uuid.UUID, settings: Settings) -> str:
|
||||
return _encode_token(user_id, TokenType.DB_VIEWER_SESSION, timedelta(minutes=60), settings)
|
||||
|
||||
|
||||
def _encode_token(
|
||||
user_id: uuid.UUID,
|
||||
token_type: TokenType,
|
||||
|
||||
@@ -153,6 +153,7 @@ class SecurityEventType(StrEnum):
|
||||
EMAIL_VERIFIED = "email_verified"
|
||||
SERVER_SECRET_UPDATED = "server_secret_updated"
|
||||
API_KEY_UPDATED = "api_key_updated"
|
||||
DB_VIEWER_SESSION_CREATED = "db_viewer_session_created"
|
||||
|
||||
|
||||
class ApiKeyProvider(StrEnum):
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
"""Settings -> Database viewer: mint (admin-gated) -> bootstrap (token ->
|
||||
session cookie) -> verify (cookie -> live is_admin check) round trip.
|
||||
|
||||
Cookies are extracted from Set-Cookie headers and passed explicitly on
|
||||
follow-up requests rather than relying on TestClient's cookie jar - the
|
||||
session cookie is marked Secure, and TestClient's base_url is plain http,
|
||||
so a real cookie jar wouldn't resend it anyway."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import jwt
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import get_settings
|
||||
from app.repositories.user_repository import UserRepository
|
||||
|
||||
|
||||
def _unique_email() -> str:
|
||||
return f"user-{uuid.uuid4().hex[:12]}@example.com"
|
||||
|
||||
|
||||
async def _register_admin_and_login(client: TestClient, db_session: AsyncSession) -> dict[str, str]:
|
||||
email = f"admin-{uuid.uuid4().hex[:12]}@example.com"
|
||||
client.post(
|
||||
"/api/v1/auth/register",
|
||||
json={"email": email, "password": "correct-horse-1", "display_name": "Admin"},
|
||||
)
|
||||
user = await UserRepository(db_session).get_by_email(email)
|
||||
user.is_admin = True
|
||||
await db_session.commit()
|
||||
tokens = client.post(
|
||||
"/api/v1/auth/login", json={"email": email, "password": "correct-horse-1"}
|
||||
).json()
|
||||
return {"Authorization": f"Bearer {tokens['access_token']}"}
|
||||
|
||||
|
||||
async def _register_non_admin_and_login(client: TestClient) -> dict[str, str]:
|
||||
email = _unique_email()
|
||||
client.post(
|
||||
"/api/v1/auth/register",
|
||||
json={"email": email, "password": "correct-horse-1", "display_name": "T"},
|
||||
)
|
||||
tokens = client.post(
|
||||
"/api/v1/auth/login", json={"email": email, "password": "correct-horse-1"}
|
||||
).json()
|
||||
return {"Authorization": f"Bearer {tokens['access_token']}"}
|
||||
|
||||
|
||||
def _extract_cookie(set_cookie_header: str) -> tuple[str, str]:
|
||||
first_pair = set_cookie_header.split(";", 1)[0]
|
||||
name, value = first_pair.split("=", 1)
|
||||
return name, value
|
||||
|
||||
|
||||
# --- /db-viewer/session (mint) --------------------------------------------
|
||||
|
||||
|
||||
def test_create_session_requires_auth(client: TestClient):
|
||||
resp = client.post("/api/v1/db-viewer/session")
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
async def test_create_session_non_admin_forbidden(client: TestClient):
|
||||
headers = await _register_non_admin_and_login(client)
|
||||
resp = client.post("/api/v1/db-viewer/session", headers=headers)
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
async def test_admin_can_mint_a_bootstrap_token(client: TestClient, db_session: AsyncSession):
|
||||
headers = await _register_admin_and_login(client, db_session)
|
||||
resp = client.post("/api/v1/db-viewer/session", headers=headers)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["token"]
|
||||
|
||||
|
||||
async def test_minting_a_session_is_logged_to_the_admins_account_activity(
|
||||
client: TestClient, db_session: AsyncSession
|
||||
):
|
||||
headers = await _register_admin_and_login(client, db_session)
|
||||
client.post("/api/v1/db-viewer/session", headers=headers)
|
||||
|
||||
events = client.get("/api/v1/auth/security-events", headers=headers).json()
|
||||
assert any(e["event_type"] == "db_viewer_session_created" for e in events)
|
||||
|
||||
|
||||
# --- /db-viewer/bootstrap (token -> cookie) -------------------------------
|
||||
|
||||
|
||||
async def test_bootstrap_with_a_valid_token_sets_a_session_cookie_and_redirects(
|
||||
client: TestClient, db_session: AsyncSession
|
||||
):
|
||||
headers = await _register_admin_and_login(client, db_session)
|
||||
token = client.post("/api/v1/db-viewer/session", headers=headers).json()["token"]
|
||||
|
||||
resp = client.get(
|
||||
"/api/v1/db-viewer/bootstrap", params={"token": token}, follow_redirects=False
|
||||
)
|
||||
assert resp.status_code == 302
|
||||
assert resp.headers["location"] == "/"
|
||||
assert "db_viewer_session" in resp.headers["set-cookie"]
|
||||
assert "HttpOnly" in resp.headers["set-cookie"]
|
||||
assert "Secure" in resp.headers["set-cookie"]
|
||||
|
||||
|
||||
def test_bootstrap_rejects_a_garbage_token(client: TestClient):
|
||||
resp = client.get(
|
||||
"/api/v1/db-viewer/bootstrap", params={"token": "not-a-real-token"}, follow_redirects=False
|
||||
)
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
def test_bootstrap_rejects_an_expired_token(client: TestClient):
|
||||
settings = get_settings()
|
||||
now = datetime.now(UTC)
|
||||
expired_token = jwt.encode(
|
||||
{
|
||||
"sub": str(uuid.uuid4()),
|
||||
"type": "db_viewer_bootstrap",
|
||||
"iat": now - timedelta(minutes=10),
|
||||
"exp": now - timedelta(minutes=5),
|
||||
"jti": "x",
|
||||
},
|
||||
settings.jwt_secret,
|
||||
algorithm="HS256",
|
||||
)
|
||||
resp = client.get(
|
||||
"/api/v1/db-viewer/bootstrap", params={"token": expired_token}, follow_redirects=False
|
||||
)
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
def test_bootstrap_rejects_a_session_type_token_used_as_a_bootstrap_token(client: TestClient):
|
||||
"""Type confusion guard: a DB_VIEWER_SESSION token must not work as a
|
||||
DB_VIEWER_BOOTSTRAP token, even though both are signed with the same
|
||||
jwt_secret."""
|
||||
settings = get_settings()
|
||||
now = datetime.now(UTC)
|
||||
session_typed_token = jwt.encode(
|
||||
{
|
||||
"sub": str(uuid.uuid4()),
|
||||
"type": "db_viewer_session",
|
||||
"iat": now,
|
||||
"exp": now + timedelta(minutes=2),
|
||||
"jti": "x",
|
||||
},
|
||||
settings.jwt_secret,
|
||||
algorithm="HS256",
|
||||
)
|
||||
resp = client.get(
|
||||
"/api/v1/db-viewer/bootstrap",
|
||||
params={"token": session_typed_token},
|
||||
follow_redirects=False,
|
||||
)
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
# --- /db-viewer/verify (cookie -> live is_admin check) --------------------
|
||||
|
||||
|
||||
async def test_verify_succeeds_for_a_live_admin_with_a_valid_session_cookie(
|
||||
client: TestClient, db_session: AsyncSession
|
||||
):
|
||||
headers = await _register_admin_and_login(client, db_session)
|
||||
token = client.post("/api/v1/db-viewer/session", headers=headers).json()["token"]
|
||||
bootstrap_resp = client.get(
|
||||
"/api/v1/db-viewer/bootstrap", params={"token": token}, follow_redirects=False
|
||||
)
|
||||
cookie_name, cookie_value = _extract_cookie(bootstrap_resp.headers["set-cookie"])
|
||||
|
||||
verify_resp = client.get("/api/v1/db-viewer/verify", cookies={cookie_name: cookie_value})
|
||||
assert verify_resp.status_code == 200
|
||||
|
||||
|
||||
def test_verify_rejects_a_missing_cookie(client: TestClient):
|
||||
resp = client.get("/api/v1/db-viewer/verify")
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
async def test_verify_rejects_a_session_cookie_once_admin_is_revoked(
|
||||
client: TestClient, db_session: AsyncSession
|
||||
):
|
||||
headers = await _register_admin_and_login(client, db_session)
|
||||
token = client.post("/api/v1/db-viewer/session", headers=headers).json()["token"]
|
||||
bootstrap_resp = client.get(
|
||||
"/api/v1/db-viewer/bootstrap", params={"token": token}, follow_redirects=False
|
||||
)
|
||||
cookie_name, cookie_value = _extract_cookie(bootstrap_resp.headers["set-cookie"])
|
||||
|
||||
# Sanity: still works before revocation.
|
||||
assert (
|
||||
client.get("/api/v1/db-viewer/verify", cookies={cookie_name: cookie_value}).status_code
|
||||
== 200
|
||||
)
|
||||
|
||||
admin_email_resp = client.get("/api/v1/auth/me", headers=headers)
|
||||
admin = await UserRepository(db_session).get_by_email(admin_email_resp.json()["email"])
|
||||
admin.is_admin = False
|
||||
await db_session.commit()
|
||||
|
||||
assert (
|
||||
client.get("/api/v1/db-viewer/verify", cookies={cookie_name: cookie_value}).status_code
|
||||
== 401
|
||||
)
|
||||
Reference in New Issue
Block a user