/**
 * SAML assertion verification.
 *
 * Two defects, both allowing account takeover:
 *
 *  1. Fail-open. Signature verification ran only `if (idpCertPem && trim())`,
 *     so an org whose SAML config had a blank idp_certificate accepted ANY
 *     forged SAMLResponse. The assertion's email selects the account to log
 *     in as, so that is unauthenticated takeover of any account in the org.
 *
 *  2. Signature wrapping. verifySamlSignature checks only that SignedInfo
 *     carries a valid RSA signature; the Reference DigestValue is never
 *     recomputed. A genuinely-signed assertion could be edited — or a second
 *     forged Assertion added beside the signed one — and still verify.
 *
 * Full XML-DSig needs exclusive c14n and a vetted library. These lock in the
 * fail-closed behaviour and the structural anti-wrapping checks that stand in
 * until then.
 */

import { describe, expect, it } from "bun:test";
import { readFileSync } from "fs";

const SRC = readFileSync("src/routes/saml-sso.tsx", "utf8");

describe("verification is mandatory (fail-closed)", () => {
  it("refuses when no IdP certificate is configured", () => {
    expect(SRC).toContain("if (!idpCertPem || !idpCertPem.trim())");
    expect(SRC).toContain("Refusing to accept an unverified assertion");
  });

  it("no longer makes verification conditional on the cert being present", () => {
    // The original bug shape.
    expect(SRC).not.toMatch(/if \(idpCertPem && idpCertPem\.trim\(\)\) \{\s*\n\s*const sigValid/);
  });
});

describe("anti-wrapping structural checks", () => {
  it("runs before signature verification", () => {
    const coverage = SRC.indexOf("assertSignatureCoversAssertion(xml)");
    const verify = SRC.indexOf("if (!verifySamlSignature(xml, idpCertPem))");
    expect(coverage).toBeGreaterThan(-1);
    expect(verify).toBeGreaterThan(-1);
    // A rewritten-but-validly-signed document must not reach attribute
    // extraction just because SignedInfo checks out.
    expect(coverage).toBeLessThan(verify);
  });

  it("rejects multiple Assertions", () => {
    expect(SRC).toContain("assertionIds.length > 1");
    expect(SRC).toContain("signature-wrapping attempt");
  });

  it("rejects a Reference that covers neither the Response nor the Assertion", () => {
    expect(SRC).toContain("referenced !== assertionIds[0] && referenced !== responseId");
  });

  it("rejects a response with no Assertion at all", () => {
    expect(SRC).toContain("assertionIds.length === 0");
  });
});

describe("signature algorithm selection", () => {
  it("reads Algorithm from SignatureMethod, not the first match in the doc", () => {
    // The old regex /Algorithm="([^"]+)"/ matched CanonicalizationMethod,
    // which appears first in a normal response — so the real algorithm was
    // never read and it silently fell back to SHA1.
    expect(SRC).toContain("SignatureMethod[^>]*\\bAlgorithm=");
    expect(SRC).not.toMatch(/const algMatch = xml\.match\(\/Algorithm=/);
  });

  it("refuses an unrecognised algorithm instead of defaulting to SHA1", () => {
    expect(SRC).toContain("unrecognised SignatureMethod");
  });
});

describe("the incompleteness is documented, not hidden", () => {
  it("verifySamlSignature is marked as not proving assertion integrity", () => {
    // Whoever reads this next must not mistake it for full XML-DSig.
    expect(SRC).toContain("INCOMPLETE BY DESIGN");
  });
});
