iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / core / lib / src / cli / cloudflare-access.test.tsmain at aacbc74

import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, test, vi } from "vitest";
import {
  BILLING_SCOPE,
  briefAccess,
  CARD_SCOPE,
  DEPLOY_SCOPES,
  keptTokenServes,
  describeNetworkError,
  dropKeptAccess,
  KeptSignIn,
  keptSignInStep,
  lockHeld,
  lockKept,
  madeByTheDeploy,
  parsed,
  renewedSignIn,
  resilientFetch,
} from "./cloudflare-access.ts";

const now = Date.parse("2026-11-19T10:00:00Z");
const kept: KeptSignIn = {
  kind: "iterate-cloudflare-sign-in",
  accessToken: "access-1",
  refreshToken: "refresh-1",
  expiresAt: now + 30 * 60_000,
  scopes: DEPLOY_SCOPES.join(" "),
  lacks: [],
  signedInAt: "2026-11-19T09:30:00.000Z",
};

test("a kept sign-in is read from its JSON, with or without spaces around it, and nothing else is one", () => {
  expect(parsed(KeptSignIn, ` ${JSON.stringify(kept)}\n`)).toEqual(kept);
  expect(parsed(KeptSignIn, JSON.stringify({ ...kept, kind: "other" }))).toBeUndefined();
  expect(parsed(KeptSignIn, JSON.stringify({ ...kept, refreshToken: undefined }))).toBeUndefined();
  expect(parsed(KeptSignIn, "not json")).toBeUndefined();
});

test("a kept access token serves a run while it has more than 20 minutes left, and is renewed after", () => {
  expect(keptSignInStep(kept, now)).toBe("use");
  expect(keptSignInStep(kept, now + 10 * 60_000)).toBe("renew");
  expect(keptSignInStep({ ...kept, expiresAt: now - 1 }, now)).toBe("renew");
});

test("a renewal keeps Cloudflare's new refresh token and the scopes it names, and a lost renewal says whether a person must sign in again", () => {
  const renewed = renewedSignIn(
    kept,
    {
      access_token: "access-2",
      refresh_token: "refresh-2",
      expires_in: 3600,
      scope: DEPLOY_SCOPES.filter((scope) => scope !== "d1.write").join(" "),
    },
    now,
  );
  expect(renewed).toEqual({
    renewed: {
      ...kept,
      accessToken: "access-2",
      refreshToken: "refresh-2",
      expiresAt: now + 3600_000,
      lacks: ["d1.write"],
      renewedAt: "2026-11-19T10:00:00.000Z",
    },
  });
  // no new refresh token: the earlier one stays; no scope named: what was known stays
  expect(renewedSignIn(kept, { access_token: "access-2" }, now)).toMatchObject({
    renewed: { refreshToken: "refresh-1", lacks: [] },
  });

  expect(
    renewedSignIn(kept, { error: "invalid_grant", error_description: "revoked" }, now),
  ).toEqual({ ended: true, why: "invalid_grant: revoked" });
  expect(renewedSignIn(kept, { error: "temporarily_unavailable" }, now)).toMatchObject({
    ended: false,
  });
  expect(renewedSignIn(kept, { error: "HTTP 429" }, now)).toMatchObject({ ended: false });
  expect(renewedSignIn(kept, { error: "invalid_client" }, now)).toMatchObject({ ended: false });
  expect(renewedSignIn(kept, {}, now)).toEqual({ ended: false, why: "an answer with no token" });
});

test("a lock holds while the process it names lives, and a lock with no live process is taken over", () => {
  const alive = (pid: number) => pid === 42;
  expect(lockHeld("42", alive)).toBe(true);
  expect(lockHeld("42\n", alive)).toBe(true);
  expect(lockHeld("43", alive)).toBe(false);
  expect(lockHeld("", alive)).toBe(false);
  expect(lockHeld("-1", alive)).toBe(false);
});

test("the tokens that a sign-out lists are the stack's two telemetry tokens, by name", () => {
  expect(madeByTheDeploy("iterate-iterate-telemetry-catalog")).toBe(true);
  expect(madeByTheDeploy("iterate-garple-telemetry-analytics")).toBe(true);
  expect(madeByTheDeploy("iterate deploy")).toBe(false);
  expect(madeByTheDeploy("iterate-jeeves-telemetry-catalog-old")).toBe(false);
});

test("a command refuses a kept sign-in whose lock a live process holds", () => {
  const folder = mkdtempSync(join(tmpdir(), "kept-lock-"));
  const file = join(folder, "sign-in.json");
  writeFileSync(`${file}.lock`, String(process.ppid));
  try {
    expect(() => lockKept(file)).toThrow(`Another command (process ${process.ppid})`);
  } finally {
    rmSync(folder, { recursive: true, force: true });
  }
});

