Repository navigation
test(electric-proxy): lock tenant filters and upstream auth stripping - #5470
DivyamTalwar wants to merge 1 commit into
Conversation
📝 WalkthroughWalkthroughThis PR adds Bun test suites for the electric-proxy app: tests for ChangesElectric proxy testing
Estimated code review effort: 2 (Simple) | ~15 minutes Related PRs: None identified. Suggested labels: tests, electric-proxy Suggested reviewers: None identified. 🐰 tests hop in, quiet and neat, verifying proxies, clause complete, tiny scripts to keep them fleet. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Ready to review this PR? Stage has broken it down into 5 individual chapters for you:
Chapters generated by Stage for commit b631325 on Jul 6, 2026 6:44pm UTC. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
apps/electric-proxy/src/index.test.ts (1)
25-71: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMissing test for "invalid or expired token" path.
Coverage exists for a missing bearer header (40-47) and out-of-membership org (61-71), but no test drives
verifyJWTto resolve falsy to exercise the401 "Invalid or expired token"branch inapps/electric-proxy/src/index.ts(context snippet 2). The PR/commit description explicitly calls out locking down rejection of "invalid or missing auth" — the "invalid" half is untested.✅ Suggested additional test
+ test("rejects invalid or expired tokens", async () => { + verifyJWT.mockResolvedValueOnce(null); + const response = await worker.fetch( + request("/shape?table=tasks&organizationId=org-1", { + headers: { Authorization: "Bearer bad-token" }, + }), + env, + ); + + expect(response.status).toBe(401); + expect(await response.text()).toBe("Invalid or expired token"); + });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/electric-proxy/src/index.test.ts` around lines 25 - 71, Add a test in electric proxy worker coverage that forces verifyJWT to return a falsy value so the invalid/expired token branch in worker.fetch is exercised. Update the existing electric proxy tests in index.test.ts by mocking verifyJWT for one case to resolve null/undefined and assert the response is 401 with the "Invalid or expired token" message, alongside the existing bearer-header and organization checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@apps/electric-proxy/src/index.test.ts`:
- Around line 25-71: Add a test in electric proxy worker coverage that forces
verifyJWT to return a falsy value so the invalid/expired token branch in
worker.fetch is exercised. Update the existing electric proxy tests in
index.test.ts by mocking verifyJWT for one case to resolve null/undefined and
assert the response is 401 with the "Invalid or expired token" message,
alongside the existing bearer-header and organization checks.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 1e9299b1-5675-4c53-906c-5bf7a9bc5b8c
⛔ Files ignored due to path filters (1)
bun.lockis excluded by!**/*.lock
📒 Files selected for processing (5)
apps/electric-proxy/package.jsonapps/electric-proxy/src/electric.test.tsapps/electric-proxy/src/index.test.tsapps/electric-proxy/src/where.test.tsapps/electric-proxy/tsconfig.json
Greptile SummaryThis PR adds executable security regression tests for the Electric proxy without touching any production code. It covers tenant-scoping contracts (
Confidence Score: 4/5Safe to merge — no production code is changed; all risk is limited to test coverage completeness. The production Electric proxy is untouched. The new tests are well-structured and correctly exercise the most critical paths (org scoping, header stripping, column restrictions). Two scenarios named in the PR description — unknown-table rejection and auth.organizations with an empty JWT — are validated only at the unit layer; the HTTP integration harness does not reach those branches. The sort-order invariant for auth.organizations params is also not exercised by the current mock data. None of these omissions introduce regressions, but they leave stated coverage claims partially unfulfilled. apps/electric-proxy/src/index.test.ts — missing integration assertions for the unknown-table 400 path and the zero-org auth.organizations path; also the sort-order of organization params is not validated by the current mock data.
|
| Filename | Overview |
|---|---|
| apps/electric-proxy/src/where.test.ts | Adds unit tests for buildWhereClause; covers org-scoped tables, auth.organizations (multi-org and empty), and auth.apikeys — auth.users and the table-not-in-list paths are not directly asserted |
| apps/electric-proxy/src/electric.test.ts | Adds unit tests for buildUpstreamUrl; verifies client-supplied where/secret/columns are stripped and that source credentials take priority over ELECTRIC_SECRET |
| apps/electric-proxy/src/index.test.ts | Integration tests for the full worker handler; verifies auth, org-membership gating, and header stripping — missing integration tests for unknown-table rejection and the zero-org auth.organizations edge case that the PR description lists as covered |
| apps/electric-proxy/package.json | Adds test script (bun test src) and bun-types dev dependency to make tests discoverable via Turbo |
| apps/electric-proxy/tsconfig.json | Adds bun-types to the types array so bun:test imports resolve correctly under tsc |
Sequence Diagram
%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant Client
participant Worker as Electric Proxy Worker (index.ts)
participant Auth as auth.ts (verifyJWT)
participant Where as where.ts (buildWhereClause)
participant Electric as upstream Electric
Client->>Worker: "GET /shape?table=...&organizationId=..."
Worker->>Auth: verifyJWT(token, AUTH_URL)
Auth-->>Worker: "{ organizationIds, sub, email }"
alt missing/invalid token
Worker-->>Client: 401
end
alt "table != auth.organizations and missing/unauthorized orgId"
Worker-->>Client: 400 / 403
end
Worker->>Where: buildWhereClause(table, orgId, sortedOrgIds)
Where-->>Worker: "WhereClause | null"
alt unknown table (null)
Worker-->>Client: 400 Unknown table
end
Worker->>Electric: fetch(upstreamUrl, stripped headers)
Note over Worker,Electric: strips Authorization & Cookie, sets server-side where/secret/columns
Electric-->>Worker: shape response
Worker-->>Client: response + CORS headers (Vary: Authorization)
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant Client
participant Worker as Electric Proxy Worker (index.ts)
participant Auth as auth.ts (verifyJWT)
participant Where as where.ts (buildWhereClause)
participant Electric as upstream Electric
Client->>Worker: "GET /shape?table=...&organizationId=..."
Worker->>Auth: verifyJWT(token, AUTH_URL)
Auth-->>Worker: "{ organizationIds, sub, email }"
alt missing/invalid token
Worker-->>Client: 401
end
alt "table != auth.organizations and missing/unauthorized orgId"
Worker-->>Client: 400 / 403
end
Worker->>Where: buildWhereClause(table, orgId, sortedOrgIds)
Where-->>Worker: "WhereClause | null"
alt unknown table (null)
Worker-->>Client: 400 Unknown table
end
Worker->>Electric: fetch(upstreamUrl, stripped headers)
Note over Worker,Electric: strips Authorization & Cookie, sets server-side where/secret/columns
Electric-->>Worker: shape response
Worker-->>Client: response + CORS headers (Vary: Authorization)
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 2
apps/electric-proxy/src/index.test.ts:1-20
**Two integration paths listed in the PR description are untested**
The PR description states "unknown tables are rejected" as a covered scenario, but `index.test.ts` has no test that sends a request for e.g. `table=unknown_table` and verifies the worker returns `400 Unknown table: ...`. The `where.test.ts` unit test verifies `buildWhereClause` returns `null`, but the HTTP-layer rejection at `index.ts` line 81 (`corsResponse(400, \`Unknown table: ${tableName}\`)`) is never exercised through the worker.
Similarly, the `auth.organizations`-with-empty-JWT path — where `buildWhereClause` returns `{ fragment: "1 = 0", params: [] }` — is tested in `where.test.ts` but is not wired through the integration harness in `index.test.ts`.
### Issue 2 of 2
apps/electric-proxy/src/index.test.ts:111-133
**`auth.organizations` param ordering is not stress-tested**
The production code sorts `auth.organizationIds` before passing them to `buildWhereClause` (`[...auth.organizationIds].sort()` in `index.ts` line 74). The intent is a stable ordering so Electric produces a consistent shape handle regardless of JWT claim order. However, the test mock supplies `["org-1", "org-2"]` which is already in sorted order, so the sort is never actually exercised. A mock value of `["org-2", "org-1"]` would properly validate that the upstream URL receives `params[1]=org-1` and `params[2]=org-2` after sorting, rather than accidentally passing in JWT order.
Reviews (1): Last reviewed commit: "test(electric-proxy): lock tenant filter..." | Re-trigger Greptile
There was a problem hiding this comment.
All reported issues were addressed across 6 files
Architecture diagram
sequenceDiagram
participant Client
participant Proxy as Electric Proxy Worker
participant Auth as Auth Service (JWT)
participant Electric as Upstream Electric
Note over Client,Electric: Shape request flow (covered by regression tests)
Client->>Proxy: GET /shape?table=tasks&organizationId=org-1
Note right of Proxy: Authorization: Bearer <token>
Proxy->>Auth: verifyJWT(token)
Auth-->>Proxy: { sub, email, organizationIds: ["org-1","org-2"] }
alt Missing or invalid token
Proxy-->>Client: 401 Missing or invalid Authorization
else Missing organizationId for org-scoped table
Proxy-->>Client: 400 Missing organizationId parameter
else Organization not in JWT memberships
Proxy-->>Client: 403 Not a member of this organization
else Success
Proxy->>Proxy: buildWhereClause(table, orgId, jwtOrgs)
alt Table is unknown
Proxy-->>Client: 400 Unknown table
else Table is auth.organizations
Note over Proxy: where = "id" IN ($1,$2) with JWT orgs
else Table is auth.apikeys
Note over Proxy: where = "organization_id" = $1
else Org-scoped table (e.g., tasks)
Note over Proxy: where = "organization_id" = $1
end
Proxy->>Proxy: buildUpstreamUrl(clientUrl, table, whereClause)
Note over Proxy: Strips client‑supplied where/secret/columns
Note over Proxy: Adds server‑derived where, secret
Note over Proxy: Projects columns for auth.apikeys
Proxy->>Proxy: Remove Authorization & Cookie headers from upstream request
Proxy->>Electric: GET /v1/shape?table=tasks&where=...&secret=...
Note right of Proxy: Only non‑auth headers forwarded (e.g., X-Client-Header)
Electric-->>Proxy: Response (shape data)
Proxy->>Proxy: Strip content‑encoding, content‑length
Proxy->>Proxy: Add access‑control‑allow‑origin: *
Proxy-->>Client: 200 shape data
end
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
b631325 to
b34896e
Compare
Keyless before/after verificationThe Electric multi-tenant WHERE builder and upstream-auth stripping had zero test coverage on Before — base After — the fix Review threads addressed: unknown-table 400 path and JWT-claim sort ordering now have explicit coverage. CI: @Kitenite — updated per the bot review; would appreciate a look when you have a moment. 🙏 |
Electric proxy responses are security-sensitive because every shape request must be scoped to the caller's authorized organizations while avoiding upstream leakage of bearer tokens or cookies. This adds the missing test script and regression coverage for table scoping, sensitive column restrictions, source credential handling, membership rejection, and upstream auth header stripping. Constraint: Electric proxy runs as a Cloudflare Worker but the repo uses Bun tests for workspace-level regression coverage. Rejected: Rely only on typecheck/manual inspection | tenant isolation and auth stripping need executable regression tests. Confidence: high Scope-risk: narrow Directive: Keep Electric proxy tests exercising both pure URL/where builders and the worker fetch boundary when auth or table scoping changes. Tested: bun --cwd apps/electric-proxy test Tested: bun run test --filter=electric-proxy Tested: bun --cwd apps/electric-proxy typecheck Tested: bunx @biomejs/[email protected] check apps/electric-proxy/package.json apps/electric-proxy/tsconfig.json apps/electric-proxy/src/where.test.ts apps/electric-proxy/src/electric.test.ts apps/electric-proxy/src/index.test.ts bun.lock Tested: git diff --check Not-tested: live Cloudflare Worker deployment; behavior is covered at the fetch handler and pure helper level.
b34896e to
3ceb629
Compare



Description
This PR adds executable security regression coverage for the Electric proxy. The new tests lock down the tenant-scoping and upstream-forwarding contracts that protect Electric shape requests:
auth.organizationsis limited to JWT organization membershipsauth.apikeysuses the restricted organization column and sensitive column projectionwhere,secret, andcolumnsparams are not forwarded as trusted upstream paramsThe PR also adds the missing
testscript and Bun test types for this workspace so the tests are discoverable through Turbo.Related Issues
No existing issue. This was discovered during repository analysis.
Type of Change
Testing
Commands run:
bun --cwd apps/electric-proxy test— passedbun run test --filter=electric-proxy— passedbun --cwd apps/electric-proxy typecheck— passedbunx @biomejs/[email protected] check apps/electric-proxy/package.json apps/electric-proxy/tsconfig.json apps/electric-proxy/src/where.test.ts apps/electric-proxy/src/electric.test.ts apps/electric-proxy/src/index.test.ts bun.lock— passedgit diff --check— passedScreenshots (if applicable)
N/A.
Additional Notes
Risk level: low. This PR does not change production Electric proxy behavior; it adds regression coverage and a workspace test script for security-critical tenant filtering and auth-header stripping.
Summary by cubic
Adds executable security regression tests for the Electric proxy to lock tenant scoping, upstream auth stripping, and response header sanitization for shape requests, including source credential handling and sensitive column restrictions. Also locks stable handles by sorting JWT organization IDs and allows
auth.organizationswithout an organizationId; adds a workspacetestscript andbun-typesso tests run under Turbo.Written for commit 3ceb629. Summary will update on new commits.
Summary by CodeRabbit
Bug Fixes
Chores