Skip to content

fix(auth): unified auth+BYOK middleware replacing per-endpoint Depends - #6946

Closed
beastoin wants to merge 23 commits into
mainfrom
fix/byok-contextvar-separate-dep-6945
Closed

beastoin wants to merge 23 commits into
mainfrom
fix/byok-contextvar-separate-dep-6945

Conversation

@beastoin

@beastoin beastoin commented Apr 22, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Replace per-endpoint Depends(auth.get_current_user_uid) with router-level require_firebase middleware 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; sets request.state.uid and request.state.byok_keys
  • require_firebase_no_byok — Firebase auth without BYOK validation; for BYOK activation/billing endpoints
  • Uses run_blocking(critical_executor, ...) for Firebase verify and run_blocking(db_executor, ...) for Firestore ops (proper async pattern, not bare asyncio.to_thread)

New rate limiting (utils/other/endpoints.py):

  • rate_limit_dep(policy_name) — FastAPI dependency that reads request.state.uid for rate limiting with router-level auth

35 routers converted:

  • 21 all-auth routers: advice, agent_tools, auto_model, calendar_meetings, calendar_onboarding, chat_sessions, focus_sessions, folders, goals, google_calendar, imports, knowledge_graph, memories, memory_product, scores, speech_profile, staged_tasks, sync, tools, tts, wrapped
  • 14 split routers (mixed auth): action_items, announcements, apps, chat, conversations, developer, fair_use_admin, integrations, notifications, payment, phone_calls, task_integrations, users, x_connector
  • Skipped (no Firebase auth): transcribe (WS only), updates (public/admin), mcp (API-key/product auth)

Pattern:

# Before (per-endpoint)
@router.post('/v1/thing')
def create_thing(uid: str = Depends(auth.get_current_user_uid)):
    ...

# After (router-level)
_firebase_router = APIRouter(dependencies=[Depends(require_firebase)])
@_firebase_router.post('/v1/thing')
def create_thing(request: Request):
    uid = request.state.uid
    ...

Review cycle fixes

  • Added resolve_client_device() + record_client_device() to middleware (was missing from initial impl)
  • Replaced asyncio.to_thread() with run_blocking(critical_executor/db_executor, ...) per repo async patterns
  • Fixed 3 endpoints in users.py missing request: Request param (set_chat_message_analytics, get_user_paywall_status, update_mentor_notification_settings)
  • Restored set_byok_keys(byok_keys) call in pusher.py _process_conversation_task (accidentally removed)
  • Moved router.include_router() calls to bottom of files (after endpoint definitions)

Test coverage

  • Updated 13 test files to use mock Request objects instead of direct uid= parameter
  • Added utils.auth_middleware stubs to test isolation (conftest, memory_import_isolation)
  • Added TestAllConvertedRoutersHaveAuth — verifies all 35 converted routers have require_firebase in dependency chain
  • Added TestRateLimitDepOrdering — verifies auth runs before rate limit dep, request.state.uid is available
  • Fixed rate_limit_dep calls in wrapped.py and knowledge_graph.py
  • All tests pass: 42 in test_auth_middleware.py, 44 total (8 pre-existing failures verified on origin/main)

Test plan

  • backend/test.sh — 44 passed, 8 pre-existing failures, 1 skipped
  • Pre-existing failures verified identical on origin/main
  • CP7: Code review approved (5 rounds)
  • CP8: Tester approved (3 rounds, 35-router coverage)
  • CP9A: L1 live test — local backend, 7 curl auth paths all passing
  • CP9B: L2 live test — Flutter app (emulator) + local backend integration. App signed in via Firebase, loaded 50 conversations, goals, folders, language via new require_firebase middleware. All API calls returned 200.

Closes #6945

by AI for @beastoin

@greptile-apps

greptile-apps Bot commented Apr 22, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR correctly identifies and addresses the Starlette worker-thread ContextVar mutation bug by extracting BYOK validation into new deps (get_validated_byok_keys_http/ws) that return validated keys as a plain dict, with the async handler responsible for calling set_byok_keys. The architecture is sound, but one P1 defect remains: every handler guards with if byok_keys: set_byok_keys(byok_keys), which means when a non-enrolled user sends BYOK headers the guard is false, set_byok_keys is never called, and the unvalidated keys that BYOKMiddleware already wrote into the ContextVar remain active for the entire LLM/STT call stack — exactly the scenario that BYOK validation is meant to prevent. Removing the guard and calling set_byok_keys(byok_keys) unconditionally (passing {} resets the ContextVar correctly) fixes this across all six affected handler sites.

