Cotton code
288 lines · 17.0 KB · TypeScriptRaw
/** * OTP_MODE=twilio: the code goes out and is checked through Twilio Verify * (v2: POST Services/{sid}/Verifications { To, Channel=sms }, then POST * Services/{sid}/VerificationCheck { To, Code } answering status "approved"), * the number in E.164, Basic auth of the account sid and auth token. Twilio * is a fake fetch here; the sids are made up. */import { env, runInDurableObject } from "cloudflare:test";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { CODES_PER_HOUR, codesPerHour, issueCode, proveCode, testCodes } from "../src/auth.ts";import type { Env } from "../src/env.ts";import { Refused } from "../src/http.ts";import { Store } from "../src/store.ts";const SID = `AC${"0".repeat(32)}`;const VERIFY = `VA${"1".repeat(32)}`;const TWILIO: Env = { ...env, OTP_MODE: "twilio", TWILIO_ACCOUNT_SID: SID, TWILIO_AUTH_TOKEN: "test-auth-token", TWILIO_VERIFY_SID: VERIFY };const PHONE = "+15550100";const TESTER = "+12025550101";const TESTER_TWO = "+12025550102";interface Call {  url: string;  method: string;  authorization: string | null;  type: string | null;  form: Record<string, string>;}type Answer = () => Response;/** Twilio, answering each call with the next of `answers` (made at the call: a body belongs to the object that reads it); the calls it saw. */function twilio(...answers: Answer[]): Call[] {  const calls: Call[] = [];  vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {    const request = new Request(input as RequestInfo, init);    calls.push({ url: request.url, method: request.method, authorization: request.headers.get("authorization"), type: request.headers.get("content-type"), form: Object.fromEntries(new URLSearchParams(await request.text())) });    const next = answers.shift();    if (!next) throw new Error("Twilio was called more times than the test expects");    return next();  });  return calls;}const answer = (status: number, body: Record<string, unknown>): Answer => () => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });/** A run against a fresh object's own store, as the object runs auth. */function within<T>(slug: string, fn: (store: Store) => Promise<T>): Promise<T> {  return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_instance, state) => fn(new Store(state.storage.sql, () => new Date())));}async function refusal(run: Promise<unknown>): Promise<{ status: number; code: string }> {  const error = await run.then(    () => null,    (e: unknown) => e,  );  expect(error).toBeInstanceOf(Refused);  return { status: (error as Refused).status, code: (error as Refused).code };}async function refusedWith(run: Promise<unknown>): Promise<Refused> {  const error = await run.then(    () => null,    (e: unknown) => e,  );  expect(error).toBeInstanceOf(Refused);  return error as Refused;}// Each test starts a fresh SMS day: the directory's per-number cap (AUDIT A H2, SMS_PER_NUMBER_PER_DAY) counts every// send to the same synthetic number across this file's tests otherwise.beforeEach(async () => {  await runInDurableObject(env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")), (_i, state) => void state.storage.sql.exec("DELETE FROM sms_sent"));});afterEach(() => {  vi.restoreAllMocks();});describe("Twilio Verify", () => {  it("starts a verification by SMS to the number in E.164, and checks the code there", async () => {    const calls = twilio(answer(201, { sid: "VE1", status: "pending", channel: "sms" }), answer(200, { sid: "VE1", status: "approved", valid: true }));    const proved = await within("twilio-ok", async (store) => {      const { challenge_id } = await issueCode(TWILIO, store, new Date(), PHONE, "phone-1");      return proveCode(TWILIO, store, new Date(), challenge_id, " 482913 ", "phone-1");    });    expect(proved).toBe(PHONE);    const basic = `Basic ${btoa(`${SID}:test-auth-token`)}`;    expect(calls).toEqual([      { url: `https://verify.twilio.com/v2/Services/${VERIFY}/Verifications`, method: "POST", authorization: basic, type: "application/x-www-form-urlencoded", form: { To: PHONE, Channel: "sms" } },      { url: `https://verify.twilio.com/v2/Services/${VERIFY}/VerificationCheck`, method: "POST", authorization: basic, type: "application/x-www-form-urlencoded", form: { To: PHONE, Code: "482913" } },    ]);  });  it("refuses a code Twilio does not approve, counting the try, and one Twilio no longer holds", async () => {    twilio(answer(201, { status: "pending" }), answer(200, { status: "pending", valid: false }), answer(404, { code: 20404, message: "The requested resource was not found" }));    await within("twilio-wrong", async (store) => {      const { challenge_id } = await issueCode(TWILIO, store, new Date(), PHONE, "phone-1");      expect(await refusal(proveCode(TWILIO, store, new Date(), challenge_id, "000000", "phone-1"))).toEqual({ status: 401, code: "invalid_code" });      expect(store.code(challenge_id)?.tries).toBe(1);      expect(await refusal(proveCode(TWILIO, store, new Date(), challenge_id, "111111", "phone-1"))).toEqual({ status: 401, code: "invalid_code" });    });  });  it("does not count a try when Twilio fails the check", async () => {    twilio(answer(201, { status: "pending" }), answer(503, { code: 20503, message: "Service unavailable" }));    await within("twilio-check-down", async (store) => {      const { challenge_id } = await issueCode(TWILIO, store, new Date(), PHONE, "phone-1");      expect(await refusal(proveCode(TWILIO, store, new Date(), challenge_id, "482913", "phone-1"))).toEqual({ status: 503, code: "sms_unavailable" });      expect(store.code(challenge_id)?.tries).toBe(0);    });  });  it("says a code could not be sent when Twilio fails the start, and sends nothing without its three secrets", async () => {    twilio(answer(503, { code: 20503, message: "Service unavailable for +15550100" }), answer(500, { message: "Internal" }), () => new Response("<html>bad gateway</html>", { status: 502 }));    await within("twilio-down", async (store) => {      for (let i = 0; i < 3; i++) {        const refused = await refusedWith(issueCode(TWILIO, store, new Date(), PHONE, "phone-1"));        expect([refused.status, refused.code]).toEqual([503, "sms_unavailable"]);        expect(refused.message).not.toMatch(/Service unavailable|Internal|html|\+1555/);      }      const unset: Env = { ...TWILIO, TWILIO_VERIFY_SID: undefined };      expect(await refusal(issueCode(unset, store, new Date(), PHONE, "phone-1"))).toEqual({ status: 503, code: "sms_unavailable" });    });  });  it("answers a number Twilio will not send to as bad_phone, and Twilio's own limit as too_many_codes", async () => {    twilio(      answer(400, { code: 60200, message: "Invalid parameter `To`: +15550100" }),      answer(400, { code: 21211, message: "Invalid 'To' Phone Number" }),      answer(403, { code: 60220, message: "Permission to send an SMS has not been enabled for the region" }),      answer(403, { code: 60605, message: "Verification delivery attempt blocked" }),      answer(429, { code: 60203, message: "Max send attempts reached" }),      answer(429, { message: "Too Many Requests" }),      answer(401, { code: 20003, message: "Authenticate" }),    );    await within("twilio-refuses", async (store) => {      const seen = [];      for (let i = 0; i < 7; i++) {        const refused = await refusedWith(issueCode({ ...TWILIO, CODES_PER_HOUR: "100" }, store, new Date(), PHONE, "phone-1"));        expect(refused.message).not.toMatch(/Invalid|Permission|blocked|Max send|Authenticate|\+1555/);        seen.push(`${refused.status} ${refused.code}`);      }      // Our own account failing (401) is Twilio failing, not the number.      expect(seen).toEqual(["400 bad_phone", "400 bad_phone", "400 bad_phone", "400 bad_phone", "429 too_many_codes", "429 too_many_codes", "503 sms_unavailable"]);    });  });  it("treats a verification Twilio no longer holds or has closed as a wrong code, never a 500", async () => {    twilio(      answer(201, { status: "pending" }),      answer(404, { code: 20404, message: "The requested resource /Services/VA/VerificationCheck was not found" }),      answer(429, { code: 60202, message: "Max check attempts reached" }),      answer(400, { code: 60200, message: "Invalid parameter: Code" }),      () => new Response("not json", { status: 200 }),    );    await within("twilio-gone", async (store) => {      const { challenge_id } = await issueCode(TWILIO, store, new Date(), PHONE, "phone-1");      const said = [];      for (const code of ["482913", "482913", "abc"]) {        const refused = await refusedWith(proveCode(TWILIO, store, new Date(), challenge_id, code, "phone-1"));        expect([refused.status, refused.code]).toEqual([401, "invalid_code"]);        said.push(refused.message);      }      // A right code refused says why: the verification is gone, or its tries ran out; only a wrong one is called invalid.      expect(said).toEqual(["that code is no longer good; ask for a new code", "too many tries on that code; wait ten minutes, then ask for a new code", "invalid or expired code"]);      expect(store.code(challenge_id)?.tries).toBe(3);      expect(await refusal(proveCode(TWILIO, store, new Date(), challenge_id, "482913", "phone-1"))).toEqual({ status: 503, code: "sms_unavailable" });    });  });});const CODES = JSON.stringify({ [TESTER]: "246810", [TESTER_TWO]: "135790" });describe("named test numbers (OTP_TEST_CODES)", () => {  it("prove their own code without Twilio, in twilio mode, on several devices", async () => {    const calls = twilio();    const withTests: Env = { ...TWILIO, ENV_LABEL: "production", OTP_TEST_CODES: CODES };    await within("tester-twilio", async (store) => {      const one = await issueCode(withTests, store, new Date(), TESTER, "phone-1");      const two = await issueCode(withTests, store, new Date(), TESTER, "phone-2");      expect(await refusal(proveCode(withTests, store, new Date(), one.challenge_id, "123456", "phone-1"))).toEqual({ status: 401, code: "invalid_code" });      expect(store.code(one.challenge_id)?.tries).toBe(1);      expect(await proveCode(withTests, store, new Date(), one.challenge_id, " 246810 ", "phone-1")).toBe(TESTER);      expect(await proveCode(withTests, store, new Date(), two.challenge_id, "246810", "phone-2")).toBe(TESTER);      const other = await issueCode(withTests, store, new Date(), TESTER_TWO, "phone-3");      expect(await refusal(proveCode(withTests, store, new Date(), other.challenge_id, "246810", "phone-3"))).toEqual({ status: 401, code: "invalid_code" });      expect(await proveCode(withTests, store, new Date(), other.challenge_id, "135790", "phone-3")).toBe(TESTER_TWO);    });    expect(calls).toEqual([]);  });  it("prove their own code in fixed mode, where the fixed code does not open them", async () => {    const fixed: Env = { ...env, OTP_MODE: "fixed", OTP_FIXED_CODE: "123456", OTP_TEST_CODES: CODES };    await within("tester-fixed", async (store) => {      const { challenge_id } = await issueCode(fixed, store, new Date(), TESTER, "phone-1");      expect(await refusal(proveCode(fixed, store, new Date(), challenge_id, "123456", "phone-1"))).toEqual({ status: 401, code: "invalid_code" });      expect(await proveCode(fixed, store, new Date(), challenge_id, "246810", "phone-1")).toBe(TESTER);      const real = await issueCode(fixed, store, new Date(), PHONE, "phone-1");      expect(await proveCode(fixed, store, new Date(), real.challenge_id, "123456", "phone-1")).toBe(PHONE);    });  });  it("keep the hour's limit, the tries and the expiry", async () => {    const withTests: Env = { ...TWILIO, OTP_TEST_CODES: CODES };    await within("tester-limits", async (store) => {      const { challenge_id } = await issueCode(withTests, store, new Date(), TESTER, "phone-1");      for (let i = 0; i < 5; i++) await refusal(proveCode(withTests, store, new Date(), challenge_id, "000000", "phone-1"));      expect(await refusal(proveCode(withTests, store, new Date(), challenge_id, "246810", "phone-1"))).toEqual({ status: 401, code: "invalid_code" });      const late = await issueCode(withTests, store, new Date(), TESTER, "phone-1");      expect(await refusal(proveCode(withTests, store, new Date(Date.now() + 301_000), late.challenge_id, "246810", "phone-1"))).toEqual({ status: 401, code: "invalid_code" });      for (let i = 2; i < CODES_PER_HOUR; i++) await issueCode(withTests, store, new Date(), TESTER, "phone-1");      expect(await refusal(issueCode(withTests, store, new Date(), TESTER, "phone-1"))).toEqual({ status: 429, code: "too_many_codes" });    });  });  it("AUDIT FIX B1 (B-12): a number a person could hold gets no fixed code, and the log does not name it", () => {    const real = "+919000099999";    const logged: string[] = [];    const spy = vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => void logged.push(args.join(" ")));    const read = testCodes({ OTP_TEST_CODES: JSON.stringify({ [TESTER]: "246810", [real]: "111111" }) });    spy.mockRestore();    expect(read).toEqual({ ok: true, codes: new Map([[TESTER, "246810"]]) });    expect(logged.join("\n")).toContain("1 number(s)");    expect(logged.join("\n")).not.toContain(real);  });  it("are read strictly: a malformed value refuses the numbers it names, logs why but never the value, and leaves every other number to Twilio", async () => {    const errors = vi.spyOn(console, "error").mockImplementation(() => {});    for (const bad of [`{"${TESTER}": "246810",}`, `["${TESTER}"]`, `{"${TESTER}": 246810}`, `{"${TESTER}": "24 68"}`, `{"+1 555 0101": "246810"}`, `{"${TESTER}": "12"}`, `{"${TESTER}": "13579"}`, `{"${TESTER}": "1357900"}`]) {      expect(testCodes({ OTP_TEST_CODES: bad }).ok).toBe(false);    }    expect(testCodes({})).toEqual({ ok: true, codes: new Map() });    expect(testCodes({ OTP_TEST_CODES: CODES })).toEqual({ ok: true, codes: new Map([[TESTER, "246810"], [TESTER_TWO, "135790"]]) });    const calls = twilio(answer(201, { status: "pending" }));    const broken: Env = { ...TWILIO, OTP_TEST_CODES: `{"${TESTER}": "246810",}` };    await within("tester-malformed", async (store) => {      expect(await refusal(issueCode(broken, store, new Date(), TESTER, "phone-1"))).toEqual({ status: 503, code: "otp_unconfigured" });      await issueCode(broken, store, new Date(), PHONE, "phone-1");      // A challenge issued while the value was whole is refused once it is broken.      const whole: Env = { ...TWILIO, OTP_TEST_CODES: CODES };      const { challenge_id } = await issueCode(whole, store, new Date(), TESTER, "phone-1");      expect(await refusal(proveCode(broken, store, new Date(), challenge_id, "246810", "phone-1"))).toEqual({ status: 503, code: "otp_unconfigured" });    });    expect(calls.map((c) => c.form.To)).toEqual([PHONE]);    const logged = errors.mock.calls.flat().join(" ");    expect(logged).toContain("OTP_TEST_CODES is malformed");    expect(logged).not.toContain("246810");  });});describe("fixed mode", () => {  it("runs on the dev Worker and the test pool alone", async () => {    vi.spyOn(console, "error").mockImplementation(() => {});    const calls = twilio();    await within("fixed-where", async (store) => {      const dev: Env = { ...env, OTP_MODE: "fixed", OTP_FIXED_CODE: "123456", ENV_LABEL: "dev" };      const { challenge_id } = await issueCode(dev, store, new Date(), PHONE, "phone-1");      expect(await proveCode(dev, store, new Date(), challenge_id, "123456", "phone-1")).toBe(PHONE);      for (const label of ["production", undefined, "staging"]) {        const live: Env = { ...env, OTP_MODE: "fixed", OTP_FIXED_CODE: "123456", ENV_LABEL: label };        expect(await refusal(issueCode(live, store, new Date(), PHONE, "phone-1"))).toEqual({ status: 503, code: "otp_unconfigured" });      }      // A challenge kept under fixed is not proved by a Worker that may not run it.      const kept = await issueCode(dev, store, new Date(), PHONE, "phone-1");      const live: Env = { ...env, OTP_MODE: "fixed", OTP_FIXED_CODE: "123456", ENV_LABEL: "production" };      expect(await refusal(proveCode(live, store, new Date(), kept.challenge_id, "123456", "phone-1"))).toEqual({ status: 503, code: "otp_unconfigured" });      const twilioLive: Env = { ...TWILIO, ENV_LABEL: "production" };      expect(await refusal(proveCode(twilioLive, store, new Date(), kept.challenge_id, "123456", "phone-1"))).toEqual({ status: 401, code: "invalid_code" });      // No mode, or one that is neither, sends nothing.      for (const mode of [undefined, "Twilio", "off"]) {        expect(await refusal(issueCode({ ...env, OTP_MODE: mode }, store, new Date(), PHONE, "phone-1"))).toEqual({ status: 503, code: "otp_unconfigured" });      }    });    expect(calls).toEqual([]);  });});describe("the hour's code limit", () => {  it("is the constant unless the Worker's var names a whole number", () => {    expect(codesPerHour({})).toBe(CODES_PER_HOUR);    expect(codesPerHour({ CODES_PER_HOUR: "100" })).toBe(100);    expect(codesPerHour({ CODES_PER_HOUR: "many" })).toBe(CODES_PER_HOUR);    expect(codesPerHour({ CODES_PER_HOUR: "-1" })).toBe(CODES_PER_HOUR);  });});