/**
 * Webhook delivery SSRF: redirect hops and the DNS layer.
 *
 * Two independent bypasses of the guard that webhook delivery relies on:
 *
 * 1. `fetch()` defaults to `redirect: "follow"`. assertPublicUrl only ever saw
 *    the URL the user registered, so a genuinely public endpoint could answer
 *    302 → http://169.254.169.254/latest/meta-data/ and fetch would follow it.
 *    One redirect defeated the entire guard.
 *
 * 2. resolvesToPrivate() — the DNS layer that catches a public-looking
 *    hostname pointing at a private address — existed, was fully unit-tested,
 *    and had ZERO production callers. Only src/__tests__/ssrf-guard.test.ts
 *    imported it. `evil.example.com A 127.0.0.1` passed the literal check.
 *
 * These assertions are structural. A functional test would need to bind a
 * redirecting server on localhost, but the guard deliberately default-allows
 * private addresses under the test env, so the harness would have to disable
 * the very behaviour under test. The guard's own address-classification logic
 * is already covered functionally by ssrf-guard.test.ts.
 */

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

const SRC = readFileSync("src/lib/webhook-delivery.ts", "utf8");
const fn = SRC.slice(
  SRC.indexOf("async function deliverFollowingRedirects"),
  SRC.indexOf("// ---", SRC.indexOf("async function deliverFollowingRedirects"))
);

describe("redirects cannot escape the guard", () => {
  it("never lets fetch follow redirects itself", () => {
    expect(fn).toContain('redirect: "manual"');
  });

  it("no bare fetch(row.url) with default redirect handling remains", () => {
    // The original call site. If this reappears the guard is bypassable again.
    expect(SRC).not.toMatch(/await fetch\(row\.url, \{\s*\n\s*method: "POST"/);
  });

  it("re-validates the URL on every hop, not just the first", () => {
    // assertPublicUrl must be inside the loop.
    const loopStart = fn.indexOf("for (let hop");
    const guardCall = fn.indexOf("assertPublicUrl(url)");
    expect(loopStart).toBeGreaterThan(-1);
    expect(guardCall).toBeGreaterThan(loopStart);
  });

  it("bounds the hop count so a redirect cycle cannot spin", () => {
    expect(SRC).toContain("MAX_REDIRECTS");
    expect(fn).toContain("hop <= MAX_REDIRECTS");
    expect(fn).toContain("more than ${MAX_REDIRECTS} redirects");
  });

  it("resolves a relative Location against the current hop", () => {
    // `Location: /latest/meta-data/` on a redirect must not be treated as
    // an absolute URL or silently dropped.
    expect(fn).toContain("new URL(location, url)");
  });

  it("treats a 3xx with no Location as a terminal response", () => {
    expect(fn).toContain("if (!location) return { status: res.status }");
  });
});

describe("the DNS layer is actually wired in", () => {
  it("webhook delivery calls resolvesToPrivate", () => {
    // It had zero production callers before this.
    expect(SRC).toContain("resolvesToPrivate");
    expect(fn).toContain("await resolvesToPrivate(guard.url.hostname)");
  });

  it("checks DNS before issuing the request", () => {
    const dns = fn.indexOf("resolvesToPrivate");
    const req = fn.indexOf("await fetch(url");
    expect(dns).toBeLessThan(req);
  });

  it("honours the same allow-private escape hatch as assertPublicUrl", () => {
    // Without this the DNS layer blocks 127.0.0.1 under SSRF_ALLOW_PRIVATE=1
    // and in the test env, breaking suites that point webhooks at a local
    // Bun.serve() — which is exactly what it did on the first attempt.
    expect(fn).toContain("ssrfPrivateAllowed()");
    expect(fn).toContain("enforcing &&");
  });
});

describe("blocked deliveries are reported as blocked", () => {
  it("surfaces an SSRF block distinctly from an HTTP error", () => {
    expect(SRC).toContain("blockedReason");
    expect(SRC).toContain("(SSRF protection)");
  });
});
