From 4eab5337d70b3829b92ecaa001b7734a2ca5f48f Mon Sep 17 00:00:00 2001 From: Natalie Boedecker Date: Sun, 1 Nov 2026 01:07:50 -0400 Subject: [PATCH 1/3] feat: build the web interface foundation Add server-rendered pages for Phase 3, starting with sign-in and a searchable, paged works list, built as a thin layer over the existing service functions so it can't do anything the API can't. - Add cookie-based web sessions, stored by hash, with a 14-day lifetime and a synchronizer CSRF token per session. - Use a double-submit cookie for the sign-in form itself, since it runs before a session exists. - Split accounts.login into sign_in and issue_login_token so the UI can authenticate without issuing a bearer token. - Add Jinja2 templates, static assets, and security headers (CSP, no-sniff, no-store) for all non-API routes. - Add a @ui_route decorator and parity tests that confirm each page declares and calls the same service function as its matching API operation. Assisted-by: Claude Code Signed-off-by: Natalie Boedecker --- AGENTS.md | 3 +- CHANGELOG.md | 1 + docs/design/architecture.md | 2 +- docs/getting-started.md | 8 +- migrations/versions/0002_add_web_sessions.py | 35 ++ pyproject.toml | 4 +- src/librelibrary/api/v1/accounts.py | 7 +- src/librelibrary/app.py | 90 ++++- src/librelibrary/models/__init__.py | 2 + src/librelibrary/models/system.py | 15 + src/librelibrary/services/accounts.py | 24 +- src/librelibrary/services/websessions.py | 80 +++++ src/librelibrary/settings.py | 1 + src/librelibrary/ui/__init__.py | 31 ++ src/librelibrary/ui/deps.py | 55 +++ src/librelibrary/ui/pages.py | 138 ++++++++ src/librelibrary/ui/static/style.css | 101 ++++++ src/librelibrary/ui/templates/base.html | 28 ++ src/librelibrary/ui/templates/error.html | 7 + src/librelibrary/ui/templates/login.html | 16 + src/librelibrary/ui/templates/works.html | 44 +++ src/librelibrary/ui/templating.py | 10 + tests/test_contract.py | 7 +- tests/test_ui.py | 339 +++++++++++++++++++ tests/test_ui_parity.py | 147 ++++++++ uv.lock | 13 + 26 files changed, 1177 insertions(+), 31 deletions(-) create mode 100644 migrations/versions/0002_add_web_sessions.py create mode 100644 src/librelibrary/services/websessions.py create mode 100644 src/librelibrary/ui/__init__.py create mode 100644 src/librelibrary/ui/deps.py create mode 100644 src/librelibrary/ui/pages.py create mode 100644 src/librelibrary/ui/static/style.css create mode 100644 src/librelibrary/ui/templates/base.html create mode 100644 src/librelibrary/ui/templates/error.html create mode 100644 src/librelibrary/ui/templates/login.html create mode 100644 src/librelibrary/ui/templates/works.html create mode 100644 src/librelibrary/ui/templating.py create mode 100644 tests/test_ui.py create mode 100644 tests/test_ui_parity.py diff --git a/AGENTS.md b/AGENTS.md index b5090cd..f3ba264 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,12 +6,13 @@ Rules for any AI coding agent working in this repository. Human contributors: se LibreLibrary is a self-hosted personal library server with a web interface, a versioned REST API, and a built-in MCP server. The design is in `docs/design/architecture.md`; read it rather than relying on a copy here. -**Status:** early development. The core exists: the data model, migrations, the REST API, local sign-in, tokens, and the policy layer. There is no web interface yet. +**Status:** early development. The core exists: the data model, migrations, the REST API, local sign-in, tokens, and the policy layer. The web interface has its foundation: cookie sessions, CSRF protection, sign-in, and a works list. The rest of Phase 3 is still to build. ## Repository layout - `src/librelibrary/`: the application. - `api/v1/`: thin REST routes. + - `ui/`: server-rendered pages. Each route uses `@ui_route` to declare the API operation it fulfills. - `services/`: business logic. Each public function declares a policy action with `@policy_action`. - `authz/`: the policy layer and query scoping. - `auth/`: passwords, tokens, and sign-in rate limits. diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bf08d7..14995fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,3 +15,4 @@ The format is based on [Keep a Changelog 1.1.0](https://keepachangelog.com/en/1. - Four privacy levels (personal, library, group, and server), groups of users and libraries, and admin transfer of library ownership. - Database migrations that run at startup, on SQLite and PostgreSQL. - The `librelibrary` command, with `create-admin` and `migrate`. +- A web interface foundation: browser sign-in and sign-out with server-side cookie sessions, CSRF protection, and a searchable, paged list of works. diff --git a/docs/design/architecture.md b/docs/design/architecture.md index 1643e13..f6def80 100644 --- a/docs/design/architecture.md +++ b/docs/design/architecture.md @@ -163,7 +163,7 @@ Roles are `admin`, `member`, and `guest` (read-only). Library roles (owner, edit ### Web protections -- **Cookie sessions:** arrive in Phase 3 with the pages that use them. Server-side, `Secure`, `HttpOnly`, `SameSite=Lax`, with a synchronizer CSRF token on every state-changing request. Bearer-token requests don't use cookies and skip CSRF. +- **Cookie sessions:** arrive in Phase 3 with the pages that use them. Server-side, `Secure`, `HttpOnly`, `SameSite=Lax`, with a synchronizer CSRF token on every state-changing request. Bearer-token requests don't use cookies and skip CSRF. **Built:** the `web_session` table holds a hash of the cookie value and the session's CSRF token. A page accepts only the cookie, and the API accepts only a bearer token, so one can't be used for the other. The sign-in form has no session yet, so it uses a double-submit token: a short-lived `SameSite=Lax` cookie that the form must repeat. A session lasts 14 days, set by `LIBRELIBRARY_SESSION_LIFETIME_DAYS`, and signing out deletes it on the server. - **Rate limiting:** the [`limits`](https://pypi.org/pypi/limits/json) library (MIT) in middleware, per IP and per username for sign-in. slowapi is not used because [it does not declare 3.14 support](https://pypi.org/pypi/slowapi/json). **Decided:** counters live in the application's database, so limits hold across workers with no new service. Each counted attempt writes a row, so per-token limits on ordinary API requests are not built yet, and need their own decision before they are. - **Reverse proxy:** forwarded headers are honored only from `TRUSTED_PROXIES`. `BASE_URL` sets generated links, including a path prefix. - **Importers:** size limits, no XML entity expansion, and outbound fetches restricted to approved providers, blocking private addresses unless an admin allows them. diff --git a/docs/getting-started.md b/docs/getting-started.md index 403fe4f..d010df5 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -1,6 +1,6 @@ # Getting started -LibreLibrary has no release yet. These steps work from a checkout of the repository, and they cover the REST API only, because the web interface doesn't exist yet. +LibreLibrary has no release yet. These steps work from a checkout of the repository, and they cover the REST API and the first pages of the web interface. ## Run the server @@ -23,7 +23,11 @@ docker exec --interactive --tty librelibrary \ librelibrary create-admin --username admin ``` -## Sign in +## Sign in on the web + +Open `http://localhost:8000/` and sign in with the admin's username and password. The pages so far are the sign-in form and a searchable, paged list of works. The session cookie is marked `Secure`, so browsers send it only over HTTPS. Chrome and Firefox also accept it on `localhost`, but a server on another host needs HTTPS in front of it. + +## Sign in to the API Sign in to get a bearer token, and send that token with each request: diff --git a/migrations/versions/0002_add_web_sessions.py b/migrations/versions/0002_add_web_sessions.py new file mode 100644 index 0000000..3a9b93e --- /dev/null +++ b/migrations/versions/0002_add_web_sessions.py @@ -0,0 +1,35 @@ +"""add web sessions + +Revision ID: 0002 +Revises: 0001 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '0002' +down_revision = '0001' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """Apply this migration.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('web_session', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('session_hash', sa.String(length=64), nullable=False), + sa.Column('csrf_token', sa.String(length=64), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['user_account.id'], name=op.f('fk_web_session_user_id_user_account'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('pk_web_session')), + sa.UniqueConstraint('session_hash', name=op.f('uq_web_session_session_hash')) + ) + with op.batch_alter_table('web_session', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_web_session_expires_at'), ['expires_at'], unique=False) + batch_op.create_index(batch_op.f('ix_web_session_user_id'), ['user_id'], unique=False) + + # ### end Alembic commands ### diff --git a/pyproject.toml b/pyproject.toml index c91fdea..81067b4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,9 +11,11 @@ dependencies = [ "alembic==1.20.1", "argon2-cffi==25.1.0", "fastapi==0.162.0", + "jinja2==3.1.6", "limits==5.8.0", "pg8000==1.31.6", "pydantic-settings==2.16.2", + "python-multipart==0.0.33", "sqlalchemy==2.1.6", "structlog==26.1.0", "uvicorn==0.54.0", @@ -57,7 +59,7 @@ select = ["B", "D", "E", "F", "I", "N", "S", "UP", "W"] convention = "pep257" [tool.ruff.lint.per-file-ignores] -"tests/**" = ["S101"] +"tests/**" = ["S101", "S105", "S106"] "tools/**" = ["S603"] "noxfile.py" = ["S603"] diff --git a/src/librelibrary/api/v1/accounts.py b/src/librelibrary/api/v1/accounts.py index 8a3312f..92dcf70 100644 --- a/src/librelibrary/api/v1/accounts.py +++ b/src/librelibrary/api/v1/accounts.py @@ -53,13 +53,18 @@ def login( ) -> TokenCreatedOut: """Check a username and password, and issue a bearer token.""" limiter = cast(RateLimiter, request.app.state.login_limiter) - issued = accounts.login( + user = accounts.sign_in( session, limiter=limiter, settings=settings, ip=client_ip(request, settings), username=payload.username, password=payload.password, + ) + issued = accounts.issue_login_token( + session, + settings=settings, + user=user, token_name=payload.token_name, scopes=[str(scope) for scope in payload.scopes], ) diff --git a/src/librelibrary/app.py b/src/librelibrary/app.py index 40bef90..86af03d 100644 --- a/src/librelibrary/app.py +++ b/src/librelibrary/app.py @@ -7,7 +7,8 @@ import structlog from fastapi import APIRouter, FastAPI, Request, Response, status from fastapi.exceptions import RequestValidationError -from fastapi.responses import JSONResponse +from fastapi.responses import JSONResponse, RedirectResponse +from fastapi.staticfiles import StaticFiles from limits.strategies import FixedWindowRateLimiter from sqlalchemy import Engine from sqlalchemy.exc import DBAPIError @@ -23,6 +24,9 @@ from librelibrary.migrate import run_migrations from librelibrary.schemas import ErrorOut from librelibrary.settings import Settings +from librelibrary.ui import pages +from librelibrary.ui.deps import LoginRequired +from librelibrary.ui.templating import UI_DIRECTORY, templates _ERROR_RESPONSES: dict[int | str, dict[str, Any]] = { status.HTTP_401_UNAUTHORIZED: {"model": ErrorOut}, @@ -32,42 +36,80 @@ } -def _error(code: int, detail: str, **headers: str) -> JSONResponse: - return JSONResponse({"detail": detail}, status_code=code, headers=headers or None) +_PAGE_ERRORS = { + 401: ("Sign in required", "Sign in to continue."), + 403: ("Not allowed", "You can't do that."), + 404: ("Not found", "That page doesn't exist, or you can't see it."), + 409: ("Conflict", "That conflicts with the current state."), + 422: ("Invalid request", "Something in the request wasn't valid."), + 429: ("Too many attempts", "Wait a minute and try again."), + 500: ("Something went wrong", "The server hit an error."), +} +_SECURITY_HEADERS = { + "Content-Security-Policy": ( + "default-src 'self'; frame-ancestors 'none'; form-action 'self'; " + "base-uri 'none'" + ), + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "same-origin", +} + + +def _error(request: Request, code: int, detail: str, **headers: str) -> Response: + """Answer the API with JSON, and the web interface with a page.""" + if request.url.path.startswith("/api/"): + return JSONResponse( + {"detail": detail}, status_code=code, headers=headers or None + ) + heading, message = _PAGE_ERRORS[code] + return templates.TemplateResponse( + request, + "error.html", + {"heading": heading, "message": message}, + status_code=code, + ) def _add_error_handlers(app: FastAPI) -> None: + @app.exception_handler(LoginRequired) + async def login_required(_request: Request, _error_: Exception) -> Response: + return RedirectResponse("/login", status_code=303) + @app.exception_handler(Unauthenticated) - async def unauthenticated(_request: Request, _error_: Exception) -> Response: - return _error(401, "Not authenticated", **{"WWW-Authenticate": "Bearer"}) + async def unauthenticated(request: Request, _error_: Exception) -> Response: + return _error( + request, 401, "Not authenticated", **{"WWW-Authenticate": "Bearer"} + ) @app.exception_handler(Denied) - async def denied(_request: Request, _error_: Exception) -> Response: - return _error(403, "Not allowed") + async def denied(request: Request, _error_: Exception) -> Response: + return _error(request, 403, "Not allowed") @app.exception_handler(NotFound) - async def not_found(_request: Request, _error_: Exception) -> Response: - return _error(404, "Not found") + async def not_found(request: Request, _error_: Exception) -> Response: + return _error(request, 404, "Not found") @app.exception_handler(Conflict) - async def conflict(_request: Request, _error_: Exception) -> Response: - return _error(409, "Conflict with the current state") + async def conflict(request: Request, _error_: Exception) -> Response: + return _error(request, 409, "Conflict with the current state") @app.exception_handler(RateLimited) - async def rate_limited(_request: Request, _error_: Exception) -> Response: - return _error(429, "Too many attempts. Try again later.") + async def rate_limited(request: Request, _error_: Exception) -> Response: + return _error(request, 429, "Too many attempts. Try again later.") @app.exception_handler(DBAPIError) - async def database_error(_request: Request, error: Exception) -> Response: + async def database_error(request: Request, error: Exception) -> Response: if isinstance(error, DBAPIError) and is_constraint_violation(error): - return _error(409, "Conflict with the current state") + return _error(request, 409, "Conflict with the current state") structlog.get_logger().error("database_error", kind=type(error).__name__) - return _error(500, "Internal server error") + return _error(request, 500, "Internal server error") @app.exception_handler(RequestValidationError) - async def invalid(_request: Request, error: Exception) -> Response: + async def invalid(request: Request, error: Exception) -> Response: """Describe what is wrong without echoing the input, which may be secret.""" assert isinstance(error, RequestValidationError) # noqa: S101 + if not request.url.path.startswith("/api/"): + return _error(request, 422, "Invalid request") details = [ {"type": item["type"], "loc": item["loc"], "msg": item["msg"]} for item in error.errors() @@ -112,5 +154,19 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: protected.include_router(module.router) api.include_router(protected) app.include_router(api) + app.include_router(pages.router) + app.mount("/static", StaticFiles(directory=UI_DIRECTORY / "static"), name="static") + + @app.middleware("http") + async def secure_pages(request: Request, call_next: Any) -> Response: + """Add browser protections to every page; the API is JSON only.""" + response: Response = await call_next(request) + if not request.url.path.startswith("/api/"): + for name, value in _SECURITY_HEADERS.items(): + response.headers.setdefault(name, value) + if not request.url.path.startswith("/static/"): + response.headers.setdefault("Cache-Control", "no-store") + return response + _add_error_handlers(app) return app diff --git a/src/librelibrary/models/__init__.py b/src/librelibrary/models/__init__.py index c408b91..98413d1 100644 --- a/src/librelibrary/models/__init__.py +++ b/src/librelibrary/models/__init__.py @@ -37,6 +37,7 @@ RateLimitCounter, Setting, User, + WebSession, ) __all__ = [ @@ -70,6 +71,7 @@ "Subject", "Tag", "User", + "WebSession", "Work", "WorkSubject", ] diff --git a/src/librelibrary/models/system.py b/src/librelibrary/models/system.py index c88806c..a441b2a 100644 --- a/src/librelibrary/models/system.py +++ b/src/librelibrary/models/system.py @@ -43,6 +43,21 @@ class ApiToken(Base): revoked_at: Mapped[datetime | None] = mapped_column(UTCDateTime) +class WebSession(Base): + """A browser sign-in; only the hash of its cookie value is stored.""" + + __tablename__ = "web_session" + + id: Mapped[int] = mapped_column(primary_key=True) + user_id: Mapped[int] = mapped_column( + ForeignKey("user_account.id", ondelete="CASCADE"), index=True + ) + session_hash: Mapped[str] = mapped_column(String(64), unique=True) + csrf_token: Mapped[str] = mapped_column(String(64)) + created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow) + expires_at: Mapped[datetime] = mapped_column(UTCDateTime, index=True) + + class AuditEvent(Base): """A security-relevant event. Never holds a secret.""" diff --git a/src/librelibrary/services/accounts.py b/src/librelibrary/services/accounts.py index a2ccc99..e835741 100644 --- a/src/librelibrary/services/accounts.py +++ b/src/librelibrary/services/accounts.py @@ -116,7 +116,7 @@ def _hit_login_limits( raise RateLimited -def login( # noqa: PLR0913 +def sign_in( # noqa: PLR0913 session: Session, *, limiter: RateLimiter, @@ -124,10 +124,8 @@ def login( # noqa: PLR0913 ip: str, username: str, password: str, - token_name: str, - scopes: list[str], -) -> IssuedToken: - """Check a password and issue a token. The caller has no identity yet.""" +) -> User: + """Check a password and return the user. The caller has no identity yet.""" if not settings.local_auth_enabled: raise Denied _hit_login_limits(limiter, settings, ip, username) @@ -142,10 +140,22 @@ def login( # noqa: PLR0913 audit.record(session, user.id, "login_failed", f"user:{user.id}") session.commit() raise Unauthenticated - if Scope.ADMIN.value in scopes and user.role != Role.ADMIN.value: - raise Denied if needs_rehash(user.password_hash): user.password_hash = hash_password(password) + return user + + +def issue_login_token( + session: Session, + *, + settings: Settings, + user: User, + token_name: str, + scopes: list[str], +) -> IssuedToken: + """Issue the bearer token that a successful sign-in earns.""" + if Scope.ADMIN.value in scopes and user.role != Role.ADMIN.value: + raise Denied expires = utcnow() + timedelta(days=settings.login_token_lifetime_days) issued = _issue_token(session, user.id, token_name, scopes, expires) audit.record(session, user.id, "login", f"user:{user.id}") diff --git a/src/librelibrary/services/websessions.py b/src/librelibrary/services/websessions.py new file mode 100644 index 0000000..c6714d7 --- /dev/null +++ b/src/librelibrary/services/websessions.py @@ -0,0 +1,80 @@ +"""Browser sessions: the server-side record behind the sign-in cookie. + +The cookie holds a long random value and the table holds only its hash, as with +tokens. Each session also holds the synchronizer token that its forms must send. +""" + +import hashlib +import hmac +import secrets +from datetime import timedelta + +from sqlalchemy import delete, select +from sqlalchemy.orm import Session + +from librelibrary.authz.policy import Actor, Role, Scope +from librelibrary.db import utcnow +from librelibrary.errors import Unauthenticated +from librelibrary.models import User, WebSession +from librelibrary.services import audit +from librelibrary.settings import Settings + + +def _hash(cookie_value: str) -> str: + return hashlib.sha256(cookie_value.encode()).hexdigest() + + +def start(session: Session, *, settings: Settings, user: User) -> str: + """Open a session for a user who has signed in; return the cookie value.""" + now = utcnow() + session.execute(delete(WebSession).where(WebSession.expires_at <= now)) + cookie_value = secrets.token_urlsafe(32) + session.add( + WebSession( + user_id=user.id, + session_hash=_hash(cookie_value), + csrf_token=secrets.token_urlsafe(32), + expires_at=now + timedelta(days=settings.session_lifetime_days), + ) + ) + audit.record(session, user.id, "web_login", f"user:{user.id}") + session.commit() + return cookie_value + + +def actor_for_session( + session: Session, cookie_value: str | None +) -> tuple[Actor, WebSession]: + """Return who a cookie acts for, with its session, or raise Unauthenticated. + + A browser acts with the user's full rights, so the actor holds the read and + write scopes, and the admin scope for an admin. + """ + if not cookie_value: + raise Unauthenticated + row = session.execute( + select(WebSession, User) + .join(User, WebSession.user_id == User.id) + .where(WebSession.session_hash == _hash(cookie_value)) + ).one_or_none() + if row is None: + raise Unauthenticated + web_session, user = row + if web_session.expires_at <= utcnow() or not user.is_active: + raise Unauthenticated + scopes = {Scope.LIBRARY_READ, Scope.LIBRARY_WRITE} + if user.role == Role.ADMIN.value: + scopes.add(Scope.ADMIN) + return Actor(user.id, Role(user.role), frozenset(scopes)), web_session + + +def csrf_matches(web_session: WebSession, submitted: str) -> bool: + """Compare a submitted synchronizer token with the session's, in constant time.""" + return hmac.compare_digest(web_session.csrf_token, submitted) + + +def end(session: Session, web_session: WebSession) -> None: + """Close a session, so that its cookie stops working at once.""" + audit.record(session, web_session.user_id, "web_logout") + session.delete(web_session) + session.commit() diff --git a/src/librelibrary/settings.py b/src/librelibrary/settings.py index 0e9367b..1b48a55 100644 --- a/src/librelibrary/settings.py +++ b/src/librelibrary/settings.py @@ -18,3 +18,4 @@ class Settings(BaseSettings): login_rate_limit_per_username: str = "10/minute" login_token_lifetime_days: int = 30 trusted_proxies: list[str] = [] + session_lifetime_days: int = 14 diff --git a/src/librelibrary/ui/__init__.py b/src/librelibrary/ui/__init__.py new file mode 100644 index 0000000..20e3caf --- /dev/null +++ b/src/librelibrary/ui/__init__.py @@ -0,0 +1,31 @@ +"""The server-rendered web interface. + +Every route here is a thin caller of the service layer, like the REST routes. +""" + +from collections.abc import Callable +from typing import Any + +from fastapi import APIRouter + +HTTP_METHODS = {"GET": "get", "POST": "post"} + + +def ui_route( + router: APIRouter, method: str, path: str, *, api: str | None +) -> Callable[[Callable[..., Any]], Callable[..., Any]]: + """Register a page route and declare the REST operation it fulfills. + + `api` is the `operationId` of the API operation that does the same job, so a + test can confirm that the interface can't do what the API can't. A page that + reads or changes no records, such as the sign-in form, passes `api=None`, and + the parity tests list it by name. + """ + + def decorate(function: Callable[..., Any]) -> Callable[..., Any]: + function.__ui_api__ = api # type: ignore[attr-defined] + register = getattr(router, HTTP_METHODS[method]) + register(path, include_in_schema=False)(function) + return function + + return decorate diff --git a/src/librelibrary/ui/deps.py b/src/librelibrary/ui/deps.py new file mode 100644 index 0000000..0aa3fe0 --- /dev/null +++ b/src/librelibrary/ui/deps.py @@ -0,0 +1,55 @@ +"""What page routes share: the signed-in user and CSRF checking.""" + +from typing import Annotated + +from fastapi import Depends, Form, Request + +from librelibrary.api.deps import DbSession +from librelibrary.authz.policy import Actor, Denied +from librelibrary.errors import Unauthenticated +from librelibrary.models import WebSession +from librelibrary.services import websessions + +SESSION_COOKIE = "librelibrary_session" +LOGIN_CSRF_COOKIE = "librelibrary_login_csrf" + + +class LoginRequired(Exception): # noqa: N818 + """A page needs a signed-in user; the app redirects to the sign-in form.""" + + +class SignedIn: + """The user behind a page request.""" + + def __init__(self, actor: Actor, web_session: WebSession) -> None: + """Hold the actor and the session that identified them.""" + self.actor = actor + self.web_session = web_session + + @property + def csrf_token(self) -> str: + """Return the token that this user's forms must send.""" + return self.web_session.csrf_token + + +def get_signed_in(request: Request, session: DbSession) -> SignedIn: + """Identify the user from the session cookie.""" + try: + actor, web_session = websessions.actor_for_session( + session, request.cookies.get(SESSION_COOKIE) + ) + except Unauthenticated: + raise LoginRequired from None + return SignedIn(actor, web_session) + + +CurrentUser = Annotated[SignedIn, Depends(get_signed_in)] + + +def verify_csrf(user: CurrentUser, csrf_token: Annotated[str, Form()] = "") -> None: + """Refuse a state-changing request without the session's synchronizer token.""" + if not websessions.csrf_matches(user.web_session, csrf_token): + raise Denied + + +CsrfChecked = Depends(verify_csrf) diff --git a/src/librelibrary/ui/pages.py b/src/librelibrary/ui/pages.py new file mode 100644 index 0000000..8cb7b14 --- /dev/null +++ b/src/librelibrary/ui/pages.py @@ -0,0 +1,138 @@ +"""Page routes: sign-in, sign-out, and the catalog.""" + +import secrets +from typing import Annotated, cast + +from fastapi import APIRouter, Depends, Form, Query, Request +from fastapi.responses import RedirectResponse, Response +from limits.strategies import RateLimiter + +from librelibrary.api.deps import DbSession, client_ip, get_settings +from librelibrary.authz.policy import Denied +from librelibrary.errors import RateLimited, Unauthenticated +from librelibrary.schemas import Page, WorkOut +from librelibrary.services import accounts, catalog, websessions +from librelibrary.settings import Settings +from librelibrary.ui import ui_route +from librelibrary.ui.deps import ( + LOGIN_CSRF_COOKIE, + SESSION_COOKIE, + CsrfChecked, + CurrentUser, +) +from librelibrary.ui.templating import templates + +router = APIRouter() +PAGE_SIZE = 25 +_SEE_OTHER = 303 +_COOKIE_FLAGS = {"httponly": True, "secure": True, "samesite": "lax", "path": "/"} +_LOGIN_FAILED = { + Unauthenticated: (401, "The username or password is wrong."), + RateLimited: (429, "Too many attempts. Wait a minute and try again."), + Denied: (403, "Password sign-in is turned off on this server."), +} + + +@ui_route(router, "GET", "/", api=None) +def home() -> Response: + """Send visitors to the catalog, which asks them to sign in if needed.""" + return RedirectResponse("/works", status_code=_SEE_OTHER) + + +def _login_page( + request: Request, csrf_token: str, status_code: int = 200, error: str = "" +) -> Response: + response = templates.TemplateResponse( + request, + "login.html", + {"csrf_token": csrf_token, "error": error}, + status_code=status_code, + ) + response.set_cookie( + LOGIN_CSRF_COOKIE, + csrf_token, + max_age=600, + **_COOKIE_FLAGS, # type: ignore[arg-type] + ) + return response + + +@ui_route(router, "GET", "/login", api=None) +def login_form(request: Request) -> Response: + """Show the sign-in form, with a fresh token that the cookie repeats.""" + return _login_page(request, secrets.token_urlsafe(32)) + + +@ui_route(router, "POST", "/login", api="auth_login") +def login( # noqa: PLR0913 + request: Request, + session: DbSession, + username: Annotated[str, Form(max_length=64)], + password: Annotated[str, Form(max_length=1024)], + csrf_token: Annotated[str, Form()] = "", + settings: Settings = Depends(get_settings), # noqa: B008 +) -> Response: + """Check a password, and open a browser session.""" + cookie_token = request.cookies.get(LOGIN_CSRF_COOKIE, "") + if not (cookie_token and secrets.compare_digest(cookie_token, csrf_token)): + raise Denied + limiter = cast(RateLimiter, request.app.state.login_limiter) + try: + user = accounts.sign_in( + session, + limiter=limiter, + settings=settings, + ip=client_ip(request, settings), + username=username, + password=password, + ) + except (Unauthenticated, RateLimited, Denied) as error: + code, message = _LOGIN_FAILED[type(error)] + return _login_page(request, secrets.token_urlsafe(32), code, message) + cookie_value = websessions.start(session, settings=settings, user=user) + response = RedirectResponse("/works", status_code=_SEE_OTHER) + response.set_cookie( + SESSION_COOKIE, + cookie_value, + max_age=settings.session_lifetime_days * 86400, + **_COOKIE_FLAGS, # type: ignore[arg-type] + ) + response.delete_cookie(LOGIN_CSRF_COOKIE, path="/") + return response + + +@ui_route(router, "POST", "/logout", api=None) +def logout( + session: DbSession, user: CurrentUser, _csrf: None = CsrfChecked +) -> Response: + """Close the browser session.""" + websessions.end(session, user.web_session) + response = RedirectResponse("/login", status_code=_SEE_OTHER) + response.delete_cookie(SESSION_COOKIE, path="/") + return response + + +@ui_route(router, "GET", "/works", api="works_list") +def works( + request: Request, + session: DbSession, + user: CurrentUser, + q: Annotated[str | None, Query(max_length=200, pattern=r"^[^\x00]*$")] = None, + page: Annotated[int, Query(ge=1, le=1_000_000)] = 1, +) -> Response: + """List works, with a search box and paging.""" + listing = Page[WorkOut].model_validate( + catalog.list_works(session, user.actor, q, PAGE_SIZE, (page - 1) * PAGE_SIZE) + ) + last_page = max(1, -(-listing.total // PAGE_SIZE)) + return templates.TemplateResponse( + request, + "works.html", + { + "user": user, + "listing": listing, + "q": q or "", + "page": page, + "last_page": last_page, + }, + ) diff --git a/src/librelibrary/ui/static/style.css b/src/librelibrary/ui/static/style.css new file mode 100644 index 0000000..5e1c74e --- /dev/null +++ b/src/librelibrary/ui/static/style.css @@ -0,0 +1,101 @@ +:root { + color-scheme: light dark; + --bg: #ffffff; + --fg: #1b1b1f; + --muted: #55555f; + --accent: #1d4ed8; + --border: #c9c9d1; + --error: #a4161a; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #15161a; + --fg: #ececf1; + --muted: #a8a8b3; + --accent: #8ab4ff; + --border: #3a3b44; + --error: #ff8a8d; + } +} + +* { box-sizing: border-box; } + +body { + margin: 0; + background: var(--bg); + color: var(--fg); + font: 1rem/1.5 system-ui, sans-serif; +} + +a { color: var(--accent); } + +:focus-visible { + outline: 3px solid var(--accent); + outline-offset: 2px; +} + +.skip-link { + position: absolute; + left: -999px; +} + +.skip-link:focus { + left: 1rem; + top: 1rem; + background: var(--bg); + padding: 0.5rem 1rem; +} + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); +} + +.site-header { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 1rem; + padding: 0.75rem 1rem; + border-bottom: 1px solid var(--border); +} + +.brand { font-weight: 700; text-decoration: none; color: var(--fg); } +.site-header nav { display: flex; gap: 1rem; flex: 1; } +.site-header nav a[aria-current="page"] { font-weight: 700; } + +main { max-width: 60rem; margin: 0 auto; padding: 1rem; } + +.stack { display: grid; gap: 0.5rem; max-width: 24rem; } + +input, button { + font: inherit; + min-height: 2.75rem; + padding: 0.25rem 0.75rem; + border: 1px solid var(--border); + border-radius: 0.375rem; + background: var(--bg); + color: var(--fg); +} + +button { cursor: pointer; background: var(--accent); color: var(--bg); border: 0; } + +.link-button { + background: none; + color: var(--accent); + text-decoration: underline; +} + +.error { color: var(--error); font-weight: 600; } +.search { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; } + +table { width: 100%; border-collapse: collapse; margin: 1rem 0; } +th, td { text-align: left; padding: 0.5rem; border-bottom: 1px solid var(--border); } +thead th { color: var(--muted); } +tbody th { font-weight: 600; } + +.pager { display: flex; gap: 1rem; align-items: center; } diff --git a/src/librelibrary/ui/templates/base.html b/src/librelibrary/ui/templates/base.html new file mode 100644 index 0000000..b088180 --- /dev/null +++ b/src/librelibrary/ui/templates/base.html @@ -0,0 +1,28 @@ + + + + + + + {% block title %}{% endblock %} · LibreLibrary + + + + + +
+ {% block content %}{% endblock %} +
+ + diff --git a/src/librelibrary/ui/templates/error.html b/src/librelibrary/ui/templates/error.html new file mode 100644 index 0000000..41ede4e --- /dev/null +++ b/src/librelibrary/ui/templates/error.html @@ -0,0 +1,7 @@ +{% extends "base.html" %} +{% block title %}{{ heading }}{% endblock %} +{% block content %} +

