Skip to content

Harden auth, SSRF, and CSRF gaps left open from the April disclosure - #10638

Merged
Git-on-my-level merged 3 commits into
BasedHardware:mainfrom
amowpheth:security/post-disclosure-hardening
Jul 27, 2026
Merged

Git-on-my-level merged 3 commits into
BasedHardware:mainfrom
amowpheth:security/post-disclosure-hardening

Conversation

@amowpheth

@amowpheth amowpheth commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Three months after the coordinated disclosure (GHSA-4j2c-fmg6-8h42, 17 findings, CVSS 10.0 aggregate), several of the reported issues are still exploitable in the current backend/ and web/admin/. RCE, the hardcoded encryption key, path traversal, and the unauthenticated-conversations gap are already fixed upstream — this PR closes the remaining ones with a live exploit path, while staying backward compatible with this repo's own test suites, dev-harness, and production gauntlet that depend on the same env vars/token formats.

  • ADMIN_KEY prefix-match auth bypass (backend/utils/other/endpoints.py) — anyone holding ADMIN_KEY could impersonate any uid via token.startswith(admin_key). Switched to constant-time comparison, added audit logging on every use, and added an opt-out flag (ADMIN_KEY_AUTH_ENABLED) — kept the existing concatenated-token format (ADMIN_KEY<uid>) intact since it's documented in AGENTS.md and used throughout backend/testing/, backend/tests/integration/, and the prod-facing memory-continuity gauntlet.
  • LOCAL_DEVELOPMENT hardcoded-uid bypass — any invalid Firebase token + LOCAL_DEVELOPMENT=true returned uid '123' with no further check. Now inert once real Firebase credentials (SERVICE_ACCOUNT_JSON / GOOGLE_APPLICATION_CREDENTIALS) are configured, which every real deployment sets and every legitimate dev/test path (emulator-based) already avoids.
  • SSRF via developer-configured webhook_url / setup_completed_url (app_integrations.py, oauth.py, utils/http_client.py) — requests to app-developer-supplied URLs had no destination validation. Added a check that rejects private/loopback/link-local/reserved-address targets (including the cloud metadata IP) before dispatch.
  • OAuth authorize/token-exchange CSRF (routers/oauth.py) — the state param was accepted and echoed back but never validated against anything. Added a double-submit cookie set on /v1/oauth/authorize and checked on /v1/oauth/token.
  • BYOK fingerprint hashing (utils/byok.py) — unsalted SHA-256. Added an opt-in HMAC pepper (BYOK_FINGERPRINT_PEPPER) with legacy-value fallback so existing fingerprints keep validating.
  • CORS — main.py had no CORSMiddleware at all; added an explicit default-deny policy.
  • Dockerfile — final stage ran as root; added a non-root USER.
  • payment.py — one endpoint echoed a raw exception string from the PayPal payment-details call back to the client; now logs server-side and returns a generic message.