test("dropKeptAccess still removes the file when the revoke fails, and answers why", async () => {
  const folder = mkdtempSync(join(tmpdir(), "kept-access-"));
  const file = join(folder, "cloudflare-access.json");
  const fetcher = (async () => {
    throw new Error("network down");
  }) as unknown as typeof fetch;
  try {
    writeFileSync(
      file,
      JSON.stringify({
        token: "cf-kept-token",
        expiresAt: now + 3600_000,
        scopes: DEPLOY_SCOPES.join(" "),
        lacks: [],
      }),
    );
    expect(await dropKeptAccess({ file, fetcher })).toContain("network down");
    expect(existsSync(file)).toBe(false);
  } finally {
    rmSync(folder, { recursive: true, force: true });
  }
});

test("describeNetworkError unwraps Node fetch cause and gives actionable hints for TLS and IPv6/timeout failures", () => {
  const certErr = new TypeError("fetch failed", {
    cause: Object.assign(new Error("unable to verify the first certificate"), {
      code: "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
    }),
  });
  const certText = describeNetworkError(certErr, "https://dash.cloudflare.com/oauth2/device/auth");
  expect(certText).toContain("dash.cloudflare.com");
  expect(certText).toContain("UNABLE_TO_VERIFY_LEAF_SIGNATURE");
  expect(certText).toContain("NODE_USE_SYSTEM_CA=1");

  const timeoutErr = new TypeError("fetch failed", {
    cause: Object.assign(new Error("connect ETIMEDOUT"), { code: "ETIMEDOUT" }),
  });
  const timeoutText = describeNetworkError(timeoutErr, "https://api.cloudflare.com/client/v4/user");
  expect(timeoutText).toContain("ETIMEDOUT");
  expect(timeoutText).toContain("ipv4first");
});

test("resilientFetch retries transient network errors and 503 responses, then surfaces cause on exhaustion", async () => {
  let calls = 0;
  const ok = await resilientFetch(
    "https://api.cloudflare.com/client/v4/user",
    { method: "GET" },
    {
      attempts: 3,
      backoffMs: 1,
      wait: async () => {},
      fetcher: (async () => {
        calls++;
        if (calls === 1) throw new TypeError("fetch failed", { cause: { code: "ECONNRESET" } });
        if (calls === 2) return new Response("busy", { status: 503 });
        return Response.json({ success: true });
      }) as unknown as typeof fetch,
    },
  );
  expect(ok).toMatchObject({ status: 200 });
  expect(calls).toBe(3);

  await expect(
    resilientFetch(
      "https://dash.cloudflare.com/oauth2/device/auth",
      { method: "POST" },
      {
        attempts: 2,
        backoffMs: 1,
        wait: async () => {},
        fetcher: (async () => {
          throw new TypeError("fetch failed", { cause: { code: "ENETUNREACH" } });
        }) as unknown as typeof fetch,
      },
    ),
  ).rejects.toThrow(/dash\.cloudflare\.com.*ENETUNREACH.*ipv4first/);
});

test("dropKeptAccess removes the kept access file and revokes its token, and is a no-op when absent", async () => {
  const folder = mkdtempSync(join(tmpdir(), "kept-access-"));
  const file = join(folder, "cloudflare-access.json");
  const calls: { url: string; body: string }[] = [];
  const fetcher = (async (url: string | URL | Request, init?: RequestInit) => {
    calls.push({ url: String(url), body: String(init?.body || "") });
    return Response.json({});
  }) as unknown as typeof fetch;
  try {
    // absent file: no request, no throw
    await dropKeptAccess({ file, fetcher });
    expect(calls).toEqual([]);

    writeFileSync(
      file,
      JSON.stringify({
        token: "cf-kept-token",
        expiresAt: now + 3600_000,
        scopes: DEPLOY_SCOPES.join(" "),
        lacks: [],
      }),
    );
    expect(await dropKeptAccess({ file, fetcher })).toBeUndefined();
    expect(existsSync(file)).toBe(false);
    expect(calls).toHaveLength(1);
    expect(calls[0]).toMatchObject({ url: "https://dash.cloudflare.com/oauth2/revoke" });
    expect(new URLSearchParams(calls[0]!.body).get("token")).toBe("cf-kept-token");
  } finally {
    rmSync(folder, { recursive: true, force: true });
  }
});

test("a token in the config folder from before the card's scope still serves a deploy; one that lacks a needed scope, or ends soon, does not", () => {
  const at = 1_800_000_000_000;
  const before = { scopes: DEPLOY_SCOPES.join(" "), expiresAt: at + 40 * 60_000 };
  // the deploy asks a new sign-in for CARD_SCOPE too, and needs it for nothing
  expect(keptTokenServes(before, DEPLOY_SCOPES, at)).toBe(true);
  const withCard = { ...before, scopes: [...DEPLOY_SCOPES, CARD_SCOPE].join(" ") };
  expect(keptTokenServes(withCard, DEPLOY_SCOPES, at)).toBe(true);
  expect(DEPLOY_SCOPES).not.toContain(CARD_SCOPE);

  const lacking = { ...before, scopes: DEPLOY_SCOPES.filter((s) => s !== "d1.write").join(" ") };
  expect(keptTokenServes(lacking, DEPLOY_SCOPES, at)).toBe(false);
  expect(keptTokenServes({ ...before, expiresAt: at + 19 * 60_000 }, DEPLOY_SCOPES, at)).toBe(false);
});

