Skip to content

test(electric-proxy): lock tenant filters and upstream auth stripping - #5470

Closed
DivyamTalwar wants to merge 1 commit into
ParadevAI:mainfrom
DivyamTalwar:test/electric-proxy-tenant-contracts
Closed

DivyamTalwar wants to merge 1 commit into
ParadevAI:mainfrom
DivyamTalwar:test/electric-proxy-tenant-contracts

Conversation

@DivyamTalwar

@DivyamTalwar DivyamTalwar commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • organization-owned tables include the requested organization filter
  • auth.organizations is limited to JWT organization memberships
  • auth.apikeys uses the restricted organization column and sensitive column projection
  • unknown tables are rejected
  • client-provided where, secret, and columns params are not forwarded as trusted upstream params
  • bearer/cookie headers are stripped before forwarding to Electric
  • invalid/missing auth and unauthorized organizations are rejected at the worker boundary

The PR also adds the missing test script 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

  • Bug fix
  • New feature
  • Documentation
  • Refactor
  • Other (please describe): security regression tests / test infrastructure

Testing

Commands run:

  • bun --cwd apps/electric-proxy test — passed
  • bun run test --filter=electric-proxy — passed
  • bun --cwd apps/electric-proxy typecheck — passed
  • 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 — passed
  • git diff --check — passed

Screenshots (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.


Open in Stage

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.organizations without an organizationId; adds a workspace test script and bun-types so tests run under Turbo.

Written for commit 3ceb629. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • Bug Fixes

    • Improved proxy request handling for organization-scoped access, authorization checks, and upstream forwarding behavior.
    • Tightened handling of query parameters and headers to make forwarded requests more consistent and secure.
  • Chores

    • Added automated test coverage for core proxy behaviors.
    • Updated project setup to support Bun-based testing and typings.

@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds Bun test suites for the electric-proxy app: tests for buildUpstreamUrl and buildWhereClause utility functions, and tests for the proxy worker's request handling (auth, org scoping, header sanitization). It also adds bun-types dependency, a test npm script, and updates tsconfig.json types.

Changes

Electric proxy testing

Layer / File(s) Summary
Test tooling configuration
apps/electric-proxy/package.json, apps/electric-proxy/tsconfig.json
Adds bun-types devDependency, a test script (bun test src), and includes bun-types in compilerOptions.types.
buildUpstreamUrl tests
apps/electric-proxy/src/electric.test.ts
Adds tests validating Electric parameter forwarding/filtering, auth.apikeys column restriction, and source credential selection.
buildWhereClause tests
apps/electric-proxy/src/where.test.ts
Adds tests for organization scoping, JWT membership filtering, deny-all behavior, apikeys column restriction, and unknown table handling.
Electric proxy worker request tests
apps/electric-proxy/src/index.test.ts
Adds a mocked JWT/fetch test harness and tests covering auth rejection, missing/invalid organizationId, upstream forwarding with header sanitization, and auth.organizations handling.

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)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is conventional, concise, and accurately summarizes the main change: locking tenant filters and upstream auth stripping.
Description check ✅ Passed The description covers the change, testing, related issues, and notes, but it omits the repository's checklist section.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@ghost

ghost commented Jul 6, 2026

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 5 individual chapters for you:

Title
1 Configure Bun test infrastructure
2 Test tenant filtering and table access
3 Test upstream URL construction and sanitization
4 Test end-to-end worker request handling
5 Other changes
Open in Stage

Chapters generated by Stage for commit b631325 on Jul 6, 2026 6:44pm UTC.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
apps/electric-proxy/src/index.test.ts (1)

25-71: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Missing 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 verifyJWT to resolve falsy to exercise the 401 "Invalid or expired token" branch in apps/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

📥 Commits

Reviewing files that changed from the base of the PR and between ab22a76 and b631325.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • apps/electric-proxy/package.json
  • apps/electric-proxy/src/electric.test.ts
  • apps/electric-proxy/src/index.test.ts
  • apps/electric-proxy/src/where.test.ts
  • apps/electric-proxy/tsconfig.json

@greptile-apps

greptile-apps Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds executable security regression tests for the Electric proxy without touching any production code. It covers tenant-scoping contracts (buildWhereClause), upstream URL construction (buildUpstreamUrl), and the full request handler (auth gating, org-membership checks, and auth-header stripping).

  • where.test.ts — unit tests for buildWhereClause: org-scoped tables, auth.organizations (multi-org and empty-org denial), auth.apikeys restricted column fragment, and unknown-table rejection.
  • electric.test.ts — unit tests for buildUpstreamUrl: verifies client-supplied where, secret, and columns are not forwarded, protocol params (handle, offset) are forwarded, and source credentials take priority over ELECTRIC_SECRET.
  • index.test.ts — integration tests through the full Cloudflare worker handler: bearer-token requirement, org-membership enforcement, and Authorization/Cookie stripping before upstream forwarding; two paths mentioned in the PR description (unknown-table rejection and zero-org auth.organizations) are tested only at the unit layer, not through the HTTP handler.

Confidence Score: 4/5

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

Important Files Changed

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)
Loading
%%{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)
Loading
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

Comment thread apps/electric-proxy/src/index.test.ts Resolved
Comment thread apps/electric-proxy/src/index.test.ts Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread apps/electric-proxy/src/index.test.ts Resolved
Comment thread apps/electric-proxy/src/index.test.ts Resolved
@DivyamTalwar
DivyamTalwar force-pushed the test/electric-proxy-tenant-contracts branch from b631325 to b34896e Compare July 22, 2026 10:25
@DivyamTalwar

DivyamTalwar commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Keyless before/after verification

The Electric multi-tenant WHERE builder and upstream-auth stripping had zero test coverage on main. This PR adds regression contracts pinning per-org scoping, empty-membership deny-all, and Authorization/Cookie stripping.

summary

Before — base main
main guards nothing; a demo regression (deny-all 1 = 0 → allow-all 1 = 1) is caught by the new contract → 1 fail.

before

After — the fix
Contracts active → 14 pass / 0 fail across 3 files (added HTTP unknown-table rejection + an unsorted-claim test that exercises the .sort() per review feedback).

after

Review threads addressed: unknown-table 400 path and JWT-claim sort ordering now have explicit coverage.

CI: mergeable = MERGEABLE, single clean commit (Divyam Talwar <[email protected]>), rebased onto latest main. BLOCKED = awaiting required maintainer review.

@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.
@DivyamTalwar
DivyamTalwar force-pushed the test/electric-proxy-tenant-contracts branch from b34896e to 3ceb629 Compare July 22, 2026 11:37
@Kitenite

Copy link
Copy Markdown
Member

Closing: main already ships this. apps/electric-proxy no longer exists (b671c27 #6328). Thanks for the PR; if you think the shipped version misses a case, open an issue and link this.

@Kitenite Kitenite closed this Aug 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants