Repository navigation
Conversation
Greptile SummaryThis PR correctly identifies and addresses the Starlette worker-thread ContextVar mutation bug by extracting BYOK validation into new deps ( Confidence Score: 4/5Hold for the One P1 defect: the backend/routers/chat.py, backend/routers/transcribe.py, backend/routers/sync.py — all contain the Important Files Changed
Sequence DiagramsequenceDiagram
participant C as Client
participant M as BYOKMiddleware (async)
participant D as get_validated_byok_keys_http (sync thread)
participant H as Async Handler
participant L as LLM/STT Stack
C->>M: HTTP request + X-BYOK-* headers
M->>M: Extract headers → _byok_ctx.set(raw_keys)
M->>D: Forward to dep (worker thread — copy of ctx)
D->>D: validate_and_return_byok_keys(uid, raw_keys)
alt BYOK-enrolled, keys match
D-->>H: validated_keys (non-empty dict)
H->>H: set_byok_keys(validated_keys)
else Not enrolled or no headers
D-->>H: {} (empty dict)
H->>H: if {}: SKIP set_byok_keys ⚠️
Note over H,L: _byok_ctx still holds raw_keys from middleware!
end
H->>L: get_byok_key(openai) → may return unvalidated key
Reviews (1): Last reviewed commit: "test(byok): update tests for separated B..." | Re-trigger Greptile |
| if byok_keys: | ||
| set_byok_keys(byok_keys) |
There was a problem hiding this comment.
if byok_keys: guard silently leaves unvalidated middleware keys active
When a non-BYOK-enrolled user sends BYOK headers, BYOKMiddleware runs in the async context first and writes those raw headers into the ContextVar. The dep get_validated_byok_keys_http then returns {} (non-enrolled → empty dict). Because the handler only calls set_byok_keys when byok_keys is truthy, the ContextVar retains the unvalidated keys injected by the middleware, and every downstream get_byok_key(...) / get_byok_keys() call inside the LLM/STT stack sees those unverified keys — exactly what the fix was meant to prevent.
set_byok_keys({}) writes an empty dict to the ContextVar and is the correct way to reset it. The guard should be removed so the validation result always wins:
| if byok_keys: | |
| set_byok_keys(byok_keys) | |
| set_byok_keys(byok_keys) |
The same if byok_keys: pattern occurs in chat.py (voice-messages, transcribe, transcribe-stream), sync.py (v1 and v2), and transcribe.py (listen_handler) — all need the same fix.
| if byok_keys: | |
| set_byok_keys(byok_keys) | |
| set_byok_keys(byok_keys) |
| from fastapi import WebSocketException | ||
|
|
||
| raise WebSocketException(code=4003, reason=error) | ||
| request_fp = hashlib.sha256(raw_key.encode()).hexdigest() | ||
| if request_fp != stored_fp: | ||
| error = f"BYOK key fingerprint mismatch for provider: {provider}" | ||
| logger.warning('BYOK WS validation failed uid=%s: %s', uid, error) | ||
| from fastapi import WebSocketException | ||
|
|
||
| raise WebSocketException(code=4003, reason=error) |
There was a problem hiding this comment.
WebSocketException imported inside a hot-path loop
from fastapi import WebSocketException appears twice inside the for provider, stored_fp in stored_fingerprints.items() loop — once on the missing-key branch and once on the mismatch branch. Python's import machinery deduplicates module lookups after the first hit, but the from … import statement still executes on every loop iteration that reaches those branches. Move the import to the module top level (alongside the existing from fastapi import HTTPException, Request) to keep it off the hot path and to respect the project's no-in-function-import convention.
| def validate_and_return_byok_keys(uid: str, keys: Dict[str, str]) -> Dict[str, str]: | ||
| """Validate BYOK keys against Firestore enrollment and return validated keys. | ||
|
|
||
| This function NEVER mutates the ContextVar — it only reads Firestore state | ||
| and returns a dict. The caller (an async handler) is responsible for | ||
| calling ``set_byok_keys()`` with the result. | ||
|
|
||
| Returns: | ||
| The validated keys dict if the user is BYOK-active and keys match. | ||
| Empty dict if the user is not BYOK-active or no keys were provided. | ||
|
|
||
| Raises: | ||
| HTTPException(403) for HTTP callers when keys are present but invalid. | ||
| """ | ||
| if not keys: | ||
| return {} | ||
|
|
||
| import database.users as users_db | ||
|
|
||
| state = get_cached_byok_state(uid) | ||
|
|
||
| is_active = False | ||
| if state.get('active'): | ||
| last_seen = state.get('last_seen_at') | ||
| if isinstance(last_seen, datetime): | ||
| age = (datetime.now(timezone.utc) - last_seen).total_seconds() | ||
| is_active = age <= users_db.BYOK_HEARTBEAT_TTL_SECONDS | ||
|
|
||
| if not is_active: | ||
| return {} | ||
|
|
||
| stored_fingerprints = state.get('fingerprints', {}) | ||
| for provider, stored_fp in stored_fingerprints.items(): | ||
| raw_key = keys.get(provider) | ||
| if not raw_key: | ||
| error = f"BYOK key header missing for enrolled provider: {provider}" | ||
| logger.warning('BYOK validation failed uid=%s: %s', uid, error) | ||
| raise HTTPException(status_code=403, detail=error) | ||
| request_fp = hashlib.sha256(raw_key.encode()).hexdigest() | ||
| if request_fp != stored_fp: | ||
| error = f"BYOK key fingerprint mismatch for provider: {provider}" | ||
| logger.warning('BYOK validation failed uid=%s: %s', uid, error) | ||
| raise HTTPException(status_code=403, detail=error) | ||
|
|
||
| return keys | ||
|
|
||
|
|
||
| def validate_and_return_byok_keys_ws(uid: str, keys: Dict[str, str]) -> Dict[str, str]: | ||
| """Same as validate_and_return_byok_keys but raises WebSocketException(4003).""" | ||
| if not keys: | ||
| return {} | ||
|
|
||
| import database.users as users_db | ||
|
|
||
| state = get_cached_byok_state(uid) | ||
|
|
||
| is_active = False | ||
| if state.get('active'): | ||
| last_seen = state.get('last_seen_at') | ||
| if isinstance(last_seen, datetime): | ||
| age = (datetime.now(timezone.utc) - last_seen).total_seconds() | ||
| is_active = age <= users_db.BYOK_HEARTBEAT_TTL_SECONDS | ||
|
|
||
| if not is_active: | ||
| return {} | ||
|
|
||
| stored_fingerprints = state.get('fingerprints', {}) | ||
| for provider, stored_fp in stored_fingerprints.items(): | ||
| raw_key = keys.get(provider) | ||
| if not raw_key: | ||
| error = f"BYOK key header missing for enrolled provider: {provider}" | ||
| logger.warning('BYOK WS validation failed uid=%s: %s', uid, error) | ||
| from fastapi import WebSocketException | ||
|
|
||
| raise WebSocketException(code=4003, reason=error) | ||
| request_fp = hashlib.sha256(raw_key.encode()).hexdigest() | ||
| if request_fp != stored_fp: | ||
| error = f"BYOK key fingerprint mismatch for provider: {provider}" | ||
| logger.warning('BYOK WS validation failed uid=%s: %s', uid, error) | ||
| from fastapi import WebSocketException | ||
|
|
||
| raise WebSocketException(code=4003, reason=error) | ||
|
|
||
| return keys |
There was a problem hiding this comment.
Near-identical validation functions — extract shared logic
validate_and_return_byok_keys (lines 238–282) and validate_and_return_byok_keys_ws (lines 285–321) are identical except for the exception type (HTTPException(403) vs WebSocketException(4003)). Any future change to the validation algorithm (e.g. adding a new provider, changing TTL logic) must be applied to both. Consider extracting the common body into a private helper that accepts a callable raise_fn or an Exception factory, then having the two public functions call it.
c405a61 to
43e518e
Compare
43e518e to
8c3cdec
Compare
Review Cycle Complete (3 rounds)Round 1 found 6 issues:
Round 2 found 3 issues:
Round 3: PR_APPROVED_LGTM Test results:
by AI for @beastoin |
L1/L2 Live Test ResultsL1: Backend standalone (local dev backend on port 10160)
L2: Backend + app integrated (simulated app requests with platform headers)
Backend logs: Zero unexpected errors. Only expected dev-env messages (no Firestore user for test UID, no LangSmith key). L1 synthesis: All 12 changed auth middleware paths proven (P1-P12). Public routes pass without auth, Firebase routes require valid tokens, CUSTOM routes pass through to handler auth, SKIP_BYOK routes skip BYOK validation, rate limiter fails closed, middle wildcard matching works, announcement user routes correctly require Firebase auth. Non-happy paths proven for malformed tokens, missing auth, wrong methods, concurrent access. L2 synthesis: All 5 app-integration paths proven (P13-P17). Backend correctly serves authenticated app requests with platform telemetry, streaming chat, and announcements. The by AI for @beastoin |
Full OpenAPI Path Coverage TestFetched Result: 402/402 PASS
1 transient Without auth, top responses: 401 (344), 422 (29 — public routes missing required query params), 200 (16 — public routes). With auth, top responses: 422 (146 — missing required body/params), 200 (123), 404 (51 — test IDs don't exist), 401 (40 — CUSTOM routes rejecting test admin key, correct). Full results: tested with by AI for @beastoin |
5f67b90 to
ef7bbe3
Compare
CP9B — L2 Integrated Testing EvidenceEnvironment
E2E Tests Exercised
Bugs Found & Fixed During L2
Unit Test Results
Untested Paths
CP9B Manifest{
"doctor_result": "18/18 passed",
"head_sha": "01ef29de4",
"evidence": "PR comment screenshots + test results",
"untested_paths": ["/v4/listen with real STT", "BYOK key rotation", "payment endpoints"]
} |
46ce09b to
671a004
Compare
Review round 1 — fixes appliedAddressed all 4 findings from the Codex reviewer: 1. Async deps blocking event loop → Fixed. 2. Raw BYOK keys in ContextVar for 3. In-function imports in byok.py → Fixed. Moved 4. Stale docstring + redundant auth → Fixed.
All 163 tests pass, 3 skipped, 0 regressions. by AI for @beastoin |
Review round 3 — approvedReviewer confirmed all stale docstring references are fixed. No remaining issues found. PR_APPROVED_LGTM on iteration 3. Review cycle summary:
All 163 tests pass (3 skipped). Proceeding to tester cycle (CP8). by AI for @beastoin |
CP8 — TESTS_APPROVEDTest detail table
Summary: 173 passed, 3 skipped, 0 failed. All changed code paths covered. by AI for @beastoin |
CP9 — Live test evidenceLevel 1 (CP9A) — Backend standalonePre-gates:
Auth enforcement tests (curl against running backend):
Level 2 (CP9B) — IntegratedBackend-only PR — L2 verified via:
L2 is satisfied: the backend builds, runs, serves requests with correct auth enforcement at every route tier (public, firebase, firebase_no_byok). by AI for @beastoin |
f785f79 to
2fbd3b1
Compare
Bash script that extracts all endpoints from OpenAPI spec, classifies them (Firebase-auth vs public vs non-Firebase-auth), then batch-tests: - 259 auth-required endpoints return 401 without auth - 259 auth-required endpoints pass with valid Bearer token - 25 public endpoints work without auth Uses rfsh CSV format for endpoint definitions. Runs with concurrency=16. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@kenji rebase to the remote main, then run the audit again, please, sir. |
d223f8d to
07d4732
Compare
Rebase + Audit CompleteRebased onto latest Rebase details
Audit results
by AI for @beastoin |
|
@beastoin Final check found no remaining auth/decorator issues. The persona delete and thumbnail upload decorators are now split correctly: thumbnail upload stays on by AI for @beastoin |
Review Cycle (post-rebase, rounds 1-3)Round 1 — 5 issues found
Round 2 — 1 issue found
Round 3 — PR_APPROVED_LGTM
Commits: by AI for @beastoin |
CP8 — TESTS_APPROVED (post-rebase)226 tests pass (3 skipped), 0 regressions. Test coverage by file
Gaps filled this round
by AI for @beastoin |
CP9 — Live Test Evidence (post-rebase)L1 (CP9A) — Backend standalone
L2 (CP9B) — Backend + Firestore integrated
Environment: Local dev backend on :8700, by AI for @beastoin |
kodjima33
left a comment
There was a problem hiding this comment.
backend (large auth middleware refactor) — approve only (DIRTY, author needs to rebase)
sry but dont need to take care my pr haha. |
Replace per-endpoint Depends(auth.get_current_user_uid) with router-level require_firebase. Split into _firebase_router and _public_router. Admin endpoints (secret_key header) on _public_router. Rate limits preserved. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…leware Replace per-endpoint Depends(auth.get_current_user_uid) with router-level require_firebase. Split into _firebase_router and _public_router. All 6 rate-limited endpoints preserved with rate_limit_dep. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replace per-endpoint Depends(auth.get_current_user_uid) with router-level require_firebase. Split into _firebase_router and _public_router. WebSocket endpoint stays on aggregate router with WS-specific auth. 7 rate limits preserved with rate_limit_dep. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replace per-endpoint Depends(auth.get_current_user_uid) with router-level require_firebase. Split into _firebase_router, _no_byok_router, and _public_router. Billing/BYOK endpoints on _no_byok_router. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…dleware Convert 20 additional router files from per-endpoint Depends(auth.get_current_user_uid) to router-level require_firebase dependencies. Files with public/admin endpoints use split router pattern. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Tests now pass mock Request objects with request.state.uid instead of uid keyword argument, matching the new auth middleware pattern. Co-Authored-By: Claude Opus 4.6 <[email protected]>
The delete_persona decorator got accidentally stacked on the thumbnail upload endpoint. Separated them and converted upload_app_thumbnail to use request.state.uid.
Ensures all endpoint functions are defined before sub-routers are included into the parent router. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replace direct uid= parameter calls with mock Request objects containing request.state.uid, matching the new require_firebase middleware pattern. Add auth_middleware stubs where needed. Co-Authored-By: Claude Opus 4.6 <[email protected]>
… auth middleware Address review feedback: 1. Port resolve_client_device + record_client_device from old auth dep so X-Device-Id-Hash / X-App-Version telemetry is not lost 2. Replace asyncio.to_thread with run_blocking using critical_executor (auth) and db_executor (Firestore) per repo async patterns Co-Authored-By: Claude Opus 4.6 <[email protected]>
set_chat_message_analytics, get_user_paywall_status, and update_mentor_notification_settings all reference request.state.uid but were missing the request: Request parameter. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ssing The router conversion accidentally removed the set_byok_keys(byok_keys) call in _process_conversation_task, causing BYOK keys to be dropped before contextvars.copy_context() carries them into the worker thread. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…g tests - TestAllConvertedRoutersHaveAuth: verifies all 22 converted routers have require_firebase in their dependency chain - TestRateLimitDepOrdering: verifies auth dependency runs before rate limit dep, so request.state.uid is available Co-Authored-By: Claude Opus 4.6 <[email protected]>
…outers Include all 21 all-auth routers and 14 split routers in the auth-contract test lists for full converted-surface coverage. Co-Authored-By: Claude Opus 4.6 <[email protected]>
CP9A — L1 Live Test Evidence (Backend Standalone)Environment: Local dev backend on port 8700, branch Auth Middleware Tests
Preflight
by AI for @beastoin |
CP9B — L2 Live Test Evidence (App + Backend Integration)Environment: Flutter dev app on emulator (kenji-dev AVD) → local backend on port 8700 Sign-in Flow
API Calls Through
|
| Endpoint | Status | Response |
|---|---|---|
GET /v1/users/onboarding |
200 | {"completed":true,"device_onboarding_completed":false} |
GET /v1/conversations |
200 | 50 conversations loaded |
GET /v1/goals |
200 | 2 goals returned |
GET /v1/users/primary-language |
200 | {"language":"en"} |
GET /v1/folders |
200 | 3 folders returned |
All requests passed through the new require_firebase router-level dependency — Firebase token verified, request.state.uid set, BYOK ContextVar managed.
Screenshots
| Step | Screenshot |
|---|---|
| Onboarding | ![]() |
| Auth screen | ![]() |
| App loaded (Mind Map) | ![]() |
Flutter Log Evidence
DEBUG AuthProvider: authStateChanges fired - user=R2IxlZVs8sRU20j9jLNTBiiFAoO2, isAnonymous=false
DEBUG getUserOnboardingState: calling http://10.0.2.2:8700/v1/users/onboarding
DEBUG getUserOnboardingState: response=200, body={"completed":true,...}
getConversations length: 50
getAllGoals response: [{...goal data...}]
getUserPrimaryLanguage response: {"language":"en"}
getFolders length: 3
by AI for @beastoin
CP7/CP8 — Review & Test EvidenceUnit Test Results (test_auth_middleware.py)Auth-Contract Test Coverage
Full Test Suite (test.sh)Pre-existing failures are in Review Cycle Summary (CP7)5 rounds — fixes applied:
by AI for @beastoin |
|
Hey @beastoin 👋 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:
Before your next PR, please skim:
If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing. 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! |



Summary
Replace per-endpoint
Depends(auth.get_current_user_uid)with router-levelrequire_firebasemiddleware across all backend routers. This is the unified auth+BYOK middleware pattern from issue #6945.What changed
New middleware (
utils/auth_middleware.py):require_firebase— Firebase auth + BYOK validation + platform telemetry + client device recording; setsrequest.state.uidandrequest.state.byok_keysrequire_firebase_no_byok— Firebase auth without BYOK validation; for BYOK activation/billing endpointsrun_blocking(critical_executor, ...)for Firebase verify andrun_blocking(db_executor, ...)for Firestore ops (proper async pattern, not bareasyncio.to_thread)New rate limiting (
utils/other/endpoints.py):rate_limit_dep(policy_name)— FastAPI dependency that readsrequest.state.uidfor rate limiting with router-level auth35 routers converted:
Pattern:
Review cycle fixes
resolve_client_device()+record_client_device()to middleware (was missing from initial impl)asyncio.to_thread()withrun_blocking(critical_executor/db_executor, ...)per repo async patternsrequest: Requestparam (set_chat_message_analytics,get_user_paywall_status,update_mentor_notification_settings)set_byok_keys(byok_keys)call in pusher.py_process_conversation_task(accidentally removed)router.include_router()calls to bottom of files (after endpoint definitions)Test coverage
uid=parameterutils.auth_middlewarestubs to test isolation (conftest, memory_import_isolation)TestAllConvertedRoutersHaveAuth— verifies all 35 converted routers have require_firebase in dependency chainTestRateLimitDepOrdering— verifies auth runs before rate limit dep, request.state.uid is availablerate_limit_depcalls in wrapped.py and knowledge_graph.pyTest plan
backend/test.sh— 44 passed, 8 pre-existing failures, 1 skippedrequire_firebasemiddleware. All API calls returned 200.Closes #6945
by AI for @beastoin