FastAPI: Patron check-ins endpoint allows invalid date insertion and crashes on invalid edition_key
Problem
When patron check-ins were migrated to FastAPI (openlibrary/fastapi/checkins.py), the validation model CheckInRequest omitted critical date range and edition_key format validations that were previously enforced in the legacy handler (openlibrary/plugins/upstream/checkins.py).
Specifically:
- Corrupted Date Insertion into Database:
CheckInRequestdoes not validate month ranges (1 <= month <= 12) or day ranges (1 <= day <= 31). An API request sent with invalid date components (e.g.,month: 99, day: 99) passes Pydantic validation and callsmake_date_string(2026, 99, 99), creating a corrupt date string"2026-99-99"that gets saved directly into thebookshelves_eventsdatabase table. Furthermore, when the patron views their reading log later (openlibrary/fastapi/public_my_books.py), calling.strftime()on the corrupted date raisesValueError: month must be in 1..12, crashing the user's reading log page with an HTTP 500 error. - Unhandled 500 Error on Malformed
edition_key:edition_keyinCheckInRequestlacks regex format validation (unlike other FastAPI endpoints which enforcepattern=r"(?i)^(?:/books/)?OL\d+M$"). If a client passes an invalid key (e.g.,"abc"),extract_numeric_id_from_olid("abc")returns"ab". Passing string"ab"into the integeredition_iddatabase column causes a Postgres syntax error and an unhandled 500 Internal Server Error instead of returning a 422 Unprocessable Entity response. - Unvalidated Path Parameters: Path parameters
work_idandcheck_in_idcurrently accept non-positive integers (e.g.,<= 0), causing unnecessary database queries for invalid IDs.
Proposed Solution
- In
openlibrary/fastapi/checkins.py:- Add path parameter bounds:
work_id: Annotated[int, Path(gt=0)]andcheck_in_id: Annotated[int, Path(gt=0)]. - Update
CheckInRequestfields with Pydantic range constraints:year(gt=0),month(Field(None, ge=1, le=12)), andday(Field(None, ge=1, le=31)). - Import
is_valid_datefromopenlibrary.plugins.upstream.checkinsand call it inside@model_validator(mode="after")to validate calendar date consistency (e.g. preventing Feb 31st). - Add regex pattern validation to
edition_key:Field(None, pattern=r"(?i)^(?:/books/)?OL\d+M$"). - Ensure
edition_idextracted fromedition_keyis safely cast tointbefore passing toBookshelvesEvents.
- Add path parameter bounds:
- Add a new unit test suite in
openlibrary/tests/fastapi/test_checkins.pyto verify that invalid dates, malformededition_keyvalues, and invalid path IDs return HTTP 422 validation errors.
Proposed Changes
diff --git a/openlibrary/fastapi/checkins.py b/openlibrary/fastapi/checkins.py
index a1b2c3d4e..f5e6d7c8b 100644
--- a/openlibrary/fastapi/checkins.py
+++ b/openlibrary/fastapi/checkins.py
@@ -6,13 +6,13 @@
from __future__ import annotations
from typing import Annotated
-from fastapi import APIRouter, Depends, HTTPException, Response, status
-from pydantic import BaseModel, field_validator, model_validator
+from fastapi import APIRouter, Depends, HTTPException, Path, Response, status
+from pydantic import BaseModel, Field, field_validator, model_validator
from openlibrary.core.bookshelves_events import BookshelfEvent, BookshelvesEvents
from openlibrary.fastapi.auth import (
AuthenticatedUser,
require_authenticated_user,
)
-from openlibrary.plugins.upstream.checkins import make_date_string
+from openlibrary.plugins.upstream.checkins import is_valid_date, make_date_string
from openlibrary.utils import extract_numeric_id_from_olid
router = APIRouter()
class CheckInRequest(BaseModel):
"""Request model for creating/updating check-in events."""
- event_type: int
- year: int
- month: int | None = None
- day: int | None = None
- edition_key: str | None = None
+ event_type: int = Field(..., description="Event type enum value (1=start, 2=update, 3=finish)")
+ year: int = Field(..., gt=0, description="Four-digit year (>0)")
+ month: int | None = Field(None, ge=1, le=12, description="Month (1-12)")
+ day: int | None = Field(None, ge=1, le=31, description="Day (1-31)")
+ edition_key: str | None = Field(None, pattern=r"(?i)^(?:/books/)?OL\d+M$", description="Edition OLID (e.g. OL123M)")
event_id: int | None = None
@field_validator("event_type")
@classmethod
def validate_event_type(cls, v: int) -> int:
if not BookshelfEvent.has_value(v):
raise ValueError("Invalid event type")
return v
@model_validator(mode="after")
def validate_date(self) -> CheckInRequest:
if self.day and not self.month:
raise ValueError("Month is required when day is provided")
+ if not is_valid_date(self.year, self.month, self.day):
+ raise ValueError("Invalid calendar date combination")
return self
@router.post("/works/OL{work_id}W/check-ins")
@router.post("/works/OL{work_id}W/check-ins.json")
async def create_or_update_patron_check_in(
- work_id: int,
+ work_id: Annotated[int, Path(gt=0)],
data: CheckInRequest,
user: Annotated[AuthenticatedUser, Depends(require_authenticated_user)],
) -> CheckInResponse:
"""Create or update a check-in event.
If event_id is provided, updates existing event. Otherwise creates a new one.
"""
edition_id = None
if data.edition_key:
- edition_id = extract_numeric_id_from_olid(data.edition_key)
+ edition_id = int(extract_numeric_id_from_olid(data.edition_key))
date_str = make_date_string(data.year, data.month, data.day)
@router.delete("/check-ins/{check_in_id}")
async def delete_patron_check_in(
- check_in_id: int,
+ check_in_id: Annotated[int, Path(gt=0)],
user: Annotated[AuthenticatedUser, Depends(require_authenticated_user)],
) -> Response:
Verification / Testing in Dev
The proposed changes have been verified in local development:
- Automated Tests: Added comprehensive unit test coverage in
openlibrary/tests/fastapi/test_checkins.pytesting creation, updates, deletions, out-of-bound dates (month=99,day=99,month=13), and invalidedition_keystrings ("abc"). All tests pass with 422 responses. - Manual API Verification: Posting invalid check-in payloads via
curlnow returns HTTP 422 Unprocessable Entity instead of creating corrupt database records or throwing unhandled 500 errors.
Related Files
openlibrary/fastapi/checkins.pyopenlibrary/plugins/upstream/checkins.py[NEW] openlibrary/tests/fastapi/test_checkins.py
- URL:
https://openlibrary.org/works/OL1W/check-ins.json
Reproducing the bug
- Send a POST request to the check-ins endpoint with an invalid month and day:
curl -X POST "https://openlibrary.org/works/OL1W/check-ins" \ -H "Content-Type: application/json" \ -b /tmp/cookies.txt \ -d '{"event_type": 1, "year": 2026, "month": 99, "day": 99}' - Send a POST request with an invalid
edition_key:curl -X POST "https://openlibrary.org:8080/works/OL1W/check-ins" \ -H "Content-Type: application/json" \ -b /tmp/cookies.txt \ -d '{"event_type": 1, "year": 2026, "month": 5, "day": 10, "edition_key": "invalid_key"}'
-
Expected behavior:
- Payload 1 should fail Pydantic validation and return
HTTP 422 Unprocessable Entity. - Payload 2 should fail
edition_keypattern validation and returnHTTP 422 Unprocessable Entity.
- Payload 1 should fail Pydantic validation and return
-
Actual behavior:
- Payload 1 passes validation, creates
"2026-99-99", and inserts it intobookshelves_events. Viewing the user's reading log later fails withHTTP 500due tostrftimefailure. - Payload 2 causes Postgres to throw a syntax error on integer conversion, returning an unhandled
HTTP 500 Internal Server Error.
- Payload 1 passes validation, creates
Context
- Browser (Chrome, Safari, Firefox, etc): All
- OS (Windows, Mac, etc): All
- Logged in (Y/N): N
- Environment (prod, dev, local): prod, local
Breakdown
Implementation Details (for maintainers)
Requirements Checklist
- [ ] Add
Path(gt=0)constraints forwork_idandcheck_in_id - [ ] Add Pydantic field bounds for
year(gt=0),month(ge=1, le=12), andday(ge=1, le=31) inCheckInRequest - [ ] Integrate
is_valid_datein@model_validatorinCheckInRequest - [ ] Add regex pattern validator
pattern=r"(?i)^(?:/books/)?OL\d+M$"foredition_key - [ ] Cast extracted
edition_idtointincreate_or_update_patron_check_in - [ ] Create unit tests in
[NEW] test_checkins.pyasserting 422 responses for malformed inputs
Related files
openlibrary/fastapi/checkins.pyopenlibrary/plugins/upstream/checkins.pyopenlibrary/tests/fastapi/test_checkins.py
Instructions for Contributors
- Please run these commands to ensure your repository is up to date before creating a new branch to work on this issue and each time after pushing code to Github, because the pre-commit bot may add commits to your PRs upstream.
While investigating the same validation gap pattern, I found a related issue in openlibrary/fastapi/yearly_reading_goals.py:
The year field in ReadingGoalForm also lacks range validation:
year: int | None = Field(
default=None,
description="Year for this reading goal..."
)
There are no bounds constraints (gt=0, le=9999), meaning a patron can POST year: -500 and it silently inserts directly into the yearly_reading_goals DB table.
The fix follows the same pattern as the proposed diff above — adding Field(None, gt=0, le=9999) to both.
I have submitted a Pull Request resolving this issue along with unit test coverage:
- Enforced range bounds (
gt=0, le=9999for year,ge=1, le=12for month,ge=1, le=31for day) inCheckInRequest(openlibrary/fastapi/checkins.py). - Added regex pattern matching for edition OLIDs (
pattern=r"(?i)^(?:/books/)?OL\d+M$"). - Integrated calendar date integrity checks (
is_valid_dateanddatetime.date) to reject invalid date combinations (e.g. Feb 31st). - Added
Path(gt=0)constraints forwork_idandcheck_in_idpath parameters. - Added year bounds constraints to
ReadingGoalForm,ReadingGoalItem, and query params inopenlibrary/fastapi/yearly_reading_goals.py. - Created dedicated Pytest suites in
openlibrary/tests/fastapi/test_checkins.pyandtest_yearly_reading_goals.py(12 tests passing).
Any suggestions by maintainers and fellow contributors are welcome. PR is ready for review!