openlibrary icon indicating copy to clipboard operation
openlibrary copied to clipboard

FastAPI: Patron check-ins endpoint allows invalid date insertion and crashes on invalid edition_key

Open RsbhThakur opened this issue 4 months ago • 2 comments

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:

  1. Corrupted Date Insertion into Database: CheckInRequest does 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 calls make_date_string(2026, 99, 99), creating a corrupt date string "2026-99-99" that gets saved directly into the bookshelves_events database table. Furthermore, when the patron views their reading log later (openlibrary/fastapi/public_my_books.py), calling .strftime() on the corrupted date raises ValueError: month must be in 1..12, crashing the user's reading log page with an HTTP 500 error.
  2. Unhandled 500 Error on Malformed edition_key: edition_key in CheckInRequest lacks regex format validation (unlike other FastAPI endpoints which enforce pattern=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 integer edition_id database column causes a Postgres syntax error and an unhandled 500 Internal Server Error instead of returning a 422 Unprocessable Entity response.
  3. Unvalidated Path Parameters: Path parameters work_id and check_in_id currently accept non-positive integers (e.g., <= 0), causing unnecessary database queries for invalid IDs.

Proposed Solution

  1. In openlibrary/fastapi/checkins.py:
    • Add path parameter bounds: work_id: Annotated[int, Path(gt=0)] and check_in_id: Annotated[int, Path(gt=0)].
    • Update CheckInRequest fields with Pydantic range constraints: year (gt=0), month (Field(None, ge=1, le=12)), and day (Field(None, ge=1, le=31)).
    • Import is_valid_date from openlibrary.plugins.upstream.checkins and 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_id extracted from edition_key is safely cast to int before passing to BookshelvesEvents.
  2. Add a new unit test suite in openlibrary/tests/fastapi/test_checkins.py to verify that invalid dates, malformed edition_key values, 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:

  1. Automated Tests: Added comprehensive unit test coverage in openlibrary/tests/fastapi/test_checkins.py testing creation, updates, deletions, out-of-bound dates (month=99, day=99, month=13), and invalid edition_key strings ("abc"). All tests pass with 422 responses.
  2. Manual API Verification: Posting invalid check-in payloads via curl now returns HTTP 422 Unprocessable Entity instead of creating corrupt database records or throwing unhandled 500 errors.

Related Files

  • openlibrary/fastapi/checkins.py
  • openlibrary/plugins/upstream/checkins.py
  • [NEW] openlibrary/tests/fastapi/test_checkins.py
  • URL: https://openlibrary.org/works/OL1W/check-ins.json

Reproducing the bug

  1. 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}'
    
  2. 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_key pattern validation and return HTTP 422 Unprocessable Entity.
  • Actual behavior:

    • Payload 1 passes validation, creates "2026-99-99", and inserts it into bookshelves_events. Viewing the user's reading log later fails with HTTP 500 due to strftime failure.
    • Payload 2 causes Postgres to throw a syntax error on integer conversion, returning an unhandled HTTP 500 Internal Server Error.

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 for work_id and check_in_id
  • [ ] Add Pydantic field bounds for year (gt=0), month (ge=1, le=12), and day (ge=1, le=31) in CheckInRequest
  • [ ] Integrate is_valid_date in @model_validator in CheckInRequest
  • [ ] Add regex pattern validator pattern=r"(?i)^(?:/books/)?OL\d+M$" for edition_key
  • [ ] Cast extracted edition_id to int in create_or_update_patron_check_in
  • [ ] Create unit tests in [NEW] test_checkins.py asserting 422 responses for malformed inputs

Related files

  • openlibrary/fastapi/checkins.py
  • openlibrary/plugins/upstream/checkins.py
  • openlibrary/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.

RsbhThakur avatar Jul 13 '26 07:07 RsbhThakur

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.

RsbhThakur avatar Jul 15 '26 07:07 RsbhThakur

I have submitted a Pull Request resolving this issue along with unit test coverage:

  • Enforced range bounds (gt=0, le=9999 for year, ge=1, le=12 for month, ge=1, le=31 for day) in CheckInRequest (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_date and datetime.date) to reject invalid date combinations (e.g. Feb 31st).
  • Added Path(gt=0) constraints for work_id and check_in_id path parameters.
  • Added year bounds constraints to ReadingGoalForm, ReadingGoalItem, and query params in openlibrary/fastapi/yearly_reading_goals.py.
  • Created dedicated Pytest suites in openlibrary/tests/fastapi/test_checkins.py and test_yearly_reading_goals.py (12 tests passing).

Any suggestions by maintainers and fellow contributors are welcome. PR is ready for review!

RsbhThakur avatar Jul 15 '26 19:07 RsbhThakur