← Model losses

Head-to-head comparison

openai / gpt-6.1-sol / xhigh / xhigh effort preferred over openai / gpt-6.1-sol / low / low effort · close win.

Primary judge: Sol 6.1, requested Low. Effective provider effort and internal attempts were not verified. A close win is still a scored preference; it does not establish a material defect.

Reviewed public evidence

Task goal

Review the tenant isolation and scanner ingestion security boundary in this [REDACTED: private project name] repository snapshot. Use the named migrations, scanner handler, and RLS tests as your evidence. Identify only concrete vulnerabilities or missing controls supported by these files. For each finding, cite the exact file and policy/function/table, describe a plausible request or actor and the resulting data access or integrity impact, state severity and preconditions, and distinguish proven behavior from assumptions. Examine tenant identity derivation, RLS enforcement, SECURITY DEFINER behavior, service-role use, scanner authentication, and cross-tenant writes where the source permits. Compare each finding with the existing assertions in test-rls.sql; do not claim any test ran. Finish with prioritized findings and minimal regression-test scenarios. Do not edit code.

openai / gpt-6.1-sol / xhigh / xhigh effort answer

## Conclusion

The strongest finding is **SQL injection in a `SECURITY DEFINER` policy-management function**, potentially allowing an authenticated caller to disable RLS and grant cross-tenant access. Its reachability depends on function privileges and API exposure.

This was an independent, read-only review of the supplied snapshot. **No tests were executed.**

## Boundary assessment and uncertainties

- Standard policies check membership for both existing and replacement rows: `USING (app.is_member(tenant_id)) WITH CHECK (app.is_member(tenant_id))` in `supabase/migrations/00008_enable_rls_and_policies.sql:36–45`. The implementation of `app.is_member` is outside the packet, so its identity derivation cannot be verified.
- `supabase/migrations/00015_hardening.sql:4–22` removes direct `authenticated` privileges on `app` tables and instead grants reads on five `public.api_*` views. Those view definitions are not supplied; **view-based RLS bypass is not proven**. The assertion that views automatically inherit RLS in `supabase/test-rls.sql:237` is insufficient—ordinary PostgreSQL views can use their owner’s privileges.
- Scanner tenant identity comes directly from request JSON, not a JWT or membership lookup: `supabase/functions/scanner/index.ts:30,56,89,111`. The database client uses the service-role key at lines 39–43, normally bypassing RLS. This is a global administrative ingestion interface, not a tenant-scoped one. **Selecting another tenant while holding that global key is not independently an authorization vulnerability**: the credential already grants broad authority.
- S3 prefixes are literal strings; `../` does not establish filesystem-style traversal. Cross-tenant relationship corruption through foreign asset/survey identifiers also cannot be established without the relevant constraints.

## Prioritized findings

### 1. Critical, conditional: injectable privileged policy helper

**Evidence:** `supabase/migrations/00008_enable_rls_and_policies.sql:21–46`, function `app.apply_member_policies(text)`.

The function runs as `SECURITY DEFINER` and interpolates caller-controlled text into SQL using unquoted `%s`, both as a policy-name fragment and as a relation expression.

A representative argument is:

```text
app.asset; ALTER TABLE app.asset DISABLE ROW LEVEL SECURITY; GRANT SELECT ON app.asset TO authenticated; --.asset
```

The final `.asset` makes the extracted policy-name fragment `asset`; the preceding commands remain in the relation expression. The comment suppresses the generated suffix. This permits additional commands in the function owner’s privilege context.

**Actor and impact:** An authenticated caller able to execute this function could disable RLS on `app.asset` and restore `SELECT`, exposing assets from every tenant. The injected grant also defeats the table-privilege restriction introduced by hardening.

**Preconditions and confidence:**
- PostgreSQL normally grants new functions `EXECUTE` to `PUBLIC`.
- `supabase/migrations/00015_hardening.sql:9,13` revokes privileges from `authenticated`, **not `PUBLIC`**; line 5 grants authenticated schema usage.
- Thus the shown hardening does not close default PUBLIC execution. Actual inherited ACLs and whether `app` RPCs are exposed are not supplied.
- The function owner must possess the relevant table privileges; the migration’s legitimate policy-creation calls already require substantial ownership authority.

**Confidence:** High in the injection defect; conditional in externally reachable exploitation.

**Existing tests:** `supabase/test-rls.sql:124–131` checks policy existence only. No assertion tests this helper’s execution permissions, hostile arguments, privilege changes, or RLS disabling.

**Minimal fix:** Restrict execution to a migration/admin role, revoke PUBLIC execution explicitly, and accept only allowlisted, correctly quoted identifiers.

