// Background/no-GUC sweep finding (2026-06-25) — SSO pre-auth config resolution false-green.
//
// The SSO /login//callback flow is PRE-AUTHENTICATION: no session, no tenant. tenantMiddleware
// defaults a sessionless request to the 'default' tenant, so a scoped read of sso_configs (an
// RLS-enrolled TENANT_TABLE) returns only 'default' rows and CANNOT see a real tenant's config —
// the lookup silently fails "config not found" when the config exists (the Finding #2 false-green
// class; here fail-closed = SSO silently broken for real tenants, not a bypass).
//
// The fix: storage.getSsoConfigByIdUnscoped resolves the config cross-tenant via withBypassRls (the
// mandated pre-tenant-lookup pattern, same as API-key validation). This proves both halves: a
// 'default'-scoped read does NOT find the config (the bug), the unscoped lookup DOES (the fix).
//
// The suite DB doesn't run initRlsPolicies, so this test provisions RLS + the bypass role for
// sso_configs only (robust teardown), to exercise the live RLS path. Requires DATABASE_URL + env.

import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { sql } from "drizzle-orm";
import { auditDb, withTenantRls } from "../server/db.js";
import { storage } from "../server/storage.js";

const RUN = `sso-preauth-${Date.now()}`;
const CONFIG_ID = `${RUN}-cfg`;
const REAL_TENANT = `${RUN}-tenantX`;

describe("SSO pre-auth config resolution (false-green fix)", () => {
  before(async () => {
    await auditDb.execute(sql`CREATE OR REPLACE FUNCTION public.current_tenant_id() RETURNS text LANGUAGE sql STABLE AS $func$ SELECT NULLIF(current_setting('app.current_tenant_id', true), '') $func$`);
    // Provision the bypass role + RLS on sso_configs (scoped to this one table; the suite DB does
    // not run initRlsPolicies). aegis_app must be a member of aegis_rls_bypass to SET LOCAL ROLE.
    await auditDb.execute(sql`ALTER ROLE aegis_rls_bypass BYPASSRLS`);
    await auditDb.execute(sql`GRANT aegis_rls_bypass TO aegis_app`);
    await auditDb.execute(sql`GRANT ALL ON sso_configs TO aegis_app`);
    await auditDb.execute(sql`GRANT ALL ON sso_configs TO aegis_rls_bypass`);
    await auditDb.execute(sql`ALTER TABLE sso_configs ENABLE ROW LEVEL SECURITY`);
    await auditDb.execute(sql`DROP POLICY IF EXISTS tenant_isolation ON sso_configs`);
    await auditDb.execute(sql`CREATE POLICY tenant_isolation ON sso_configs USING (tenant_id = current_tenant_id()) WITH CHECK (tenant_id = current_tenant_id())`);
    // Seed an SSO config under a REAL tenant (NOT 'default').
    await auditDb.execute(sql`INSERT INTO sso_configs (id, tenant_id, provider, is_active) VALUES (${CONFIG_ID}, ${REAL_TENANT}, 'azure_ad', true)`);
  });
  after(async () => {
    try { await auditDb.execute(sql`DELETE FROM sso_configs WHERE id = ${CONFIG_ID}`); } catch { /* throwaway DB */ }
    try { await auditDb.execute(sql`DROP POLICY IF EXISTS tenant_isolation ON sso_configs`); } catch { /* noop */ }
    try { await auditDb.execute(sql`ALTER TABLE sso_configs DISABLE ROW LEVEL SECURITY`); } catch { /* noop */ }
  });

  test("BUG: a pre-auth scoped read (as the 'default' tenant) CANNOT see a real tenant's config", async () => {
    const rows = await withTenantRls("default", (tdb: any) =>
      tdb.execute(sql`SELECT id FROM sso_configs WHERE id = ${CONFIG_ID}`).then((r: any) => (r.rows ?? r)));
    assert.equal(rows.length, 0, "a 'default'-scoped read must NOT find the real tenant's config — this is the false-green the fix addresses");
  });

  test("FIX: getSsoConfigByIdUnscoped resolves the config cross-tenant (pre-auth bypass)", async () => {
    const found = await storage.getSsoConfigByIdUnscoped(CONFIG_ID);
    assert.ok(found, "the unscoped pre-auth lookup MUST resolve the real tenant's config");
    assert.equal(found!.id, CONFIG_ID);
    assert.equal(found!.tenantId, REAL_TENANT);
  });
});