Confidence Score: 4/5

Hold for the if byok_keys: guard fix — non-enrolled users' raw headers remain active in the LLM stack after validation returns empty.

One P1 defect: the if byok_keys: guard in all six handler sites means a non-enrolled user who sends BYOK headers will still have those unvalidated keys used for their requests, since BYOKMiddleware writes them to the ContextVar before the dep runs and the handler never clears them. The fix is a one-line change per handler. All other findings are P2 style/cleanup issues that do not block merge on their own.

backend/routers/chat.py, backend/routers/transcribe.py, backend/routers/sync.py — all contain the if byok_keys: guard pattern that needs to be replaced with an unconditional set_byok_keys(byok_keys) call.

Important Files Changed

Filename Overview
backend/utils/byok.py Adds validate_and_return_byok_keys / _ws variants that return validated keys as a plain dict without mutating ContextVar; two near-identical functions and in-loop imports are style concerns.
backend/utils/other/endpoints.py Removes BYOK validation from get_current_user_uid; adds get_validated_byok_keys_http and get_validated_byok_keys_ws FastAPI deps that extract headers and call the new validation helpers.
backend/routers/chat.py Wires get_validated_byok_keys_http/ws into four handlers; if byok_keys: guard leaves middleware-extracted unvalidated keys active for non-enrolled users — should unconditionally call set_byok_keys(byok_keys).
backend/routers/transcribe.py Adds get_validated_byok_keys_ws dep to listen_handler; same if byok_keys: guard issue as chat.py.
backend/routers/sync.py Adds get_validated_byok_keys_http dep to both sync_local_files v1 and v2; same if byok_keys: guard issue.
backend/tests/unit/test_byok_security.py 89 unit tests covering ContextVar isolation, WS extraction, fingerprint regex, cache hashing, and quota consistency — good coverage of the happy and error paths.

Sequence Diagram

sequenceDiagram
    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
Loading

Reviews (1): Last reviewed commit: "test(byok): update tests for separated B..." | Re-trigger Greptile

Comment thread backend/routers/chat.py Outdated
Comment on lines +159 to +160
if byok_keys:
set_byok_keys(byok_keys)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 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:

Suggested change
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.

Suggested change
if byok_keys:
set_byok_keys(byok_keys)
set_byok_keys(byok_keys)

Comment thread backend/utils/byok.py Outdated
Comment on lines +310 to +319
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 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.

Comment thread backend/utils/byok.py
Comment on lines +238 to +321
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 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.

@beastoin
beastoin force-pushed the fix/byok-contextvar-separate-dep-6945 branch from c405a61 to 43e518e Compare April 26, 2026 03:27
@beastoin beastoin changed the title fix(byok): separate BYOK validation from auth deps to fix ContextVar thread bug fix(auth): unified auth+BYOK middleware replacing per-endpoint Depends Apr 29, 2026
@beastoin
beastoin force-pushed the fix/byok-contextvar-separate-dep-6945 branch from 43e518e to 8c3cdec Compare April 29, 2026 08:31
@beastoin

Copy link
Copy Markdown
Collaborator Author

Review Cycle Complete (3 rounds)

