← Model losses

Head-to-head comparison

openai / gpt-6-luna / low / low effort preferred over deepseek / deepseek-flash / none / unknown 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-luna / low / low effort answer

## Prioritized findings

1. **Scanner authorization accepts a substring rather than validating a credential. Severity: High, conditional on the service-role key being nonempty and the handler being reachable.**  
   In `supabase/functions/scanner/index.ts`, lines 20–27, authorization uses `authHeader.includes(SUPABASE_SERVICE_ROLE_KEY)`. Thus, a request whose `Authorization` header contains the key as any substring passes this check; it need not equal a bearer credential. A caller who learns the key, or can induce a request carrying it in a larger header value, can submit a chosen `tenant_id` and `prefix` (lines 29–36, 56) and trigger scanner writes. The latter exploit path depends on deployment and request-proxy behavior not shown here. The key is also used to create a service-role Supabase client (lines 39–43), so subsequent writes run with that client’s privileges. The RLS tests do not test scanner authentication or malformed authorization headers.

2. **Scanner trusts caller-supplied tenant and prefix for privileged cross-tenant ingestion. Severity: High, if an attacker can invoke the function with an accepted authorization header.**  
   The handler takes `tenant_id` and `prefix` directly from JSON (lines 29–36), constructs the S3 prefix as `${tenant_id}/${prefix}` (line 56), then upserts `manifest` and inserts `job` rows using that same tenant ID (lines 85–119). It does not verify that the tenant exists, that the caller is authorized for it, or that the S3 object’s tenant matches it. With a valid/accepted scanner credential, a caller can request another tenant’s S3 prefix and create or update its manifest/job records. Actual cross-tenant impact depends on S3 bucket contents, database constraints, and service-role privileges, which are not established in this packet. `test-rls.sql` describes user-level isolation assertions (lines 156–185, 218–231), but does not exercise scanner writes or service-role behavior.

3. **Tenant membership helper and RLS execution details are not evidenced; isolation claims in the test are largely expectations, not demonstrated assertions.**  
   `00008_enable_rls_and_policies.sql` enables RLS on `app` base tables (lines 5–18) and creates standard policies using `app.is_member(tenant_id)` (lines 20–47, applied to listed tables at lines 51–66). The definition, tenant-identity derivation, and privileges of `app.is_member` are absent, so it is not possible to establish whether it correctly derives identity from `auth.uid()`, whether it is `SECURITY DEFINER`, or whether it can be abused. The helper that creates policies is itself `SECURITY DEFINER` (lines 21–25), but its body only drops/creates policies using the supplied table name (lines 29–46); whether its execution privileges or input are exploitable is not established by the packet. `00015_hardening.sql` revokes authenticated access to `app` tables, sequences, and functions (lines 3–13), then grants authenticated users select on named public views (lines 15–22). It does not establish service-role restrictions.  
   In `test-rls.sql`, the membership check at lines 59–61 is described as expected behavior, while lines 108–115 and 170–185 explicitly say users must be tested through the app and that SQL Editor/service-role use cannot impersonate them. Cross-tenant results at lines 218–231 are stated as expected, not executed user assertions. No test is claimed to have run.

## Regression scenarios

1. Send scanner requests with the key absent, exact, embedded in a larger authorization value, and empty/unset in the environment; require only the intended credential form to pass.
2. Invoke scanner for tenant B while authenticated only for tenant A; assert no S3 scan and no tenant-B manifest/job changes.
3. As authenticated users in separate tenants, assert SELECT and insert/update/delete isolation on each listed tenant-scoped table, including attempts to supply another tenant’s ID.
4. Inspect and test `app.is_member` under real user JWTs, including whether its identity is `auth.uid()` and whether its privileges or definer context permit membership bypass.
5. Verify access through the granted `public.api_*` views under distinct user JWTs; do not treat service-role SQL results as user-isolation evidence.

The packet does not include the `app.is_member` definition, table constraints, or deployment configuration; conclusions depending on those are conditional.

deepseek / deepseek-flash / none / unknown effort answer

I'll analyze the supplied evidence directly. Note one important dependency gap up front: `app.is_member()` — the linchpin of every RLS policy here — is not defined in this packet, so its internals are an assumption, not proven.

# Tenant Isolation & Scanner Ingestion Security Review — 4-File Snapshot

## Findings (prioritized)

