diff --git a/AGENTS.md b/AGENTS.md index b5090cd..cf5aa4b 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 cookie sessions, CSRF protection, sign-in, and pages for works, editions, libraries, and copies. 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 49a4032..23e1709 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,3 +19,6 @@ 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, a searchable, paged list of works, and work pages to view, add, edit, and delete. +- Web pages for libraries, copies, and editions: list and open the libraries you belong to, add and change a library and its settings, add copies from an edition, and edit or delete a copy. Each page offers only what your role allows. +- Library member lists in the API now include each member's display name. 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 56c3861..954ba41 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/openapi/openapi.json b/openapi/openapi.json index 1548966..c5aee4b 100644 --- a/openapi/openapi.json +++ b/openapi/openapi.json @@ -1417,8 +1417,12 @@ "type": "object" }, "MemberOut": { - "description": "A user's role in a library.", + "description": "A user's role in a library, with the name other members know them by.", "properties": { + "display_name": { + "title": "Display Name", + "type": "string" + }, "role": { "$ref": "#/components/schemas/LibraryRole" }, @@ -1429,7 +1433,8 @@ }, "required": [ "user_id", - "role" + "role", + "display_name" ], "title": "MemberOut", "type": "object" 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 0675f8c..554c87d 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 @@ -24,6 +25,11 @@ from librelibrary.proxy import ForwardedProtoMiddleware from librelibrary.schemas import ErrorOut from librelibrary.settings import Settings +from librelibrary.ui import copies as copy_pages +from librelibrary.ui import libraries as library_pages +from librelibrary.ui import pages, works +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}, @@ -33,42 +39,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() @@ -116,5 +160,22 @@ 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.include_router(works.router) + app.include_router(library_pages.router) + app.include_router(copy_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/personal.py b/src/librelibrary/models/personal.py index 91d90aa..c94df37 100644 --- a/src/librelibrary/models/personal.py +++ b/src/librelibrary/models/personal.py @@ -12,9 +12,10 @@ UniqueConstraint, text, ) -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship from librelibrary.db import Base, Hundredths, UTCDateTime, utcnow +from librelibrary.models.system import User class Group(Base): @@ -79,6 +80,13 @@ class LibraryMember(Base): ) role: Mapped[str] = mapped_column(String(16)) + user: Mapped["User"] = relationship(viewonly=True, lazy="joined") + + @property + def display_name(self) -> str: + """Return the member's name, so that members can tell each other apart.""" + return self.user.display_name + class Copy(Base): """A physical or digital item someone owns.""" 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/schemas.py b/src/librelibrary/schemas.py index d417105..167261c 100644 --- a/src/librelibrary/schemas.py +++ b/src/librelibrary/schemas.py @@ -437,10 +437,11 @@ class MemberIn(_In): class MemberOut(_Out): - """A user's role in a library.""" + """A user's role in a library, with the name other members know them by.""" user_id: int role: LibraryRole + display_name: str class CopyIn(_In): 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/libraries.py b/src/librelibrary/services/libraries.py index 81e4850..91cbdfa 100644 --- a/src/librelibrary/services/libraries.py +++ b/src/librelibrary/services/libraries.py @@ -85,6 +85,21 @@ def list_libraries( return paginate(session, statement, limit, offset) +@policy_action(Action.COPY_READ) +def my_roles(session: Session, actor: Actor) -> dict[int, LibraryRole]: + """Return the actor's role in each library they belong to. + + Pages use this to offer only the actions that the policy layer would allow. + The policy layer still decides every request. + """ + rows = session.execute( + select(LibraryMember.library_id, LibraryMember.role).where( + LibraryMember.user_id == actor.user_id + ) + ) + return {library_id: LibraryRole(role) for library_id, role in rows} + + @policy_action(Action.LIBRARY_CREATE) def create_library(session: Session, actor: Actor, payload: LibraryIn) -> Library: """Create a library owned by the actor.""" 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/copies.py b/src/librelibrary/ui/copies.py new file mode 100644 index 0000000..b2d8051 --- /dev/null +++ b/src/librelibrary/ui/copies.py @@ -0,0 +1,291 @@ +"""Page routes for copies: detail, add, edit, and delete.""" + +from typing import Annotated, Any + +from fastapi import APIRouter, Form, Query, Request +from fastapi.responses import RedirectResponse, Response +from pydantic import ValidationError + +from librelibrary.api.deps import DbSession, PathId +from librelibrary.authz.policy import Action, LibraryResource, require +from librelibrary.schemas import CopyIn, CopyOut, CopyPatch, LibraryOut, Page +from librelibrary.services import libraries +from librelibrary.ui import ui_route +from librelibrary.ui.deps import CsrfChecked, CurrentUser +from librelibrary.ui.forms import FormText, blank_to_none, problems +from librelibrary.ui.support import allowed, edition_labels, money +from librelibrary.ui.templating import templates + +router = APIRouter() +ALL = 200 +_SEE_OTHER = 303 +_ID = Annotated[int, Form(ge=1, le=2_147_483_647)] +_LABELS = { + "condition": "the condition", + "location": "the location", + "acquired": "the date acquired", + "source": "the source", + "price": "the price", + "currency": "the currency", + "privacy": "the sharing", + "library_id": "the library", + "edition_id": "the edition", +} + + +def _fields( # noqa: PLR0913 + condition: str, + location: str, + acquired: str, + source: str, + price: str, + currency: str, + privacy: str, +) -> dict[str, str | None]: + code = blank_to_none(currency) + return { + "condition": blank_to_none(condition), + "location": blank_to_none(location), + "acquired": blank_to_none(acquired), + "source": blank_to_none(source), + "price": blank_to_none(price), + "currency": code.upper() if code else None, + "privacy": blank_to_none(privacy), + } + + +def _values_of(copy: CopyOut) -> dict[str, Any]: + return { + "condition": copy.condition, + "location": copy.location, + "acquired": copy.acquired.isoformat() if copy.acquired else None, + "source": copy.source, + "price": money(copy.price) if copy.price is not None else None, + "currency": copy.currency, + "privacy": copy.privacy, + } + + +def _writable_libraries(session: DbSession, user: CurrentUser) -> list[LibraryOut]: + """List the libraries where I may add copies.""" + roles = libraries.my_roles(session, user.actor) + listing = Page[LibraryOut].model_validate( + libraries.list_libraries(session, user.actor, ALL, 0) + ) + return [ + library + for library in listing.items + if allowed( + user.actor, Action.LIBRARY_EDIT, LibraryResource(roles.get(library.id)) + ) + ] + + +def _new_form( # noqa: PLR0913 + request: Request, + session: DbSession, + user: CurrentUser, + *, + edition_id: int, + values: dict[str, Any], + errors: list[str], + status_code: int = 200, +) -> Response: + label = edition_labels(session, user.actor, [edition_id])[edition_id] + return templates.TemplateResponse( + request, + "copy_form.html", + { + "user": user, + "nav": "libraries", + "copy": None, + "edition_id": edition_id, + "label": label, + "choices": _writable_libraries(session, user), + "values": values, + "errors": errors, + }, + status_code=status_code, + ) + + +def _edit_form( # noqa: PLR0913 + request: Request, + session: DbSession, + user: CurrentUser, + *, + copy: CopyOut, + values: dict[str, Any], + errors: list[str], + status_code: int = 200, +) -> Response: + label = edition_labels(session, user.actor, [copy.edition_id])[copy.edition_id] + return templates.TemplateResponse( + request, + "copy_form.html", + { + "user": user, + "nav": "libraries", + "copy": copy, + "edition_id": copy.edition_id, + "label": label, + "choices": [], + "values": values, + "errors": errors, + }, + status_code=status_code, + ) + + +@ui_route(router, "GET", "/copies/new", api=None) +def new_copy_form( + request: Request, + session: DbSession, + user: CurrentUser, + edition_id: Annotated[int, Query(ge=1, le=2_147_483_647)], +) -> Response: + """Show the form to add a copy of an edition.""" + return _new_form( + request, session, user, edition_id=edition_id, values={}, errors=[] + ) + + +@ui_route(router, "POST", "/copies/new", api="copies_create") +def create_copy( # noqa: PLR0913 + request: Request, + session: DbSession, + user: CurrentUser, + library_id: _ID, + edition_id: _ID, + _csrf: None = CsrfChecked, + condition: FormText = "", + location: FormText = "", + acquired: FormText = "", + source: FormText = "", + price: FormText = "", + currency: FormText = "", + privacy: FormText = "", +) -> Response: + """Add a copy to a library from the form.""" + values: dict[str, Any] = { + "library_id": library_id, + "edition_id": edition_id, + **_fields(condition, location, acquired, source, price, currency, privacy), + } + try: + payload = CopyIn(**values) + except ValidationError as error: + return _new_form( + request, + session, + user, + edition_id=edition_id, + values=values, + errors=problems(error, _LABELS), + status_code=422, + ) + copy = libraries.create_copy(session, user.actor, payload) + return RedirectResponse(f"/copies/{copy.id}", status_code=_SEE_OTHER) + + +@ui_route(router, "GET", "/copies/{copy_id}", api="copies_get") +def copy_detail( + request: Request, copy_id: PathId, session: DbSession, user: CurrentUser +) -> Response: + """Show a copy I can see.""" + copy = CopyOut.model_validate(libraries.get_copy(session, user.actor, copy_id)) + label = edition_labels(session, user.actor, [copy.edition_id])[copy.edition_id] + role = libraries.my_roles(session, user.actor).get(copy.library_id) + library = None + if role is not None: + library = LibraryOut.model_validate( + libraries.get_library(session, user.actor, copy.library_id) + ) + return templates.TemplateResponse( + request, + "copy.html", + { + "user": user, + "nav": "libraries", + "copy": copy, + "label": label, + "library": library, + "can_edit": allowed(user.actor, Action.LIBRARY_EDIT, LibraryResource(role)), + }, + ) + + +@ui_route(router, "GET", "/copies/{copy_id}/edit", api="copies_get") +def edit_copy_form( + request: Request, copy_id: PathId, session: DbSession, user: CurrentUser +) -> Response: + """Show the form to change a copy; only editors and owners may.""" + copy = CopyOut.model_validate(libraries.get_copy(session, user.actor, copy_id)) + role = libraries.my_roles(session, user.actor).get(copy.library_id) + require(user.actor, Action.LIBRARY_EDIT, LibraryResource(role)) + return _edit_form( + request, session, user, copy=copy, values=_values_of(copy), errors=[] + ) + + +@ui_route(router, "POST", "/copies/{copy_id}/edit", api="copies_update") +def update_copy( # noqa: PLR0913 + request: Request, + copy_id: PathId, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + condition: FormText = "", + location: FormText = "", + acquired: FormText = "", + source: FormText = "", + price: FormText = "", + currency: FormText = "", + privacy: FormText = "", +) -> Response: + """Change a copy from the form. A blank optional field clears it.""" + values = _fields(condition, location, acquired, source, price, currency, privacy) + # Sharing can't be cleared, so a blank choice means "leave it as it is". + changes: dict[str, Any] = { + k: v for k, v in values.items() if not (k == "privacy" and v is None) + } + try: + payload = CopyPatch(**changes) + except ValidationError as error: + copy = CopyOut.model_validate(libraries.get_copy(session, user.actor, copy_id)) + return _edit_form( + request, + session, + user, + copy=copy, + values=values, + errors=problems(error, _LABELS), + status_code=422, + ) + libraries.update_copy(session, user.actor, copy_id, payload) + return RedirectResponse(f"/copies/{copy_id}", status_code=_SEE_OTHER) + + +@ui_route(router, "POST", "/copies/{copy_id}/delete", api="copies_delete") +def delete_copy( # noqa: PLR0913 + request: Request, + copy_id: PathId, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + confirm: Annotated[str, Form(max_length=10)] = "", +) -> Response: + """Delete a copy, once the box is ticked.""" + copy = CopyOut.model_validate(libraries.get_copy(session, user.actor, copy_id)) + if confirm != "yes": + return _edit_form( + request, + session, + user, + copy=copy, + values=_values_of(copy), + errors=["Tick the box to confirm the delete."], + status_code=422, + ) + libraries.delete_copy(session, user.actor, copy_id) + return RedirectResponse(f"/libraries/{copy.library_id}", status_code=_SEE_OTHER) diff --git a/src/librelibrary/ui/deps.py b/src/librelibrary/ui/deps.py new file mode 100644 index 0000000..8b47a7a --- /dev/null +++ b/src/librelibrary/ui/deps.py @@ -0,0 +1,65 @@ +"""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, Role +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 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.""" + 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/forms.py b/src/librelibrary/ui/forms.py new file mode 100644 index 0000000..2668085 --- /dev/null +++ b/src/librelibrary/ui/forms.py @@ -0,0 +1,19 @@ +"""Helpers for reading HTML forms, which send every field as text.""" + +from typing import Annotated + +from fastapi import Form +from pydantic import ValidationError + +FormText = Annotated[str, Form(max_length=400_000)] + + +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/libraries.py b/src/librelibrary/ui/libraries.py new file mode 100644 index 0000000..284b56c --- /dev/null +++ b/src/librelibrary/ui/libraries.py @@ -0,0 +1,233 @@ +"""Page routes for libraries: list, detail, create, edit, and delete.""" + +from typing import Annotated, Any + +from fastapi import APIRouter, Form, Query, Request +from fastapi.responses import RedirectResponse, Response +from pydantic import ValidationError + +from librelibrary.api.deps import DbSession, PathId +from librelibrary.authz.policy import Action, LibraryResource, require +from librelibrary.schemas import ( + CopyOut, + LibraryIn, + LibraryOut, + LibraryPatch, + MemberOut, + Page, +) +from librelibrary.services import libraries +from librelibrary.ui import ui_route +from librelibrary.ui.deps import CsrfChecked, CurrentUser +from librelibrary.ui.forms import FormText, blank_to_none, problems +from librelibrary.ui.support import allowed, edition_labels +from librelibrary.ui.templating import templates + +router = APIRouter() +PAGE_SIZE = 25 +ALL = 200 +_SEE_OTHER = 303 +_LABELS = {"name": "the name", "default_privacy": "the default sharing"} + + +def _fields( + name: str, default_privacy: str, editors_see_personal: str +) -> dict[str, Any]: + return { + "name": blank_to_none(name), + "default_privacy": default_privacy.strip() or "personal", + "editors_see_personal": editors_see_personal == "yes", + } + + +def _form( + request: Request, + user: CurrentUser, + *, + library: LibraryOut | None, + values: dict[str, Any], + errors: list[str], + status_code: int = 200, +) -> Response: + return templates.TemplateResponse( + request, + "library_form.html", + { + "user": user, + "nav": "libraries", + "library": library, + "values": values, + "errors": errors, + }, + status_code=status_code, + ) + + +def _values_of(library: LibraryOut) -> dict[str, Any]: + return { + "name": library.name, + "default_privacy": library.default_privacy, + "editors_see_personal": library.editors_see_personal, + } + + +@ui_route(router, "GET", "/libraries", api="libraries_list") +def library_list(request: Request, session: DbSession, user: CurrentUser) -> Response: + """List the libraries I belong to, with my role in each.""" + listing = Page[LibraryOut].model_validate( + libraries.list_libraries(session, user.actor, ALL, 0) + ) + roles = libraries.my_roles(session, user.actor) + return templates.TemplateResponse( + request, + "libraries.html", + {"user": user, "nav": "libraries", "listing": listing, "roles": roles}, + ) + + +@ui_route(router, "GET", "/libraries/new", api=None) +def new_library_form(request: Request, user: CurrentUser) -> Response: + """Show the form for a new library.""" + values = {"default_privacy": "personal", "editors_see_personal": True} + return _form(request, user, library=None, values=values, errors=[]) + + +@ui_route(router, "POST", "/libraries/new", api="libraries_create") +def create_library( # noqa: PLR0913 + request: Request, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + name: FormText = "", + default_privacy: FormText = "", + editors_see_personal: FormText = "", +) -> Response: + """Create a library that I own.""" + values = _fields(name, default_privacy, editors_see_personal) + try: + payload = LibraryIn(**values) + except ValidationError as error: + return _form( + request, + user, + library=None, + values=values, + errors=problems(error, _LABELS), + status_code=422, + ) + library = libraries.create_library(session, user.actor, payload) + return RedirectResponse(f"/libraries/{library.id}", status_code=_SEE_OTHER) + + +@ui_route(router, "GET", "/libraries/{library_id}", api="libraries_get") +def library_detail( + request: Request, + library_id: PathId, + session: DbSession, + user: CurrentUser, + page: Annotated[int, Query(ge=1, le=1_000_000)] = 1, +) -> Response: + """Show a library with its members and the copies I can see in it.""" + library = LibraryOut.model_validate( + libraries.get_library(session, user.actor, library_id) + ) + role = libraries.my_roles(session, user.actor).get(library_id) + resource = LibraryResource(role) + members = Page[MemberOut].model_validate( + libraries.list_members(session, user.actor, library_id, ALL, 0) + ) + copies = Page[CopyOut].model_validate( + libraries.list_copies( + session, user.actor, library_id, None, PAGE_SIZE, (page - 1) * PAGE_SIZE + ) + ) + labels = edition_labels(session, user.actor, [c.edition_id for c in copies.items]) + return templates.TemplateResponse( + request, + "library.html", + { + "user": user, + "nav": "libraries", + "library": library, + "role": role, + "can_manage": allowed(user.actor, Action.LIBRARY_MANAGE, resource), + "can_edit": allowed(user.actor, Action.LIBRARY_EDIT, resource), + "members": members, + "copies": copies, + "labels": labels, + "page": page, + "last_page": max(1, -(-copies.total // PAGE_SIZE)), + }, + ) + + +@ui_route(router, "GET", "/libraries/{library_id}/edit", api="libraries_get") +def edit_library_form( + request: Request, library_id: PathId, session: DbSession, user: CurrentUser +) -> Response: + """Show the form to change a library; only its owner may.""" + library = LibraryOut.model_validate( + libraries.get_library(session, user.actor, library_id) + ) + role = libraries.my_roles(session, user.actor).get(library_id) + require(user.actor, Action.LIBRARY_MANAGE, LibraryResource(role)) + return _form(request, user, library=library, values=_values_of(library), errors=[]) + + +@ui_route(router, "POST", "/libraries/{library_id}/edit", api="libraries_update") +def update_library( # noqa: PLR0913 + request: Request, + library_id: PathId, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + name: FormText = "", + default_privacy: FormText = "", + editors_see_personal: FormText = "", +) -> Response: + """Change a library from the form.""" + values = _fields(name, default_privacy, editors_see_personal) + try: + checked = LibraryIn(**values) + except ValidationError as error: + library = LibraryOut.model_validate( + libraries.get_library(session, user.actor, library_id) + ) + return _form( + request, + user, + library=library, + values=values, + errors=problems(error, _LABELS), + status_code=422, + ) + libraries.update_library( + session, user.actor, library_id, LibraryPatch(**checked.model_dump()) + ) + return RedirectResponse(f"/libraries/{library_id}", status_code=_SEE_OTHER) + + +@ui_route(router, "POST", "/libraries/{library_id}/delete", api="libraries_delete") +def delete_library( # noqa: PLR0913 + request: Request, + library_id: PathId, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + confirm: Annotated[str, Form(max_length=10)] = "", +) -> Response: + """Delete a library with its copies, once the box is ticked.""" + if confirm != "yes": + library = LibraryOut.model_validate( + libraries.get_library(session, user.actor, library_id) + ) + return _form( + request, + user, + library=library, + values=_values_of(library), + errors=["Tick the box to confirm the delete."], + status_code=422, + ) + libraries.delete_library(session, user.actor, library_id) + return RedirectResponse("/libraries", status_code=_SEE_OTHER) diff --git a/src/librelibrary/ui/pages.py b/src/librelibrary/ui/pages.py new file mode 100644 index 0000000..68416da --- /dev/null +++ b/src/librelibrary/ui/pages.py @@ -0,0 +1,110 @@ +"""Page routes: sign-in, sign-out, and the catalog.""" + +import secrets +from typing import Annotated, cast + +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.services import accounts, 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() +_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 diff --git a/src/librelibrary/ui/static/style.css b/src/librelibrary/ui/static/style.css new file mode 100644 index 0000000..95a0372 --- /dev/null +++ b/src/librelibrary/ui/static/style.css @@ -0,0 +1,142 @@ +: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; } + +.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; } + +select { + 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); +} +ul.hint { padding-left: 1.25rem; } diff --git a/src/librelibrary/ui/support.py b/src/librelibrary/ui/support.py new file mode 100644 index 0000000..68e7029 --- /dev/null +++ b/src/librelibrary/ui/support.py @@ -0,0 +1,80 @@ +"""Helpers that page routes and templates share.""" + +from collections.abc import Iterable +from dataclasses import dataclass + +from sqlalchemy.orm import Session + +from librelibrary.authz.policy import Action, Actor, Denied, Resource, require +from librelibrary.services import catalog + +PRIVACY_CHOICES = [ + ( + "personal", + "Personal", + "Only the library's owner, and its editors if the library allows it.", + ), + ("library", "Library", "Everyone in this library."), + ( + "group", + "Group", + "Everyone in this library, and in groups that include it.", + ), + ("server", "Server", "Everyone signed in to this server."), +] +PRIVACY_LABELS = {value: label for value, label, _hint in PRIVACY_CHOICES} + + +def allowed(actor: Actor, action: Action, resource: Resource | None = None) -> bool: + """Say whether the policy layer would allow an action, to offer or hide a link. + + This only shapes a page. The service layer checks again on every request. + """ + try: + require(actor, action, resource) + except Denied: + return False + return True + + +def privacy_label(value: str) -> str: + """Return the name of a sharing level.""" + return PRIVACY_LABELS.get(value, value) + + +def money(value: object) -> str: + """Show a price with two decimal places.""" + return "" if value is None else f"{value:.2f}" + + +@dataclass(frozen=True) +class EditionLabel: + """What a page needs to name an edition and its work.""" + + work_id: int + work_title: str + edition_title: str | None + publisher: str | None + format: str | None + + +def edition_labels( + session: Session, actor: Actor, edition_ids: Iterable[int] +) -> dict[int, EditionLabel]: + """Look up the titles for some editions, one read per edition and work.""" + labels: dict[int, EditionLabel] = {} + titles: dict[int, str] = {} + for edition_id in sorted(set(edition_ids)): + edition = catalog.get_edition(session, actor, edition_id) + if edition.work_id not in titles: + titles[edition.work_id] = catalog.get_work( + session, actor, edition.work_id + ).title + labels[edition_id] = EditionLabel( + edition.work_id, + titles[edition.work_id], + edition.title, + edition.publisher, + edition.format, + ) + return labels diff --git a/src/librelibrary/ui/templates/_fields.html b/src/librelibrary/ui/templates/_fields.html new file mode 100644 index 0000000..df9e6a5 --- /dev/null +++ b/src/librelibrary/ui/templates/_fields.html @@ -0,0 +1,23 @@ +{% macro privacy_select(id, name, selected, blank_label=none) %} + + +{% endmacro %} + +{% macro pager(base, page, last_page) %} +{% if last_page > 1 %} + +{% endif %} +{% endmacro %} diff --git a/src/librelibrary/ui/templates/base.html b/src/librelibrary/ui/templates/base.html new file mode 100644 index 0000000..bf8eae0 --- /dev/null +++ b/src/librelibrary/ui/templates/base.html @@ -0,0 +1,29 @@ + + + + + + + {% block title %}{% endblock %} · LibreLibrary + + + + + +
+ {% block content %}{% endblock %} +
+ + diff --git a/src/librelibrary/ui/templates/copy.html b/src/librelibrary/ui/templates/copy.html new file mode 100644 index 0000000..d21d9b9 --- /dev/null +++ b/src/librelibrary/ui/templates/copy.html @@ -0,0 +1,20 @@ +{% extends "base.html" %} +{% block title %}{{ label.work_title }}{% endblock %} +{% block content %} +{% if library %}

← {{ library.name }}

{% endif %} +

{{ label.work_title }}

+{% if label.edition_title or label.publisher %} +

{{ label.edition_title or "" }}{% if label.edition_title and label.publisher %}, {% endif %}{{ label.publisher or "" }}

+{% endif %} +
+
Library
+
{% if library %}{{ library.name }}{% else %}A library you aren't a member of{% endif %}
+
Sharing
{{ copy.privacy | privacy_label }}
+ {% if copy.location %}
Location
{{ copy.location }}
{% endif %} + {% if copy.condition %}
Condition
{{ copy.condition }}
{% endif %} + {% if copy.acquired %}
Acquired
{{ copy.acquired.isoformat() }}
{% endif %} + {% if copy.source %}
Source
{{ copy.source }}
{% endif %} + {% if copy.price is not none %}
Price
{{ copy.price | money }}{% if copy.currency %} {{ copy.currency }}{% endif %}
{% endif %} +
+{% if can_edit %}

Edit this copy

{% endif %} +{% endblock %} diff --git a/src/librelibrary/ui/templates/copy_form.html b/src/librelibrary/ui/templates/copy_form.html new file mode 100644 index 0000000..bfe5bf4 --- /dev/null +++ b/src/librelibrary/ui/templates/copy_form.html @@ -0,0 +1,68 @@ +{% extends "base.html" %} +{% from "_fields.html" import privacy_select %} +{% set heading = "Edit copy" if copy else "Add a copy" %} +{% block title %}{{ heading }}{% endblock %} +{% block content %} +

{{ heading }}

+

{{ label.work_title }}{% if label.edition_title %}, {{ label.edition_title }}{% endif %}{% if label.publisher %} ({{ label.publisher }}){% endif %}

+{% if errors %} + +{% endif %} +{% if copy or choices %} +
+ + {% if not copy %} + + + + {% endif %} + + + + + + + + + + +

A number with up to two decimal places, such as 12.99.

+ + +

A three-letter code, such as USD.

+ + {{ privacy_select("privacy", "privacy", values.get("privacy"), none if copy else "Use the library's default") }} +
+ + Cancel +
+
+{% else %} +

You can't add copies to any library yet. A library's owner can make you an editor{% if user.can_edit %}, or you can add a library of your own{% endif %}.

+{% endif %} +{% if copy %} +
+

Delete this copy

+

This also removes its loan history.

+
+ + + +
+
+{% endif %} +{% endblock %} diff --git a/src/librelibrary/ui/templates/edition_form.html b/src/librelibrary/ui/templates/edition_form.html new file mode 100644 index 0000000..c746869 --- /dev/null +++ b/src/librelibrary/ui/templates/edition_form.html @@ -0,0 +1,42 @@ +{% extends "base.html" %} +{% block title %}Add an edition{% endblock %} +{% block content %} +

Add an edition

+

of {{ work.title }}

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

Leave blank to use the work's title.

+ + + + + + + + + + +

For example, paperback, hardback, or audiobook.

+ + +
+ + Cancel +
+
+{% 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/libraries.html b/src/librelibrary/ui/templates/libraries.html new file mode 100644 index 0000000..5f0ec02 --- /dev/null +++ b/src/librelibrary/ui/templates/libraries.html @@ -0,0 +1,25 @@ +{% extends "base.html" %} +{% block title %}Libraries{% endblock %} +{% block content %} +

Libraries

+{% if user.can_edit %}

Add a library

{% endif %} +{% if listing.items %} + + + + + + + {% for library in listing.items %} + + + + + + {% endfor %} + +
NameYour roleDefault sharing
{{ library.name }}{{ roles[library.id] }}{{ library.default_privacy | privacy_label }}
+{% else %} +

You aren't in any library yet.{% if user.can_edit %} Add one to start keeping track of your copies.{% endif %}

+{% endif %} +{% endblock %} diff --git a/src/librelibrary/ui/templates/library.html b/src/librelibrary/ui/templates/library.html new file mode 100644 index 0000000..ee47a67 --- /dev/null +++ b/src/librelibrary/ui/templates/library.html @@ -0,0 +1,49 @@ +{% extends "base.html" %} +{% from "_fields.html" import pager %} +{% block title %}{{ library.name }}{% endblock %} +{% block content %} +

← All libraries

+

{{ library.name }}

+
+
Your role
{{ role }}
+
Default sharing
{{ library.default_privacy | privacy_label }}
+
Editors see personal copies
{{ "Yes" if library.editors_see_personal else "No" }}
+
+{% if can_manage %}

Edit this library

{% endif %} +

Members

+ + + + {% for member in members.items %} + + {% endfor %} + +
NameRole
{{ member.display_name }}{{ member.role }}
+

Copies

+{% if can_edit %} +

To add a copy, find the work, then choose “Add a copy” on one of its editions.

+{% endif %} +{% if copies.items %} + + + + + + + + {% for copy in copies.items %} + {% set label = labels[copy.edition_id] %} + + + + + + + {% endfor %} + +
Copies, page {{ page }} of {{ last_page }}
WorkEditionLocationSharing
{{ label.work_title }}{{ label.edition_title or "" }}{{ copy.location or "" }}{{ copy.privacy | privacy_label }}
+{{ pager("/libraries/%d" % library.id, page, last_page) }} +{% else %} +

There are no copies you can see in this library yet.

+{% endif %} +{% endblock %} diff --git a/src/librelibrary/ui/templates/library_form.html b/src/librelibrary/ui/templates/library_form.html new file mode 100644 index 0000000..fa2a9d2 --- /dev/null +++ b/src/librelibrary/ui/templates/library_form.html @@ -0,0 +1,41 @@ +{% extends "base.html" %} +{% from "_fields.html" import privacy_select %} +{% set heading = "Edit library" if library else "Add a library" %} +{% block title %}{{ heading }}{% endblock %} +{% block content %} +

{{ heading }}

+{% if errors %} + +{% endif %} +
+ + + + + {{ privacy_select("default_privacy", "default_privacy", values.get("default_privacy")) }} + +
+ + Cancel +
+
+{% if library %} +
+

Delete this library

+

This also removes every copy in it, and its loans.

+
+ + + +
+
+{% endif %} +{% 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/work.html b/src/librelibrary/ui/templates/work.html new file mode 100644 index 0000000..4d861c7 --- /dev/null +++ b/src/librelibrary/ui/templates/work.html @@ -0,0 +1,42 @@ +{% extends "base.html" %} +{% block title %}{{ work.title }}{% endblock %} +{% block content %} +

← All works

+

{{ work.title }}

+{% if work.contributions %} +

+ {% for contribution in work.contributions %} + {{ names[contribution.person_id] }} ({{ contribution.role }}){% if not loop.last %}, {% endif %} + {% endfor %} +

+{% 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 user.can_edit %}

Add an edition

{% endif %} +{% if editions.items %} + + + + {% if user.can_edit %}{% endif %} + + {% for edition in editions.items %} + + + + {% if user.can_edit %}{% endif %} + {% endfor %} + +
TitlePublisherPublishedFormatActions
{{ edition.title or work.title }}{{ edition.publisher or "" }}{{ edition.published or "" }}{{ edition.format or "" }}Add a copy
+{% 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 new file mode 100644 index 0000000..463761c --- /dev/null +++ b/src/librelibrary/ui/templates/works.html @@ -0,0 +1,45 @@ +{% extends "base.html" %} +{% set nav = "works" %} +{% block title %}Works{% endblock %} +{% block content %} +

Works

+{% if user.can_edit %}

Add a work

{% endif %} + +{% 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..a6ca676 --- /dev/null +++ b/src/librelibrary/ui/templating.py @@ -0,0 +1,15 @@ +"""The Jinja2 environment for the web interface.""" + +from pathlib import Path + +from fastapi.templating import Jinja2Templates + +from librelibrary.ui.support import PRIVACY_CHOICES, money, privacy_label + +UI_DIRECTORY = Path(__file__).parent + +# Autoescaping is on for .html templates, which is every template here. +templates = Jinja2Templates(directory=UI_DIRECTORY / "templates") +templates.env.filters["privacy_label"] = privacy_label +templates.env.filters["money"] = money +templates.env.globals["PRIVACY_CHOICES"] = PRIVACY_CHOICES diff --git a/src/librelibrary/ui/works.py b/src/librelibrary/ui/works.py new file mode 100644 index 0000000..b53e403 --- /dev/null +++ b/src/librelibrary/ui/works.py @@ -0,0 +1,321 @@ +"""Page routes for works: list, detail, create, edit, and delete.""" + +from typing import Annotated + +from fastapi import APIRouter, Form, Query, Request +from fastapi.responses import RedirectResponse, Response +from pydantic import ValidationError + +from librelibrary.api.deps import DbSession, PathId +from librelibrary.schemas import EditionIn, EditionOut, Page, WorkIn, WorkOut, WorkPatch +from librelibrary.services import catalog +from librelibrary.ui import ui_route +from librelibrary.ui.deps import CsrfChecked, CurrentUser +from librelibrary.ui.forms import FormText, blank_to_none, problems +from librelibrary.ui.templating import templates + +router = APIRouter() +PAGE_SIZE = 25 +_SEE_OTHER = 303 +_LABELS = { + "title": "the title", + "original_language": "the original language", + "first_published": "the first published date", + "description": "the description", +} + + +def _fields( + title: str, original_language: str, first_published: str, description: str +) -> dict[str, str | None]: + return { + "title": blank_to_none(title), + "original_language": blank_to_none(original_language), + "first_published": blank_to_none(first_published), + "description": blank_to_none(description), + } + + +def _form( + request: Request, + user: CurrentUser, + *, + work: WorkOut | None, + values: dict[str, str | None], + errors: list[str], + status_code: int = 200, +) -> Response: + return templates.TemplateResponse( + request, + "work_form.html", + { + "user": user, + "nav": "works", + "work": work, + "values": values, + "errors": errors, + }, + status_code=status_code, + ) + + +@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, + "nav": "works", + "listing": listing, + "q": q or "", + "page": page, + "last_page": last_page, + }, + ) + + +@ui_route(router, "GET", "/works/new", api=None) +def new_work_form(request: Request, user: CurrentUser) -> Response: + """Show the form for a new work.""" + return _form(request, user, work=None, values={}, errors=[]) + + +@ui_route(router, "POST", "/works/new", api="works_create") +def create_work( # noqa: PLR0913 + request: Request, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + title: FormText = "", + original_language: FormText = "", + first_published: FormText = "", + description: FormText = "", +) -> Response: + """Create a work from the form.""" + values = _fields(title, original_language, first_published, description) + try: + payload = WorkIn(**values) # type: ignore[arg-type] + except ValidationError as error: + return _form( + request, + user, + work=None, + values=values, + errors=problems(error, _LABELS), + status_code=422, + ) + work = catalog.create_work(session, user.actor, payload) + return RedirectResponse(f"/works/{work.id}", status_code=_SEE_OTHER) + + +@ui_route(router, "GET", "/works/{work_id}", api="works_get") +def work_detail( + request: Request, work_id: PathId, session: DbSession, user: CurrentUser +) -> Response: + """Show a work with its contributors and editions.""" + work = WorkOut.model_validate(catalog.get_work(session, user.actor, work_id)) + editions = Page[EditionOut].model_validate( + catalog.list_editions(session, user.actor, work_id, 100, 0) + ) + names = { + contribution.person_id: catalog.get_person( + session, user.actor, contribution.person_id + ).name + for contribution in work.contributions + } + return templates.TemplateResponse( + request, + "work.html", + { + "user": user, + "nav": "works", + "work": work, + "editions": editions, + "names": names, + }, + ) + + +@ui_route(router, "GET", "/works/{work_id}/edit", api="works_get") +def edit_work_form( + request: Request, work_id: PathId, session: DbSession, user: CurrentUser +) -> Response: + """Show the form to change a work.""" + work = WorkOut.model_validate(catalog.get_work(session, user.actor, work_id)) + values = _fields( + work.title, + work.original_language or "", + work.first_published or "", + work.description or "", + ) + return _form(request, user, work=work, values=values, errors=[]) + + +@ui_route(router, "POST", "/works/{work_id}/edit", api="works_update") +def update_work( # noqa: PLR0913 + request: Request, + work_id: PathId, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + title: FormText = "", + original_language: FormText = "", + first_published: FormText = "", + description: FormText = "", +) -> Response: + """Change a work from the form. A blank optional field clears it.""" + values = _fields(title, original_language, first_published, description) + messages = ["Enter a title."] if values["title"] is None else [] + payload = None + if not messages: + try: + payload = WorkPatch(**values) # type: ignore[arg-type] + except ValidationError as error: + messages = problems(error, _LABELS) + if payload is None: + work = WorkOut.model_validate(catalog.get_work(session, user.actor, work_id)) + return _form( + request, user, work=work, values=values, errors=messages, status_code=422 + ) + catalog.update_work(session, user.actor, work_id, payload) + return RedirectResponse(f"/works/{work_id}", status_code=_SEE_OTHER) + + +@ui_route(router, "POST", "/works/{work_id}/delete", api="works_delete") +def delete_work( # noqa: PLR0913 + request: Request, + work_id: PathId, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + confirm: Annotated[str, Form(max_length=10)] = "", +) -> Response: + """Delete a work, once the box is ticked.""" + if confirm != "yes": + work = WorkOut.model_validate(catalog.get_work(session, user.actor, work_id)) + values = _fields( + work.title, + work.original_language or "", + work.first_published or "", + work.description or "", + ) + return _form( + request, + user, + work=work, + values=values, + errors=["Tick the box to confirm the delete."], + status_code=422, + ) + catalog.delete_work(session, user.actor, work_id) + return RedirectResponse("/works", status_code=_SEE_OTHER) + + +_EDITION_LABELS = { + "title": "the title", + "subtitle": "the subtitle", + "publisher": "the publisher", + "published": "the publication date", + "language": "the language", + "format": "the format", + "pages": "the page count", +} + + +def _edition_fields( # noqa: PLR0913 + title: str, + subtitle: str, + publisher: str, + published: str, + language: str, + format_: str, + pages: str, +) -> dict[str, str | None]: + return { + "title": blank_to_none(title), + "subtitle": blank_to_none(subtitle), + "publisher": blank_to_none(publisher), + "published": blank_to_none(published), + "language": blank_to_none(language), + "format": blank_to_none(format_), + "pages": blank_to_none(pages), + } + + +def _edition_form( + request: Request, + user: CurrentUser, + *, + work: WorkOut, + values: dict[str, str | None], + errors: list[str], + status_code: int = 200, +) -> Response: + return templates.TemplateResponse( + request, + "edition_form.html", + { + "user": user, + "nav": "works", + "work": work, + "values": values, + "errors": errors, + }, + status_code=status_code, + ) + + +@ui_route(router, "GET", "/works/{work_id}/editions/new", api=None) +def new_edition_form( + request: Request, work_id: PathId, session: DbSession, user: CurrentUser +) -> Response: + """Show the form to add an edition to a work.""" + work = WorkOut.model_validate(catalog.get_work(session, user.actor, work_id)) + return _edition_form(request, user, work=work, values={}, errors=[]) + + +@ui_route(router, "POST", "/works/{work_id}/editions/new", api="editions_create") +def create_edition( # noqa: PLR0913 + request: Request, + work_id: PathId, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + title: FormText = "", + subtitle: FormText = "", + publisher: FormText = "", + published: FormText = "", + language: FormText = "", + format: FormText = "", # noqa: A002 + pages: FormText = "", +) -> Response: + """Add an edition to a work from the form.""" + values = _edition_fields( + title, subtitle, publisher, published, language, format, pages + ) + try: + payload = EditionIn(**values) # type: ignore[arg-type] + except ValidationError as error: + work = WorkOut.model_validate(catalog.get_work(session, user.actor, work_id)) + return _edition_form( + request, + user, + work=work, + values=values, + errors=problems(error, _EDITION_LABELS), + status_code=422, + ) + catalog.create_edition(session, user.actor, work_id, payload) + return RedirectResponse(f"/works/{work_id}", status_code=_SEE_OTHER) diff --git a/tests/conftest.py b/tests/conftest.py index 0b6da80..0c6e724 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -25,6 +25,8 @@ from librelibrary.models import ApiToken, User # noqa: E402 from librelibrary.settings import Settings # noqa: E402 +from .ui_support import Scene, build_scene # noqa: E402 + @pytest.fixture(scope="session") def database_url(tmp_path_factory: pytest.TempPathFactory) -> str: @@ -77,6 +79,18 @@ def client(app: FastAPI) -> TestClient: return TestClient(app) +@pytest.fixture +def browser(app: FastAPI) -> TestClient: + """Give a test a browser-like client, which sends cookies over HTTPS.""" + return TestClient(app, base_url="https://testserver", follow_redirects=False) + + +@pytest.fixture +def scene(app: FastAPI, session: Session) -> Scene: + """Give a test a library with an owner, an editor, a viewer, and an outsider.""" + return build_scene(app, session) + + ALL_SCOPES = ("library:read", "library:write") diff --git a/tests/test_api.py b/tests/test_api.py index 4b2c4cc..02ddf6f 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -192,7 +192,9 @@ def test_new_library_belongs_to_its_creator(api: Api, owner: Account) -> None: """The creator gets a member row with the owner role.""" library = make_library(api, owner) members = api.call(owner, "GET", f"/libraries/{library}/members")["items"] - assert members == [{"user_id": owner.id, "role": "owner"}] + assert members == [ + {"user_id": owner.id, "role": "owner", "display_name": owner.username} + ] def test_non_members_cannot_learn_a_library_exists( 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_copies.py b/tests/test_ui_copies.py new file mode 100644 index 0000000..b9d48e7 --- /dev/null +++ b/tests/test_ui_copies.py @@ -0,0 +1,383 @@ +"""Test the copy pages, and the add-edition page that copies depend on.""" + +from decimal import Decimal + +import pytest +from fastapi import FastAPI +from sqlalchemy import select +from sqlalchemy.orm import Session + +from librelibrary.models import Copy, Edition + +from .ui_support import Scene, sign_in + + +def new_copy(scene: Scene, who: str = "owner", **fields: str) -> dict[str, str]: + """Build the fields of a new-copy form.""" + person = getattr(scene, who) + return { + "csrf_token": person.csrf, + "library_id": str(scene.library_id), + "edition_id": str(scene.edition_id), + **fields, + } + + +def test_the_new_copy_form_names_the_edition_and_my_libraries( + scene: Scene, +) -> None: + """The form shows what is being added and where I may add it.""" + page = scene.editor.browser.get(f"/copies/new?edition_id={scene.edition_id}").text + + assert "Dune (paperback)" in page + assert f'