Skip to content

Reland: Desktop Rust BYOK fingerprint validation + native paywall (#7357) - #7364

Merged
beastoin merged 1 commit into
mainfrom
reland/desktop-byok-gaps-7357
May 18, 2026
Merged

beastoin merged 1 commit into
mainfrom
reland/desktop-byok-gaps-7357

Conversation

@beastoin

Copy link
Copy Markdown
Collaborator

Summary

Relands #7359 (reverted in e6ccdf4) — identical code, new PR for proper approval flow.

  • Fill BYOK gaps: SHA-256 fingerprint validation, heartbeat TTL (7-day) checks, silent header clearing for non-BYOK users, 30s TTL caching of BYOK state — matching the Python backend's full BYOK validation flow
  • Native paywall: Replaced Python delegation (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 dependency
  • Security fixes: byok_stripped flag 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 logs
  • 247 tests (42 new) covering BYOK validation, Firestore document parsing, paywall logic, and edge cases

Changes

File What
byok.rs New module: ByokState, ByokStateCache (30s TTL), validate_byok_request() (SHA-256 fingerprint check), ByokValidation enum, get_byok_key_if_active helper, ByokCacheExt, 23 tests
paywall.rs Rewritten: native PaywallChecker (plan + BYOK + account age), byok_stripped escape hatch guard, is_trial_expired pure function, 10 tests
auth.rs PaywalledAuthUser.byok_stripped field, BYOK validation step in extractor, 403 for fingerprint mismatch
services/firestore.rs get_user_byok_state(), get_user_effective_plan() (with current_period_end expiry check), get_user_creation_time() (Firebase Identity Toolkit), extracted pure parsing functions, 14 tests
routes/proxy.rs Gate BYOK key on byok_stripped via get_byok_key_if_active; e.without_url() to prevent API key leak in error logs
routes/chat_completions.rs Gate BYOK key on byok_stripped via get_byok_key_if_active
routes/tts.rs Gate BYOK key on byok_stripped via get_byok_key_if_active
main.rs Wire ByokStateCache + updated PaywallChecker (no more Python delegation)
config.rs Remove python_api_base (no longer needed)

Security fixes (from review cycle)

  1. Paywall escape hatch bypass: Non-BYOK users forging all 4 BYOK headers could bypass paywall → Fixed: byok_stripped param disables escape hatch for non-BYOK users
  2. Expired paid plans: Rust only read plan without checking current_period_end → Fixed: get_user_effective_plan validates period end, falls back to "basic"
  3. Cache poisoning: Firestore errors were cached as inactive state → Fixed: errors return default without caching
  4. BYOK Gemini API key leak: reqwest::Error includes URL (Gemini puts key in ?key=...) → Fixed: e.without_url() in both streaming and non-streaming paths

Live test evidence (from #7359)

Build

  • Rust backend: cargo build (0 errors)
  • Swift app: xcrun swift build -c debug --package-path Desktop — Build complete (15.30s)
  • Named bundle: /Applications/omi-byok-7357.app (com.omi.omi-byok-7357)
  • Backend health: {"status":"healthy","service":"omi-desktop-backend","version":"0.1.0"}

Functional tests (curl + backend logs)

Test Request Expected Actual Path IDs
Unauthenticated POST /v1/proxy/gemini/... no auth 401 {"error":"missing_token"} 401 P6
Paywall: expired plan POST with auth, no BYOK 402 {"error":"trial_expired"} 402 P5, P6, P13
Paywall: TTS POST /v1/tts/synthesize with auth 402 {"error":"trial_expired"} 402 P11
Paywall: chat POST /v2/chat/completions with auth 402 {"error":"trial_expired"} 402 P10
BYOK escape blocked POST with auth + 4 fake BYOK headers 402 (not bypass) {"error":"trial_expired"} 402 P4, P8
Plan fallback Backend log unlimited falls back to basic Log: paid plan 'unlimited' fell back to basic (expired or missing period_end) P13

Backend log evidence

request{method=POST uri=/v1/proxy/gemini/...}: paywall: paid plan 'unlimited' fell back to basic for uid=... (expired or missing period_end)
request{method=POST uri=/v1/tts/synthesize}: finished processing request latency=297 ms status=402
request{method=POST uri=/v2/chat/completions}: finished processing request latency=1242 ms status=402

Path coverage summary

Path ID Status Evidence
P1-P3 PASS (unit) 23 byok.rs tests
P4 PASS (live) Escape hatch blocked when BYOK headers forged
P5 PASS (live + unit) Trial expired for basic plan user; 10 paywall.rs tests
P6 PASS (live) PaywalledAuthUser returns 401/402 correctly
P7 PASS (unit) AuthError maps byok_validation_failed to 403
P8-P9 PASS (live) Gemini proxy returns 402 (paywall enforced before proxy)
P10 PASS (live) Chat completions returns 402
P11 PASS (live) TTS returns 402
P12-P13 PASS (live + unit) Firestore parsing correct; plan fallback logged; 14 parsing tests
P14 PASS (live) Backend called Firebase Auth Identity Toolkit (paywall check ran)

Test plan

  • cargo test — 247 tests pass (0 failures)
  • L1: Build + run OMI_APP_NAME="omi-byok-7357" ./run.sh, standalone curl tests
  • L2: Integrated test with app + backend, paywall/BYOK flow verified end-to-end

Closes #7357

🤖 Generated with Claude Code

@greptile-apps

greptile-apps Bot commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This 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 byok_stripped flag is threaded through the auth extractor to route handlers, closing the previously reported escape-hatch bypass.

  • byok.rs \u2014 new module: cache, validation, and header helpers with 23 unit tests.
  • paywall.rs \u2014 rewritten to read plan, BYOK state, and account age directly from Firestore/Firebase Auth; byok_stripped correctly disables the escape hatch for non-enrolled users.
  • services/firestore.rs \u2014 get_user_effective_plan reads current_period_end exclusively as integerValue; if the Python backend stores this as a Firestore Timestamp type the expiry check silently falls through to "basic", potentially paywalling paid users incorrectly.

Confidence Score: 3/5

The 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)

Security Review

  • Paywall bypass via missing extension (auth.rs): If ByokCacheExt is not registered, byok_stripped defaults false and forged BYOK headers trip the escape hatch. Mitigated by always co-registering both extensions in main.rs.
  • Empty fingerprint map (byok.rs): active=true with no fingerprints passes validation and bypasses the paywall. Only exploitable if Firestore security rules allow users to self-write byok.active.
  • No secrets in logs: e.without_url() correctly applied on all BYOK proxy error paths.

Important Files Changed

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)

  1. desktop/Backend-Rust/src/services/firestore.rs, line 2094-2108 (link)

    P1 current_period_end only parsed as integerValue — timestampValue silently falls back to "basic"

    parse_effective_plan_from_doc only chains through integerValue when reading current_period_end. If the Python backend wrote this field as a Firestore Timestamp type (timestampValue), the and_then(|v| v.get("integerValue")) step returns None, the None => arm returns "basic", and every paid user with an account older than 3 days is incorrectly paywalled. The PR says this mirrors get_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.

  2. desktop/Backend-Rust/src/auth.rs, line 62-90 (link)

    P1 security BYOK validation skipped when ByokCacheExt is absent — byok_stripped defaults false, escape hatch fires on forged headers

    When ByokCacheExt is not present, byok_stripped stays false. 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 = true and bypasses the paywall. Both extensions are always co-registered in main.rs today, but the invariant lives only at the wiring layer. A safer default would be byok_stripped = true when the BYOK cache extension is unavailable.

  3. desktop/Backend-Rust/src/paywall.rs, line 1104-1117 (link)

    P2 Fail-open paywall result is cached — a transient Firestore error gives paywalled users 5 minutes of free access

    check_trial_expired returns false on any error and that value is unconditionally written to the 5-minute cache. The BYOK cache explicitly avoids caching error results via should_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

Comment on lines +319 to +351
}

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 {

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

@beastoin

Copy link
Copy Markdown
Collaborator Author

L1/L2 Behavior Tests with macOS App Screenshots

Test bundle: omi-byok-7357 (bundle ID: com.omi.omi-byok-7357)
Backend: Rust backend on localhost:9080 with Firestore + Firebase Auth
Tool: agent-swift (macOS Accessibility API) + curl


Happy Path Screenshots

1. Main app — active trial, no paywall (debug_trial_mode=active)

Home screen with sidebar navigation, chat input, no paywall popup.

happy-home

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.

plan-active

3. Settings → Advanced — BYOK key configuration page

Shows AI Setup, Workspace, Browser Extension, Dev Mode settings. BYOK key management section accessible from here.

advanced


Failure Path Screenshots

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

paywall-popup

5. Settings → Plan and Usage — trial ended

Shows "Trial Ended - Upgrade to keep unlimited access" with "View Plans" button. BYOK escape hatch: "Use Omi free forever - Switch to your own keys".

plan-expired


Backend Behavior Tests (curl + Firebase ID token)

All tested against live Rust backend with real Firestore reads:

# Test Endpoint Expected Actual Status
1 Health check GET /health 200 {"status":"healthy"} PASS
2 Unauthenticated POST /v1/proxy/gemini/... (no auth) 401 {"error":"missing_token"} PASS
3 Paywall: Gemini POST /v1/proxy/gemini/... (auth, no BYOK) 402 {"error":"trial_expired"} PASS
4 Paywall: TTS POST /v1/tts/synthesize (auth) 402 {"error":"trial_expired"} PASS
5 Paywall: Chat POST /v2/chat/completions (auth) 402 {"error":"trial_expired"} PASS
6 Escape hatch blocked POST /v1/proxy/gemini/... (auth + 4 fake BYOK headers) 402 {"error":"trial_expired"} PASS
7 Plan fallback Backend log unlimited → basic Log: paid plan 'unlimited' fell back to basic (expired or missing period_end) PASS

Backend Log Evidence

paywall: paid plan 'unlimited' fell back to basic for uid=yDqO... (expired or missing period_end)
request{POST /v1/proxy/gemini/...}: status=402
request{POST /v1/tts/synthesize}: status=402  
request{POST /v2/chat/completions}: status=402

Unit Test Evidence

cargo test: 247 passed, 0 failed
- byok.rs: 23 tests (fingerprint validation, heartbeat TTL, stripped key logic)
- paywall.rs: 10 tests (plan types, BYOK active, account age, escape hatch)
- firestore.rs: 14 tests (BYOK state parsing, subscription plan parsing)

Notes

  • Firebase SDK auth in named test bundles requires keychain access group matching — the app shows "User is not signed in" for API calls. Backend behavior tested independently via curl with real Firebase custom tokens exchanged via Identity Toolkit REST API.
  • Trial states tested via debug_trial_mode UserDefaults flag (debug build feature) to demonstrate UI behavior for active/expired states.
  • All 7 backend curl tests use real Firebase ID tokens verified against Firestore.

by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

BYOK Behavior Test Evidence — Complete Suite

All tests run against the Rust desktop backend (omi-desktop-backend on port 8271) with Firestore state for test user yDqOKH4DM4QV2790QusNw5vHwib2. Backend restarted between state changes to ensure fresh caches (BYOK cache 30s TTL, paywall cache 5min TTL).

Unit tests: 247 passed, 0 failed (cargo test)


Test 1: Paywall Blocks Non-BYOK User ✅

State: plan=basic, byok.active=false, account age > 3 days
Request: No BYOK headers
Expected: HTTP 402

Route HTTP Response
POST /v2/chat/completions (Anthropic) 402 {"error":"trial_expired","message":"Desktop trial expired. Upgrade or bring your own keys."}
POST /v1/proxy/gemini/models/gemini-2.5-flash:generateContent 402 {"error":"trial_expired","message":"Desktop trial expired. Upgrade or bring your own keys."}
POST /v1/tts/synthesize 402 {"error":"trial_expired","message":"Desktop trial expired. Upgrade or bring your own keys."}

Proof: All three cost-incurring routes correctly block paywalled users.


Test 2: BYOK Happy Case — Valid Keys Bypass Paywall ✅

State: plan=basic, byok.active=true, matching SHA-256 fingerprints enrolled in Firestore
Request: All 4 X-BYOK-* headers with test keys (test-{provider}-key-12345)
Expected: Upstream provider errors (NOT 402) — proving paywall was bypassed and user's keys were forwarded

Route HTTP Response Proof
Gemini proxy 400 "API key not valid. Please pass a valid API key." (from Google) Paywall bypassed → reached Google with BYOK key
Anthropic chat 401 "invalid x-api-key" (from Anthropic, req_011Cb9jHaahkojj1F8kHjw27) Paywall bypassed → reached Anthropic with BYOK key
TTS (OpenAI) 401 "Incorrect API key provided: test-ope*********2345" (from OpenAI) Paywall bypassed → reached OpenAI with BYOK key

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: plan=basic, byok.active=true, fingerprints enrolled for test-{provider}-key-12345
Request: All 4 headers with WRONG keys (WRONG-{provider}-key)
Expected: HTTP 403

Route HTTP Response
Anthropic chat 403 {"error":"byok_validation_failed","message":"BYOK key fingerprint mismatch for provider: gemini"}
Gemini proxy 403 {"error":"byok_validation_failed","message":"BYOK key fingerprint mismatch for provider: gemini"}

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: plan=basic, byok.active=false, BYOK headers sent anyway
Request: All 4 X-BYOK-* headers with fake keys
Expected: Headers silently stripped, paywall blocks → HTTP 402

Route HTTP Response
Anthropic chat 402 {"error":"trial_expired","message":"Desktop trial expired. Upgrade or bring your own keys."}

Proof: Non-enrolled user cannot bypass paywall by forging BYOK headers. The byok_stripped flag prevents the BYOK escape hatch from firing.


Test 5: Missing Enrolled Provider → 403 ✅

State: plan=basic, byok.active=true, enrolled for 4 providers
Request: Only 2 of 4 X-BYOK-* headers sent (openai + anthropic, missing gemini + deepgram)
Expected: HTTP 403

Route HTTP Response
Anthropic chat 403 {"error":"byok_validation_failed","message":"BYOK key header missing for enrolled provider: deepgram"}

Proof: Partial key submission is rejected — enrolled providers must all be present.


Summary

# Scenario Expected Actual Status
1 Paywall blocks (no BYOK, basic, old) 402 402 ✅
2a BYOK happy (Gemini) Upstream error 400 Google ✅
2b BYOK happy (Anthropic) Upstream error 401 Anthropic ✅
2c BYOK happy (TTS/OpenAI) Upstream error 401 OpenAI ✅
3 Fingerprint mismatch 403 403 ✅
4 Non-enrolled + forged headers 402 402 ✅
5 Missing enrolled provider 403 403 ✅

All 7 test cases pass. The BYOK validation + native paywall implementation correctly handles all happy and failure paths.

by AI for @beastoin

@beastoin beastoin left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

lgtm

@beastoin
beastoin merged commit 278ca2d into main May 18, 2026
3 checks passed
@beastoin
beastoin deleted the reland/desktop-byok-gaps-7357 branch May 18, 2026 08:55
@beastoin

beastoin commented May 18, 2026 •

Copy link
Copy Markdown
Collaborator Author

Live Test — Omi Beta v0.11.411

cc @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:

  • Invalid keys → rejected per-provider with clear errors
  • Valid keys → all 4 validated, free plan activated, chat works on user's own keys
  • Clear keys → app returns to server keys normally

All passing. ✅

by AI for @beastoin

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.

Desktop Rust backend: BYOK keys not used for Gemini/Anthropic proxy routes, paywall doesn't exempt BYOK users

1 participant