### F1 — HIGH (proven): Scanner service-role key check is a substring test on a caller-supplied header

- **Location:** `supabase/functions/scanner/index.ts:21-27`
- **Code:** `if (!authHeader?.includes(Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") || ""))`
- **Actor / request:** Anyone who can reach the function URL. Two failure modes are proven from source:
  1. **Empty-secret bypass:** if `SUPABASE_SERVICE_ROLE_KEY` is unset (or empty), `Deno.env.get(...) || ""` yields `""`, and *any* string `.includes("")` is `true`. The guard passes with no credential at all. (`|| ""` is itself the tell that unset-env is a considered state.)
  2. **Substring / position-agnostic match:** the check never parses a scheme or compares tokens. `Authorization: X<service_role_key>Y`, `Authorization: Bearer <key>`, or any header merely *containing* the secret substring is accepted. On the Slack/Atlassian signing-secret bug class, this is the canonical "contains" anti-pattern.
- **Impact:** Full service-role access to the ingestion path: attacker supplies any `tenant_id` and causes manifest/job writes in arbitrary tenants (see F2). The scanner also builds an S3 client from ambient `AWS_*` credentials and lists the whole bucket space named by the caller's `tenant_id` (line 56), so a pass-through grants cross-tenant S3 enumeration.
- **Preconditions:** Unset service-role env (case 1: no precondition on secrets) or knowledge/guess of the substring (case 2). Reachability of the function URL.
- **Proven vs assumed:** The `.includes()` semantics and the `|| ""` fallback are *proven from source*. Whether the env is actually unset in production is *assumed/unverified*; whether Deno's env access can yield undefined here is *proven by the `|| ""` author assumption* but not by runtime evidence.

### F2 — HIGH (proven): Scanner trusts caller-supplied `tenant_id`; no derivation from authenticated identity; no cross-tenant write control

- **Location:** `index.ts:30` (`const { tenant_id, prefix = "" } = await req.json()`), used at `:56` (S3 prefix), `:89` (manifest upsert), `:111` (job insert).
- **Actor / request:** A caller who satisfies (or bypasses, per F1) the header gate posts `{"tenant_id":"<victim-tenant>","prefix":"..."}`.
- **Impact:** (a) **S3 enumeration** of any tenant prefix — `scanPrefix = tenant_id + "/" + prefix` with no allowlist or membership check. (b) **Cross-tenant row injection:** the service-role client (`:40-43`) bypasses RLS, so `manifest` and `job` rows are written with the attacker-chosen `tenant_id`. Because the upsert conflict target is `(tenant_id, sha256)` and `ignoreDuplicates:false` (`:94-97`), an attacker who reuses a victim's plausible hash can **overwrite** `bundle_uri`/`detected_format` on an existing victim manifest row — an integrity, not just confidentiality, impact. There is no integrity check that `tenant_id` belongs to the caller.
- **Preconditions:** Satisfying F1's gate (or an environment where the key is unset). No tenant membership needed — the service role is the whole authorization model, and it is tenant-agnostic.
- **Proven vs assumed:** Flow and conflict-key overwrite behavior are *proven from source*. That manifest/job are actually RLS-protected and would block this via a normal client is *proven from 00008*; that the *service-role client* bypasses RLS is standard Postgres/Supabase behavior but *assumed — not demonstrated in these four files*.

### F3 — MEDIUM-HIGH (proven partial): Tenant identity derivation for normal users is opaque; `00015` makes `app` non-executable except via views, but grants usage and view SELECT

- **Location:** `00015_hardening.sql:4-22`; policy bodies in `00008:38,44,73,84,91`.
- **Analysis:** `00015` does `revoke all on schema app from authenticated; grant usage on schema app;` then `revoke all on all tables/sequences/functions in schema app from authenticated`, and grants SELECT only on five `public.api_*` views. This is *defense-in-depth that is directionally correct*: an authenticated REST user cannot select `app.asset` directly; only the curated views remain. **However**, the correctness of the remaining path depends entirely on the views' own `security_invoker`/`security_definer` semantics and their `WHERE` clauses, which are **not in this snapshot** (uncertainty). The `app.is_member()` function body is likewise absent.
- **Impact:** If any `public.api_*` view is `security definer` (or owned by a superuser/definer role) and does not itself filter by `auth.uid()`/`is_member`, it becomes a **cross-tenant read oracle** for every authenticated user — exactly the failure mode `00015`'s header comment claims to prevent. This cannot be confirmed or refuted from the packet.
- **Severity/preconditions:** MEDIUM-HIGH *if* view semantics are wrong; currently **unproven**. Precondition: an authenticated account (trivially obtainable via signup, if enabled — also not in packet).
- **Proven vs assumed:** The revoke/grant statements are *proven*; the view and `is_member` internals are *assumed absent*.

### F4 — MEDIUM (proven): `SECURITY DEFINER` policy factory has no hardened `search_path` and no `public` EXECUTE revoke; dynamic SQL is string-formatted

- **Location:** `00008:21-47` (`app.apply_member_policies`, `security definer`), invoked at `00008:52-66`.
- **Analysis:** The function is `SECURITY DEFINER` with **no `SET search_path`** (the standard CVE-2018-1058 hardening is missing here; note that later migration `00015` does revoke EXECUTE from `authenticated`, but only *after* the fact and only for `authenticated`, not `public`). It builds policies via `execute format(...)` from a `text` argument. In this snapshot the argument is always a literal (`'app.asset'`, etc.), so **no injection is demonstrated**; the risk is an *assumed* future caller passing attacker-influenced `tbl_name`. The `policy_name := regexp_replace(tbl_name, '^.*\.', '')` line (`:30`) also means a name with embedded dots/percent signs would produce surprising policy names.
- **Impact if realized:** a definer-context function called by a non-owner could be used to run the DDL `execute` against arbitrary identifiers, or be hijacked via a schema-shadowed `format`/`regexp_replace` when `search_path` includes an attacker schema. Both require a caller with EXECUTE plus either (a) an unvalidated argument path or (b) a writable schema earlier in `search_path`.
- **Severity/preconditions:** MEDIUM as latent; LOW-as-demonstrated (no evidence of an untrusted call path in this packet). Precondition: EXECUTE grant to a lower role and an argument-controllable caller *or* unsafe `search_path`.
- **Proven vs assumed:** definer + missing `search_path` + string-formatted DDL are *proven*; exploitability is *assumed* and depends on grants not shown (`00015` implies `authenticated` lost EXECUTE on `app` functions, which **mitigates** this for that role).

### F5 — MEDIUM (proven): The RLS test script cannot fail — it is a manual self-check, not an executable test

- **Location:** `test-rls.sql` throughout; key lines `55-61`, `134-153`, `155-185`, `218-231`, `270`, `285`.
- **Analysis:** Every isolation assertion is a "Expected: …" comment executed in the SQL Editor, which the script itself acknowledges uses the **service role** (`:113`, `:175`). Concretely:
  - TEST 4 (`:141-153`) counts `app.asset` as service role, which **bypasses RLS** — a *pass* here proves nothing about User A's real access.
  - TEST 5 (`:179-183`) evaluates `exists(select 1 from app.tenant_member where user_id='<USER_B_ID>')` — this is a **membership lookup, not an RLS test**. It returns `false` *because the row is absent*, independently of whether RLS works. It would return `false` even if every `app` table had RLS disabled.
  - TEST 6 (`:218-231`) explicitly states "with RLS, User A would only see…" but performs no query as either user; the cross-tenant isolation claim is asserted, never exercised.
  - TEST 7 (`:238-239`) claims "Views should inherit RLS from base tables" and runs the counts as — again — the service role, so the result cannot distinguish inherited-RLS from definer bypass. (This connects directly to F3: the one place that *could* have validated the view boundary is neutered by running as the wrong role.)
  - There is no `BEGIN … ROLLBACK`, no `SET ROLE authenticated`, no `SET request.jwt.claims`, and no assertion/`RAISE` mechanism. `:285` ("STOP and fix RLS") is prose.
