Files
CIAgent/apps/api/app/api/v1/db_viewer.py
T
sakshamandClaude Sonnet 5 4ee38b6241 Add DB viewer access logging, account deletion, and forced password change
Logs a distinct db_viewer_accessed event (not just the earlier
session_created "requested" event) when an admin's browser actually
completes the hand-off into Adminer. Adds a password-confirmed
account-deletion box to Settings, relying on the existing ON DELETE
CASCADE foreign keys to clean up everything the account owns. Adds an
admin-only "require password change" flag that get_current_user
enforces server-side (403 on everything except /auth/me,
/auth/change-password, /auth/logout) - meant for handing a demo
account to someone with a known sample password.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-08-05 23:41:21 -04:00

147 lines
5.9 KiB
Python

"""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(
request: Request,
token: str = Query(...),
settings: Settings = Depends(get_settings),
db: AsyncSession = Depends(get_db),
) -> 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
# Logged here, not at /session mint time, because this is the point the
# admin's browser actually completes the hand-off into Adminer - minting
# a token only proves they clicked the button, not that they got in.
await UserSecurityEventRepository(db).create(
user_id=decoded.user_id,
event_type=SecurityEventType.DB_VIEWER_ACCESSED,
ip_address=get_client_ip(request, settings),
)
await db.commit()
session_token = create_db_viewer_session_token(decoded.user_id, settings)
# Adminer's own driver dropdown defaults to MySQL, not Postgres - a bare
# "/" redirect leaves it selecting MySQL against a host that only speaks
# Postgres, producing a "Connection refused" error that has nothing to
# do with this app's own auth. `?pgsql=postgres` pre-selects the right
# driver and server (the internal Compose service name, same in dev and
# prod) - only the Postgres password itself is left for the admin to type.
response = RedirectResponse(url="/?pgsql=postgres", 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)