test("the billing access is asked for alone, held in no file, used for the one act and ended at Cloudflare, also when the act throws", async () => {
  // the scope that can spend is in no list that a kept or cached sign-in asks for
  expect(DEPLOY_SCOPES).not.toContain(BILLING_SCOPE);
  expect(CARD_SCOPE).not.toBe(BILLING_SCOPE);

  const calls: { path: string; form: Record<string, string> }[] = [];
  let revokeFails = false;
  let extra: Record<string, string> = {};
  const cloudflareSays = (granted: string) =>
    vi.stubGlobal("fetch", async (url: string | URL, init?: RequestInit) => {
      const path = new URL(String(url)).pathname;
      const form = Object.fromEntries(new URLSearchParams(String(init?.body)));
      calls.push({ path, form });
      const answer = path.endsWith("/device/auth")
        ? {
            device_code: "device-1",
            user_code: "ABCD-EFGH",
            verification_uri: "https://dash.cloudflare.com/oauth2/device",
            expires_in: 300,
            interval: 1,
          }
        : path.endsWith("/token")
          ? { access_token: "billing-token", expires_in: 3600, scope: granted, ...extra }
          : {};
      if (path.endsWith("/revoke") && revokeFails) return new Response("{}", { status: 400 });
      return new Response(JSON.stringify(answer), { headers: { "content-type": "application/json" } });
    });
  const revoked = () => calls.filter((call) => call.path.endsWith("/revoke")).map((call) => call.form.token);
  try {
    cloudflareSays(BILLING_SCOPE);
    let shown = "";
    const made = await briefAccess(
      [BILLING_SCOPE],
      ({ code }) => {
        shown = code;
      },
      async (token) => `acted with ${token}`,
    );
    expect(shown).toBe("ABCD-EFGH");
    expect(made).toEqual({ lacks: [], done: "acted with billing-token" });
    expect(calls[0]!.form.scope).toBe(BILLING_SCOPE);
    expect(revoked()).toEqual(["billing-token"]);

    // an act that throws: the access is ended all the same
    calls.length = 0;
    await expect(
      briefAccess([BILLING_SCOPE], () => {}, async () => {
        throw new Error("Cloudflare is down");
      }),
    ).rejects.toThrow("Cloudflare is down");
    expect(revoked()).toEqual(["billing-token"]);

    // an approval without the scope: no act, and the access is ended
    calls.length = 0;
    cloudflareSays("user-details.read");
    let acted = false;
    expect(
      await briefAccess([BILLING_SCOPE], () => {}, async () => {
        acted = true;
      }),
    ).toEqual({ lacks: [BILLING_SCOPE] });
    expect(acted).toBe(false);
    expect(revoked()).toEqual(["billing-token"]);

    // a revocation that Cloudflare refuses: asked for three times, and said, never silent
    calls.length = 0;
    revokeFails = true;
    cloudflareSays(BILLING_SCOPE);
    const waits: number[] = [];
    const notEnded = await briefAccess(
      [BILLING_SCOPE],
      () => {},
      async () => "acted",
      async (ms) => void waits.push(ms),
    );
    expect(notEnded).toEqual({
      lacks: [],
      done: "acted",
      notEnded: "the access token: HTTP 400",
    });
    expect(revoked()).toEqual(["billing-token", "billing-token", "billing-token"]);
    expect(waits).toEqual([1000, 2000]);
    await expect(
      briefAccess(
        [BILLING_SCOPE],
        () => {},
        async () => {
          throw new Error("The act failed.");
        },
        async () => {},
      ),
    ).rejects.toThrow(
      "The act failed. The access for it was not ended at Cloudflare (the access token: HTTP 400)",
    );

    // a refresh token that came unasked: its end is tried three times and its failure is named
    calls.length = 0;
    extra = { refresh_token: "refresh-unasked" };
    const both = await briefAccess([BILLING_SCOPE], () => {}, async () => "acted", async () => {});
    expect(both.notEnded).toBe(
      "the access token: HTTP 400; the refresh token, which does not end by itself: HTTP 400",
    );
    expect(revoked().filter((token) => token === "refresh-unasked")).toHaveLength(3);
  } finally {
    vi.unstubAllGlobals();
  }
  // each sign-in here waits one second for the device flow's first poll
}, 20_000);