feat(auth): single-admin password login (signed cookie) — gate tuning + Sources catalog, keep chat and document viewer public
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
"""Auth API — single-admin sign-in (phase 16; A10 revised 2026-08-22).
|
||||
|
||||
* ``POST /api/login`` — 204 + signed session cookie on success; 401
|
||||
``invalid password`` on any mismatch (constant-time, one generic
|
||||
message, no session set).
|
||||
* ``POST /api/logout`` — 204; clears the session and expires the cookie
|
||||
(idempotent for anonymous callers).
|
||||
* ``GET /api/whoami`` — ``{"authenticated": bool, "role":
|
||||
"admin"|"anonymous"}``; the single source of truth for all UI gating.
|
||||
|
||||
The public API otherwise stays stateless (A10): chat, the document
|
||||
content endpoint (soft rule — anonymous may open any document by direct
|
||||
URL), suggestions, and health never require the cookie.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
|
||||
from app.config import get_settings
|
||||
from app.core.auth import ADMIN_SESSION_KEY, check_password, sign_in, sign_out
|
||||
from app.schemas import LoginRequest, WhoamiResponse
|
||||
|
||||
router = APIRouter(tags=["auth"])
|
||||
|
||||
|
||||
@router.post("/login", status_code=204)
|
||||
def login(payload: LoginRequest, request: Request) -> Response:
|
||||
"""Sign in the single admin.
|
||||
|
||||
Success: 204 + the signed ``bor_session`` cookie (``same_site=lax``,
|
||||
12 h default lifetime). Failure: one generic 401 — the admin count is
|
||||
one, so there is nothing else to leak, and a wrong password must not
|
||||
set any session state.
|
||||
"""
|
||||
settings = get_settings()
|
||||
if check_password(payload.password, settings.admin_password):
|
||||
sign_in(request.session)
|
||||
return Response(status_code=204)
|
||||
raise HTTPException(status_code=401, detail="invalid password")
|
||||
|
||||
|
||||
@router.post("/logout", status_code=204)
|
||||
def logout(request: Request, response: Response) -> Response:
|
||||
"""Sign out: clear the session AND expire the browser cookie.
|
||||
|
||||
``sign_out`` empties the session dict (which the middleware does not
|
||||
re-persist — an empty session has nothing to sign), so this route also
|
||||
sends ``delete_cookie`` to make the browser drop the signed cookie
|
||||
right now. Idempotent: an anonymous logout is still a 204.
|
||||
"""
|
||||
sign_out(request.session)
|
||||
response.delete_cookie(get_settings().session_cookie, path="/")
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.get("/whoami", response_model=WhoamiResponse)
|
||||
def whoami(request: Request) -> WhoamiResponse:
|
||||
"""Who is the caller? Drives every UI gating decision (phase 16)."""
|
||||
authenticated = bool(request.session.get(ADMIN_SESSION_KEY))
|
||||
return WhoamiResponse(
|
||||
authenticated=authenticated,
|
||||
role="admin" if authenticated else "anonymous",
|
||||
)
|
||||
+15
-3
@@ -13,6 +13,7 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.auth import require_admin
|
||||
from app.db import get_db
|
||||
from app.models import Chunk, Document
|
||||
from app.schemas import DocContent, DocList, DocSummary
|
||||
@@ -28,11 +29,17 @@ def doc_format(path: str) -> str:
|
||||
|
||||
|
||||
@router.get("/docs", response_model=DocList)
|
||||
def list_documents(db: Session = Depends(get_db)) -> DocList: # noqa: B008
|
||||
def list_documents(
|
||||
db: Session = Depends(get_db), # noqa: B008
|
||||
_admin: None = Depends(require_admin), # noqa: B008
|
||||
) -> DocList:
|
||||
"""All indexed documents with per-document chunk counts.
|
||||
|
||||
An empty list means the knowledge base has not been imported yet —
|
||||
the Sources page renders its designed empty state in that case.
|
||||
Admin-only (phase 16 — the catalog is what the sign-in gates; the
|
||||
document viewer itself stays public, see below). Anonymous callers
|
||||
get 403 ``admin only`` and the Sources page renders its sign-in gate
|
||||
instead. An empty list means the knowledge base has not been imported
|
||||
yet — the Sources page renders its designed empty state in that case.
|
||||
"""
|
||||
rows = db.execute(
|
||||
select(
|
||||
@@ -71,6 +78,11 @@ def get_document_content(
|
||||
Stateless (A10) and database-only: unknown pairs — including traversal
|
||||
strings such as ``../../etc/passwd`` — are just non-existent rows and
|
||||
map to 404 ``{detail: "document not found"}``.
|
||||
|
||||
Deliberately PUBLIC for anonymous callers (phase 16 soft rule, owner
|
||||
decision 2026-08-22): the *catalog* (``GET /api/docs``) is what the
|
||||
sign-in gates, not the viewer — chat cites documents and anyone may
|
||||
open a cited document by direct URL.
|
||||
"""
|
||||
row = db.execute(
|
||||
select(Document, func.count(Chunk.id).label("chunks"))
|
||||
|
||||
+14
-6
@@ -1,11 +1,14 @@
|
||||
"""Steering notes API — tune how Brain answers (phase 15, story
|
||||
``steering-notes``).
|
||||
|
||||
Stateless CRUD under ``/api/steering`` (A10): notes are owner instructions
|
||||
stored in Postgres (``steering_notes``) and read into the system prompt of
|
||||
**every** chat turn as the ``<tuning>`` section (see
|
||||
:func:`app.rag.prompts.build_steering_section` and
|
||||
:func:`app.api.chat.chat`).
|
||||
Admin-only CRUD under ``/api/steering`` (phase 16, A10 revised): notes
|
||||
are owner instructions stored in Postgres (``steering_notes``) and read
|
||||
into the system prompt of **every** chat turn as the ``<tuning>`` section
|
||||
(see :func:`app.rag.prompts.build_steering_section` and
|
||||
:func:`app.api.chat.chat`). The whole router sits behind
|
||||
:func:`app.core.auth.require_admin` — anonymous callers get 403 on every
|
||||
steering route (the chat turn itself reads the table in-process and
|
||||
stays public).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,12 +18,17 @@ from fastapi import APIRouter, Depends, HTTPException, Response
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.auth import require_admin
|
||||
from app.db import get_db
|
||||
from app.models import SteeringNote
|
||||
from app.schemas import SteeringNote as SteeringNoteOut
|
||||
from app.schemas import SteeringNoteIn, SteeringNoteList
|
||||
|
||||
router = APIRouter(prefix="/steering", tags=["steering"])
|
||||
router = APIRouter(
|
||||
prefix="/steering",
|
||||
tags=["steering"],
|
||||
dependencies=[Depends(require_admin)], # phase 16: tuning is admin-only
|
||||
)
|
||||
|
||||
|
||||
def load_steering_notes(db: Session) -> list[str]:
|
||||
|
||||
Reference in New Issue
Block a user