Skip to content

fix(backend): bound image chunk index to prevent IndexError on listen WS - #8303

Closed
ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/transcribe-image-chunk-bounds
Closed

ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/transcribe-image-chunk-bounds

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The /v4/listen WebSocket accepts image uploads in chunks, and handle_image_chunk stores each chunk into a pre-sized list at a client-supplied index. The handler checks index < total but has no lower bound, so a negative index is accepted: a large negative value raises IndexError and tears down the whole listen session, and a small negative value like -1 silently writes into the wrong slot via Python negative indexing. This adds the missing lower bound so out-of-range indices are dropped, the same way an out-of-range positive index is already dropped. This is a proactive hardening change; there is no filed GitHub issue for it.

Root cause

In backend/routers/transcribe.py, handle_image_chunk (a closure inside _stream_handler) indexes the per-upload chunk buffer with the client value:

chunks_data = image_chunks_cache[temp_id]['chunks']
if index < total and chunks_data[index] is None:
    chunks_data[index] = data

index is taken straight from the inbound chunk message (chunk_data.get('index')). The earlier validation only checks isinstance(index, int), which passes for negatives. The guard index < total is true for every negative number, so the code falls through to chunks_data[index]. When abs(index) is greater than total, that subscript raises IndexError, which propagates out of the receive task and ends the listen WebSocket connection mid-session. When index is negative but within range (for example -1 with total of 3), there is no exception, but Python negative indexing rewrites chunks_data[-1], the final slot, with the wrong chunk's bytes. The reassembled image is then silently corrupt.

Fix

Add the lower bound so only a real in-range index is stored:

chunks_data = image_chunks_cache[temp_id]['chunks']
if 0 <= index < total and chunks_data[index] is None:
    chunks_data[index] = data

A negative or otherwise out-of-range index now falls through and is ignored, matching the existing behavior for an index past total. Valid in-bounds indices store exactly as before, so there is no change for well-formed uploads.

Testing

Added backend/tests/unit/test_transcribe_image_chunk_bounds.py (registered in backend/test.sh). handle_image_chunk is a closure nested inside the ~2900 line _stream_handler, and importing transcribe.py pulls in heavy top-level dependencies, so the test loads it from source: it parses transcribe.py with ast, extracts the real handle_image_chunk function node, compiles just that node, injects its free names (logger, time, spawn, MAX_IMAGE_CHUNKS, and so on) as harmless stubs, and calls the function. This exercises the actual source lines rather than a reimplementation. The cases covered: a far-negative index (-1_000_000) is ignored instead of raising IndexError and dispatches nothing; an in-range negative index (-1) leaves the final slot untouched instead of corrupting it; and a control case where two valid in-bounds indices are still stored in the right slots. Verified red to green: the test fails on current main and passes with this change.

PR status check

No open PR changes this logic. PR #6946 (the unified auth and BYOK middleware refactor) rewires the auth dependencies across many routers including this one, but it does not change this handler's body logic, so it does not address this bug. The lower-bound guard added here does not appear anywhere in this file's history (handle_image_chunk was introduced with the omiglass upload support and has carried the unbounded check since), 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.

1 issue found across 3 files

Confidence score: 2/5

  • In backend/routers/transcribe.py, the chunk bounds check still relies on each chunk’s reported total, so a malformed later chunk can bypass validation and cause an IndexError; merging as-is risks transcription request failures (likely 500s) on bad or out-of-order input — validate indexes against len(chunks_data) (or a trusted cached total) before merging.

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Re-trigger cubic

Comment thread backend/routers/transcribe.py Resolved
@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.

2 participants