{{ heading }}

+

{{ message }}

+

Go to the start page

+{% endblock %} diff --git a/src/librelibrary/ui/templates/login.html b/src/librelibrary/ui/templates/login.html new file mode 100644 index 0000000..ee39dfc --- /dev/null +++ b/src/librelibrary/ui/templates/login.html @@ -0,0 +1,16 @@ +{% extends "base.html" %} +{% block title %}Sign in{% endblock %} +{% block content %} +

Sign in

+{% if error %}{% endif %} +
+ + + + + + +
+{% endblock %} diff --git a/src/librelibrary/ui/templates/works.html b/src/librelibrary/ui/templates/works.html new file mode 100644 index 0000000..0f7b728 --- /dev/null +++ b/src/librelibrary/ui/templates/works.html @@ -0,0 +1,44 @@ +{% extends "base.html" %} +{% set nav = "works" %} +{% block title %}Works{% endblock %} +{% block content %} +

Works

+ +{% if listing.items %} + + + + + + + + {% for work in listing.items %} + + + + + + {% endfor %} + +
+ Works, page {{ page }} of {{ last_page }} +
TitleFirst publishedLanguage
{{ work.title }}{{ work.first_published or "" }}{{ work.original_language or "" }}
+{% else %} +

{% if q %}No works match “{{ q }}”.{% else %}There are no works yet.{% endif %}