- **Impact:** The repository's only stated tenant-isolation verification provides **zero regression protection**. A future change that drops a policy or rewrites `apply_member_policies` would leave every "test" still reporting success.
- **Severity/preconditions:** MEDIUM (assurance/process), HIGH in consequence when combined with F1–F3, because the missing test is what would have caught them.
- **Proven vs assumed:** The script's content and the service-role admissions are *proven*; the author's intent (manual checklist) is stated in `:1-3, 257-270`.
- **Comparison with existing assertions:** F1's bypass, F2's cross-tenant write, F4's `SECURITY DEFINER` function, and F3's view path are each **untested** by `test-rls.sql`. The script's nearest claim — `:131` "Should see `r_<table>_select` and `r_<table>_mod` policies" — only confirms *existence* of policies for `asset`/`survey`/`observation`, not behavior for any of the other 12 tables listed in `00008:52-66` (`manifest`, `job`, `unit_cost`, `los_target`, `amp_*`, `kpi_card_defs`, `saved_views_meta`, `semantic_registry`, `doc_index`). Notably, the tables the scanner actually writes — `manifest` and `job` — are **never covered** by any behavioral assertion.

### F6 — LOW-MEDIUM (proven): Non-cryptographic content hash used as the dedup/integrity key

- **Location:** `index.ts:76-78,95`.
- **Analysis:** `sha256 = obj.ETag?.replace(/"/g,"") || "unknown"` with an explicit in-code admission "not cryptographically secure" and a `TODO`. For multipart/SSE-KMS objects, S3 ETag is not the content MD5; and the `"unknown"` fallback means **any number of distinct objects with no ETag collapse to the same `(tenant_id,"unknown")` conflict key**, so each new object *overwrites* the prior one via the `ignoreDuplicates:false` upsert (`:96`). This makes the manifest table's integrity claim false and creates a low-cost overwrite/`unknown`-collision path that reinforces F2.
- **Preconditions:** Objects lacking an ETag (edge/assumption) or multipart/SSE objects sharing the `(tenant_id, sha256)` key.
- **Proven vs assumed:** the code and TODO admission are *proven*; that real S3 responses omit ETag is *assumed*.

### F7 — LOW (proven): Scanner ignores `tenant_member`/existence and returns full S3 inventory to caller

- **Location:** `index.ts:126,129-137`.
- **Analysis:** The response echoes every scanned URI and computed hash. Combined with F1/F2 this is an enumeration exfil primitive. Even in the intended "cron" use (`:3`), returning full object listings in the HTTP body broadens disclosure beyond what a scheduled job needs.
- **Severity/preconditions:** LOW standalone; MEDIUM combined with F1.

## Discarded hypotheses / likely false positives

- **SQL injection in `apply_member_policies`:** *Not established.* All `format()` arguments in this snapshot are hard-coded literals (`00008:52-66`). No attacker-controlled path is shown. Reported only as a latent hardening gap (F4), not a live injection.
- **`00015` grants `authenticated` broad access:** *Refuted by the file itself.* It revokes and then grants SELECT on five specific `public.api_*` views only. Any claim that `authenticated` can still read `app.*` directly is unsupported by this snapshot. The residual risk is view internals (F3), not the grants.
- **`audit_event` policy leak (`00008:71-73`):** the SELECT predicate is `user_id = auth.uid() OR app.is_member(tenant_id)`, so a *member* can read **all** tenant members' audit rows, not just their own (contradicting the header comment "users can only read their own events," `:68`). This is intra-tenant, not cross-tenant, and may be intended for tenant admins; severity LOW-MEDIUM, noted as an intent/clause mismatch rather than a cross-tenant break.

## Missing evidence / dependencies (with consequence)

1. **`app.is_member()` body** — not in packet. Every RLS policy reduces to it. If it returns `true` for unauthenticated callers (e.g., a missing `auth.uid()` null-check, or a fallback), every policy collapses. **All tenant-isolation conclusions above are conditional on this function being correct and non-null-returning.**
2. **`app.tenant_member` INSERT/UPDATE/DELETE policies** — `00008:87-91` creates **SELECT only**; the table otherwise has RLS enabled with no write policy. Yet `test-rls.sql:30-37,200-206` inserts memberships directly. Whether that is intended (service-role-only provisioning) or an accidental lockout (self-service admin flows broken) cannot be determined here. This is a *potential missing control or a potential functional bug* — unresolved.
3. **`public.api_*` view definitions and ownership / `security_invoker`** — required to adjudicate F3.
4. **Grants on `app.apply_member_policies` before vs. after `00015`** — the `00015:9` revoke covers `all functions in schema app`, but a function created *later* by a `SECURITY DEFINER` owner might reintroduce EXECUTE; default-privilege interaction is assumed, not shown.
5. **`00015` has no `alter function … set search_path` statement**, so F4's hardening gap persists for any definer function in `app` — but I cannot confirm no such ALTER exists in other, unsupplied migrations.
6. **REST/PostgREST exposure of `app` schema** — `00015:5` grants `usage on schema app`, which is a precondition for `app`-schema RPC/table exposure to `authenticated`. Whether PostgREST's exposed-schemas setting includes `app` is outside the packet and materially changes F3's severity.