Test plan

  • ADMIN_KEY_AUTH_ENABLED unset/false → admin-key auth path fully disabled
  • ADMIN_KEY_AUTH_ENABLED=true + existing Bearer <ADMIN_KEY><uid> format from backend/tests/integration/test_live_chat_service.py and backend/testing/*_stack/run.py still authenticates correctly
  • LOCAL_DEVELOPMENT=true without emulator/real credentials still works against the hermetic harness (backend/testing/e2e/conftest.py), and cannot activate once SERVICE_ACCOUNT_JSON/GOOGLE_APPLICATION_CREDENTIALS is set
  • Webhook delivery to 169.254.169.254, 127.0.0.1, and RFC1918 targets is rejected; delivery to a public HTTPS endpoint still succeeds
  • /v1/oauth/authorize → /v1/oauth/token round-trip succeeds with matching cookie/state; fails when state/cookie are mismatched or missing
  • Existing BYOK fingerprints (no pepper) still validate after BYOK_FINGERPRINT_PEPPER is introduced; new fingerprints are peppered when the var is set
  • docker build + run as non-root in the final stage (not verified in this environment — no Docker daemon available; please confirm in CI)

🤖 Generated with Claude Code

Review in cubic

@Git-on-my-level Git-on-my-level added security-review Touches auth, provider routing, secrets, or security-sensitive surfaces needs-tests PR introduces logic that should be covered by tests needs-maintainer-review Needs a human maintainer to sign off before merge labels Jul 26, 2026

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for picking up these post-disclosure hardening gaps — the direction is valuable, especially default-deny CORS, refusing obvious private/link-local callback targets, not echoing unexpected PayPal persistence errors, and making the BYOK fingerprint storage optionally peppered.

I don’t think this should merge in its current form yet because these are security-sensitive auth/webhook changes and there are no targeted regression tests covering the new behavior. Before maintainer merge review, please add focused tests for at least:

  • assert_public_http_url: rejects loopback/private/link-local/reserved hosts and non-http(s) schemes, accepts ordinary public http/https, and handles multi-address DNS results safely.
  • OAuth CSRF: /authorize emits the CSRF cookie/template token, /token rejects missing or mismatched token/cookie pairs, and accepts the valid pair.
  • BYOK fingerprint migration: newly stored peppered fingerprints validate, existing legacy plain fingerprints still validate, and mismatches fail.
  • verify_token: LOCAL_DEVELOPMENT=true only falls back to uid 123 when real Firebase credentials are absent, and ADMIN_KEY_AUTH_ENABLED=false disables the admin-key path.

One additional security point for human review: the SSRF helper validates DNS before the later httpx request, but the actual connection resolves again. That is a good improvement for direct private-IP/internal-host callbacks, but it is not full DNS-rebinding protection. If this PR is intended to close the disclosure item completely, please either pin/connect to the validated address (or otherwise enforce validation at connection time), or clearly scope this as a partial mitigation so maintainers can decide whether the residual risk is acceptable.

Because this touches auth, OAuth, BYOK, webhook destinations, CORS, and container privileges, I’m marking this for security/maintainer review rather than approving automatically.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

amowpheth

This comment was marked as off-topic.

amowpheth added a commit to amowpheth/omi that referenced this pull request Jul 26, 2026
…YOK hardening

Addresses the maintainer review on BasedHardware#10638: no regression coverage for the
security-sensitive changes, and the SSRF guard validated DNS before the
request but didn't pin the connection to what it validated.

- utils/http_client.py: assert_public_http_url now returns the resolved IP;
  new pin_to_resolved_ip/safe_request_target rewrite the request to connect
  directly to that address (Host header + TLS sni_hostname extension kept as
  the original hostname), so a hostname can't resolve differently between
  the validation lookup and the actual connect (DNS rebinding). All four
  webhook/setup_completed_url call sites (app_integrations.py x3, oauth.py)
  now go through safe_request_target instead of validate-then-request.
- New tests: assert_public_http_url (scheme/host rejection, every private/
  loopback/link-local/reserved case, multi-address DNS handling, mocked
  DNS throughout — no real network calls), OAuth authorize/token CSRF
  (cookie+page-token emission, missing/mismatched/stale-pair rejection,
  valid-pair acceptance), BYOK fingerprint pepper migration (new peppered
  enrollments validate, legacy unpeppered ones still validate, mismatches
  fail both ways), and verify_token's ADMIN_KEY_AUTH_ENABLED /
  LOCAL_DEVELOPMENT gating (default-on backward compat, explicit opt-out,
  credential-presence inertness).
- Fixed two existing test files broken by the earlier CSRF/SSRF changes to
  oauth.py that nobody had re-run since: test_oauth_token_async_boundaries.py
  (hand-rolled utils.http_client stub was missing safe_request_target/
  UnsafeWebhookURLError; direct oauth_token() calls didn't pass the new
  csrf_token/oauth_csrf_cookie params) and test_async_app_integrations.py /
  test_async_realtime_integrations_offload.py (same missing stub attribute).

Verified: all new tests pass, plus the full existing test_oauth_token_async_
boundaries.py, test_async_app_integrations.py, test_async_realtime_
integrations_offload.py, test_users_webhook_url_validation.py, and
test_async_http_infrastructure.py suites (166 passed). Ran against the
actual pinned dependency versions (fastapi==0.121.0, starlette==0.49.1,
pytest==9.1.1, etc.) in an isolated venv, not whatever happened to be on
the global PATH — the globally installed starlette was a newer major
version with a breaking TemplateResponse signature change that would have
produced false failures. test_app_integrations_safe_messages.py,
test_byok_security.py, and test_byok_llm_logging.py weren't run to
completion: they need the full production dependency tree (stripe,
anthropic, etc.) unrelated to this change. test_auth_redirect_uri.py's
failures are pre-existing and unrelated (a different router, an
asyncio/pytest-asyncio event-loop quirk in this environment).

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@amowpheth amowpheth left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The original fix asked "does this hostname resolve to a public IP?" and then, a moment later, made the HTTP request to that same hostname which so happens to trigger a second, independent DNS lookup. An attacker who controls DNS for their webhook domain can answer those two lookups differently: public IP for the check, private/metadata IP for the real connection. The check and the connection weren't atomic, so the check was decorative.

Remedial action: resolve once, validate once, then force the actual socket to connect to that exact IP never letting the HTTP client look the hostname up again. Still sent the original hostname as the Host header and as the TLS SNI value, so that the request looks completely normal to the receiving server and certificate checks still validate against the real domain, not the IP. you can run this yourself in a MAC terminal with the lines below:

cd ~/omi/backend
./.test-venv/bin/python -m pytest tests/unit/test_ssrf_public_url_guard.py tests/unit/test_oauth_csrf.py tests/unit/test_byok_fingerprint_pepper_migration.py tests/unit/test_verify_token_admin_and_local_dev_gating.py -v

@Git-on-my-level
Git-on-my-level force-pushed the security/post-disclosure-hardening branch from 913b8b3 to 9793b05 Compare July 26, 2026 19:53

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the follow-up here. The main blockers from the earlier automation review are materially improved now: the PR adds focused coverage for the OAuth CSRF path, BYOK fingerprint migration, admin/local-dev auth gates, and the SSRF URL guard, and the webhook call sites now try to connect to the validated/pinned address instead of re-resolving the hostname.

I’m still requesting changes because the current head is not green: the Backend unit suite is failing in tests/unit/test_listen_finalization_cloud_tasks.py::test_finalizer_completes_when_an_app_permanently_rejects_the_delivery for both asyncio and trio. The log shows the fanout path now fails before exercising the mocked 401 response:

gather_safe[trigger_integrations] item 0 failed: BlockedNetworkError("Blocked DNS resolution for 'app.test'")
AssertionError: Expected record_failure('omi-google-drive-integration', 401, 'HTTP 401') to be called once. Called 0 times.

That looks like the existing listen-finalization unit harness needs the same kind of safe_request_target/UnsafeWebhookURLError stub update added to the other integration tests, so the test can keep validating permanent webhook rejection instead of being intercepted by the new DNS guard.

One security-review note to keep on the maintainer radar after CI is fixed: the pinned-address approach is directionally right, but because this is auth/webhook/OAuth/BYOK/CORS/container hardening from a first-time contributor, I still would not auto-approve it. A human maintainer/security pass should confirm the httpx pinned-IP + Host/SNI behavior, redirect handling, deployment CORS expectations, and the Docker non-root runtime assumptions before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

amowpheth and others added 3 commits July 27, 2026 15:41
Closes the security gaps surfaced by the April disclosure and the
follow-up review. No new dependencies — stdlib ipaddress + native httpx.

SSRF (developer-configured webhook_url / setup_completed_url):
- assert_public_http_url rejects non-http(s) schemes and any resolved
  address that is private/loopback/link-local/multicast/reserved/
  unspecified, inspecting every address a hostname resolves to (not just
  the first), so a multi-address DNS answer can't sneak an unsafe IP.
- Explicitly reject RFC 6598 CGNAT 100.64.0.0/10: Python's ipaddress
  flags it as neither is_private nor is_reserved, so it was wrongly
  accepted as "public" (e.g. 100.64.0.1).
- safe_request_target pins the validated IP for the actual connection
  (Host header + TLS sni_hostname preserved, cert verified against the
  original hostname) so a DNS record can't be swapped between validation
  and connect (DNS rebinding). follow_redirects=False on these calls so
  a public target can't redirect to an internal one.
- The blocking getaddrinfo is offloaded through the owned db_executor at
  every async boundary (oauth_token + all three webhook _single fan-outs)
  via run_blocking — never asyncio.to_thread, never inline on the loop.
  scan_async_blockers passes clean.
- UnsafeWebhookURLError in the webhook fan-outs is a configuration
  rejection, not a delivery failure: logged and returned without recording
  a webhook failure, tripping the circuit breaker, or raising
  ExternalIntegrationFanoutError on the durable path.

CSRF (oauth authorize -> token):
- Double-submit token Omi generates itself (HttpOnly SameSite=Strict
  cookie + value embedded in the consent page); /token requires both to
  match via hmac.compare_digest. The third-party `state` param is opaque
  to Omi and was never server-validated; this closes that gap.

Auth:
- ADMIN_KEY<uid> impersonation is preserved (the concatenated-uid form is
  documented and depended on by repo tooling and the memory-continuity
  gauntlet; it is authenticated-by-key, not an unauthenticated bypass)
  but the prefix compare is constant-time, every use is audit-logged, and
  ADMIN_KEY_AUTH_ENABLED (default true) lets an operator disable it.
- LOCAL_DEVELOPMENT=true uid '123' fallback is inert the moment a real
  Firebase credential is present (SERVICE_ACCOUNT_JSON /
  GOOGLE_APPLICATION_CREDENTIALS), so a misconfigured prod deploy can't
  silently bypass token verification.

BYOK:
- Stored key fingerprints are wrapped with a server-only HMAC pepper
  (BYOK_FINGERPRINT_PEPPER); unset = legacy identity (no forced
  re-enrollment). The per-request check accepts both peppered and legacy
  plain forms.

Hardening:
- Explicit default-deny CORS (CORS_ALLOWED_ORIGINS opt-in; "*" rejected;
  credentials never forwarded). Browser default-deny already applied;
  this makes the boundary explicit and operator-controllable.
- PayPal save broad-except no longer echoes raw exception text.
- Backend image runs as non-root (uid 10001); /app is chowned so the
  relative syncing/<uid>/ write path stays writable.

Tests (hermetic, no network): SSRF validator private/loopback/link-local/
reserved/CGNAT rejection + public acceptance + CGNAT boundary; webhook
private-URL config rejection (no breaker/failure/durable trip); OAuth
authorize/token CSRF round trip + missing/mismatched rejection; ADMIN_KEY
enable/disable + backward-compat + LOCAL_DEVELOPMENT-with-real-creds;
BYOK legacy + peppered fingerprint validation. Async test stubs expose
the new http_client exports (safe_request_target, UnsafeWebhookURLError).

Verification:
- backend: black --line-length 120 --skip-string-normalization (clean)
- python scripts/scan_async_blockers.py --dirs routers utils (0 findings)
- python -m pytest <the 7 new/changed test files> (74 passed)
- make preflight (20/20 checks pass)
- IP pinning HTTPS cert verified empirically against example.com (200 OK,
  cert validated via sni_hostname) — pinning does not break HTTPS webhooks
- Dockerfile non-root write paths source-verified (all writes under
  /app[chowned] or /tmp[world-writable]); full image build could not run
  (private base image gcr.io/.../python:3.11-slim-forky, 403 anonymous pull)

Co-authored-by: multica-agent <[email protected]>
…tion stub

The `integration_harness` `utils.http_client` AutoMockModule stub omitted
`safe_request_target` and `UnsafeWebhookURLError`. The auto-mock therefore
returned a non-tuple (tuple-unpacking `ValueError`) and a non-exception
class, so the production `except UnsafeWebhookURLError` clause at
`utils/app_integrations.py:808-809` raised
`TypeError: catching classes that do not inherit from BaseException is not
allowed`. Both realtime webhook tests failed in CI for every external app.

Follow the convention already established in test_async_app_integrations,
test_async_realtime_integrations_offload, and test_oauth_token_async_boundaries:
a real `UnsafeWebhookURLError(Exception)` plus a `safe_request_target`
MagicMock returning the `(pinned_url, {headers, extensions})` shape the
webhook delivery path unpacks. The production SSRF guard is unchanged.

Add `test_realtime_non_public_webhook_rejected_fail_soft` to pin the stub
contract (a genuine exception class the production except clause can match)
and the SSRF fail-soft boundary (reject a non-public URL before delivery,
never trip the circuit breaker for a config error).

Verification (reproduced, then fixed, via the prescribed runner):
  : > /tmp/omi-backend-unit-failures.txt
  echo tests/unit/test_realtime_integrations_usage_tracking.py >> ...
  BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-backend-unit-failures.txt bash test.sh
  -> 9 passed (was 2 failed: test_realtime_message_uses_async_notification_boundary,
     test_realtime_notification_failure_remains_fail_soft)
  Directly relevant suites green (same runner):
    test_ssrf_public_url_guard.py (26), test_async_app_integrations.py (15),
    test_async_realtime_integrations_offload.py (6),
    test_oauth_token_async_boundaries.py (3)
  make preflight: 20/20 manifest checks passed (incl. backend-module-isolation)

Failure-Class: none | this is a test-isolation-stub repair; no production
behavior changed (the SSRF guard is untouched and already covered by
test_ssrf_public_url_guard.py).

Co-authored-by: multica-agent <[email protected]>
Stub safe_request_target in the durable finalization 401 regression so the synthetic app.test URL still exercises HTTP delivery while production SSRF validation remains unchanged. Assert the pinned request contract and webhook-health 401 recording path.

Verified: selected finalization file via backend/test.sh (82 passed); neighboring SSRF and webhook isolation files via backend/test.sh (59 passed); make preflight (20 checks passed).
Co-authored-by: multica-agent <[email protected]>
@Git-on-my-level
Git-on-my-level force-pushed the security/post-disclosure-hardening branch from 4063b04 to 9e927a7 Compare July 27, 2026 19:49
@Git-on-my-level
Git-on-my-level merged commit b210e7a into BasedHardware:main Jul 27, 2026
31 checks passed
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks for the work on this, next time please submit a private PR first per best practice, but really appreciate the work on this

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.

2 participants