+{% endif %} +{% if last_page > 1 %} + +{% endif %} +{% endblock %} diff --git a/src/librelibrary/ui/templating.py b/src/librelibrary/ui/templating.py new file mode 100644 index 0000000..6a7d8ea --- /dev/null +++ b/src/librelibrary/ui/templating.py @@ -0,0 +1,10 @@ +"""The Jinja2 environment for the web interface.""" + +from pathlib import Path + +from fastapi.templating import Jinja2Templates + +UI_DIRECTORY = Path(__file__).parent + +# Autoescaping is on for .html templates, which is every template here. +templates = Jinja2Templates(directory=UI_DIRECTORY / "templates") diff --git a/tests/test_contract.py b/tests/test_contract.py index a30a9e1..4ee3f2d 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -151,7 +151,12 @@ } SERVICE_FUNCTIONS_WITHOUT_ACTOR = { "accounts.actor_for_token", - "accounts.login", + "accounts.sign_in", + "accounts.issue_login_token", + "websessions.start", + "websessions.csrf_matches", + "websessions.actor_for_session", + "websessions.end", "accounts.create_first_admin", "audit.record", "common.paginate", diff --git a/tests/test_ui.py b/tests/test_ui.py new file mode 100644 index 0000000..93c7c0b --- /dev/null +++ b/tests/test_ui.py @@ -0,0 +1,339 @@ +"""Test the web interface: sign-in, sessions, CSRF, and the catalog page.""" + +import re +from datetime import timedelta + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from sqlalchemy import select +from sqlalchemy.orm import Session + +from librelibrary.auth.passwords import hash_password +from librelibrary.db import utcnow +from librelibrary.models import AuditEvent, User, Work + +from .conftest import MakeAccount + +PASSWORD = "a long test password" +HTTPS = "https://testserver" + + +@pytest.fixture +def browser(app: FastAPI) -> TestClient: + """Give a test a client that sends Secure cookies back, as a browser does.""" + return TestClient(app, base_url=HTTPS, follow_redirects=False) + + +@pytest.fixture +def user(session: Session) -> User: + """Create a member who can sign in with a password.""" + account = User( + username="reader", + display_name="Reader", + role="member", + password_hash=hash_password(PASSWORD), + ) + session.add(account) + session.commit() + return account + + +def _token(page: str) -> str: + match = re.search(r'name="csrf_token" value="([^"]+)"', page) + assert match + return match.group(1) + + +def sign_in(browser: TestClient, username: str = "reader", password: str = PASSWORD): # type: ignore[no-untyped-def] # noqa: ANN201 + """Submit the sign-in form the way a browser would.""" + form = browser.get("/login") + return browser.post( + "/login", + data={ + "username": username, + "password": password, + "csrf_token": _token(form.text), + }, + ) + + +def add_works(session: Session, *titles: str) -> None: + """Create works directly.""" + session.add_all(Work(title=title) for title in titles) + session.commit() + + +def test_sign_in_opens_a_session_with_safe_cookie_flags( + browser: TestClient, user: User +) -> None: + """A correct password redirects to the catalog and sets a hardened cookie.""" + response = sign_in(browser) + + assert response.status_code == 303 + assert response.headers["location"] == "/works" + cookies = [ + value + for name, value in response.headers.multi_items() + if name == "set-cookie" and value.startswith("librelibrary_session=") + ] + assert len(cookies) == 1 + flags = cookies[0].lower() + assert "httponly" in flags + assert "secure" in flags + assert "samesite=lax" in flags + assert browser.get("/works").status_code == 200 + + +def test_the_database_keeps_only_a_hash_of_the_cookie( + browser: TestClient, user: User, session: Session +) -> None: + """A stolen database can't be replayed as a cookie.""" + sign_in(browser) + cookie = browser.cookies["librelibrary_session"] + + from librelibrary.models import WebSession # noqa: PLC0415 + + stored = session.scalars(select(WebSession)).all() + assert len(stored) == 1 + assert cookie not in (stored[0].session_hash, stored[0].csrf_token) + + +@pytest.mark.parametrize( + ("username", "password"), + [("reader", "wrong password"), ("nobody", PASSWORD)], +) +def test_bad_credentials_show_one_message_and_no_session( + browser: TestClient, user: User, username: str, password: str +) -> None: + """A wrong password and an unknown user look the same.""" + response = sign_in(browser, username, password) + + assert response.status_code == 401 + assert "The username or password is wrong." in response.text + assert "librelibrary_session" not in browser.cookies + assert browser.get("/works").status_code == 303 + + +def test_sign_in_without_the_login_token_is_refused( + browser: TestClient, user: User +) -> None: + """A forged cross-site sign-in has no matching token.""" + response = browser.post("/login", data={"username": "reader", "password": PASSWORD}) + + assert response.status_code == 403 + assert "librelibrary_session" not in browser.cookies + + +def test_sign_in_with_a_mismatched_login_token_is_refused( + browser: TestClient, user: User +) -> None: + """The form token has to match the cookie, not merely exist.""" + browser.get("/login") + response = browser.post( + "/login", + data={"username": "reader", "password": PASSWORD, "csrf_token": "forged"}, + ) + + assert response.status_code == 403 + + +def test_sign_in_is_rate_limited(browser: TestClient, user: User) -> None: + """Page sign-in shares the API's limits.""" + for _ in range(10): + sign_in(browser, password="wrong password") + + response = sign_in(browser) + + assert response.status_code == 429 + + +def test_inactive_users_cannot_sign_in( + browser: TestClient, user: User, session: Session +) -> None: + """A deactivated account is refused even with the right password.""" + user.is_active = False + session.commit() + + assert sign_in(browser).status_code == 401 + + +def test_sign_in_is_audited(browser: TestClient, user: User, session: Session) -> None: + """Sign-ins and failures leave audit events without secrets.""" + sign_in(browser, password="wrong password") + sign_in(browser) + + actions = {event.action for event in session.scalars(select(AuditEvent))} + assert {"login_failed", "web_login"} <= actions + + +def test_a_session_id_is_not_reused_after_sign_in( + browser: TestClient, user: User +) -> None: + """Signing in twice issues a different cookie each time.""" + sign_in(browser) + first = browser.cookies["librelibrary_session"] + browser.cookies.clear() + sign_in(browser) + + assert browser.cookies["librelibrary_session"] != first + + +def test_the_catalog_needs_a_session(browser: TestClient) -> None: + """An anonymous visitor is sent to sign in.""" + for path in ("/works", "/"): + response = browser.get(path, follow_redirects=path == "/") + if path == "/works": + assert response.status_code == 303 + assert response.headers["location"] == "/login" + else: + assert str(response.url).endswith("/login") + + +def test_a_bearer_token_is_not_a_session( + browser: TestClient, make_account: MakeAccount +) -> None: + """Pages answer only to cookies.""" + account = make_account() + + assert browser.get("/works", headers=account.headers).status_code == 303 + + +def test_a_session_cookie_is_not_an_api_credential( + browser: TestClient, user: User +) -> None: + """The API still wants a bearer token, so a cookie can't be ridden by a page.""" + sign_in(browser) + + assert browser.get("/api/v1/works").status_code == 401 + + +def test_a_forged_cookie_is_refused(browser: TestClient) -> None: + """An unknown cookie value is the same as none.""" + browser.cookies.set("librelibrary_session", "forged", domain="testserver") + + assert browser.get("/works").status_code == 303 + + +def test_an_expired_session_is_refused( + browser: TestClient, user: User, session: Session +) -> None: + """A session ends when its lifetime does.""" + from librelibrary.models import WebSession # noqa: PLC0415 + + sign_in(browser) + stored = session.scalars(select(WebSession)).one() + stored.expires_at = utcnow() - timedelta(seconds=1) + session.commit() + + assert browser.get("/works").status_code == 303 + + +def test_deactivating_a_user_ends_their_session( + browser: TestClient, user: User, session: Session +) -> None: + """A deactivated user's open browser stops working at once.""" + sign_in(browser) + user.is_active = False + session.commit() + + assert browser.get("/works").status_code == 303 + + +def test_sign_out_needs_the_session_token(browser: TestClient, user: User) -> None: + """A cross-site form can't sign someone out, or do anything else.""" + sign_in(browser) + + missing = browser.post("/logout") + wrong = browser.post("/logout", data={"csrf_token": "forged"}) + + assert missing.status_code == 403 + assert wrong.status_code == 403 + assert browser.get("/works").status_code == 200 + + +def test_sign_out_without_a_session_goes_to_sign_in(browser: TestClient) -> None: + """An anonymous post is redirected, not served.""" + assert browser.post("/logout").status_code == 303 + + +def test_sign_out_closes_the_session_on_the_server( + browser: TestClient, user: User +) -> None: + """The old cookie is dead even if a browser keeps it.""" + sign_in(browser) + cookie = browser.cookies["librelibrary_session"] + token = _token(browser.get("/works").text) + + response = browser.post("/logout", data={"csrf_token": token}) + + assert response.status_code == 303 + assert response.headers["location"] == "/login" + browser.cookies.set("librelibrary_session", cookie, domain="testserver") + assert browser.get("/works").status_code == 303 + + +def test_pages_carry_browser_protections(browser: TestClient, user: User) -> None: + """Pages forbid framing, sniffing, and caching, and limit where scripts load.""" + response = browser.get("/login") + + assert "default-src 'self'" in response.headers["content-security-policy"] + assert "frame-ancestors 'none'" in response.headers["content-security-policy"] + assert response.headers["x-content-type-options"] == "nosniff" + assert response.headers["cache-control"] == "no-store" + + +def test_works_page_lists_searches_and_pages( + browser: TestClient, user: User, session: Session +) -> None: + """The catalog page shows works, filters by title, and pages through.""" + add_works(session, *(f"Book {number:02d}" for number in range(30)), "Odd one") + sign_in(browser) + + first = browser.get("/works") + second = browser.get("/works?page=2") + found = browser.get("/works?q=odd") + + assert "Book 00" in first.text + assert "Odd one" not in first.text + assert "Page 1 of 2" in first.text + assert "Odd one" in second.text + assert "Odd one" in found.text + assert "Book 00" not in found.text + assert "No works match" in browser.get("/works?q=zzz").text + + +def test_works_page_escapes_titles( + browser: TestClient, user: User, session: Session +) -> None: + """Catalog text can't inject markup.""" + add_works(session, "") + sign_in(browser) + + text = browser.get("/works").text + + assert "" not in text + assert "<script>" in text + + +def test_works_page_rejects_a_bad_page_number(browser: TestClient, user: User) -> None: + """Out-of-range input gets an error page, not a crash.""" + sign_in(browser) + + assert browser.get("/works?page=0").status_code == 422 + + +def test_guests_can_read_the_catalog(browser: TestClient, session: Session) -> None: + """Read-only users see pages but hold no write scope.""" + session.add( + User( + username="guest", + display_name="Guest", + role="guest", + password_hash=hash_password(PASSWORD), + ) + ) + session.commit() + sign_in(browser, "guest") + + assert browser.get("/works").status_code == 200 diff --git a/tests/test_ui_parity.py b/tests/test_ui_parity.py new file mode 100644 index 0000000..0353e70 --- /dev/null +++ b/tests/test_ui_parity.py @@ -0,0 +1,147 @@ +"""Parity rules: the web interface can do nothing the API can't. + +Every page route declares the API operation it fulfills, and calls the same +service function that operation calls. +""" + +import ast +import importlib +import inspect +import pkgutil +import textwrap +from collections.abc import Callable +from typing import Any, cast + +import pytest +from fastapi import APIRouter +from fastapi.routing import APIRoute + +import librelibrary.api.v1 +import librelibrary.services +import librelibrary.ui +from librelibrary.app import create_app +from librelibrary.settings import Settings + +# Pages that read or change no records, so no API operation matches them. +NO_API_EQUIVALENT = {"home", "login_form", "logout"} +SERVICE_MODULES = { + module.name for module in pkgutil.iter_modules(librelibrary.services.__path__) +} + + +def page_routes() -> list[APIRoute]: + """Return the routes of every web page router.""" + routes: list[APIRoute] = [] + seen: list[APIRouter] = [] + for module_info in pkgutil.iter_modules(librelibrary.ui.__path__): + module = importlib.import_module(f"librelibrary.ui.{module_info.name}") + for value in vars(module).values(): + if isinstance(value, APIRouter) and value not in seen: + seen.append(value) + routes.extend(r for r in value.routes if isinstance(r, APIRoute)) + return routes + + +def declared_api(route: APIRoute) -> str | None: + """Return the operationId a page route declared, or None if it declared none.""" + return cast(str | None, vars(route.endpoint)["__ui_api__"]) + + +def api_endpoints() -> dict[str, Callable[..., Any]]: + """Return each API operation's handler by operationId.""" + endpoints = {} + for module_info in pkgutil.iter_modules(librelibrary.api.v1.__path__): + module = importlib.import_module(f"librelibrary.api.v1.{module_info.name}") + router = getattr(module, "router", None) + if router is None: + continue + for route in router.routes: + if isinstance(route, APIRoute) and route.operation_id: + endpoints[route.operation_id] = route.endpoint + return endpoints + + +def service_calls(function: Callable[..., Any]) -> list[str]: + """List the service functions a handler calls, in source order.""" + tree = ast.parse(textwrap.dedent(inspect.getsource(function))) + calls = [] + for node in ast.walk(tree): + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and isinstance(node.func.value, ast.Name) + and node.func.value.id in SERVICE_MODULES + ): + calls.append((node.lineno, node.col_offset, node.func.attr)) + return [ + f"{module}.{name}" + for _line, _col, name in sorted(calls) + for module in [_module_of(name)] + ] + + +def _module_of(function_name: str) -> str: + for module_name in sorted(SERVICE_MODULES): + module = importlib.import_module(f"librelibrary.services.{module_name}") + if hasattr(module, function_name): + return module_name + raise AssertionError(function_name) + + +def test_there_are_page_routes() -> None: + """The rest of this file means nothing if it finds no pages.""" + assert len(page_routes()) >= 5 + + +def test_every_page_route_declares_its_api_operation() -> None: + """A page without a declaration fails the build.""" + undeclared = [ + route.path + for route in page_routes() + if not hasattr(route.endpoint, "__ui_api__") + ] + assert undeclared == [] + + +def test_declared_operations_exist_in_the_spec() -> None: + """A page can't name an operation that isn't in the API.""" + operations = set(api_endpoints()) + for route in page_routes(): + declared = declared_api(route) + name = route.endpoint.__name__ + if declared is None: + assert name in NO_API_EQUIVALENT, name + else: + assert declared in operations, name + + +def test_pages_without_an_api_equivalent_are_listed_and_real() -> None: + """The exemption list can't grow stale.""" + exempt = { + route.endpoint.__name__ + for route in page_routes() + if declared_api(route) is None + } + assert exempt == NO_API_EQUIVALENT + + +def test_pages_are_not_in_the_api_spec() -> None: + """The spec describes the API alone.""" + app = create_app(Settings(database_url="sqlite://")) + assert all(path.startswith("/api/") for path in app.openapi()["paths"]) + + +@pytest.mark.parametrize( + "route", + [route for route in page_routes() if declared_api(route) is not None], + ids=lambda route: route.endpoint.__name__, +) +def test_a_page_and_its_operation_call_the_same_service(route: APIRoute) -> None: + """The page calls the service function that the API operation calls first.""" + operation = declared_api(route) + assert operation + api_calls = service_calls(api_endpoints()[operation]) + page_calls = service_calls(route.endpoint) + + assert api_calls + assert api_calls[0] in page_calls diff --git a/uv.lock b/uv.lock index 803836d..b6fcc1e 100644 --- a/uv.lock +++ b/uv.lock @@ -866,9 +866,11 @@ dependencies = [ { name = "alembic" }, { name = "argon2-cffi" }, { name = "fastapi" }, + { name = "jinja2" }, { name = "limits" }, { name = "pg8000" }, { name = "pydantic-settings" }, + { name = "python-multipart" }, { name = "sqlalchemy" }, { name = "structlog" }, { name = "uvicorn" }, @@ -898,9 +900,11 @@ requires-dist = [ { name = "alembic", specifier = "==1.20.1" }, { name = "argon2-cffi", specifier = "==25.1.0" }, { name = "fastapi", specifier = "==0.162.0" }, + { name = "jinja2", specifier = "==3.1.6" }, { name = "limits", specifier = "==5.8.0" }, { name = "pg8000", specifier = "==1.31.6" }, { name = "pydantic-settings", specifier = "==2.16.2" }, + { name = "python-multipart", specifier = "==0.0.33" }, { name = "sqlalchemy", specifier = "==2.1.6" }, { name = "structlog", specifier = "==26.1.0" }, { name = "uvicorn", specifier = "==0.54.0" }, @@ -1686,6 +1690,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/60/d1/38f3a3405989a89ac18390803e70c6ad7c7760da4f9b83cbeca0c44a0c72/python_dotenv-1.2.4-py3-none-any.whl", hash = "sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc", size = 23266, upload-time = "2026-10-01T05:36:08.633Z" }, ] +[[package]] +name = "python-multipart" +version = "0.0.33" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9f/b7/15b905f6142a9a8a68f66900788da1a32e4d4254452783b37ad1eccb0506/python_multipart-0.0.33.tar.gz", hash = "sha256:b8112424a6abd162ec08d390565dd113ad699f2fe6fef3c987b8bbcbfe9e390d", size = 50499, upload-time = "2026-10-31T14:23:47.461Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dd/1b/6b1b4164ec734cac911460ab599bfbe46afedd42c5c9627fe4235942c314/python_multipart-0.0.33-py3-none-any.whl", hash = "sha256:8f16c07b36add9da6b2ee87d3efcaf0a45a6de9c3d0a5dd94e9ccf7675a7bc45", size = 32253, upload-time = "2026-10-31T14:23:46.33Z" }, +] + [[package]] name = "pyyaml" version = "6.0.3" From 2d1019bde329e4e6afe3d75d322a4e0fdf97fd73 Mon Sep 17 00:00:00 2001 From: Natalie Boedecker Date: Sun, 1 Nov 2026 01:49:24 -0400 Subject: [PATCH 2/3] feat: add work pages to view, add, edit, and delete Move the works list route into a new works module and add detail, create, edit, and delete pages, reusing the existing catalog service functions so the UI still can't do anything the API can't. - Show editing links to non-guests and the delete form only to admins, while leaving the actual authorization to the policy layer. - Add form helpers that trim text to None for blank optional fields and turn validation errors into field-level messages without echoing submitted values back verbatim. - Require a ticked confirmation checkbox before deleting a work. Assisted-by: Claude Code Signed-off-by: Natalie Boedecker --- CHANGELOG.md | 2 +- src/librelibrary/app.py | 3 +- src/librelibrary/ui/deps.py | 12 +- src/librelibrary/ui/forms.py | 14 + src/librelibrary/ui/pages.py | 32 +- src/librelibrary/ui/static/style.css | 30 ++ src/librelibrary/ui/templates/work.html | 39 +++ src/librelibrary/ui/templates/work_form.html | 46 +++ src/librelibrary/ui/templates/works.html | 3 +- src/librelibrary/ui/works.py | 224 +++++++++++++ tests/test_ui_parity.py | 2 +- tests/test_ui_works.py | 316 +++++++++++++++++++ 12 files changed, 688 insertions(+), 35 deletions(-) create mode 100644 src/librelibrary/ui/forms.py create mode 100644 src/librelibrary/ui/templates/work.html create mode 100644 src/librelibrary/ui/templates/work_form.html create mode 100644 src/librelibrary/ui/works.py create mode 100644 tests/test_ui_works.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 14995fc..14a4ab7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,4 +15,4 @@ The format is based on [Keep a Changelog 1.1.0](https://keepachangelog.com/en/1. - Four privacy levels (personal, library, group, and server), groups of users and libraries, and admin transfer of library ownership. - Database migrations that run at startup, on SQLite and PostgreSQL. - The `librelibrary` command, with `create-admin` and `migrate`. -- A web interface foundation: browser sign-in and sign-out with server-side cookie sessions, CSRF protection, and a searchable, paged list of works. +- A web interface foundation: browser sign-in and sign-out with server-side cookie sessions, CSRF protection, a searchable, paged list of works, and work pages to view, add, edit, and delete. diff --git a/src/librelibrary/app.py b/src/librelibrary/app.py index 86af03d..123d042 100644 --- a/src/librelibrary/app.py +++ b/src/librelibrary/app.py @@ -24,7 +24,7 @@ from librelibrary.migrate import run_migrations from librelibrary.schemas import ErrorOut from librelibrary.settings import Settings -from librelibrary.ui import pages +from librelibrary.ui import pages, works from librelibrary.ui.deps import LoginRequired from librelibrary.ui.templating import UI_DIRECTORY, templates @@ -155,6 +155,7 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: api.include_router(protected) app.include_router(api) app.include_router(pages.router) + app.include_router(works.router) app.mount("/static", StaticFiles(directory=UI_DIRECTORY / "static"), name="static") @app.middleware("http") diff --git a/src/librelibrary/ui/deps.py b/src/librelibrary/ui/deps.py index 0aa3fe0..8b47a7a 100644 --- a/src/librelibrary/ui/deps.py +++ b/src/librelibrary/ui/deps.py @@ -5,7 +5,7 @@ from fastapi import Depends, Form, Request from librelibrary.api.deps import DbSession -from librelibrary.authz.policy import Actor, Denied +from librelibrary.authz.policy import Actor, Denied, Role from librelibrary.errors import Unauthenticated from librelibrary.models import WebSession from librelibrary.services import websessions @@ -26,6 +26,16 @@ def __init__(self, actor: Actor, web_session: WebSession) -> None: self.actor = actor self.web_session = web_session + @property + def can_edit(self) -> bool: + """Say whether to offer editing; the policy layer still decides.""" + return self.actor.role != Role.GUEST + + @property + def is_admin(self) -> bool: + """Say whether to offer admin actions; the policy layer still decides.""" + return self.actor.role == Role.ADMIN + @property def csrf_token(self) -> str: """Return the token that this user's forms must send.""" diff --git a/src/librelibrary/ui/forms.py b/src/librelibrary/ui/forms.py new file mode 100644 index 0000000..32d874c --- /dev/null +++ b/src/librelibrary/ui/forms.py @@ -0,0 +1,14 @@ +"""Helpers for reading HTML forms, which send every field as text.""" + +from pydantic import ValidationError + + +def blank_to_none(value: str) -> str | None: + """Trim a text field, and turn an empty one into None.""" + return value.strip() or None + + +def problems(error: ValidationError, labels: dict[str, str]) -> list[str]: + """Describe which fields failed, without echoing what was typed.""" + fields = {str(item["loc"][0]) for item in error.errors() if item["loc"]} + return [f"Check {labels.get(field, field)}." for field in sorted(fields)] diff --git a/src/librelibrary/ui/pages.py b/src/librelibrary/ui/pages.py index 8cb7b14..68416da 100644 --- a/src/librelibrary/ui/pages.py +++ b/src/librelibrary/ui/pages.py @@ -3,15 +3,14 @@ import secrets from typing import Annotated, cast -from fastapi import APIRouter, Depends, Form, Query, Request +from fastapi import APIRouter, Depends, Form, Request from fastapi.responses import RedirectResponse, Response from limits.strategies import RateLimiter from librelibrary.api.deps import DbSession, client_ip, get_settings from librelibrary.authz.policy import Denied from librelibrary.errors import RateLimited, Unauthenticated -from librelibrary.schemas import Page, WorkOut -from librelibrary.services import accounts, catalog, websessions +from librelibrary.services import accounts, websessions from librelibrary.settings import Settings from librelibrary.ui import ui_route from librelibrary.ui.deps import ( @@ -23,7 +22,6 @@ from librelibrary.ui.templating import templates router = APIRouter() -PAGE_SIZE = 25 _SEE_OTHER = 303 _COOKIE_FLAGS = {"httponly": True, "secure": True, "samesite": "lax", "path": "/"} _LOGIN_FAILED = { @@ -110,29 +108,3 @@ def logout( response = RedirectResponse("/login", status_code=_SEE_OTHER) response.delete_cookie(SESSION_COOKIE, path="/") return response - - -@ui_route(router, "GET", "/works", api="works_list") -def works( - request: Request, - session: DbSession, - user: CurrentUser, - q: Annotated[str | None, Query(max_length=200, pattern=r"^[^\x00]*$")] = None, - page: Annotated[int, Query(ge=1, le=1_000_000)] = 1, -) -> Response: - """List works, with a search box and paging.""" - listing = Page[WorkOut].model_validate( - catalog.list_works(session, user.actor, q, PAGE_SIZE, (page - 1) * PAGE_SIZE) - ) - last_page = max(1, -(-listing.total // PAGE_SIZE)) - return templates.TemplateResponse( - request, - "works.html", - { - "user": user, - "listing": listing, - "q": q or "", - "page": page, - "last_page": last_page, - }, - ) diff --git a/src/librelibrary/ui/static/style.css b/src/librelibrary/ui/static/style.css index 5e1c74e..d0a00ab 100644 --- a/src/librelibrary/ui/static/style.css +++ b/src/librelibrary/ui/static/style.css @@ -99,3 +99,33 @@ thead th { color: var(--muted); } tbody th { font-weight: 600; } .pager { display: flex; gap: 1rem; align-items: center; } + +.wide { max-width: 40rem; } +textarea { + font: inherit; + padding: 0.5rem 0.75rem; + border: 1px solid var(--border); + border-radius: 0.375rem; + background: var(--bg); + color: var(--fg); +} +.hint { margin: 0; color: var(--muted); font-size: 0.875rem; } +.actions { display: flex; gap: 1rem; align-items: center; } +.button { + display: inline-block; + padding: 0.5rem 1rem; + border-radius: 0.375rem; + background: var(--accent); + color: var(--bg); + text-decoration: none; +} +.byline { color: var(--muted); } +dl { display: grid; grid-template-columns: max-content 1fr; gap: 0.25rem 1rem; } +dt { font-weight: 600; } +dd { margin: 0; } +.description { white-space: pre-wrap; max-width: 40rem; } +.danger { margin-top: 2rem; padding-top: 1rem; border-top: 1px solid var(--border); } +.danger-button { background: var(--error); } +.check { display: flex; gap: 0.5rem; align-items: center; } +.check input { min-height: auto; } +ul.error { margin: 0; } diff --git a/src/librelibrary/ui/templates/work.html b/src/librelibrary/ui/templates/work.html new file mode 100644 index 0000000..6107a62 --- /dev/null +++ b/src/librelibrary/ui/templates/work.html @@ -0,0 +1,39 @@ +{% extends "base.html" %} +{% block title %}{{ work.title }}{% endblock %} +{% block content %} +