### 2. Medium: scanner can overwrite manifest provenance and replay ingestion

**Evidence:** `supabase/functions/scanner/index.ts:76–99,106–119`, writes to `manifest` and `job`.

The scanner substitutes an S3 ETag—or the constant `"unknown"`—for `sha256`. It then performs an updating upsert on `(tenant_id,sha256)`, replacing `bundle_uri`, format and status with `"queued"`, and attempts another parse-job insertion.

**Actor and impact:** An actor who can place objects under a tenant’s scanned prefix can influence ingestion during a legitimate scheduled scan. Two objects producing the same selected value can target the same manifest and replace its source URI. Independently, rescanning an unchanged object attempts to reset its manifest to queued and enqueue parsing again.

**Preconditions and limits:**
- Database constraints must accept these values and permit the conflict update.
- Missing ETags cause deterministic `"unknown"` collisions if such responses occur.
- Distinct-content ETag collisions depend on the storage backend; no specific ETag algorithm is proven here.
- Duplicate jobs may be prevented by an unseen database constraint, but the handler unconditionally attempts insertion.
- The conflict key includes `tenant_id`; **this is not a demonstrated cross-tenant hash collision**.

**Confidence:** High in the overwrite/replay behavior attempted by the handler; conditional in database acceptance and downstream impact.

**Existing tests:** `supabase/test-rls.sql:67–102` creates asset/survey/observation fixtures. It contains no manifest, job, hash-integrity, collision or rescan assertions.

**Minimal fix:** Compute a real content hash, avoid unconditional mutation of existing manifests, and enqueue work idempotently.

### 3. Medium, latent: audit inserts do not require tenant membership

**Evidence:** `supabase/migrations/00008_enable_rls_and_policies.sql:71–77`, policies `audit_event_select` and `audit_event_insert` on `app.audit_event`.

The insert policy requires only:

```sql
user_id = auth.uid()
```

It does not require membership in the supplied `tenant_id`.

**Actor and impact:** A non-bypass user with effective `INSERT` permission could submit an event attributed to themselves under another tenant’s ID. RLS would accept that row, potentially polluting the other tenant’s audit stream. Its members can read the event through `audit_event_select`.

**Preconditions and limits:** The hardening migration explicitly revokes authenticated table privileges. Consequently, **ordinary authenticated insertion is blocked by that layer as shown**. This is a concrete policy-level gap, not a proven currently accessible endpoint; exploitation requires an effective insert grant and no additional enforcing constraint.

**Confidence:** High in the missing membership check; conditional in exploitability.

**Existing tests:** No audit-event policy assertions appear in `supabase/test-rls.sql`; the policy inspection at lines 124–129 covers only asset, survey and observation.

**Minimal fix:** Require both self-attribution and tenant membership for ordinary user inserts.

### 4. Low: scanner authentication fails open when its secret is unset

**Evidence:** `supabase/functions/scanner/index.ts:20–27`.

The authorization predicate becomes `authHeader.includes("")` when `SUPABASE_SERVICE_ROLE_KEY` is absent or empty. Any present Authorization header then passes the guard.

**Actor and impact:** A caller without the service key can cross the handler’s authentication check during this configuration failure.

**Preconditions and limits:** The same empty key is passed to `createClient` at lines 40–43. Client initialization or subsequent database access may fail. **Successful unauthenticated ingestion or service-role access is not established.** With a nonempty secret, substring matching still requires possession of the entire secret; it is not a demonstrated keyless bypass.

**Confidence:** High in the guard defect; downstream impact unproven.

**Existing tests:** `supabase/test-rls.sql` does not exercise scanner authentication or configuration failures.

**Minimal fix:** Fail closed on missing configuration and validate the exact intended authorization format.

## Minimal regression-test scenarios

1. **Privileged helper:** As the real authenticated role, verify `app.apply_member_policies` cannot execute, including through PUBLIC privileges. In an isolated database, test hostile arguments and assert unchanged policies, RLS flags and grants.
2. **Actual tenant isolation:** Use distinct A/B JWTs and unfiltered queries against every granted `public.api_*` view. Assert each sees only its tenant. Verify direct `app` access is denied under the hardened privilege model.
3. **Audit policy:** Test self-attributed inserts for an owned and foreign tenant using a narrowly privileged, non-bypass test role. Foreign-tenant insertion must fail.
4. **Scanner authentication:** Test absent/empty server secrets, absent headers, invalid credentials and malformed headers. Failure must occur before storage or database work.
5. **Ingestion integrity:** Scan twice; assert stable manifest provenance and no unintended requeue. Test missing/repeated ETags across different objects and identical hashes across two tenants.

The existing script mostly checks fixtures and catalog state using privileged SQL. It explicitly acknowledges this limitation at `supabase/test-rls.sql:113–114,175–176,222–231`; its comments are not executed isolation assertions.

MATERIAL_EVIDENCE_CONFLICT: `supabase/migrations/00015_hardening.sql:7–22` removes authenticated app-table privileges and grants public API-view reads, while `supabase/test-rls.sql:170–173,276–283` expects authenticated direct `app.asset` queries to succeed with RLS-filtered results.

openai / gpt-6.1-sol / low / low effort answer

## Prioritized findings

Independent, read-only assessment of the supplied snapshot. No tests were run.

### 1. Privileged policy-management function accepts SQL injection
**Severity: High; potentially critical if reachable by an untrusted database/API caller.**

**Evidence:** `supabase/migrations/00008_enable_rls_and_policies.sql:21–47`, function `app.apply_member_policies(text)`:
- Runs as `SECURITY DEFINER`.
- Interpolates caller-controlled `tbl_name` and derived `policy_name` through unquoted `%s` into executable SQL.
- Has no fixed `search_path` or explicit execution restriction in this migration.

For example, this argument makes `policy_name` become `asset` while injecting an additional statement into the table expression:

```text
app.asset; ALTER TABLE app.asset DISABLE ROW LEVEL SECURITY; -- .asset
```

The first generated command becomes a valid policy drop followed by disabling RLS on `app.asset`. Execution occurs with the function owner’s privileges.

`supabase/migrations/00015_hardening.sql:9,13` revokes function privileges from `authenticated`, but does not revoke them from `PUBLIC`. PostgreSQL ordinarily grants new functions `EXECUTE` to `PUBLIC`; an explicit role-level revoke does not remove inherited `PUBLIC` access.

**Actor and impact:** An untrusted caller able to execute this function could disable isolation or execute other owner-authorized SQL, enabling cross-tenant access or corruption where table access is available.

**Preconditions and certainty:** Unsafe SQL construction is proven. Exploit reachability depends on actual function ACLs, function ownership, schema exposure, and any default privileges established outside this packet. The snapshot does not prove a remotely exposed RPC route.

**Existing tests:** `test-rls.sql:124–131` checks that policies exist, not whether an untrusted role can modify or disable them. No function-ACL or injection assertions exist.

**Minimal control:** Remove runtime execution access from `PUBLIC` and untrusted roles; preferably eliminate this migration-only function. Otherwise allowlist tables, quote identifiers correctly, and fix `search_path`.

---

### 2. Scanner ingestion overwrites existing manifest state and repeatedly queues work
**Severity: Medium.**

**Evidence:** `supabase/functions/scanner/index.ts:76–78,85–119`:
- Uses an S3 ETag, or literal `"unknown"`, as `sha256`.
- Upserts on `(tenant_id,sha256)` with `ignoreDuplicates: false`.
- Writes `bundle_uri`, `detected_format`, and `status: "queued"` even on an existing manifest.
- Inserts a fresh parse job after every successful recognized-format upsert.

**Actor and impact:** A legitimate scheduled/manual scan repeated over unchanged objects resets an existing manifest to `queued` and queues additional jobs. An actor able to upload objects into a scanned tenant prefix can cause objects sharing an ETag to target the same manifest: later processing overwrites its URI and format. Objects without ETags all use `"unknown"`.

This undermines manifest identity and ingestion-state integrity. Duplicate jobs and downstream replay are plausible, although parser behavior and actual downstream consequences are outside the packet.

**Preconditions and certainty:** Requires successful access to the intended database tables and the expected conflict constraint. Overwrite and enqueue behavior is explicit. Malicious collision exploitation additionally requires suitable S3 upload capabilities; ordinary repeat scanning does not.

**Existing tests:** `test-rls.sql` contains no scanner, manifest-idempotency, digest-integrity, or job-deduplication assertions.

**Minimal control:** Compute a real content digest, preserve existing processing state on rediscovery, and enforce idempotent job creation.

---

### 3. Scanner authentication fails open when its service key is missing
**Severity: Medium for authentication failure; downstream data impact is conditional.**

**Evidence:** `supabase/functions/scanner/index.ts:20–27` checks:

```ts
authHeader?.includes(Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") || "")
```

When the environment value is missing or empty, every supplied Authorization string includes `""`. An arbitrary header therefore passes the handler’s authorization gate.

**Actor and impact:** A caller reaching the handler with any Authorization header can proceed into request parsing and client initialization despite not possessing a scanner credential.

**Preconditions and certainty:** Requires missing/empty service-key configuration and any upstream gateway admitting the request. The local authentication bypass is proven. Successful S3 listing or database mutation is **not** proven: `createClient` receives the same empty key at lines 40–43 and may reject initialization or fail subsequent operations.

With a configured nonempty key, substring matching is unnecessarily permissive, but it does **not** independently allow a caller who lacks that key to authenticate.

**Existing tests:** No scanner authentication assertions exist.

**Minimal control:** Fail closed on absent configuration and require an exact expected authorization value.

---

### 4. The RLS script does not actually establish tenant isolation
**Severity: Medium assurance gap.**

**Evidence:** `supabase/test-rls.sql`:
- Lines 59–61 call `app.is_member` without establishing User A’s database/JWT identity.
- Lines 140–153 manually filter by tenant, which can conceal missing isolation.
- Lines 175–185 verify membership records rather than querying as User B.
- Lines 222–231 query as service role and merely describe expected user behavior.
- Lines 237–241 query views without testing an outsider or establishing caller identity.
- No assertions fail automatically on unexpected access.

Moreover, `00015_hardening.sql:7–22` removes authenticated base-table access and grants access to **public API views**, whereas the script proposes direct `app.asset` access and tests different `app` views.

**Impact:** A deployment could satisfy the scripted metadata/data checks while unauthorized tenant access remains possible through its real API surface. Conversely, correct hardening could make the proposed direct-table user tests fail with permission errors rather than return filtered rows.

**Certainty:** Missing executable role-specific assertions are proven; an actual view leak is not.

**Minimal control:** Test the final granted API surface under explicit authenticated identities, with positive and negative tenant assertions and automated failures.

## Additional boundary observations

- **Tenant identity:** Scanner `tenant_id` comes directly from the request body (`index.ts:30,89,111`). There is no per-caller tenant binding. However, a correctly authenticated service-role holder is already globally privileged; arbitrary tenant selection alone is not a demonstrated privilege escalation.
- **S3 scope:** The scanner constructs `${tenant_id}/${prefix}` (`index.ts:56`). S3 prefixes are literal strings, not filesystem paths; `../` is not evidence of cross-tenant traversal.
- **RLS/service role:** Migration 00008 enables RLS and applies membership checks to tenant-scoped tables. The scanner uses the service key (`index.ts:40–43`), so these checks should not be treated as a scanner isolation control.
- **Tenant derivation remains unverified:** The implementation of `app.is_member` is outside the packet. Its identity source and resistance to identity spoofing cannot be assessed.
- **Conditional audit-write gap:** `audit_event_insert` (`00008:75–77`) checks only `user_id = auth.uid()`, not membership in the supplied `tenant_id`. If an untrusted caller has INSERT privileges, it can attribute its own event to another tenant, potentially polluting that tenant’s audit stream because `audit_event_select` allows tenant members to read it (`71–73`). Migration 00015 removes direct authenticated table privileges, so this is not a proven reachable authenticated-write vulnerability in the final snapshot.
- **Unproven cross-tenant relationships:** Membership checks cover each row’s `tenant_id`; they do not themselves validate referenced parent tenants. Without table constraints, no concrete cross-tenant foreign-key exploit can be established.
- **Views:** The assertion that views “inherit RLS” (`test-rls.sql:237`) is not sufficient evidence. View ownership, definitions, and security options are outside this packet.

## Minimal regression scenarios, in priority order

1. As an ordinary authenticated database role, attempt `app.apply_member_policies` with both a legitimate table and the injection argument; require denial and unchanged RLS/policies.
2. As two authenticated users belonging to different tenants, query every granted public API view **without tenant filters**; require only each user’s own rows. Verify direct base-table access is denied after hardening.
3. Invoke the scanner with missing configuration, no header, arbitrary header, and an incorrect key; require rejection before S3/database activity.
4. Scan an unchanged object twice; require preserved manifest state and no duplicate parse job.
5. Scan distinct objects sharing an ETag, and objects lacking ETags; require no unintended manifest replacement.
6. If audit insertion is intentionally exposed, attempt an own-user event targeting another tenant; require rejection.

Primary judge's stated reason

A receives a slight forced preference because its constraint caveat helps a maintainer distinguish a demonstrated handler behavior from a duplicate-job outcome requiring verification. The answers are near-equivalent; this is not an established material quality difference, and an independent review could reasonably prefer B's assurance-gap presentation.

This reason is the judge's assessment. No independent factual-defect finding is asserted by this record.

Battle wave: 49363fb6-15bc-4be1-8f3d-fbf58b9098d4. Pair: brp1_90054f1eb5f49e803ea84b02332e09b2f7ad9693bb17b24687022769e3e60d6c. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.