Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

9.7 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import {
  afterAll,
  afterEach,
  beforeEach,
  describe,
  expect,
  it,
  vi
} from "vitest";
import {
  consumeOAuthState,
  consumeOAuthStateByValue,
  issueOAuthState,
  issueOAuthStates
} from "./oauth-state.server";

// The module reads its configuration once, at import.
vi.hoisted(() => {
  vi.stubEnv("DOMAIN", "localhost");
  vi.stubEnv("CARBON_EDITION", "");
  vi.stubEnv("AUTH_COOKIE_SUFFIX", "");
  vi.stubEnv("SESSION_SECRET", "test-session-secret");
});

afterAll(() => vi.unstubAllEnvs());

/** The cookie value (name=value) from a Set-Cookie header, as a browser sends it. */
function cookieHeader(setCookie: string) {
  return setCookie.split(";")[0]!;
}

function requestWithCookie(cookie: string) {
  return new Request("http://localhost/api/integrations/ramp/oauth", {
    headers: { Cookie: cookie }
  });
}

const expected = {
  integrationId: "ramp",
  userId: "user-1",
  companyId: "company-1"
};

describe("OAuth state session", () => {
  beforeEach(() => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date("2026-09-11T12:00:00Z"));
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it("round-trips the nonce and binds it to the integration, user, and company", async () => {
    const issued = await issueOAuthState(expected);
    const consumed = await consumeOAuthState(
      requestWithCookie(issued.cookie),
      issued.state,
      expected
    );

    expect(consumed.valid).toBe(true);
  });

  it("rejects a replay after the state has been consumed", async () => {
    const issued = await issueOAuthState(expected);
    const consumed = await consumeOAuthState(
      requestWithCookie(issued.cookie),
      issued.state,
      expected
    );
    const replay = await consumeOAuthState(
      requestWithCookie(consumed.cookie),
      issued.state,
      expected
    );

    expect(consumed.valid).toBe(true);
    expect(replay.valid).toBe(false);
  });

  it.each([
    ["nonce", { state: "wrong-state", expected }],
    [
      "integration",
      { state: null, expected: { ...expected, integrationId: "xero" } }
    ],
    ["user", { state: null, expected: { ...expected, userId: "user-2" } }],
    [
      "company",
      { state: null, expected: { ...expected, companyId: "company-2" } }
    ]
  ])("rejects a mismatched %s", async (_label, mismatch) => {
    const issued = await issueOAuthState(expected);
    const consumed = await consumeOAuthState(
      requestWithCookie(issued.cookie),
      mismatch.state ?? issued.state,
      mismatch.expected
    );

    expect(consumed.valid).toBe(false);
  });

  it("rejects an expired state", async () => {
    const issued = await issueOAuthState(expected);
    vi.advanceTimersByTime(60 * 60 * 1000 + 1);

    const consumed = await consumeOAuthState(
      requestWithCookie(issued.cookie),
      issued.state,
      expected
    );

    expect(consumed.valid).toBe(false);
  });

  it("keeps one pending state per integration", async () => {
    const onshape = { ...expected, integrationId: "onshape" };
    const ramp = await issueOAuthState(expected);
    const both = await issueOAuthState(
      onshape,
      requestWithCookie(cookieHeader(ramp.cookie))
    );

    const onshapeConsumed = await consumeOAuthState(
      requestWithCookie(cookieHeader(both.cookie)),
      both.state,
      onshape
    );
    const rampConsumed = await consumeOAuthState(
      requestWithCookie(cookieHeader(onshapeConsumed.cookie)),
      ramp.state,
      expected
    );

    expect(onshapeConsumed.valid).toBe(true);
    expect(rampConsumed.valid).toBe(true);
  });

  it("issues several states in one cookie", async () => {
    const payloads = ["ramp", "xero", "jira"].map((integrationId) => ({
      ...expected,
      integrationId
    }));
    const issued = await issueOAuthStates(null, payloads);

    for (const payload of payloads) {
      const consumed = await consumeOAuthState(
        requestWithCookie(cookieHeader(issued.cookie)),
        issued.states[payload.integrationId]!,
        payload
      );
      expect(consumed.valid).toBe(true);
    }
  });

  it("does not accept one integration's state for another", async () => {
    const issued = await issueOAuthStates(null, [
      expected,
      { ...expected, integrationId: "xero" }
    ]);

    const consumed = await consumeOAuthState(
      requestWithCookie(cookieHeader(issued.cookie)),
      issued.states.ramp!,
      { ...expected, integrationId: "xero" }
    );

    expect(consumed.valid).toBe(false);
  });

  it("reuses a still-fresh state so a second page load does not invalidate the first", async () => {
    const first = await issueOAuthState(expected);
    vi.advanceTimersByTime(60 * 1000);
    const second = await issueOAuthState(
      expected,
      requestWithCookie(cookieHeader(first.cookie))
    );

    expect(second.state).toBe(first.state);
  });

  it("replaces a state bound to a different user instead of reusing it", async () => {
    const first = await issueOAuthState(expected);
    const second = await issueOAuthState(
      { ...expected, userId: "user-2" },
      requestWithCookie(cookieHeader(first.cookie))
    );

    expect(second.state).not.toBe(first.state);
  });

  it("rejects an empty state even when one is stored", async () => {
    const issued = await issueOAuthState(expected);
    const consumed = await consumeOAuthState(
      requestWithCookie(cookieHeader(issued.cookie)),
      "",
      expected
    );

    expect(consumed.valid).toBe(false);
  });
});

