Repository navigation
Supersedes #14431: fix(plugins): require auth on iq-rating routes keyed only by uid - #20223
omiagent[bot] wants to merge 4 commits into
Conversation
The iq_rating router mounted in the plugins monolith trusts the client-supplied uid with no credential: - GET /iq-rating/iq/preload and /iq/refresh trigger a scrape of ALL memories and conversations for any uid via the server-side OMI_APP_SECRET - GET /iq-rating/iq and /iq/api serve the extracted people names and scores for any uid (the HTML page embeds them publicly) - POST /iq/hide, /iq/unhide, /iq/adjust mutate any uid's data Same contract violation as the merged mentor session fix, wider blast radius: one request converts a uid into a full memory/conversation scrape. Adds plugins/iq_rating/iq_auth.py mirroring the mentor/zapier pattern: IQ_RATING_SECRET env secret, Bearer or iq_rating_token query param, hmac.compare_digest, fail-closed 503 when unconfigured. Wired onto the six uid-keyed data routes; the uid-less /iq landing state and /iq/setup-status stay public. Also escapes the uid embedded in the page JS (was a reflected-XSS sink) and threads the query token into the page's hide/adjust fetches so authenticated page actions keep working. Deployment note: IQ_RATING_SECRET must be set and the Omi app/webview caller must pass iq_rating_token, matching the mentor precedent. Verification: python3 plugins/iq_rating/test_iq_auth.py — 11 tests (fail-closed unconfigured, missing/wrong/non-bearer token, bearer and query token accepted, uid trimming, optional-uid page gate, route wiring) all pass. Failure-Class: new — client-supplied uid accepted as authorization on unauthenticated plugin routes
The query token was interpolated raw inside a single-quoted JS literal — a token containing ' would break out of the string. json.dumps keeps it inside a double-quoted literal with proper escaping, same as the uid fix. Verified: render check with token x'-alert(1)-' produces const tokenParam = "iq_rating_token=x'-alert(1)-'&";; 11 iq auth tests pass.
…ermetic runs Carry-forward on the cherry-pick rebase, test harness only (no product code): - test_iq_auth.py: under pytest with fastapi installed, real fastapi is already in sys.modules, so the stub's sys.modules.setdefault is a no-op and the six negative-path tests raised real fastapi.HTTPException while asserting against the local stub class. The tests now assert against the HTTPException class the module actually binds; they pass both ways. - test_main.py: the manifest check runs this file standalone (python3 plugins/iq_rating/test_main.py), where main.py's auth import falls back to the absolute 'from iq_rating.iq_auth import ...' path; make the plugin parent dir importable so that fallback resolves, and give the hermetic fastapi stub the Request/Depends attributes the wired routes now reference. All invocation contexts pass: pytest with the backend venv (23 tests), the documented standalone runs, and the hermetic no-fastapi path. Co-authored-by: Hridya Agrawal <[email protected]> Failure-Class: none
…a islands CodeQL flagged the carried page-rendering code with a new reflected server-side XSS: JSON allows raw < > and & inside strings, so a uid or iq_rating_token value containing a closing script tag breaks out of the inline <script> element and following markup parses as HTML. This completes the injection-safety pass the original PR's second commit started: the page's three script-context values (uid, token_param, people_data_json) now ship as non-executing <script type="application/json"> data islands written through html.escape, and the page script reads them with JSON.parse at startup, so the decoded JS values are identical to the previous inline embedding. RouteWiringTest pins the island embedding and the JSON.parse reads. The str(e) HTML sink in the same handler's error branch predates this change (old-baseline, no new alert). Co-authored-by: Hridya Agrawal <[email protected]>
5b11db7 to
d36e011
Compare
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thank you for reviving #14431 — the auth direction here is right, and iq_auth.py itself is solid: fail-closed 503 when IQ_RATING_SECRET is unset, 401 on missing/wrong tokens, hmac.compare_digest for constant-time comparison, and 11 real behavioral tests in test_iq_auth.py. All six uid-keyed data routes are wired to the gate. That said, I verified three concrete bugs in the page-rendering path (reproduced with plain stdlib semantics, not speculation), so requesting changes.
1. The JSON data islands are never emitted — the populated /iq view is broken.
iq_rating_page (main.py ~line 1779) calls PEOPLE_LIST_CONTENT.format(uid=..., token_param=..., people_data_json=..., total_people=...), but the template (lines 1595–1714) no longer contains {uid}, {token_param}, or {people_data_json} placeholders — only {total_people} remains. str.format silently discards unused kwargs, so the three <script type="application/json"> islands never reach the HTML, and the page JS (lines 1609–1611) runs JSON.parse(document.getElementById('iq-data-uid').textContent) on null. The islands need explicit placeholders in PEOPLE_LIST_CONTENT (just before the <script> block).
2. html.escape(..., quote=True) breaks JSON.parse even once emitted.
_json_data_island escapes the JSON with quote-entity encoding, but <script> is a raw-text element — browsers do not decode entities there, so textContent is literally "u1" and JSON.parse throws. For script raw-text, escape only what can close the element (</script, optionally </&), not quotes.
3. People data is double-encoded.
The handler does json.dumps(people_with_iq) (line 1776) and _json_data_island dumps again, so even a working parse yields a string, not the array that sortBy/renderPeople spread and sort. Pass the list to the island helper, not the pre-dumped JSON string.
Two smaller items:
- Token leakage via share:
shareResults(line 1650) shareswindow.location.href, which now contains the bearer-equivalentiq_rating_token. Please strip that param before sharing. - The
RouteWiringTestassertions intest_iq_auth.pypass despite 1–3 because they substring-match source text rather than rendered output — a render-path test asserting the islands exist and parse would have caught this.
One design note for maintainers: the token-in-query-param transport puts the secret in access logs/proxies, and the fail-closed 503 default disables the feature for deployments that don't set IQ_RATING_SECRET. Both look like deliberate stopgap tradeoffs (and closing the uid-scraping hole documented in #14430 is worth it), but the auth semantics deserve maintainer sign-off alongside the fixes above.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
…xecuting JSON islands (BasedHardware#14430) Failure-Class: none Closes BasedHardware#14430. Supersedes abandoned BasedHardware#20223 and addresses all reviewer feedback: 1. Auth Gate (iq_auth.py): - Adds require_iq_auth and require_iq_auth_if_uid guards using IQ_RATING_SECRET. - Accepts Bearer token via Authorization header or iq_rating_token query param with hmac.compare_digest. - Fails closed with 503 if unconfigured; 401 on missing or incorrect credentials; 422 on empty uid. - Protects all six data-plane endpoints (/iq/api, /iq/hide, /iq/unhide, /iq/adjust, /iq/preload, /iq/refresh). 2. Safe Island Rendering: - Emits <script type="application/json"> data islands directly in PEOPLE_LIST_CONTENT. - Escapes </ sequences without entity-encoding quotes ("), preserving valid JSON for JSON.parse. - Passes raw people_with_iq list to island helper to prevent double-encoding. - Strips iq_rating_token from shareUrl in shareResults() to prevent token leakage. 3. Testing: - Adds test_iq_auth.py with 13 unit tests covering auth enforcement, static route wiring, and HTML render path parsing. - Adds defensive imports and stubs in test_main.py (25/25 total plugin tests passing). Signed-off-by: Hardik <[email protected]>
Supersedes #14431: fix(plugins): require auth on iq-rating routes keyed only by uid
What this does, in plain terms
The IQ Rating plugin page ranks the people around you by "IQ" scores computed from your memories and conversations. Every data route on that page takes a
uidquery parameter and returns — or edits — that user's data with no password, token, or login of any kind. Anyone who knows or guesses another user's uid can read their rated-people list and even mutate it (hide people, adjust scores). Uids are not secrets: they appear as plain parameters on other public surfaces, and issue #14430 (open, bounty- tagged) documents exactly this exposure.This change puts a shared-secret gate on those routes. A deployment sets an
IQ_RATING_SECRETenvironment variable; requests must then present a matching bearer token (Authorization: Bearer …) oriq_rating_tokenquery parameter. With no secret configured the routes fail closed with 503; with one configured, missing or wrong tokens get 401. Comparison uses constant-timehmac.compare_digest. The/iqpage itself stays reachable without a uid (it renders an empty state), but supplying a uid requires the token, and the page passes its own token through to the data calls it makes from the browser.Merging implications: for deployments that set the secret, the uid-scraping hole closes; for deployments that don't, the routes return an explicit 503 instead of silently serving data publicly — an intentional fail-closed default, so enabling the feature requires an explicit operator action. Rollback is a normal revert.
Carry-forward from #14431
Supersedes #14431 — "fix(plugins): require auth on iq-rating routes keyed only by uid" — by @hridaya423. That PR was opened 2026-09-17 against this same hole and stalled without review; the hole is still live on
main(verified at revival time: norequire_iq_auth/IQ_RATING_SECRETanywhere inplugins/iq_rating/on main, all six uid-keyed routes unauthenticated).This branch cherry-picks the author's two commits with original authorship intact (
git logcredits @hridaya423 as the author of both).Carry-forward changes (two mechanical commits, co-authored with the original author):
test:— harness compatibility, no product code. The author's new test file stubsfastapiso it runs standalone with no dependencies; under pytest with fastapi installed, real fastapi is already insys.modules, so the stub'ssys.modules.setdefaultis a no-op and the six negative-path tests raised realfastapi.HTTPExceptionwhile asserting against the local stub class. The tests now assert against the class the module actually binds. The repo's hermetic manifest check also runstest_main.pyas a standalone script, wheremain.py's absolute import fallback needs the plugin's parent dir onsys.pathand the fastapi stub needs theRequest/Dependsattributes the wired routes reference — both added to the harness.harden:— completes the injection-safety pass the original PR's second commit started. CodeQL flagged the carried page-rendering code with a new reflected server-side XSS (py/reflective-xss, high): JSON allows raw<,>,&inside strings, so a uid oriq_rating_tokenvalue containing a closing script tag can break out of the inline<script>element. The page's three script-context values (uid,token_param,people_data_json) now ship as non-executing<script type="application/json">data islands written throughhtml.escape, which the page script reads withJSON.parseat startup — decoded JS values are identical to the previous inline embedding, andRouteWiringTestpins both the island embedding and the reads. Thestr(e)HTML sink in the same handler's error branch predates this change (old-baseline, no new alert; left untouched to keep this PR's scope to the carried change).Product invariants affected
none
How it was verified
Run on this branch (merge-base = current
origin/main2f11935f93):backend/.venv/bin/python -m pytest plugins/iq_rating/test_iq_auth.py plugins/iq_rating/test_main.py→ 23 passed (11 new auth tests + 12 existing iq-rating tests).python plugins/iq_rating/test_iq_auth.py→ 11 tests OK;python3 plugins/iq_rating/test_main.py(the manifest check's invocation) → 12 tests OK under both the venv python and a bare system python3 with fastapi absent.RouteWiringTeststatically pins the fix: every uid-keyed route (/iq/api,/iq/hide,/iq/unhide,/iq/adjust,/iq/preload,/iq/refresh) must declareDepends(require_iq_auth)and the/iqpageDepends(require_iq_auth_if_uid), and the page JS must not embed a raw uid string — so the guard cannot silently fall off the routes.git grep -n "require_iq_auth\|IQ_RATING_SECRET" origin/main -- plugins/iq_rating/→ no matches.bash scripts/backend-python-format --check plugins/iq_rating/iq_auth.py plugins/iq_rating/test_iq_auth.py).plugins/iq_rating/main.pyis not black-clean onmainitself and CI's Python formatting gate scopes tobackend/**only (.github/workflows/repo-checks.yml), so this branch carries no whole-file reformat churn.Tests
Regression coverage for the security fix is the author's
plugins/iq_rating/test_iq_auth.py: fail-closed 503 on missing/blank secret, 401 on missing token / wrong token / non-bearer scheme, bearer and query-token acceptance, uid trimming, the uid-less page bypass, and the route-wiring pin described above. The one carry-forward commit adjusts only how the negative-path tests reference the exception class (mechanism explained in the carry-forward section).Failure class (fixes)
Failure-Class: none