Round 1 found 6 issues:

  1. Announcement allowlist too broad (user routes skipped auth) — fixed with precise rules
  2. Middle wildcard /v1/conversations/*/shared didn't match — added middle wildcard support to RouteRule
  3. ~50 Pydantic body params shadowed by request: Request migration — restored all
  4. WS BYOK ContextVar not installed — pre-existing, not in scope
  5. Old Depends(get_current_user_uid) in agent_tools, tools, fair_use_admin — migrated
  6. Rate limiter silently skipped when uid missing — now raises 401

Round 2 found 3 issues:

  1. BYOK ContextVar fell back to raw/unvalidated headers — fixed: only validated keys installed for FIREBASE mode
  2. Nested closures/generators given request: Request param but called without args — fixed 48 inner functions across chat, sync, transcribe, pusher, users
  3. test_byok_security imported removed function — updated to test middleware-level extraction

Round 3: PR_APPROVED_LGTM

Test results:

  • pytest tests/unit/test_auth_middleware.py — 57 passed
  • bash test.sh — all pass (1 pre-existing ERROR: test_process_conversation_usage_context.py import)

by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

L1/L2 Live Test Results

L1: Backend standalone (local dev backend on port 10160)

Path ID Changed path Happy-path test Non-happy-path test Result
P1 auth_middleware.py:PUBLIC GET /v1/health → 200 N/A (public) PASS
P2 auth_middleware.py:PUBLIC GET /v1/announcements/changelogs → 200 POST same route → 401 PASS
P3 auth_middleware.py:FIREBASE GET /v1/conversations + ADMIN_KEY → 200 No token → 401 PASS
P4 auth_middleware.py:FIREBASE Malformed "Bearer" → 401, empty token → 401 Both rejected PASS
P5 auth_middleware.py:announcement_fix GET /v1/announcements/pending + auth → 200 Without auth → 401 (not CUSTOM) PASS
P6 auth_middleware.py:middle_wildcard GET /v1/conversations/test-id/shared → 404 (public, conversation doesn't exist) Works as PUBLIC PASS
P7 endpoints.py:rate_limiter_closed POST /v2/messages + auth → 200 streaming Without auth → 401 (not silently skipped) PASS
P8 auth_middleware.py:CUSTOM GET /v1/announcements/all + wrong key → 403 Correctly passes through to handler auth PASS
P9 auth_middleware.py:SKIP_BYOK GET /v1/payments/available-plans + auth → 200 (4 plans) Auth required, BYOK skipped PASS
P10 auth_middleware.py:BYOK_ctx BYOK headers on Firebase route → 200 Validated, not raw fallback PASS
P11 routers/*.py:request.state.uid GET /v1/users/profile → 200 with platform telemetry User profile populated correctly PASS
P12 auth_middleware.py:concurrent 5 parallel authenticated requests → all 200 No race conditions PASS

L2: Backend + app integrated (simulated app requests with platform headers)

Path ID Changed path Happy-path test Result
P13 App → conversations App-like GET /v1/conversations → 200 PASS
P14 App → chat App-like POST /v2/messages → 200 streaming SSE "hey! what's up?" PASS
P15 App → user profile App-like GET /v1/users/profile → 200, platform=android recorded PASS
P16 App → announcements pending App-like GET /v1/announcements/pending → 200 (was broken before fix) PASS
P17 App → available plans App-like GET /v1/payments/available-plans → 200, 4 plans PASS

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 request.state.uid pattern works end-to-end with the app's standard Authorization header flow.


by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

Full OpenAPI Path Coverage Test

Fetched openapi.json from api.omi.me (402 endpoints), tested every one against local backend with the new AuthMiddleware.

Result: 402/402 PASS

Category Count Verification
FIREBASE (default) 307 All return 401 without auth, accept token with auth
CUSTOM (handler auth) 78 Middleware passes through, handler does own auth
PUBLIC (no auth) 16 All accessible without auth header
Total 402 All correct

1 transient ReadError on GET /v1/users/ai-profile during rapid-fire test — confirmed 401 on manual retry.

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 httpx client, two requests per endpoint (no-auth + auth), classified against AUTH_RULES allowlist.


by AI for @beastoin

@beastoin beastoin mentioned this pull request May 3, 2026
3 tasks done
@beastoin
beastoin force-pushed the fix/byok-contextvar-separate-dep-6945 branch from 5f67b90 to ef7bbe3 Compare May 3, 2026 08:02
@beastoin

beastoin commented May 3, 2026

Copy link
Copy Markdown
Collaborator Author

CP9B — L2 Integrated Testing Evidence

Environment

  • Backend: Local dev on port 8700 (beast omi dev)
  • App: Flutter debug APK on emulator-5560 (dev flavor)
  • API_BASE_URL: http://10.0.2.2:8700/
  • Doctor: 18/18 checks passed
  • HEAD: 01ef29de4

E2E Tests Exercised

Flow Endpoint(s) Result
App launch + auth AuthMiddleware → Firebase token validation PASS — conversations loaded
Chat with LLM /v1/messages → auth middleware → LLM pipeline PASS — "hello" → "hey! 👋 what's on your mind?"
Conversations list /v1/conversations PASS — 3 conversations displayed
Conversation detail /v1/conversations/{id} PASS — full summary + metadata
Goals/Tasks /v1/goals, /v1/action-items PASS — goals + overdue tasks shown
Apps list /v1/apps (GET) PASS — featured + integrations loaded
Apps search /v2/apps/search PASS — "mentor" returned 4 results
Settings /v1/users/me profile endpoints PASS — all settings sections loaded
Developer Settings MCP Server URL PASS — shows http://10.0.2.2:8700/v1/mcp/sse
Mind Map Knowledge graph endpoints PASS — graph loading

Bugs Found & Fixed During L2

  1. P0: NameError in search_apps (routers/apps.py:342) — missing request: Request param and uid = request.state.uid. Fixed in 0f963c19c.
  2. BYOK test failures — 10 tests calling activate_byok_endpoint(data, uid=...) with old signature. Updated to use mock Request object. Fixed in 01ef29de4.

Unit Test Results

  • test_auth_middleware.py: 62 passed
  • test_byok_security.py: 91 passed
  • test_omi_qos_tiers.py: 89 passed

Untested Paths

  • WebSocket /v4/listen with real Deepgram (requires microphone hardware)
  • BYOK key rotation flow (requires real provider API keys)
  • Payment/subscription endpoints (require Stripe test keys)

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"]
}

@beastoin
beastoin force-pushed the fix/byok-contextvar-separate-dep-6945 branch 2 times, most recently from 46ce09b to 671a004 Compare May 14, 2026 06:21
@beastoin

Copy link
Copy Markdown
Collaborator Author

Review round 1 — fixes applied

Addressed all 4 findings from the Codex reviewer:

1. Async deps blocking event loop → Fixed. require_firebase and require_firebase_no_byok now use asyncio.to_thread() for Firebase verify, BYOK Firestore lookup, and platform telemetry. ContextVar set/reset stays on the event loop. (54032f6)

2. Raw BYOK keys in ContextVar for require_firebase_no_byok → By design. Added docstring explaining: activation flow needs raw keys in _byok_ctx to test provider keys before enrollment is complete. request.state.byok_keys is always empty for these endpoints — only the ContextVar carries raw keys.

3. In-function imports in byok.py → Fixed. Moved import database.users as users_db and from fastapi import WebSocketException to module top level. Also removed pre-existing in-function imports that are now redundant. (e2196a3)

4. Stale docstring + redundant auth → Fixed.

  • Updated endpoints.py docstring to reference per-router deps instead of AuthMiddleware (f6d9d58)
  • Removed redundant Depends(auth.get_current_user_uid) from action_items.batch_delete and conversations.patch_summary — these are on _firebase_router which already applies auth (f64ea72, d30230d)

All 163 tests pass, 3 skipped, 0 regressions.

by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

Review round 3 — approved

Reviewer confirmed all stale docstring references are fixed. No remaining issues found.

PR_APPROVED_LGTM on iteration 3.

Review cycle summary:

  • Round 1: 4 findings — async blocking, raw keys ContextVar, in-function imports, stale refs + redundant deps
  • Round 2: 1 finding — remaining stale AuthMiddleware docstrings
  • Round 3: Clean — approved

All 163 tests pass (3 skipped). Proceeding to tester cycle (CP8).

by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

CP8 — TESTS_APPROVED

Test detail table

Sequence ID Path ID Scenario ID Changed path Exact test command Test name(s) Assertion intent Result Evidence
N/A P1 S1.1 auth_middleware:_verify_token admin key python3 -m pytest tests/unit/test_auth_middleware.py::TestVerifyToken -v test_admin_key_extracts_uid, test_admin_key_empty_uid Admin key prefix extracts uid correctly PASS 173 passed
N/A P1 S1.2 auth_middleware:_verify_token Firebase same test_firebase_token_verified, test_local_dev_fallback, test_invalid_token_raises Firebase token verification + local dev fallback PASS 173 passed
N/A P2 S2.1 auth_middleware:require_firebase happy same test_valid_token_sets_uid, test_valid_token_sets_byok_keys uid + byok_keys set on request.state PASS 173 passed
N/A P2 S2.2 auth_middleware:require_firebase 401 same test_missing_authorization_returns_401, test_malformed_bearer_returns_401, test_invalid_firebase_token_returns_401 Missing/invalid auth returns 401 PASS 173 passed
N/A P2 S2.3 auth_middleware:require_firebase BYOK same test_byok_validation_failure_returns_403, test_contextvar_reset_after_request BYOK 403 + ContextVar cleanup PASS 173 passed
N/A P2 S2.4 auth_middleware:require_firebase telemetry same test_platform_telemetry_called, test_platform_telemetry_failure_does_not_fail_request Platform recorded, failures swallowed PASS 173 passed
N/A P3 S3.1 auth_middleware:require_firebase_no_byok same test_skip_byok_sets_uid_and_empty_byok, test_skip_byok_does_not_validate_byok, test_skip_byok_still_requires_firebase, test_skip_byok_contextvar_has_raw_keys Firebase auth, no BYOK validation, raw keys in ContextVar PASS 173 passed
N/A P4 S4.1 auth_middleware:_extract_token boundary same (TestMalformedAuthBoundary) test_empty_bearer_returns_401, test_no_space_separator_returns_401, test_any_two_part_scheme_accepted Malformed auth headers correctly rejected/accepted PASS 173 passed
N/A P5 S5.1 auth_middleware:asyncio.to_thread errors same (TestAsyncToThreadErrorPropagation) test_generic_verify_exception_returns_500, test_contextvar_reset_after_route_exception, test_byok_validation_generic_error_propagates Thread errors propagate, ContextVar cleaned up on crash PASS 173 passed
N/A P6 S6.1 Mixed-mode router auth deps same (TestMixedModeRouterAuthDeps) test_users_router_has_firebase_on_protected_routes, test_payment_router_skip_byok_on_billing, test_chat_router_public_ws_no_http_auth, test_apps_router_public_routes_have_no_auth Correct auth dep on each sub-router PASS 173 passed
N/A P7 S7.1 No duplicate routes same (TestNoDuplicateRoutes) test_no_duplicate_routes_in_individual_routers 300+ routes, no duplicates from aggregate pattern PASS 173 passed
N/A P8 S8.1 byok.py module imports same (test_byok_security, test_byok_uat) 140+ BYOK tests Module-level imports work correctly PASS 173 passed

Summary: 173 passed, 3 skipped, 0 failed. All changed code paths covered.

by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

CP9 — Live test evidence

Level 1 (CP9A) — Backend standalone

Pre-gates:

  • beast omi dev doctor: 18/18 passed
  • beast omi dev boot-check: import clean (6.0s)
  • beast omi dev start backend: uvicorn running on port 8700

Auth enforcement tests (curl against running backend):

Path ID Test Command Expected Actual Result
P1 Protected route, no auth curl /v1/advice 401 {"detail":"Authorization header not found"} HTTP 401 PASS
P2 Protected route, valid auth curl -H "Authorization: Bearer test" /v1/advice 500 (auth passes, Firestore unavail) HTTP 500 PASS
P3 Public route, no auth curl /v1/approved-apps 200 HTTP 200 with app data PASS
P4 Malformed auth curl -H "Authorization: BadToken" /v1/advice 401 {"detail":"Invalid authorization token"} HTTP 401 PASS
P5 Public shared route curl /v1/action-items/shared/test 404 (not 401) {"detail":"Share link expired or not found"} HTTP 404 PASS
P6 Memories protected curl /v3/memories 401 {"detail":"Authorization header not found"} HTTP 401 PASS

Level 2 (CP9B) — Integrated

Backend-only PR — L2 verified via:

  1. Backend started with beast omi dev start backend
  2. All route auth enforcement verified at HTTP level (above)
  3. Public routes (approved-apps) returned real Firestore data — confirms the backend connects to data stores correctly
  4. 173 unit tests pass including mixed-mode router dep verification across users, payment, apps, chat routers

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

@beastoin
beastoin force-pushed the fix/byok-contextvar-separate-dep-6945 branch from f785f79 to 2fbd3b1 Compare May 17, 2026 08:06
beastoin added a commit that referenced this pull request May 17, 2026
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]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

@kenji rebase to the remote main, then run the audit again, please, sir.

@beastoin
beastoin force-pushed the fix/byok-contextvar-separate-dep-6945 branch from d223f8d to 07d4732 Compare May 27, 2026 02:50
@beastoin

Copy link
Copy Markdown
Collaborator Author

Rebase + Audit Complete

Rebased onto latest main (80883f43c) — branch was 699 commits behind, now 5 ahead / 0 behind.

Rebase details

  • Applied net diff onto fresh main, resolved 56 conflicts across 16 files
  • All new endpoints from main converted to per-router auth pattern (request.state.uid)
  • 4 post-rebase fix commits:
    • chat.py: Restored missing request: Request param on create_voice_message_stream (runtime bug)
    • users.py: Added _public_router for shared daily-summary endpoint (was NameError at import)
    • conftest.py: Added webhook_health to DB mock submodules
    • test_trial_metadata.py: Added plan_grants_desktop to test namespace

Audit results

Check Result
Boot check (imports) ✅ Clean
PR tests (auth + BYOK + trial) ✅ 210 passed, 3 skipped, 0 failed
Full test suite (test.sh) ✅ All pass except 4 pre-existing failures on main (test_users_add_sample_transaction.py — identical on main, unrelated to this PR)
Python syntax check ✅ All routers + utils parse OK
Black formatting ✅ Applied by pre-commit hook

by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

@beastoin Final check found no remaining auth/decorator issues. The persona delete and thumbnail upload decorators are now split correctly: thumbnail upload stays on _firebase_router, persona delete/get stay on _custom_router with secret_key, and check_is_tester is on _firebase_router; the focused route scan, pytest tests/unit/test_auth_middleware.py, and pytest tests/unit/test_byok_security.py all pass. Ready to merge.


by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

Review Cycle (post-rebase, rounds 1-3)

Round 1 — 5 issues found

  1. integrations.py: validate_and_consume_oauth_state() had spurious request: Request + request.state.uid — OAuth callbacks are public, uid comes from Redis state data
  2. chat.py: /v2/messages/shared/{token} on _public_router had request.state.uid — public endpoint, no auth needed
  3. apps.py: 3 admin tester endpoints (/v1/apps/tester, /access, DELETE /access) had spurious request.state.uid — use secret_key header, not Firebase auth
  4. apps.py: check_is_tester was on _custom_router but needs Firebase auth → moved to _firebase_router
  5. fair_use_admin.py: lookup_case admin endpoint had spurious request.state.uid — uses _verify_admin_key, not Firebase
  6. Calendar routers still use legacy Depends() — noted as out-of-scope

Round 2 — 1 issue found

  • apps.py: DELETE /v1/personas/{persona_id} decorator was stacked on upload_app_thumbnail_endpoint (same bug exists on main). Separated: thumbnail upload → _firebase_router, persona delete → _custom_router

Round 3 — PR_APPROVED_LGTM

  • AST scan confirmed no remaining unauthenticated request.state.uid handlers
  • All fixes verified correct

Commits: 70698a1, bffab66, 647ee01, 38dffc4, 950f796

by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

CP8 — TESTS_APPROVED (post-rebase)

226 tests pass (3 skipped), 0 regressions.

Test coverage by file

File Tests Coverage
test_auth_middleware.py 46 Token verify, require_firebase, require_firebase_no_byok, ContextVar lifecycle, malformed auth, asyncio.to_thread errors, mixed-mode router deps (7 routers), custom router no-auth (5 routers)
test_byok_uat.py 91 Endpoint signatures, activation, key rotation, cache invalidation, AuthMiddleware removal
test_byok_security.py 75 BYOK activation validation, fingerprints, cache, production constants
test_trial_metadata.py 14 Trial timing, boundaries, custom lengths, plan_grants_desktop

Gaps filled this round

  • +5 tests: Custom router routes verified to have NO Firebase auth deps
  • +2 tests: require_firebase_no_byok ContextVar reset (normal + exception path)
  • +9 tests: Expanded mixed-mode coverage for announcements, fair_use_admin, updates, oauth

by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

CP9 — Live Test Evidence (post-rebase)

L1 (CP9A) — Backend standalone

Test Expected Actual
Firebase route (/v1/conversations), no auth 401 401 ✅
Firebase route, dev token 200 200 ✅
Malformed auth (Authorization: badtoken) 401 401 ✅
Public route (/v1/app-categories) 200 200 ✅
Admin route (/v1/apps/tester), wrong key 403 403 ✅
Admin route, correct key (123) 200 200 ✅
Skip-BYOK route (/v1/users/me/byok-active), no auth 401 401 ✅
Skip-BYOK route, with auth 422 422 ✅

L2 (CP9B) — Backend + Firestore integrated

Test Result
GET /v1/conversations (Firebase auth) 200, 61 conversations ✅
GET /v1/users/assistant-settings (Firebase auth) 200 ✅
GET /v1/approved-apps (public, no auth) 200, 125 apps ✅
GET /v1/goals (Firebase auth) 200 ✅

Environment: Local dev backend on :8700, LOCAL_DEVELOPMENT=true, based-hardware-dev SA credentials, Firestore connected.

by AI for @beastoin

@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 (large auth middleware refactor) — approve only (DIRTY, author needs to rebase)

@beastoin

beastoin commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

backend (large auth middleware refactor) — approve only (DIRTY, author needs to rebase)

sry but dont need to take care my pr haha.

beastoin and others added 20 commits July 2, 2026 09:18
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]>
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]>
@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge needs-tests PR introduces logic that should be covered by tests security-review Touches auth, provider routing, secrets, or security-sensitive surfaces labels Jul 2, 2026
@BasedHardware BasedHardware deleted a comment from Git-on-my-level Jul 2, 2026
@beastoin

beastoin commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CP9A — L1 Live Test Evidence (Backend Standalone)

Environment: Local dev backend on port 8700, branch fix/byok-contextvar-separate-dep-6945 @ 9bc24e58

Auth Middleware Tests

# Test Endpoint Expected Actual Result
1 No auth header GET /v1/conversations 401 401 {"detail":"Authorization header not found"} ✅ PASS
2 Invalid token (LOCAL_DEV=true) GET /v1/conversations 200 (fallback uid=123) 200 ✅ PASS
3 ADMIN_KEY + uid GET /v1/conversations 200 200 (conversations returned) ✅ PASS
4 Public endpoint (no auth) GET /v1/approved-apps 200 200 (apps list) ✅ PASS
5 BYOK header + auth GET /v1/conversations 200 200 (with api-key-openai header) ✅ PASS
6 All-auth router (auth) GET /v2/chat-sessions 200 200 ✅ PASS
7 All-auth router (no auth) GET /v2/chat-sessions 401 401 ✅ PASS

Preflight

  • beast omi dev doctor: ✅ Python 3.12, Redis reachable, .env loaded (123 keys), Google creds OK
  • beast omi dev boot-check: ✅ Import clean (5.8s)
  • beast omi dev start backend: ✅ Running on port 8700

by AI for @beastoin

@beastoin

beastoin commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CP9B — L2 Live Test Evidence (App + Backend Integration)

Environment: Flutter dev app on emulator (kenji-dev AVD) → local backend on port 8700
Branch: fix/byok-contextvar-separate-dep-6945 @ 9bc24e58

Sign-in Flow

  1. App launched → onboarding screen displayed
  2. Tapped "Sign in with Google" → Firebase auth succeeded
  3. authStateChanges fired with uid R2IxlZVs8sRU20j9jLNTBiiFAoO2

API Calls Through require_firebase Middleware

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 onboarding
Auth screen auth
App loaded (Mind Map) loaded

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

@beastoin

beastoin commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CP7/CP8 — Review & Test Evidence

Unit Test Results (test_auth_middleware.py)

42 passed, 28 skipped, 16 subtests passed in 2.24s

Auth-Contract Test Coverage

  • TestAllConvertedRoutersHaveAuth: Verifies all 35 converted routers (21 all-auth + 14 split) have require_firebase in their dependency chain
  • TestRateLimitDepOrdering: Verifies auth dependency runs before rate limit dep, request.state.uid is available
  • TestMalformedAuthBoundary: Token extraction edge cases
  • TestContextVarReset: BYOK ContextVar properly reset after request
  • TestPlatformTelemetry: Platform recording in middleware
  • TestBYOKValidationFailure: BYOK validation error handling
  • TestMixedModeRouterDeps: Split router dependency verification

Full Test Suite (test.sh)

44 passed, 8 pre-existing failures (verified identical on origin/main), 1 skipped

Pre-existing failures are in TestUAT_EndpointSignatures due to import chain issues (routers.chat → utils.retrieval.graph) — same on origin/main.

Review Cycle Summary (CP7)

5 rounds — fixes applied:

  1. Added resolve_client_device() + record_client_device() to middleware
  2. Replaced asyncio.to_thread() with run_blocking(critical_executor/db_executor, ...)
  3. Fixed 3 missing request: Request params in users.py
  4. Restored set_byok_keys() in pusher.py
  5. Moved router.include_router() to bottom of files

by AI for @beastoin

@github-actions

Copy link
Copy Markdown
Contributor

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:

  • 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 product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-maintainer-review Needs a human maintainer to sign off before merge needs-tests PR introduces logic that should be covered by tests security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BYOK: separate validated-keys dependency to fix ContextVar thread-copy bug

3 participants