Skip to content

fix(backend): validate folder delete target exists before delegating - #8297

Closed
ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/folder-delete-target-validation
Closed

ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/folder-delete-target-validation

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

DELETE /v1/folders/{folder_id} takes an optional move_to_folder_id query parameter that says where to move the folder's conversations before the folder is deleted. The handler passes that value straight into the database layer without checking the target exists, so a client-supplied id that points at no folder re-points conversations onto a non-existent folder and then calls update() on a missing Firestore document, which raises and surfaces as an HTTP 500. The conversations are left orphaned. This change validates the target up front and returns a clean 404 instead, matching how move_conversation_to_folder in the same file already validates its target. This is a proactive hardening change; there is no filed GitHub issue for it.

Root cause

In backend/routers/folders.py, delete_folder checks the folder being deleted and the system-folder guard, then delegates immediately:

folder = folders_db.get_folder(uid, folder_id)
if not folder:
    raise HTTPException(status_code=404, detail="Folder not found")

if folder.get('is_system'):
    raise HTTPException(status_code=400, detail="Cannot delete system folder")

folders_db.delete_folder(uid, folder_id, move_to_folder_id)

move_to_folder_id comes directly from the query string and is never validated. When it names a folder the user does not have, folders_db.delete_folder re-points the conversations onto that id and then runs folder_ref.update() against a document that does not exist. Firestore raises google.cloud.exceptions.NotFound, which is unhandled and becomes a 500. By that point the conversations have already been pointed at a folder that is not there, so they are orphaned even though the request failed.

The sibling endpoint move_conversation_to_folder already guards this case: it calls folders_db.get_folder(uid, request.folder_id) and raises 404 if the target is missing before touching the data. delete_folder was missing the same check.

Fix

Look up the target folder before delegating, and return 404 if it does not exist:

if move_to_folder_id:
    target_folder = folders_db.get_folder(uid, move_to_folder_id)
    if not target_folder:
        raise HTTPException(status_code=404, detail="Target folder not found")

folders_db.delete_folder(uid, folder_id, move_to_folder_id)

The check only runs when move_to_folder_id is supplied, so the default case (no target, conversations fall back to "Other") is unchanged, and a valid target id behaves exactly as before. The only difference is that a bad target now fails fast with a 404 before any conversation is re-pointed.

Testing

Added backend/tests/unit/test_folder_delete_target_validation.py (registered in backend/test.sh). routers/folders.py has a heavy import graph, so the test imports it under a stub meta-path finder and calls delete_folder directly, the same pattern used by test_folder_conversations_malformed.py. The case patches folders_db.get_folder to resolve the source folder and then report the client-supplied target as missing, and patches folders_db.delete_folder to raise a stand-in for the Firestore NotFound that the unguarded path would hit. It asserts the handler raises HTTPException with status 404 and that folders_db.delete_folder is never called, so nothing gets orphaned. 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 target-folder validation added here does not appear anywhere in this file's history, so it 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/folders.py, the target-folder validation currently allows move_to_folder_id == folder_id, which can trigger a self-target delete flow and leave conversations pointing to a deleted folder; that creates a concrete data-integrity and user-facing retrieval risk if merged as-is. Add an explicit inequality guard (reject same source/target folder IDs) and a regression test for this case before merging.

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

Fix all with cubic | Re-trigger cubic

Comment thread backend/routers/folders.py Resolved
@Git-on-my-level

Copy link
Copy Markdown
Member

Hi @ZachL111 — thank you for finding and writing up this reliability issue. We’re consolidating this set of Firestore/data-mutation fixes into a smaller aggregate PR so the long-term shape is easier to maintain and review: #8362.

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 #8362, not because the issue is invalid. Thanks again for surfacing it.

@Git-on-my-level

Copy link
Copy Markdown
Member

Superseded by #8362. 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 is an aggregated, systematic replacement for ZachL111's
Firestore/data-mutation hardening PRs. Rather than merging a set of
one-off patches that silently skip missing records, this PR adds
explicit invariants and shared helpers:

- shared deterministic document-id helpers for system folders and
calendar meetings
- idempotent calendar meeting create/upsert that preserves the original
`created_at`
- transactional speech-sample removal so `speech_samples` and
`speech_sample_transcripts` stay aligned
- explicit `BatchMutationResult` reporting for action-item batch
updates/sync (`updated_ids`, `missing_ids`, `noop_ids`)
- downstream vector updates now run only for successfully updated sync
items
- folder delete/reorder validates targets before mutating instead of
silently skipping unknown IDs

Supersedes #8294, #8297, #8298, #8301, #8307, #8316, #8322.

Original issue discovery, reproductions, and candidate fixes by
@ZachL111 — thank you for surfacing these reliability problems. This PR
rewrites them into a smaller shared-contract shape to reduce long-term
maintenance cost.

## Test plan

- [x] `uv run --with pytest --with pydantic python -m pytest
tests/unit/test_firestore_invariant_helpers.py -q`
- [x] `python3 -m py_compile backend/database/document_ids.py
backend/database/_client.py backend/database/folders.py
backend/database/calendar_meetings.py backend/database/users.py
backend/database/action_items.py backend/routers/action_items.py
backend/routers/folders.py backend/models/folder.py
backend/tests/unit/test_firestore_invariant_helpers.py`

## Notes / intentional differences from source PRs

- #8298/#8301/#8307 are redesigned: missing IDs are explicit in the
response instead of being silently skipped or allowed to fail a whole
Firestore batch invisibly.
- #8322 uses a shared `system_folder_doc_id()` helper instead of local
seed-string construction.
- #8294 uses a shared `calendar_meeting_doc_id()` helper. The current
public API only exposes `calendar_source` and `calendar_event_id` as
provider uniqueness dimensions; if provider-account/calendar IDs are
added later, this helper is the single extension point.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/8362?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 deterministic document ID helpers for system folders and calendar meetings
- make calendar meeting creates idempotent while preserving created_at
- remove speech samples transactionally to keep samples/transcripts aligned
- report missing action-item IDs explicitly and only update downstream vectors for successful sync writes
- validate folder deletion/reorder targets before mutating

Supersedes BasedHardware#8294, BasedHardware#8297, BasedHardware#8298, BasedHardware#8301, BasedHardware#8307, BasedHardware#8316, BasedHardware#8322.
Original issue discovery, reproductions, and candidate fixes by @ZachL111.

Co-authored-by: Zach <[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