Repository navigation
fix: high-confidence security audit (SSRF, uploads, personas auth, JSON-LD) - #11304
undivisible wants to merge 44 commits into
Conversation
|
Thanks for pushing this security-hardening pass. I reviewed the sensitive surfaces statically and this is directionally strong, but I’m leaving it for human maintainer review before merge because it changes auth/SSRF behavior and the current draft head still has CI failures. Specific observations:
Blocking before this should leave draft:
Once those CI issues are cleaned up, this still needs maintainer sign-off because it is a broad security-sensitive auth/webhook/MCP/app-tool hardening PR rather than a purely mechanical low-risk change. |
|
Both blocking CI failures are fixed on this branch. Hermetic Backend E2E — the harness's DNS guard blocked Frontend Lint — root cause was the pre-commit hook: with no Also ran: |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_e27c6d0e-864b-43e3-8201-2b2ac2fe3a3a) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3f8d798914
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| PINNED_PRETTIER=$(node -p "require('./$dir/package.json').devDependencies.prettier" 2>/dev/null) | ||
| if [ -z "$PINNED_PRETTIER" ] || [ "$PINNED_PRETTIER" = "undefined" ]; then | ||
| echo "Could not read the prettier version pinned by $dir/package.json. Run 'npm install' in $dir." >&2 | ||
| exit 1 |
There was a problem hiding this comment.
Declare Prettier before requiring its package version
When a staged file belongs to web/app and that package has been installed normally, node_modules/.bin/prettier is absent and package.json has no devDependencies.prettier, so this branch always exits with an error. Running the suggested npm install cannot fix it because Prettier is not declared there, effectively blocking every web/app JS/TS commit in a clean checkout; add the pinned dependency or retain a valid formatter fallback.
AGENTS.md reference: AGENTS.md:L98-L107
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c21cecd: a directory with no pinned prettier (web/app) falls back to the default npx prettier instead of exiting 1. Verified by running the hook in a scratch repo containing only web/app/package.json and no node_modules.
| def apps_safe_filename_logic(filename): | ||
| """Extract the security-relevant logic from apps upload endpoints.""" | ||
| safe_suffix = Path(filename).name if filename else "upload" | ||
| file_path = f"_temp/apps/{uuid.uuid4().hex}_{safe_suffix}" |
There was a problem hiding this comment.
Exercise upload routes instead of duplicating the sanitizer
These helpers copy the new filename logic into the test itself rather than calling either production upload route, so deleting or regressing the actual Path(file.filename).name handling leaves every test green. Since this is the regression coverage for a path-traversal security fix, invoke the production behavior through mocked storage and a temporary directory, then assert that the actual path used remains inside the upload directory.
AGENTS.md reference: AGENTS.md:L43-L45
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 929ced7. The test now drives create_app / update_app / create_persona with storage stubbed and asserts the real path handed to the uploader, plus the shared utils.upload_temp primitive. Mutation-verified: removing the basename sanitize fails 7 tests, removing the cleanup fails 5.
There was a problem hiding this comment.
All reported issues were addressed across 30 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for the security-focused pass here. A lot of this is moving in the right direction: the developer-supplied outbound URL handling is much safer after routing webhook delivery, manifest fetches, app tool calls, setup-completed probes, and MCP calls through safe_request_target, pinning the resolved IP while preserving Host/SNI and disabling redirects. The upload filename changes in backend/routers/apps.py and backend/routers/speech_profile.py also remove the direct filename traversal/write-clobber shape, and the personas API routes now bind the requested UID to the Firebase identity instead of trusting the body.
I do need one change before this lands:
backend/routers/x_connector.py: the newis_allowed_success_redirect_url()only validates the scheme/host policy, but_redirect_html()still embeds the attacker-controlled deep link into both a meta refresh attribute and a JavaScript string after only replacing double quotes. A URL such asomi://x/callback?</script><script>alert(1)</script>passes the new scheme allowlist, and the callback page would render a literal</script>inside the inline script. Please either HTML/JS-context escape the redirect target before embedding it, or avoid emitting it inside inline script/HTML attribute contexts entirely. The newbackend/tests/unit/test_x_oauth_redirect_validation.pycovershttps://evil.example,javascript:, and normal native schemes, but it should also cover a native-scheme URL with HTML/script-breaking characters so this regression stays closed.
Other reviewed areas:
backend/utils/webhooks.pynow avoids recording webhook failures/circuit-breaker penalties for invalid non-public targets and pins the actual POST target, which matches the intended SSRF boundary.backend/utils/mcp_client.pyapplies the same validation/pinning to OAuth metadata, registration/token endpoints, JSON-RPC POST, and SSE send/receive; that is the right surface for developer-configured MCP servers.backend/utils/apps.pynow validates app re-enable probes, manifest fetches, and chat-tool endpoints before use;backend/utils/retrieval/tools/app_tools.pythen revalidates/pins at invocation time, which is useful against stale or changed DNS.web/personas-open-source/src/app/api/enable-plugins/route.ts,web/personas-open-source/src/app/api/store-facts/route.ts, andweb/personas-open-source/src/lib/server/persona-chat-gateway.mjsadd the identity-to-requested-UID check; the correspondingpersona-api-auth.test.mjscovers match, mismatch, missing UID, and anonymous identity.web/app/src/components/seo/JsonLd.tsxplusserialize-json-ld.mjscorrectly escape<,>, and&for JSON-LD script content, andweb/frontend/src/app/apps/[id]/page.tsxapplies the same escaping to generated structured data.scripts/pre-commitnow avoids floating to whatever Prettier versionnpxpicks globally, but because it changes local workflow behavior it should still get maintainer sign-off alongside the security-sensitive backend/auth changes.
I ran the lightweight JS checks for the touched web helpers locally:
cd web/app && node --test src/components/seo/serialize-json-ld.test.mjs
# pass: 1/1
cd web/personas-open-source && node --test src/lib/server/persona-api-auth.test.mjs
# pass: 4/4
Leaving this as changes requested because the X OAuth callback page still has a concrete script-injection hole in the newly reviewed redirect allowlist path; the broader SSRF/auth/workflow surfaces also need maintainer sign-off 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.
…nning Two defects in the shared SSRF pinning primitive, both reported on PR #11304: - `assert_public_http_url()` let `ValueError` from `urlparse()`/`.port` escape, so a malformed developer URL (`http://[::1`, `http://h:notaport`) surfaced as a 500 instead of the intended 400 rejection at every call site (routers/users.py, app_tools.py, routers/apps.py, utils/apps.py). Fixed at the source so no call site needs a second except clause. - `pin_to_resolved_ip()` rebuilt the authority from `parsed.hostname` only, which dropped the explicit port from the `Host` header (RFC 9110 s7.2 requires the target authority including a non-default port -- strict virtual hosts route such a request to the wrong host), dropped IPv6 literal brackets, and discarded URL userinfo entirely, so Basic-auth webhook callbacks were silently unauthenticated. SNI stays hostname-only per RFC 6066 s3. test_pin_ipv6_brackets_host_and_preserves_port asserted the bare-hostname Host value; that expectation is corrected against RFC 9110 s7.2. Verification: BACKEND_UNIT_TEST_FILE_LIST=... bash test.sh over test_ssrf_public_url_guard.py (33 passed). Mutation-verified: reverting each of the three behaviors fails 8 tests, all newly added. Failure-Class: none Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_6d631303-f713-4d61-9e98-07b9c4a0bd15) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 898732dda7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # characters; they only appear when someone is aiming at the callback page. | ||
| if any(c in redirect_uri for c in '<>"\'`') or any(c.isspace() or ord(c) < 0x20 for c in redirect_uri): | ||
| return False | ||
| parsed = urlparse(redirect_uri) |
There was a problem hiding this comment.
Reject malformed OAuth redirect URLs cleanly
When an authenticated caller supplies a malformed authority such as success_redirect_url=http://[, urlparse() raises ValueError here before x_oauth_url reaches its error-handling block, turning invalid client input into a 500 instead of the intended 400. A value such as http://localhost:notaport/x is also accepted because parsed.port is never accessed, leaving the user unable to return after completing OAuth; catch parser errors and explicitly validate the port before accepting the redirect.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in bac5bc11: is_allowed_success_redirect_url now catches ValueError from urlparse/.port (http://[ returns the existing 400 instead of a 500) and explicitly reads parsed.port in the http branch so http://localhost:notaport/x is rejected. Regression cases added to test_x_oauth_redirect_validation.py; suite green.
|
|
||
| def test_slow_dns_validation_does_not_block_the_event_loop(): | ||
| def _slow_then_reject(url): | ||
| time.sleep(BLOCKING_SECONDS) |
There was a problem hiding this comment.
Replace the timing-based async boundary test
This CI-discovered test decides whether offloading works by sleeping for 200 ms and requiring a heartbeat to run twice. On a loaded runner, scheduling delays can leave ticks < 2 even though DNS validation correctly ran in an executor, producing a flaky false failure; coordinate worker entry and event-loop progress with events or barriers instead of wall-clock sleeps.
AGENTS.md reference: AGENTS.md:L117-L120
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7fcb852b: the validator now signals entry from the executor thread and blocks on a threading.Event while the test waits for a heartbeat tick, instead of sleeping 200ms and requiring two ticks on a loaded runner. Deterministic either way: if validation ran on the loop, entry can never be signaled.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5497082e87
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Resolved on current head: X OAuth callback redirect target is now rejected/escaped in routers.x_connector and covered by test_x_oauth_redirect_validation.py.
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for the follow-up fixes here. I re-reviewed the current head and I do not see the prior blocking X OAuth callback issue on this version.
What I checked:
backend/routers/x_connector.pynow rejects markup/quote/control characters inis_allowed_success_redirect_url(), useshtml.escape(..., quote=True)for the meta-refresh attribute, and JSON-serializes the deep link for the inline script with<,>, and&escaped. That addresses the earlier script-breakout concern.backend/tests/unit/test_x_oauth_redirect_validation.pynow covers native-scheme payloads containing</script>, quote/attribute injection, callback-page escaping, and message escaping, so the fixed sink is pinned by tests.backend/utils/http_client.pynow maps malformed URLs toUnsafeWebhookURLErrorand preserves original authority details inpin_to_resolved_ip()(Host with non-default port / IPv6 brackets, userinfo kept in the request URL but not Host, SNI host-only).backend/utils/webhooks.py,backend/utils/apps.py,backend/utils/mcp_client.py, andbackend/utils/retrieval/tools/app_tools.pyconsistently route developer-controlled outbound calls through the safe target/pinning path and disable automatic redirects at the changed call sites.backend/routers/apps.py,backend/routers/speech_profile.py, andbackend/utils/upload_temp.pymove uploads to UUID-prefixed basename-only temp paths with cleanup, which closes the direct traversal/clobbering shape for those handlers.web/personas-open-source/src/app/api/enable-plugins/route.ts,web/personas-open-source/src/app/api/store-facts/route.ts, andweb/personas-open-source/src/lib/server/persona-chat-gateway.mjsnow verify the Firebase identity and bind it to the requested UID before mutating persona plugin/facts state, while preserving the anonymous-owner flow.web/app/src/components/seo/JsonLd.tsx,web/app/src/components/seo/serialize-json-ld.mjs, andweb/frontend/src/app/apps/[id]/page.tsxescape JSON-LD script contents; the shared serializer test passed locally.backend/testing/e2e/conftest.py/backend/testing/e2e/test_webhooks.pyupdate the hermetic webhook fixture to fake only the test hostname while still asserting pinned URL + Host/SNI behavior, andscripts/pre-commitpins Prettier via the directory package metadata instead of floating to the latestnpxversion.
Local validation I ran on this head:
python -m pytest backend/tests/unit/test_ssrf_public_url_guard.py -q
# 33 passed
node --test web/app/src/components/seo/serialize-json-ld.test.mjs
# 1 passed
node --test web/personas-open-source/src/lib/server/persona-api-auth.test.mjs
# 8 passed
I could not run backend/tests/unit/test_x_oauth_redirect_validation.py in this throwaway checkout because the local environment is missing firebase_admin; GitHub's backend checks are currently green on the PR.
I’m clearing the stale automation change request for the resolved X OAuth callback injection issue. Still leaving this for human maintainer review before merge because it changes security-sensitive SSRF, auth/ownership, webhook/MCP/app-tool networking, upload handling, and local workflow behavior.
by AI on behalf of David — security-sensitive auth/webhook/MCP behavior needs maintainer sign-off before merge.
…nning Two defects in the shared SSRF pinning primitive, both reported on PR #11304: - `assert_public_http_url()` let `ValueError` from `urlparse()`/`.port` escape, so a malformed developer URL (`http://[::1`, `http://h:notaport`) surfaced as a 500 instead of the intended 400 rejection at every call site (routers/users.py, app_tools.py, routers/apps.py, utils/apps.py). Fixed at the source so no call site needs a second except clause. - `pin_to_resolved_ip()` rebuilt the authority from `parsed.hostname` only, which dropped the explicit port from the `Host` header (RFC 9110 s7.2 requires the target authority including a non-default port -- strict virtual hosts route such a request to the wrong host), dropped IPv6 literal brackets, and discarded URL userinfo entirely, so Basic-auth webhook callbacks were silently unauthenticated. SNI stays hostname-only per RFC 6066 s3. test_pin_ipv6_brackets_host_and_preserves_port asserted the bare-hostname Host value; that expectation is corrected against RFC 9110 s7.2. Verification: BACKEND_UNIT_TEST_FILE_LIST=... bash test.sh over test_ssrf_public_url_guard.py (33 passed). Mutation-verified: reverting each of the three behaviors fails 8 tests, all newly added. Failure-Class: none Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2d15943 to
359f2d8
Compare
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Workflows to automatically generate PRs for you. |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_480f1fa6-9ced-4e20-9d06-c810218a92a1) |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_6816033f-27db-466e-94ba-61dc599b6ee8) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6a2ee91b80
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # app-relative, so it is still validated here. | ||
| if not (endpoint.startswith('/') and not endpoint.startswith('//')): | ||
| try: | ||
| assert_public_http_url(endpoint) |
There was a problem hiding this comment.
Isolate manifest tool DNS lookups from route workers
When an authenticated app owner supplies a manifest containing many absolute tool endpoints whose DNS lookups stall, the synchronous create, update, and refresh-manifest routes call getaddrinfo() here sequentially inside shared FastAPI route workers. Because the tools array is unbounded, a few concurrent requests can occupy those workers for many resolver timeouts and delay unrelated synchronous endpoints service-wide; make the owning routes async and dispatch bounded endpoint validation through resolver_executor rather than resolving inline.
AGENTS.md reference: backend/AGENTS.md:L271-L274
Useful? React with 👍 / 👎.
| try: | ||
| pinned_url, pin_kwargs = await run_blocking(resolver_executor, safe_request_target, app_tool.endpoint) | ||
| except (UnsafeWebhookURLError, ValueError): |
There was a problem hiding this comment.
Check the app-tool circuit breaker before resolving DNS
When a chat-tool breaker is already open, this still performs the developer-controlled DNS lookup before allow_request() can short-circuit the call; if that hostname is experiencing a resolver outage, every otherwise-rejected invocation can occupy the shared resolver bulkhead. A resolution failure also returns before record_failure() and app-webhook health accounting, so repeated DNS failures never open or auto-disable the endpoint. Check the breaker first and route transient resolution failures through the same failure path, releasing a half-open probe when no request can be attempted.
AGENTS.md reference: backend/AGENTS.md:L254-L254
Useful? React with 👍 / 👎.
Failure-Class: FC-free-quota-gate | new
Failure-Class: FC-free-quota-gate | new
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d0e370f59b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
|
||
| client = get_webhook_client() | ||
| client = get_pinned_webhook_client() | ||
| attempts = len(retry_delays) + 1 |
There was a problem hiding this comment.
Budget retries for every validated address
When DNS returns more than four public addresses and the first four are unreachable, the default schedule fixes attempts at four, so the modulo rotation never reaches the remaining validated addresses and repeated deliveries can still auto-disable an otherwise reachable integration. Fresh evidence after the earlier DNS-address fix is that the attempt budget remains len(retry_delays) + 1; ensure the bounded attempt plan can cover each validated target before giving up.
Useful? React with 👍 / 👎.
Failure-Class: none
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_fa660179-e62c-4c52-843a-b731ebe87405) |
An app owner could submit a manifest with many absolute tool endpoints; each endpoint's getaddrinfo() ran inline on FastAPI's shared sync route workers (create, update, refresh-manifest), so a few concurrent requests stalled unrelated sync endpoints service-wide for many resolver timeouts. - create_app / update_app / refresh_app_manifest are now async and offload DB, storage, Stripe, and cache work to their executor pools. - fetch_app_chat_tools_from_manifest resolves the manifest URL via the resolver pool, fetches over the shared async web-fetch client, and validates every absolute tool endpoint on the resolver pool; Redis manifest cache reads/writes are offloaded too. - validate_app_endpoints_for_reenable is async: DNS via resolver pool, each reachability probe dispatched as a leaf to postprocess_executor. Verification: backend unit suites for apps/manifest/SSRF/webhook lanes green; scan_async_blockers clean; tests updated to drive the async surfaces plus a new regression asserting manifest DNS runs off the event loop.
The Lane 2 guide said eight purpose-specific pools and the assignment map omitted cleanup_executor, so the authoritative pool map had no lane for account-deletion wipes. State the real count (nine) and give cleanup_executor its map entry alongside resolver_executor.
…path When safe_request_target failed for a chat tool, the call returned before record_failure() and app-webhook health accounting: repeated resolution failures never opened the circuit breaker nor started the 24h/48h/72h auto-disable timeline. Route the failure through the same path as connect/timeout errors and release a consumed HALF_OPEN probe since no request will settle it. Also lock in that an open breaker short-circuits before the developer-controlled DNS lookup. Verification: new regression test asserts release_probe + record_failure + webhook-health accounting fire on a resolution failure; existing SSRF and circuit-breaker suites green.
…sion The security regression only called resolvePersonaOwnerIdentity() and assertPersonaUidMatch() directly, so deleting the authorization lookup or the UID-match call from either /api/enable-plugins or /api/store-facts left the suite green. Transpile the real route handlers with the in-repo TypeScript compiler, run both POST handlers against stubbed Firebase fetch, Redis, and Omi API endpoints, and assert: - a missing token 401s before any side effect (no SADD, no Omi fetch), - a verified UID requesting another user's uid 401s before side effects, - a matching verified UID succeeds and performs the side effect. Mutation-checked: removing the header lookup or the UID-match call from either handler fails this suite.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Pinned manifest fetch reuses keepalive
- Manifest fetch now uses get_pinned_webhook_client() so IP-pinned requests do not share the web-fetch keepalive pool and cannot reuse another hostname's TLS/SNI session.
You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 0844484. Configure here.
…client IP-pinned URLs share an HTTPX origin by IP:port, so the web-fetch keepalive pool could reuse another hostname's TLS/SNI session and return the wrong app's chat-tool definitions. Route the GET through get_pinned_webhook_client(), which already disables keepalive for this reason. Failure-Class: FC-developer-supplied-url-ssrf
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0844484db0
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| response = await get_web_fetch_client().get( | ||
| pinned_url, | ||
| headers=headers, | ||
| extensions=pin_kwargs['extensions'], | ||
| follow_redirects=False, |
There was a problem hiding this comment.
Isolate pooled manifest fetches by TLS hostname
When two manifest hostnames resolve to the same IP and port, this shared get_web_fetch_client() sees both pinned URLs as the same HTTPX origin and may reuse a TLS connection established for the first hostname. The second request then retains the first connection's SNI and certificate verification, which can misroute the request or ingest a manifest from the wrong virtual host; use a no-keepalive pinned client or otherwise partition the pool by the original TLS authority.
Useful? React with 👍 / 👎.
…nd JSON-LD Owner re-enable reachability checks now run on sync_executor so they cannot starve conversation postprocess, and the app-detail JSON-LD sink is asserted in the frontend node:test lane.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9d8905e8ae
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for tool in tools: | ||
| validated_tool = _validate_tool_definition(tool) | ||
| validated_tool = await _validate_tool_definition(tool) |
There was a problem hiding this comment.
Bound manifest endpoint DNS validation
In the inspected create, update, and refresh-manifest paths, the manifest-controlled tools array remains unbounded and every absolute endpoint performs a blocking resolver job here. Four concurrent manifests containing many distinct slow or unresolvable hosts can therefore occupy all four resolver_executor workers for minutes, queueing unrelated webhook, MCP, setup, and app-tool DNS checks behind them. Fresh evidence after the route-isolation change is that the final loop still submits one resolver task per unbounded tool; cap the tools accepted before this loop and deduplicate or otherwise bound endpoint validation.
AGENTS.md reference: backend/AGENTS.md:L265-L265
Useful? React with 👍 / 👎.
| @@ -117,6 +157,18 @@ def safe_request_target(url: str) -> tuple[str, dict]: | |||
| return pin_to_resolved_ip(url, resolved_ip) | |||
There was a problem hiding this comment.
Try every validated address in pinned callers
When a manifest, MCP, setup, or app-tool hostname has multiple public addresses and the first resolver result is unreachable, this shared helper pins the request exclusively to that address; unlike the prior hostname-based HTTPX connection, the client cannot fall through to another A/AAAA record, so an otherwise healthy integration fails. Fresh evidence after the webhook-specific address-rotation fix is that these remaining callers still use safe_request_target(), which discards every address after _resolve_safe_ips(url)[0]; preserve pinning while allowing each validated address to be attempted.
Useful? React with 👍 / 👎.
The pre-commit hook fell back to a floating `npx prettier` when a web directory had no node_modules. Prettier 3 formats differently from the `^2.8.8` web/frontend pins and CI installs via `npm ci`, so the hook rewrote staged files into a shape CI rejects (BasedHardware#11304: getPlatformLink in web/frontend/src/app/apps/[id]/page.tsx), polluting four PRs in one day. The Dart path had the same class of bug: whatever `dart` is on PATH. Both now resolve the pinned toolchain (each web dir's package.json major, the flutter-version pinned in repo-checks.yml) and refuse with an actionable message instead of silently producing CI-rejected output. OMI_SKIP_WEB_FORMAT=1 / OMI_SKIP_DART_FORMAT=1 are the hatches. Web dirs are now derived from the staged paths, so web/admin is covered too. Failure-Class: none Verification: scripts/test-pre-commit-pinned-toolchains.sh passes; with scripts/pre-commit reverted to origin/main it fails, and the failure output shows npx installing [email protected] and rewriting the file.
…rated OpenAPI client When the staged package-lock.json is missing, empty, or unparseable, the web format-and-add loop fell back to a major-version-only Prettier comparison and, on a major match, proceeded to rewrite staged files with an unversioned prettier. That re-opens the BasedHardware#11304 unrestrained-reformat class for new packages. Refuse unconditionally when the lockfile pin is unresolvable, and document the OMI_SKIP_WEB_FORMAT=1 hatch. Also exclude auto-generated TypeScript (the web/admin OpenAPI client, omiApi.generated.ts) from Prettier's format-and-add so a regenerated artifact is never rewritten by the hook. Failure-Class: none
…t exclusion Add pinned-toolchain refusals for the two fail-closed web-pre-commit guards: a missing package-lock.json with a matching-major prettier must refuse instead of falling back to a major-only comparison (BasedHardware#11304), and a regenerated omiApi.generated.ts is never swept through Prettier format-and-add. The existing unstaged-edit refusal test now stages its package.json and package-lock.json: without a staged lockfile the resolvable-pin check refuses first, so the test never reaches the unstaged-edit guard it asserts.
The pre-commit hook fell back to a floating `npx prettier` when a web directory had no node_modules. Prettier 3 formats differently from the `^2.8.8` web/frontend pins and CI installs via `npm ci`, so the hook rewrote staged files into a shape CI rejects (#11304: getPlatformLink in web/frontend/src/app/apps/[id]/page.tsx), polluting four PRs in one day. The Dart path had the same class of bug: whatever `dart` is on PATH. Both now resolve the pinned toolchain (each web dir's package.json major, the flutter-version pinned in repo-checks.yml) and refuse with an actionable message instead of silently producing CI-rejected output. OMI_SKIP_WEB_FORMAT=1 / OMI_SKIP_DART_FORMAT=1 are the hatches. Web dirs are now derived from the staged paths, so web/admin is covered too. Failure-Class: none Verification: scripts/test-pre-commit-pinned-toolchains.sh passes; with scripts/pre-commit reverted to origin/main it fails, and the failure output shows npx installing [email protected] and rewriting the file.
…est lane ## Why Four independent hygiene fixes to local/CI gates. 1. **The pre-commit hook could reformat files into a shape CI rejects.** When a web directory had no `node_modules`, `scripts/pre-commit` fell back to a floating `npx prettier` — prettier 3 against the `^2.8.8` `web/frontend` pins and CI installs with `npm ci`. That rewrote `getPlatformLink` in `web/frontend/src/app/apps/[id]/page.tsx` into a CI-failing shape (#11304) and polluted four PRs in one day, plus unrelated `app/` Dart files reformatted by a locally-installed Dart SDK that differs from the repo's pinned Flutter. 2. **`web/frontend`'s test suite ran in no lane.** `package.json` has `"test": "node --test src/__tests__/*.test.mjs"` with real guards (`app-detail-not-found`, `case-status`, `shared-conversation-chat-contract`), but `.github/checks-manifest.yaml` never selected them — which is why a deleted frontend test's guards had to be re-homed into a backend pytest to keep running. 3. **`web/admin/AGENTS.md` was 137 bytes from red.** `agents-md-lean` going over budget takes `main` red and blocks every PR touching any `AGENTS.md` (#11409, fixed by #11410). 4. **The pre-push backend test cap had an unbounded escape hatch.** The root `AGENTS.md` push-gate budget says pre-push must "cap broad backend selection at 40 files", and `scripts/pre-push` does cap it — but when the selector overflows, the cap branch swaps in the diff's *own* changed backend test files and never re-applies the cap to that replacement. A diff changing more than 40 backend test files ran unbounded, while the message still printed `cap is 40`. #11018's 92-file diff stalled its push on this gate repeatedly; it had 15 changed backend test files so it stayed under the cap, but slow enough that several agents resorted to documented skip hatches — one size larger and there would have been no bound at all. ## What changed 1. `scripts/pre-commit` resolves the pinned toolchain and **refuses to format** rather than formatting with the wrong one: each web dir's `package.json` prettier major must match `node_modules/.bin/prettier`, and Dart requires the `flutter-version` pinned in `.github/workflows/repo-checks.yml`. Both fallbacks (`npx`, global `prettier`) are gone. Hatches: `OMI_SKIP_WEB_FORMAT=1`, `OMI_SKIP_DART_FORMAT=1`, both documented in the root `AGENTS.md` Formatting section. Web directories are now derived from the staged paths, so `web/admin` (previously skipped entirely) is covered. New regression test `scripts/test-pre-commit-pinned-toolchains.sh`, registered as manifest check `pre-commit-pinned-toolchains`. 2. New manifest check `web-frontend-tests` (`local` + `ci`, triggers `web/frontend/**`) running `node --test 'web/frontend/src/__tests__/**/*.test.mjs'` — the glob picks up test files added later. 3. `web/admin/AGENTS.md` networking and revenue-metrics detail moved verbatim into `web/admin/docs/data-contracts.md`, with the two top-level rules and a pointer left behind. **Budgets untouched.** 4. The `scripts/pre-push` fallback now **truncates deterministically to the cap**. The changed-test list is already `sort -u`ed, so `head -n cap` picks the same files on every push of the same diff rather than sampling a different subset. Truncation beats skipping here because the diff's own changed test files are the highest-signal local coverage available; the message now names the full changed-test count, what actually ran, and points at `cd backend && bash test.sh` for the remainder — it never prints a cap the run then exceeds. `PRE_PUSH_MAX_BACKEND_UNIT_TEST_FILES` stays the single knob. New regression test `scripts/test-pre-push-backend-test-cap.sh`, registered as manifest check `pre-push-backend-test-cap` (`local` + `ci`). Distinct lane from #11361, which narrows `flutter-codegen` selection in `scripts/pre_push_ci_prediction.py` — same class of problem, no overlapping files. ## Verification **Mutation test of the new guard** — with `scripts/pre-commit` reverted to `origin/main`, `scripts/test-pre-commit-pinned-toolchains.sh` fails and the output shows the exact hazard: ``` FAIL: missing pinned prettier — hook exited 0 instead of refusing Formatting staged web files with Prettier... npm warn exec The following package was not found and will be installed: [email protected] web/frontend/src/a.ts 34ms ``` With the fix applied: `pre-commit pinned-toolchain refusal tests passed` (refusal cases for missing prettier, prettier major mismatch, no flutter, flutter version mismatch; positive cases for the pinned versions; and both hatches). **Manifest selection** (`run_checks.py --list`): | Diff | `web-frontend-tests` | |---|---| | `web/frontend/src/app/apps/x.tsx` | SELECTED | | `web/frontend/src/__tests__/new-thing.test.mjs` | SELECTED | | `backend/main.py` | not selected | `run_checks.py --lane ci --check-id web-frontend-tests` → **47 tests pass, 0 fail**. **AGENTS.md headroom** after this PR (`python3 .github/scripts/check_agents_md_lean.py` → `ok: 7 AGENTS.md files within budget`): | File | Bytes | Headroom | |---|---|---| | `web/admin/AGENTS.md` | 457 / 1500 | **1043** | | `AGENTS.md` | 17082 / 18000 | 918 | | `.github/AGENTS.md` | 3825 / 4500 | 675 | | `app/AGENTS.md` | 10606 / 11500 | 894 | | `backend/AGENTS.md` | 38936 / 39000 | 64 | | `desktop/macos/AGENTS.md` | 45531 / 47000 | 1469 | | `omi/firmware/AGENTS.md` | 853 / 1500 | 647 | `backend/AGENTS.md` remains 64 bytes from the same failure and still needs its own PR. **Mutation test of the pre-push cap bound** — the regression test extracts the real `check_backend_unit_tests_if_needed` from the hook and runs it against a stubbed selector and backend, so it exercises production control flow rather than scraping source. With the bound reverted: ``` FAIL: fallback ran 25 backend test file(s), over the cap of 10 Selector requested broad selector fallout (500 files; running 25 changed backend test file(s) instead; cap is 10). Selected 25 backend unit test file(s): broad selector fallout ``` With the bound restored: `pre-push backend unit test cap tests passed` (over-cap truncation, stable + sorted truncation across repeated runs, the unchanged under-cap fallback message, and the unchanged empty-fallback skip). `make preflight` passes. ## Product invariants affected none ## Failure class (fixes) Failure-Class: none The pre-push cap fix is likewise `none`: no registered class covers "a bound's own fallback path must re-apply that bound", and one instance does not justify opening one. The nearest existing class, `FC-dev-fallback-masks-install-defect` (a development-only fallback must never be the reason a check passes), is scoped to packaged-app resource resolution on desktop; this is the same shape in a different subsystem but the registry transition belongs in its own PR. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/11413?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Changes are limited to git hooks, check manifest entries, and devDependency/docs wiring; no production runtime or auth paths are modified. > > **Overview** > Tightens local git hooks and CI manifest guards so formatting and pre-push selection cannot silently diverge from what CI enforces. > > **`scripts/pre-commit`** now **refuses** to auto-format when toolchains do not match repo pins: web Prettier (and `prettier-plugin-tailwindcss`) must match `package-lock.json` via local `node_modules`; Dart uses the Flutter version from `.github/workflows/repo-checks.yml` and that SDK’s `dart` binary. Floating `npx`/global Prettier fallbacks are removed. Web dirs are inferred from staged paths (so `web/admin` is included), `*.generated.ts` is skipped, and format-and-add is blocked when a file has unstaged edits. Escape hatches `OMI_SKIP_WEB_FORMAT=1` / `OMI_SKIP_DART_FORMAT=1` are documented in root **`AGENTS.md`**. > > **`scripts/pre-push`** re-applies **`PRE_PUSH_MAX_BACKEND_UNIT_TEST_FILES`** when the broad-selector fallback runs changed backend test files from the diff—deterministic sorted truncation and clearer logging instead of an unbounded run that still claimed a cap. > > **`.github/checks-manifest.yaml`** adds **`pre-commit-pinned-toolchains`**, **`pre-push-backend-test-cap`**, and **`web-frontend-tests`** (`scripts/run-web-frontend-tests.sh` → `node --test` on `web/frontend`). > > **`web/admin/AGENTS.md`** is trimmed for the lean budget; networking/revenue detail moves to **`web/admin/docs/data-contracts.md`**. **`web/admin`** and **`web/app`** pin Prettier ^2.8.8 (+ tailwind plugin) so the hook can format them safely. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 44dcc98. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
|
Status check-in: this branch has drifted behind Options:
Say the word (or react 👍 on this comment for option 1) and I'll schedule the rebase. Not auto-rebasing now because each one is a multi-hour, conflict-heavy job and these have been quiet long enough that confirming intent first avoids wasted work. |
|
Closing as stale. ~2,400 commits behind The audited hardening ideas that remain valuable (SSRF |
|
Hey @undivisible 👋 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:
Before your next PR, please skim:
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! |
…out (#14476) App name/description/author are community-supplied marketplace fields that reach <script type="application/ld+json"> via JSON.stringify, which does not escape `<`. A `</script>` in app metadata closes the element and injects markup on the public /apps/<id> pages. Escape to < (identical after JSON.parse) in web/app's JsonLd and web/frontend's generateStructuredData. Revives the JSON-LD portion of #11304 (author closed it as stale) as a minimal standalone fix. Verified: web/app vitest JsonLd.test.tsx 3/3; suite 490 pass (11 Sidebar/ StartupModals jsdom failures reproduce on clean main); web/frontend node:test checker 1/1; bun run typecheck clean. Failure-Class: new

What changed and why
High-confidence security audit of BasedHardware/omi. Closed concrete SSRF, path-traversal, open-redirect, unauthenticated personas API, and JSON-LD XSS gaps by reusing existing guards already present elsewhere in the codebase. Speculative refactors and dependency bumps were intentionally deferred.
Product invariants affected
none
How it was verified
Backend focused suite via
backend/test.shlist file covering SSRF call-sites, public-URL guard, upload sanitization, X OAuth redirect allowlist, webhook auto-disable, async webhooks, app-tool method null, and auth redirect URI tests — all passed (9 files; e.g. 12 + 26 + 16 + 13 + 11 + 22 + 105 + 3 + 61 passed across files). Re-ran after the synchttpx.Clientpin fix:test_ssrf_outbound_call_sites.py(11 passed) andtest_webhook_auto_disable.py(105 passed).Personas / JSON-LD:
pip-audit -r backend/requirements.txtreported known CVEs in aiohttp/cryptography/starlette/gitpython/h2/langchain/langgraph-checkpoint/langsmith/click — documented below; not bumped in this PR to avoid speculative lock churn.Pre-push (
OMI_PR_BODY_FILE) passed locally (shared PR contract + hygiene). Could not exercise live production OTA signing, Flutter secure-storage migration, or Android cleartext MITM on this Linux Cloud VM (no device/macOS toolchain). Those remain documented findings without code changes.Tests
backend/tests/unit/test_ssrf_outbound_call_sites.py— private URL rejection / pin usage at webhook, MCP, manifest, chat-tool, re-enable sitesbackend/tests/unit/test_apps_speech_upload_security.py— path traversal stripped for apps + speech-profile uploadsbackend/tests/unit/test_x_oauth_redirect_validation.py— rejectshttps://evil.example; keepsomi:/// loopbackweb/personas-open-source/src/lib/server/persona-api-auth.test.mjs— uid binding fails closed without verified identityweb/app/src/components/seo/serialize-json-ld.test.mjs— escapes</script>breakout charactersFindings fixed in this PR
safe_request_targeton manifest fetch + tool endpoints + invocationPath(...).name+ UUID prefix/api/store-factsunauthenticated write viaOMI_API_KEY/api/enable-pluginsunauthenticated Redis mutationdangerouslySetInnerHTML</>/&after stringifysuccess_redirect_urlopen redirectFindings recorded (not fixed here — ops / larger migration)
omi/firmware/.../root-rsa-2048.pem)usesCleartextTraffic="true"on releasepip-audit(aiohttp 3.14.1, cryptography 48.0.1, starlette 0.49.3, gitpython 3.1.55, h2 4.3.0, langchain 1.2.10, etc.)Failure class (fixes)
Failure-Class: new
Failure-class transition narrative
Introduces
FC-developer-supplied-url-ssrf: every backend request to a developer-supplied URL must reject non-public destinations and connect only to the IP that passed validation, without following unvalidated redirects.Canonical prevention: route every such target through
utils.http_client.safe_request_target, pin Host/SNI, and keepfollow_redirects=False. Guard artifacts:backend/utils/http_client.py,backend/tests/unit/test_ssrf_public_url_guard.py, and the new call-site suitebackend/tests/unit/test_ssrf_outbound_call_sites.py. Evidence baseline: #10638 (app-webhook SSRF hardening) while developer webhooks/MCP/manifests/chat-tools/setup probes remained unguarded.Related scoped cleanups in the same audit (upload basename sanitization, X OAuth redirect allowlist, personas API authz, JSON-LD escape) close adjacent high-confidence boundaries that already had sibling hardened patterns elsewhere in-tree.
New guards (only when adding a check or ratchet)
Unit call-site tests for SSRF/upload/redirect/JSON-LD/personas auth. They are narrowly scoped to the fixed surfaces rather than a new shared CI primitive because the shared primitives (
safe_request_target, auth redirect allowlist, Firebase identity lookup) already exist; the defect was missing call sites.Line-Count-Exception: backend/routers/apps.py | 2425 -> 2459 | restore enforce_chat_quota + X-App-Platform header on generate-description endpoints (security hardening)
Line-Count-Exception: backend/routers/users.py | 2175 -> 2183 | webhook URL admission validation with safe_request_target (SSRF hardening)
Line-Count-Exception: backend/utils/apps.py | 1652 -> 1716 | manifest/tool URL pinning via safe_request_target with path-relative pass-through (SSRF hardening)