← All works

+

{{ work.title }}

+{% if work.contributions %} + +{% endif %} +
+ {% if work.first_published %}
First published
{{ work.first_published }}
{% endif %} + {% if work.original_language %}
Original language
{{ work.original_language }}
{% endif %} + {% if work.series_entries %}
Series positions
+
{% for entry in work.series_entries %}{{ entry.position }}{% if not loop.last %}, {% endif %}{% endfor %}
{% endif %} + {% if work.subjects %}
Subjects
+
{% for subject in work.subjects %}{{ subject.label }}{% if not loop.last %}; {% endif %}{% endfor %}
{% endif %} +
+{% if work.description %}

{{ work.description }}

{% endif %} +{% if user.can_edit %}

Edit this work

{% endif %} +

Editions

+{% if editions.items %} + + + + + {% for edition in editions.items %} + + + + {% endfor %} + +
TitlePublisherPublishedFormat
{{ edition.title or work.title }}{{ edition.publisher or "" }}{{ edition.published or "" }}{{ edition.format or "" }}
+{% else %} +

No editions yet.

+{% endif %} +{% endblock %} diff --git a/src/librelibrary/ui/templates/work_form.html b/src/librelibrary/ui/templates/work_form.html new file mode 100644 index 0000000..d0c0fd8 --- /dev/null +++ b/src/librelibrary/ui/templates/work_form.html @@ -0,0 +1,46 @@ +{% extends "base.html" %} +{% set heading = "Edit work" if work else "Add a work" %} +{% block title %}{{ heading }}{% endblock %} +{% block content %} +

{{ heading }}

+{% if errors %} + +{% endif %} +
+ + + + + +

A language code, such as en or fr.

+ + +

A year or a full date, such as 1969 or 1969-03-14.

+ + +
+ + Cancel +
+
+{% if work and user.is_admin %} +
+

Delete this work

+

This also removes its editions. It is refused while someone owns a copy.

+
+ + + +
+
+{% endif %} +{% endblock %} diff --git a/src/librelibrary/ui/templates/works.html b/src/librelibrary/ui/templates/works.html index 0f7b728..463761c 100644 --- a/src/librelibrary/ui/templates/works.html +++ b/src/librelibrary/ui/templates/works.html @@ -3,6 +3,7 @@ {% block title %}Works{% endblock %} {% block content %}

Works

+{% if user.can_edit %}

Add a work

{% endif %}