Skip to content

fix(backend): return 400 instead of 500 on an invalid focus-sessions date - #8231

Closed
ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/focus-sessions-date-validation
Closed

ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/focus-sessions-date-validation

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

GET /v1/focus-sessions takes an optional date query param to filter a user's focus sessions to one day. The param is checked against a YYYY-MM-DD regex, but a well-formed yet impossible value like 2024-99-99 passes the regex and reaches datetime.strptime in the db layer, which raises ValueError and turns the whole list request into an HTTP 500. This PR validates the date in the handler and returns a 400 instead, so a bad date value no longer 500s the endpoint. This is a proactive hardening change; there is no filed GitHub issue for it. It is one of a set of small independent backend reliability fixes that were prepared together and are being opened at the same time, each self-contained and reviewable and mergeable on its own.

Root cause

In backend/routers/focus_sessions.py, get_focus_sessions passes the raw date string straight through to the db layer:

@router.get('/v1/focus-sessions', tags=['focus-sessions'])
def get_focus_sessions(
    limit: int = Query(100, ge=1, le=1000),
    offset: int = Query(0, ge=0),
    date: str | None = Query(None, pattern=r'^\d{4}-\d{2}-\d{2}$'),
    uid: str = Depends(auth.get_current_user_uid),
):
    return focus_sessions_db.get_focus_sessions(uid, limit=limit, offset=offset, date=date)

The Query pattern ^\d{4}-\d{2}-\d{2}$ only checks the shape, not whether the date exists. A value such as 2024-99-99 or 2024-02-30 matches the regex, so FastAPI accepts it, and it then reaches datetime.strptime(date, '%Y-%m-%d') in focus_sessions_db.get_focus_sessions, which raises ValueError. Nothing catches it, so FastAPI returns a 500. The get_focus_stats sibling in the same file takes the same date param with the same regex and has the same gap.

Fix

Parse the date in the handler before calling the db layer. If strptime raises ValueError, return a 400 with a clear message instead of letting it become a 500.

if date is not None:
    try:
        datetime.strptime(date, '%Y-%m-%d')
    except ValueError:
        raise HTTPException(status_code=400, detail='Invalid date; expected a valid YYYY-MM-DD date')
return focus_sessions_db.get_focus_sessions(uid, limit=limit, offset=offset, date=date)

A valid date and the no-date case both behave exactly as before. The response shape and contract for valid input are unchanged.

Testing

New backend/tests/unit/test_focus_sessions_date_validation.py (registered in test.sh). routers/focus_sessions.py has a heavy import graph, so the test imports it under a stub finder and calls get_focus_sessions directly. Cases: an invalid-but-well-formed date (2024-99-99) raises HTTPException with status 400; a valid date (2024-01-15) passes through to the db layer; a None date passes through to the db layer. Verified red to green: the test fails on current main and passes with this change.

PR status check

No open PR changes the date parsing or validation logic this PR fixes. PR #6946 (the unified auth and BYOK middleware refactor) rewires the auth Depends across many routers including this file, but it does not touch this handler's body, so it does not address this bug. The guard added here does not appear anywhere in this file's history, so this is not a previously reverted fix being resubmitted. No filed GitHub issue matches.

Review in cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 3 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Tip: cubic could auto-approve low-risk PRs like this, if it thinks it's safe to merge. Learn more

Re-trigger cubic

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Backend hardening bug fix with regression test; matches established pattern. (auto-review)

@ZachL111
ZachL111 force-pushed the fix/focus-sessions-date-validation branch from a6ef930 to 114fe3e Compare June 24, 2026 18:42
@Git-on-my-level

Copy link
Copy Markdown
Member

Hi @ZachL111 — thank you for finding and writing up this request/protocol boundary issue. We consolidated this group into a smaller aggregate PR with shared validation helpers and focused tests: #8367.

Your original discovery, reproduction details, and candidate fix are credited in the new PR body and commit metadata. I’m closing this individual PR as superseded by #8367, not because the issue is invalid. Thanks again for surfacing it.

@Git-on-my-level

Copy link
Copy Markdown
Member

Superseded by #8367. Thanks again @ZachL111 — credited there for the original discovery and candidate fix.

@github-actions

Copy link
Copy Markdown
Contributor

Hey @ZachL111 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our roadmap and vision

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community! 💜

Git-on-my-level added a commit that referenced this pull request Jun 25, 2026
## Summary

This aggregates the high-signal request/protocol-boundary fixes from
@ZachL111 into shared validation helpers instead of endpoint-by-endpoint
patches.

Changes:
- add `utils.request_validation` for multipart JSON form parsing,
bounded query params, real calendar dates, UTC-safe sync filename
timestamps, and image chunk envelopes
- route app/persona multipart JSON parsing through the shared helper
- enforce bounded list/history query parameters and real calendar dates
at request boundaries
- validate sync upload filename timestamps with one UTC-aware parser for
v1/v2 paths
- reject invalid websocket image chunk envelopes/sequences instead of
silently ignoring malformed chunks
- validate parallel event/action-item status arrays on the Pydantic
request models
- replace a previous `sys.meta_path`/MagicMock-heavy app JSON test with
direct helper contract coverage

Supersedes/redesigns parts of #8218, #8219, #8220, #8222, #8227, #8231,
#8260, #8263, #8275, #8278, #8279, #8280, #8295, #8303, #8309, #8321.

Original issue discovery, reproductions, and candidate fixes by
@ZachL111 — thank you for surfacing these boundary bugs. This PR keeps
the useful findings while moving the implementation toward shared
contracts and smaller tests.

## Deferred from the Oracle boundary bucket

Not included here because they need separate design or would broaden
this PR:
- #8224 shared-chat malformed record behavior
- #8240 notification payload model cleanup
- #8244 task due-date validation
- #8257 app generate-description request validation
- #8266/#8270 MCP SSE JSON-RPC validation
- #8271 segment assignment bounds beyond the shared-array model work
- #8289 social/persona not-found policy

## Test plan

- [x] `pytest tests/unit/test_request_validation_contracts.py
tests/unit/test_sync_file_paths_filename_none.py
tests/unit/test_apps_create_app_json.py
tests/unit/test_conversation_events_bounds.py -q` → 34 passed
- [x] `python -m py_compile ...` over modified modules/tests
- [x] `git diff --check`
- [x] `bash backend/testing/e2e/run.sh -q --tb=short` → 73 passed, 6
skipped


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/8367?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Git-on-my-level pushed a commit to Git-on-my-level/omi that referenced this pull request Jun 25, 2026
- add shared request validation helpers for multipart JSON, query bounds, calendar dates, sync filenames, and image chunks
- validate app/persona form JSON through a common helper
- enforce bounded list/history query parameters and real calendar dates
- validate sync upload timestamps with UTC-aware parsing
- reject invalid websocket image chunk envelopes instead of silently ignoring them
- validate parallel event/action-item status arrays at the request-model boundary

Supersedes parts of BasedHardware#8218, BasedHardware#8219, BasedHardware#8220, BasedHardware#8222, BasedHardware#8227, BasedHardware#8231, BasedHardware#8260, BasedHardware#8263, BasedHardware#8275, BasedHardware#8278, BasedHardware#8279, BasedHardware#8280, BasedHardware#8295, BasedHardware#8303, BasedHardware#8309, BasedHardware#8321.
Original issue discovery, reproductions, and candidate fixes by @ZachL111.

Co-authored-by: ZachL111 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants