Repository navigation
Desktop Rust backend: implement BYOK for Gemini/Anthropic proxies, fix paywall bypass (#7357) - #7359
Conversation
Extracts and validates X-BYOK-{OpenAI,Anthropic,Gemini,Deepgram} headers
from requests. Provides get_byok_key() for single-provider extraction and
has_all_byok_keys() to check all 4 are present (mirrors Python's
_request_has_all_byok_keys()). Includes 8 unit tests.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
PaywallChecker.is_paywalled() now accepts request headers and forwards all 4 X-BYOK-* headers to Python's /v1/users/me/paywall endpoint so its _request_has_all_byok_keys() escape hatch can fire for BYOK users. Cache is partitioned by BYOK presence (uid vs uid:byok) so a cached paywalled=true from a non-BYOK request doesn't block a subsequent BYOK request that should pass Python's escape hatch, and vice versa. Co-Authored-By: Claude Opus 4.6 <[email protected]>
) PaywalledAuthUser extractor now passes the full request headers to is_paywalled() so BYOK headers can be forwarded to Python. No presence-only bypass — all validation happens in Python's fingerprint check. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Both gemini_proxy and gemini_stream_proxy now check for x-byok-gemini header. When present: - Uses AI Studio with user's API key (can't mix with Vertex SA auth) - Skips Vertex AI routing and transforms (embedContent→predict) - Skips server-key rate limiting (user pays their own bill) - Preserves model allowlist, body sanitization, and action validation Server-key path extracted to gemini_proxy_server_key() and gemini_stream_server_key() for clarity. Co-Authored-By: Claude Opus 4.6 <[email protected]>
chat_completions handler now checks x-byok-anthropic header. When present: - Uses user's Anthropic API key instead of server key - Skips server-key rate limiting - Skips usage logging to Firestore (avoids overstating Omi spend) Both streaming and non-streaming paths support BYOK. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Greptile SummaryThis PR implements BYOK (Bring Your Own Keys) support across the Rust desktop backend — Gemini and Anthropic proxies now forward user-supplied API keys instead of the server key, and the paywall checker forwards all 4 BYOK headers to Python so the existing escape hatch fires correctly for enrolled users.
Confidence Score: 3/5The BYOK routing and paywall forwarding work correctly for legitimate users, but any authenticated user can bypass rate limiting on both proxies by sending a fake BYOK header with no key validation at the rate-limit decision point. The paywall and provider-routing logic are well-structured and the new byok.rs helpers are thoroughly tested. The gap is that is_byok in both proxy.rs and chat_completions.rs is set purely by header presence, while the PR's stated security model says validation happens in Python — but that only covers the paywall path, not the rate-limit path. Any account holder can permanently disable per-user rate limiting by including a non-empty fake BYOK header on every request. proxy.rs and chat_completions.rs — the rate-limiting bypass logic needs a closer look before merge.
|
| Filename | Overview |
|---|---|
| desktop/Backend-Rust/src/byok.rs | New module: shared BYOK header helpers with 8 unit tests covering all edge cases; clean, well-tested utility. |
| desktop/Backend-Rust/src/paywall.rs | Extends is_paywalled to accept request headers, forwards all 4 BYOK headers to Python paywall endpoint, and partitions the cache by BYOK presence; logic is sound. |
| desktop/Backend-Rust/src/auth.rs | Minimal change: passes parts.headers to is_paywalled; straightforward thread-through with no new logic. |
| desktop/Backend-Rust/src/routes/proxy.rs | Adds BYOK path for both gemini_proxy and gemini_stream_proxy; correctly skips Vertex transforms, but rate limiting is bypassed by any non-empty header value without key validation. |
| desktop/Backend-Rust/src/routes/chat_completions.rs | Adds BYOK Anthropic key support; correctly skips usage logging and rate limiting for BYOK, but rate limiting bypass requires no key validation. The if !is_byok block in the streaming handler has incorrect indentation. |
| desktop/Backend-Rust/src/main.rs | Single-line change: registers the new byok module; no issues. |
| desktop/CHANGELOG.json | Adds unreleased changelog entry describing the BYOK fix; accurate and appropriate. |
Reviews (1): Last reviewed commit: "Add changelog entry for BYOK gap fix (is..." | Re-trigger Greptile
| let byok_gemini_key = byok::get_byok_key(&headers, byok::HEADER_GEMINI); | ||
| let is_byok = byok_gemini_key.is_some(); | ||
|
|
||
| // Rate limit check — skip when using BYOK key | ||
| if !is_byok { | ||
| let decision = state.gemini_rate_limiter.check_and_record(&user.uid, state.redis.as_ref()).await; | ||
| if decision == RateDecision::Reject { | ||
| tracing::warn!("gemini_proxy: rate limit rejected uid={}", user.uid); | ||
| return Err(ProxyError::RateLimited); | ||
| } | ||
|
|
||
| // Apply model degradation if needed | ||
| let effective_path = rate_limit::maybe_rewrite_model_path(&path, &decision, action); | ||
| if effective_path != path { | ||
| tracing::info!( | ||
| "gemini_proxy: degraded uid={} {} -> {}", | ||
| user.uid, | ||
| path, | ||
| effective_path | ||
| ); | ||
| } | ||
|
|
||
| // Non-BYOK path: use server key with Vertex AI / AI Studio routing | ||
| return gemini_proxy_server_key( | ||
| &state, &user, &effective_path, action, model, &sanitized_body, | ||
| ) | ||
| .await; | ||
| } |
There was a problem hiding this comment.
Rate-limit bypass via any non-empty BYOK header
is_byok is set to true whenever the x-byok-gemini header is non-empty — there is no key fingerprint or format validation at this decision point. Any authenticated user can send x-byok-gemini: anything to permanently bypass rate limiting for both gemini_proxy and gemini_stream_proxy. Upstream Gemini will reject the fake key with a 401, so the attacker gains no useful LLM output, but they can exhaust proxy connection-pool resources without limit and completely sidestep per-user rate limiting that was put in place to protect server costs.
The same bypass exists in chat_completions.rs lines 469–488 for x-byok-anthropic. The PR's design doc says key validation happens in Python's paywall escape hatch, but that path is only exercised for the paywall check — the rate-limit decision is made purely in Rust before any Python validation.
| state: &AppState, | ||
| user: &AuthUser, | ||
| effective_path: &str, | ||
| action: &str, | ||
| model: &str, | ||
| sanitized_body: &[u8], | ||
| ) -> Result<Response, ProxyError> { |
There was a problem hiding this comment.
Unused
user parameter in extracted helper
gemini_proxy_server_key accepts user: &AuthUser but never references it — no log lines, no UID-tagged traces, nothing. Rust won't warn because function parameters are exempt from the unused-variable lint, so this dead parameter silently compiles. The same situation applies to gemini_stream_server_key which doesn't even accept user, making log attribution inconsistent between the two helpers when an error occurs deep in the Vertex/AI-Studio path.
| @@ -844,6 +867,7 @@ async fn handle_streaming( | |||
| } | |||
| }); | |||
| } | |||
| } // if !is_byok | |||
There was a problem hiding this comment.
The
if !is_byok guard was added without re-indenting the inner block, so if let Some(ref fu) sits at the same column as its parent if. The comment marker } // if !is_byok also sits one level too far to the right, making the closing brace structure difficult to read.
| // Log usage asynchronously — skip for BYOK (user pays own bill) | |
| if !is_byok { | |
| if let Some(ref fu) = final_usage { | |
| let merged = AnthropicUsage { | |
| input_tokens: initial_usage.as_ref().map_or(0, |u| u.input_tokens), | |
| output_tokens: fu.output_tokens, | |
| cache_creation_input_tokens: initial_usage.as_ref().map_or(0, |u| u.cache_creation_input_tokens), | |
| cache_read_input_tokens: initial_usage.as_ref().map_or(0, |u| u.cache_read_input_tokens), | |
| }; | |
| let cost = compute_cost(&merged, &upstream_model); | |
| let uid_clone = uid.clone(); | |
| let fs = firestore.clone(); | |
| tokio::spawn(async move { | |
| if let Err(e) = fs.record_llm_usage( | |
| &uid_clone, | |
| merged.input_tokens, | |
| merged.output_tokens, | |
| merged.cache_read_input_tokens, | |
| merged.cache_creation_input_tokens, | |
| merged.input_tokens + merged.cache_creation_input_tokens | |
| + merged.cache_read_input_tokens + merged.output_tokens, | |
| cost, | |
| "omi", | |
| ).await { | |
| tracing::error!("chat_completions: usage log failed: {}", e); | |
| } | |
| }); | |
| } | |
| } |
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
3 tests verify BYOK vs non-BYOK cache isolation: - cache_partitioned_by_byok_presence: separate keys for BYOK/non-BYOK - partial_byok_uses_non_byok_cache: missing one header → non-BYOK path - empty_byok_headers_use_non_byok_cache: empty value → non-BYOK path Co-Authored-By: Claude Opus 4.6 <[email protected]>
CP9A/CP9B Live Test Evidence — BYOK Desktop Backend (#7357)Pre-gate checks
CP9A — Level 1: Rust backend standalone
CP9B — Level 2: Backend + App integrated
Key log evidenceAll 10 changed code paths verified with both happy and non-happy tests. All 202 unit tests pass. by AI for @beastoin |
…7357) Mirrors Python's _check_byok_validity: SHA-256 fingerprint comparison against Firestore enrollment, 30s TTL in-memory cache, heartbeat TTL (7 days), silent header clearing for non-BYOK users. Adds ByokState, ByokStateCache, ByokValidation types and 10 behavior tests. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…creation time (issue #7357) get_user_byok_state: reads users/{uid}.byok map (active, fingerprints, last_seen_at) get_user_subscription_plan: reads subscription.plan with free->basic migration get_user_creation_time: Firebase Identity Toolkit accounts:lookup REST API Co-Authored-By: Claude Opus 4.6 <[email protected]>
…se Auth logic (issue #7357) Eliminates the Python GET /v1/users/me/paywall dependency. PaywallChecker now reads subscription plan and BYOK state from Firestore, account creation time from Firebase Auth REST API. Keeps BYOK escape hatch, 5-min cache, fail-open. Adds 8 behavior tests for trial expiry logic. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…thUser extractor (issue #7357) Validates BYOK fingerprints against Firestore enrollment before paywall check. Returns 403 on mismatch. Adds byok_stripped flag so route handlers can ignore BYOK headers for non-enrolled users. Updates paywall call to use native logic. Co-Authored-By: Claude Opus 4.6 <[email protected]>
) Non-BYOK-enrolled users who send BYOK headers now have them silently ignored in both gemini_proxy and gemini_stream_proxy handlers. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…7357) Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Constructs ByokStateCache, passes it + firestore + auth_project_id to PaywallChecker. Adds byok_cache_extension layer to router. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Paywall no longer delegates to Python — the OMI_PYTHON_API_URL env var and python_api_base config field are no longer needed. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Security fix: non-BYOK users forging all 4 BYOK headers could bypass the paywall escape hatch. Now is_paywalled takes a byok_stripped param and only trusts the escape hatch when headers are validated. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
…sue #7357) Renamed get_user_subscription_plan to get_user_effective_plan. Now checks current_period_end for paid plans and falls back to basic when expired, matching Python's get_user_valid_subscription behavior. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Transient Firestore failures now return default inactive state without caching, preventing a 30s window where an active BYOK user could appear paywalled due to a cached error-default. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Review fixes (iteration 1)Fixed all 3 security/correctness issues from code review: 1. Paywall escape hatch bypass (Security)Problem: Non-BYOK users forging all 4 BYOK headers could bypass the paywall — 2. Expired paid plans not caught (Correctness)Problem: Rust only read 3. Firestore error cached as inactive BYOK (Cache poisoning)Problem: Transient Firestore errors were cached as All 219 tests pass. by AI for @beastoin |
…ssue #7357) Matches Python's get_user_valid_subscription which only returns a paid plan when current_period_end exists AND is in the future. Missing or unparseable period_end now falls back to basic. Co-Authored-By: Claude Opus 4.6 <[email protected]>
) Co-Authored-By: Claude Opus 4.6 <[email protected]>
Review fixes (iteration 2)1. Missing current_period_end falls back to basicProblem: Paid plan with missing/unparseable 2. Added missing test coverage
221 tests pass. by AI for @beastoin |
… boundaries Co-Authored-By: Claude Opus 4.6 <[email protected]>
…BYOK state and plan parsing Co-Authored-By: Claude Opus 4.6 <[email protected]>
CP8 Tester Coverage ResponseAdded (21 new tests, 242 total):byok.rs (8 new tests):
firestore.rs (14 new tests — Firestore document parsing): Extracted
Pushback (infeasible in this codebase):
Coverage summary:
by AI for @beastoin |
…ge via URL Use without_url() on reqwest::Error to avoid logging BYOK API keys embedded in Gemini URL query strings during transient network failures. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Review Fix: BYOK API key leak in Gemini error logsIssue: Fix: Use Not affected: Anthropic (key in by AI for @beastoin |
…ith tests 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]>
CP9 Changed-Path Coverage ChecklistChanged executable paths from PR diff:
Test strategy:
by AI for @beastoin |
CP9A/CP9B Live Test EvidenceBuild evidence
Functional test results (curl + backend logs)
Backend log evidencePath coverage summary
by AI for @beastoin |
Merged ✓All workflow checkpoints passed (CP0–CP9B). 247 tests, 0 failures. Live tested with named bundle by AI for @beastoin |
…xies, fix paywall bypass (BasedHardware#7357) (BasedHardware#7359)" This reverts commit 777e213, reversing changes made to db341b4.
Summary
GET /v1/users/me/paywall) with native Rust logic reading subscription plan, BYOK state, and account creation time directly from Firestore/Firebase Authbyok_strippedflag to prevent non-BYOK users from forging BYOK headers to bypass paywall; expired paid plans now correctly fall back to basic; Firestore errors not cached to prevent cache poisoningChanges
byok.rsByokState,ByokStateCache(30s TTL),validate_byok_request()(SHA-256 fingerprint check),ByokValidationenum,ByokCacheExt, 18 testspaywall.rsPaywallChecker(plan + BYOK + account age),byok_strippedescape hatch guard,is_trial_expiredpure function, 10 testsauth.rsPaywalledAuthUser.byok_strippedfield, BYOK validation step in extractor, 403 for fingerprint mismatchservices/firestore.rsget_user_byok_state(),get_user_effective_plan()(withcurrent_period_endcheck),get_user_creation_time()(Firebase Identity Toolkit), extracted pure parsing functions, 14 testsroutes/proxy.rsbyok_strippedroutes/chat_completions.rsbyok_strippedroutes/tts.rsbyok_strippedmain.rsByokStateCache+ updatedPaywallChecker(no more Python delegation)config.rspython_api_base(no longer needed)Security fixes (from review cycle)
byok_strippedparam disables escape hatchplanwithout checkingcurrent_period_end→ Fixed:get_user_effective_planvalidates period endTest plan
cargo test— 242 tests pass (0 failures)OMI_APP_NAME="omi-byok-7357" ./run.shCloses #7357
🤖 Generated with Claude Code