// One redirect URI serves every workflow piece, so their callback finds the
// state by its value instead of by an integration it cannot know yet.
describe("OAuth state found by value", () => {
  const piece = {
    integrationId: "google-calendar",
    userId: "user-1",
    companyId: "company-1",
    name: "Ops calendar",
    connectionId: "icn_1"
  };
  const owner = { userId: piece.userId, companyId: piece.companyId };

  beforeEach(() => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date("2026-09-11T12:00:00Z"));
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it("returns the entry holding the value, with the integration and its extras", async () => {
    const issued = await issueOAuthState(piece);
    const consumed = await consumeOAuthStateByValue(
      requestWithCookie(cookieHeader(issued.cookie)),
      issued.state,
      owner
    );

    expect(consumed.valid).toBe(true);
    expect(consumed.payload).toMatchObject({
      integrationId: "google-calendar",
      name: "Ops calendar",
      connectionId: "icn_1"
    });
  });

  it.each([
    ["user", { ...owner, userId: "user-2" }],
    ["company", { ...owner, companyId: "company-2" }]
  ])(
    "refuses another %s, and returns nothing from the entry",
    async (_label, other) => {
      const issued = await issueOAuthState(piece);
      const consumed = await consumeOAuthStateByValue(
        requestWithCookie(cookieHeader(issued.cookie)),
        issued.state,
        other
      );

      expect(consumed.valid).toBe(false);
      expect(consumed.payload).toBeUndefined();
    }
  );

  it("refuses an expired state", async () => {
    const issued = await issueOAuthState(piece);
    vi.advanceTimersByTime(60 * 60 * 1000 + 1);

    const consumed = await consumeOAuthStateByValue(
      requestWithCookie(cookieHeader(issued.cookie)),
      issued.state,
      owner
    );

    expect(consumed.valid).toBe(false);
  });

  it("refuses a value no entry holds", async () => {
    const issued = await issueOAuthState(piece);
    const consumed = await consumeOAuthStateByValue(
      requestWithCookie(cookieHeader(issued.cookie)),
      "not-a-state",
      owner
    );

    expect(consumed.valid).toBe(false);
  });

  it("is single-use, even when the first attempt was refused", async () => {
    const issued = await issueOAuthState(piece);
    const refused = await consumeOAuthStateByValue(
      requestWithCookie(cookieHeader(issued.cookie)),
      issued.state,
      { ...owner, userId: "user-2" }
    );
    const retried = await consumeOAuthStateByValue(
      requestWithCookie(cookieHeader(refused.cookie)),
      issued.state,
      owner
    );

    expect(refused.valid).toBe(false);
    expect(retried.valid).toBe(false);
  });

  it("leaves other integrations' pending states in place", async () => {
    const ramp = await issueOAuthState(expected);
    const both = await issueOAuthState(
      piece,
      requestWithCookie(cookieHeader(ramp.cookie))
    );

    const pieceConsumed = await consumeOAuthStateByValue(
      requestWithCookie(cookieHeader(both.cookie)),
      both.state,
      owner
    );
    const rampConsumed = await consumeOAuthState(
      requestWithCookie(cookieHeader(pieceConsumed.cookie)),
      ramp.state,
      expected
    );

    expect(pieceConsumed.valid).toBe(true);
    expect(rampConsumed.valid).toBe(true);
  });

  // The account name rides the cookie into the saved connection, so a state
  // issued for one account must never serve a connect for another.
  it("issues a new state for another account instead of reusing one", async () => {
    const first = await issueOAuthState(piece);
    const second = await issueOAuthState(
      { ...piece, name: "Sales calendar", connectionId: undefined },
      requestWithCookie(cookieHeader(first.cookie))
    );

    expect(second.state).not.toBe(first.state);
    const consumed = await consumeOAuthStateByValue(
      requestWithCookie(cookieHeader(second.cookie)),
      second.state,
      owner
    );
    expect(consumed.payload?.name).toBe("Sales calendar");
    expect(consumed.payload?.connectionId).toBeUndefined();
  });
});