## Prioritized recommendations (no code edits made)

1. Fix F1/F2 at the root: verify the caller via a real secret comparison (constant-time, exact-match on a parsed bearer token or a **vault-stored shared secret / service-role + caller JWT decode**), and derive/authorize `tenant_id` server-side against `tenant_member` for the authenticated subject before any S3 or DB action. Remove the `|| ""` fallback and fail closed if the env var is absent.
2. Restrict the scanner's DB writes to a least-privileged role scoped per tenant rather than the global service role, or add an explicit server-side tenant authorization check. This removes the RLS-bypass consequence of F2 even if the gate is bypassed.
3. Harden `apply_member_policies` with `SET search_path = pg_catalog, app` and `REVOKE EXECUTE … FROM public` at definition time (F4).
4. Replace the ETag placeholder with real SHA-256 of object bytes, and reject/repair the `"unknown"` fallback so it cannot become a shared conflict key (F6).
5. Rewrite `test-rls.sql` as executable assertions (F5) — see regression scenarios below.

## Minimal regression-test scenarios

Each should be executable, self-rolling-back, and role-aware. (These are proposed tests; none were run.)

- **R1 (F1 gate):** Invoke the scanner with (a) no `Authorization` header, (b) `Authorization: Bearer <random>`, (c) `Authorization: <key>prefix`, (d) `Authorization: prefix<key>suffix`. All must return 401. Set the service-role env var to empty in one case and require 401, not 200.
- **R2 (F2 cross-tenant write):** As a valid non-member JWT (or post-gate caller), POST `{tenant_id: "<victim>"}`. Assert: 403; and `select count(*) from app.manifest where tenant_id='<victim>'` unchanged.
- **R3 (F2 upsert overwrite):** Existing victim manifest `(tenant,sha256)=('T','h1')`. Attacker invocation referencing hash `h1`. Assert `bundle_uri` unchanged after the call.
- **R4 (RLS positive/negative, real roles):** Inside a transaction: `set local role authenticated; set local request.jwt.claims = '{"sub":"<A>"}'`; assert `count(*) from app.asset` returns only Tenant A rows; repeat as `<B>` and assert 0 rows for Tenant A. `rollback`.
- **R5 (view boundary, F3):** Same impersonation, then `select count(*) from public.api_asset_geojson` as User B; assert the view does **not** expose Tenant A rows. This is the assertion `test-rls.sql:238-239` purports to make but cannot.
- **R6 (audit_event, F5 note):** As member User A, assert whether members can read other users' audit rows; assert as non-member User B that `count(*) = 0`.
- **R7 (policy coverage):** Assert `rowsecurity = true` **and** at least one INSERT/UPDATE/DELETE policy exists on every table in `00008:52-66`, including `manifest` and `job` — the scanner's own write targets, which `test-rls.sql` never asserts.
- **R8 (is_member null-safety):** Assert `app.is_member('<some-tenant>')` is `false` (not null/true) under an authenticated context with no membership, and under no `auth.uid()`.

**Bottom line:** The two highest-confidence, source-proven issues are the scanner's substring/no-op authentication (F1) and its caller-controlled `tenant_id` with service-role RLS bypass enabling cross-tenant writes to `manifest`/`job` (F2). Both are exactly the paths `test-rls.sql` fails to exercise (F5). The RLS policy layer in `00008`/`00015` is directionally sound but its correctness is unverifiable from this packet because `app.is_member()` and the `public.api_*` view definitions are not included (F3, uncertainty #1/#3).

Primary judge's stated reason

B receives a slight forced preference for reducing the risk that remediation priorities are based on an authorization-guard bypass being mistaken for demonstrated end-to-end privileged access. A's stronger coverage counterbalances that advantage. This is not an established material quality difference; an independent review could reasonably prefer A's additional supported controls analysis.

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

Battle wave: 10549f36-d72c-445b-a691-1df97fa35ca0. Pair: brp1_52f1bf59e91c51ab25ed252f33f676577e45835dfaa6e241dc0b1b3a54aa4690. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.