Repository navigation
Reland: Desktop Rust BYOK fingerprint validation + native paywall (#7357) - #7364
Conversation
Greptile SummaryThis PR replaces Python paywall delegation with native Rust logic and adds full BYOK fingerprint validation (SHA-256 against Firestore enrollment, 7-day heartbeat TTL, 30s state cache). The
Confidence Score: 3/5The core logic is well-structured and comprehensively tested, but two areas need verification before merging: the Firestore type of current_period_end and the default-false behavior of byok_stripped when extensions are absent. The current_period_end parser only handles integerValue — if the Python backend writes this as a Firestore Timestamp, paid users with accounts older than 3 days get incorrectly paywalled. The BYOK validation in auth.rs is gated on two nested extension checks; if ByokCacheExt is absent, byok_stripped defaults false and forged headers trip the escape hatch. Both issues are mitigated in the current main.rs wiring, but neither invariant is enforced at the code level. desktop/Backend-Rust/src/services/firestore.rs (current_period_end type handling) and desktop/Backend-Rust/src/auth.rs (byok_stripped default when extensions absent)
|
| Filename | Overview |
|---|---|
| desktop/Backend-Rust/src/byok.rs | New module implementing BYOK header extraction, SHA-256 fingerprint validation, and 30s TTL cache; 23 tests cover the full validation matrix. |
| desktop/Backend-Rust/src/paywall.rs | Rewritten to native Rust; correctly implements byok_stripped escape-hatch guard, but caches the fail-open false result on errors unlike the BYOK cache. |
| desktop/Backend-Rust/src/auth.rs | Adds byok_stripped field and BYOK validation step, but validation only runs when both extensions are present; defaults to false when absent. |
| desktop/Backend-Rust/src/services/firestore.rs | New BYOK/subscription methods; parse_effective_plan_from_doc only reads current_period_end as integerValue — timestampValue silently falls back to basic. |
| desktop/Backend-Rust/src/routes/proxy.rs | BYOK path correctly uses get_byok_key_if_active and e.without_url() to prevent key leaks. |
| desktop/Backend-Rust/src/routes/chat_completions.rs | Correctly gates BYOK Anthropic key on byok_stripped, skips rate-limiting and usage logging for BYOK requests. |
| desktop/Backend-Rust/src/main.rs | Wires ByokStateCache and updated PaywallChecker correctly; both extensions always registered together. |
| desktop/Backend-Rust/src/config.rs | Removes python_api_base; straightforward cleanup. |
Comments Outside Diff (3)
-
desktop/Backend-Rust/src/services/firestore.rs, line 2094-2108 (link)current_period_endonly parsed asintegerValue—timestampValuesilently falls back to "basic"parse_effective_plan_from_doconly chains throughintegerValuewhen readingcurrent_period_end. If the Python backend wrote this field as a Firestore Timestamp type (timestampValue), theand_then(|v| v.get("integerValue"))step returnsNone, theNone =>arm returns"basic", and every paid user with an account older than 3 days is incorrectly paywalled. The PR says this mirrorsget_user_valid_subscription()in Python — please confirm the canonical Firestore type for this field is always an integer. If Timestamp is possible, the parser needs to handle both branches. -
desktop/Backend-Rust/src/auth.rs, line 62-90 (link)BYOK validation skipped when
ByokCacheExtis absent —byok_strippeddefaultsfalse, escape hatch fires on forged headersWhen
ByokCacheExtis not present,byok_strippedstaysfalse. The paywall escape hatch is!byok_stripped && has_all_byok_keys(headers), so a non-enrolled user who forges all four BYOK headers finds!false && true = trueand bypasses the paywall. Both extensions are always co-registered inmain.rstoday, but the invariant lives only at the wiring layer. A safer default would bebyok_stripped = truewhen the BYOK cache extension is unavailable. -
desktop/Backend-Rust/src/paywall.rs, line 1104-1117 (link)Fail-open paywall result is cached — a transient Firestore error gives paywalled users 5 minutes of free access
check_trial_expiredreturnsfalseon any error and that value is unconditionally written to the 5-minute cache. The BYOK cache explicitly avoids caching error results viashould_cache; the paywall cache should do the same to avoid caching a fail-open result that lets paywalled users through for the full TTL.
Reviews (1): Last reviewed commit: "Reapply "Desktop Rust backend: implement..." | Re-trigger Greptile
| } | ||
|
|
||
| fn all_byok_headers_with_keys() -> HeaderMap { | ||
| headers_with(&[ | ||
| ("x-byok-openai", "sk-o"), | ||
| ("x-byok-anthropic", "sk-a"), | ||
| ("x-byok-gemini", "sk-g"), | ||
| ("x-byok-deepgram", "sk-d"), | ||
| ]) | ||
| } | ||
|
|
||
| fn fingerprints_for_keys() -> HashMap<String, String> { | ||
| let mut fp = HashMap::new(); | ||
| fp.insert( | ||
| "openai".to_string(), | ||
| hex::encode(Sha256::digest(b"sk-o")), | ||
| ); | ||
| fp.insert( | ||
| "anthropic".to_string(), | ||
| hex::encode(Sha256::digest(b"sk-a")), | ||
| ); | ||
| fp.insert( | ||
| "gemini".to_string(), | ||
| hex::encode(Sha256::digest(b"sk-g")), | ||
| ); | ||
| fp.insert( | ||
| "deepgram".to_string(), | ||
| hex::encode(Sha256::digest(b"sk-d")), | ||
| ); | ||
| fp | ||
| } | ||
|
|
||
| fn active_state_with_fingerprints(fingerprints: HashMap<String, String>) -> ByokState { |
There was a problem hiding this comment.
BYOK-active user with empty fingerprint map passes validation unconditionally
If Firestore contains byok.active = true with an empty fingerprints map and a fresh heartbeat, validate_byok_request skips the loop and returns Ok(Active), also bypassing the paywall. This is only exploitable if Firestore security rules allow users to self-write byok.active — please confirm the rules prevent that. If rules are tight this is benign; if not, the empty-fingerprint path should return Inactive or an error.
L1/L2 Behavior Tests with macOS App ScreenshotsTest bundle: Happy Path Screenshots1. Main app — active trial, no paywall (debug_trial_mode=active)Home screen with sidebar navigation, chat input, no paywall popup. 2. Settings → Plan and Usage — trial active (2d 1h remaining)Shows "Premium Trial Active" with countdown ring, included features list, and "Use Omi free forever" BYOK option. 3. Settings → Advanced — BYOK key configuration pageShows AI Setup, Workspace, Browser Extension, Dev Mode settings. BYOK key management section accessible from here. Failure Path Screenshots4. Paywall popup — trial expired (debug_trial_mode=expired, desktop_isPaywalled=true)Modal overlay: "You've hit your monthly limit" with "Upgrade" and "Bring your own keys" buttons. This is what users see when backend returns 402. 5. Settings → Plan and Usage — trial endedShows "Trial Ended - Upgrade to keep unlimited access" with "View Plans" button. BYOK escape hatch: "Use Omi free forever - Switch to your own keys". Backend Behavior Tests (curl + Firebase ID token)All tested against live Rust backend with real Firestore reads:
Backend Log EvidenceUnit Test EvidenceNotes
by AI for @beastoin |
BYOK Behavior Test Evidence — Complete SuiteAll tests run against the Rust desktop backend ( Unit tests: 247 passed, 0 failed ( Test 1: Paywall Blocks Non-BYOK User ✅State:
Proof: All three cost-incurring routes correctly block paywalled users. Test 2: BYOK Happy Case — Valid Keys Bypass Paywall ✅State:
Proof: Same user (basic plan, trial expired) that got 402 in Test 1 now reaches upstream providers. The upstream errors contain the test key values — proving the user's BYOK keys were used (not server keys). The 400/401 errors are from Google/Anthropic/OpenAI rejecting the fake test keys, exactly as expected. Test 3: BYOK Fingerprint Mismatch → 403 ✅State:
Proof: SHA-256 fingerprint validation catches key substitution and blocks the request before it reaches any upstream API. Test 4: Non-Enrolled User with BYOK Headers → Stripped + 402 ✅State:
Proof: Non-enrolled user cannot bypass paywall by forging BYOK headers. The Test 5: Missing Enrolled Provider → 403 ✅State:
Proof: Partial key submission is rejected — enrolled providers must all be present. Summary
All 7 test cases pass. The BYOK validation + native paywall implementation correctly handles all happy and failure paths. by AI for @beastoin |
Live Test — Omi Beta v0.11.411cc @kodjima33 BYOK keys now work across all Rust proxy routes (Gemini, Anthropic, TTS). Previously only TTS honored user keys — Gemini and Anthropic always used server keys, and the paywall blocked BYOK users. Now trial-expired users with valid BYOK keys are correctly exempted and their keys are used for all routes. Verified in production:
All passing. ✅ by AI for @beastoin |





Summary
Relands #7359 (reverted in e6ccdf4) — identical code, new PR for proper approval flow.
GET /v1/users/me/paywall) with native Rust logic reading subscription plan, BYOK state, and account creation time directly from Firestore/Firebase Auth — removes latency and Python dependencybyok_strippedflag prevents non-BYOK users from forging BYOK headers to bypass paywall; expired paid plans correctly fall back to basic; Firestore errors not cached (prevents cache poisoning);without_url()on reqwest errors prevents BYOK Gemini API key leaks in logsChanges
byok.rsByokState,ByokStateCache(30s TTL),validate_byok_request()(SHA-256 fingerprint check),ByokValidationenum,get_byok_key_if_activehelper,ByokCacheExt, 23 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_endexpiry check),get_user_creation_time()(Firebase Identity Toolkit), extracted pure parsing functions, 14 testsroutes/proxy.rsbyok_strippedviaget_byok_key_if_active;e.without_url()to prevent API key leak in error logsroutes/chat_completions.rsbyok_strippedviaget_byok_key_if_activeroutes/tts.rsbyok_strippedviaget_byok_key_if_activemain.rsByokStateCache+ updatedPaywallChecker(no more Python delegation)config.rspython_api_base(no longer needed)Security fixes (from review cycle)
byok_strippedparam disables escape hatch for non-BYOK usersplanwithout checkingcurrent_period_end→ Fixed:get_user_effective_planvalidates period end, falls back to "basic"reqwest::Errorincludes URL (Gemini puts key in?key=...) → Fixed:e.without_url()in both streaming and non-streaming pathsLive test evidence (from #7359)
Build
cargo build(0 errors)xcrun swift build -c debug --package-path Desktop— Build complete (15.30s)/Applications/omi-byok-7357.app(com.omi.omi-byok-7357){"status":"healthy","service":"omi-desktop-backend","version":"0.1.0"}Functional tests (curl + backend logs)
/v1/proxy/gemini/...no auth{"error":"missing_token"}401{"error":"trial_expired"}402/v1/tts/synthesizewith auth{"error":"trial_expired"}402/v2/chat/completionswith auth{"error":"trial_expired"}402{"error":"trial_expired"}402unlimitedfalls back tobasicpaid plan 'unlimited' fell back to basic (expired or missing period_end)Backend log evidence
Path coverage summary
Test plan
cargo test— 247 tests pass (0 failures)OMI_APP_NAME="omi-byok-7357" ./run.sh, standalone curl testsCloses #7357
🤖 Generated with Claude Code