aegida-console / lib / auth / types.test.ts
types.test.ts
Raw
import { describe, expect, it } from "vitest";

import {
  parseAuthIdentity,
  type AuthIdentity,
  type AuthTokenIdentity,
} from "@/lib/auth/types";

const completeIdentity: AuthIdentity = {
  id: "00000000-0000-4000-8000-000000000042",
  externalUserId: "42",
  login: "alice",
  fullName: "Alice Smith",
  position: "Engineer",
  email: "alice@example.com",
  firstName: "Alice",
  lastName: "Smith",
  middleName: "Jane",
  roles: ["admin", "employee"],
  lastModelId: "chatgpt",
};

// AuthIdentity is the complete, projected identity returned after external authentication.
// @ts-expect-error A missing role must not satisfy the complete identity contract.
const incompleteIdentity: AuthIdentity = {
  id: "00000000-0000-4000-8000-000000000042",
  externalUserId: "42",
  login: "alice",
  fullName: "Alice Smith",
  position: "Engineer",
  email: "alice@example.com",
  firstName: "Alice",
  lastName: "Smith",
  middleName: "Jane",
  lastModelId: "chatgpt",
};

const gateTokenIdentity: AuthTokenIdentity = {
  id: completeIdentity.id,
  email: completeIdentity.email,
  externalUserId: completeIdentity.externalUserId,
  tenantId: "tenant-1",
};

describe("authentication identity", () => {
  it("keeps the complete external profile available to consumers", () => {
    expect(completeIdentity.roles).toEqual(["admin", "employee"]);
    expect(incompleteIdentity).toBeDefined();
    expect(gateTokenIdentity).toEqual({
      id: completeIdentity.id,
      email: completeIdentity.email,
      externalUserId: "42",
      tenantId: "tenant-1",
    });
  });

  it("parses the complete browser identity with a decimal external ID", () => {
    expect(parseAuthIdentity(completeIdentity)).toEqual(completeIdentity);
  });

  it("accepts a browser identity with a dynamic Gate model", () => {
    expect(
      parseAuthIdentity({ ...completeIdentity, lastModelId: "claude-sonnet.4" }),
    ).toMatchObject({ lastModelId: "claude-sonnet.4" });
  });

  it.each(["GPT-4", "model/path", ".leading", "", null])(
    "rejects an identity with an invalid lastModelId %j",
    (lastModelId) => {
      expect(parseAuthIdentity({ ...completeIdentity, lastModelId })).toBeNull();
    },
  );

  it.each([42, "0", "01", "9223372036854775808"])(
    "rejects an unsafe external ID representation %j",
    (externalUserId) => {
      expect(parseAuthIdentity({ ...completeIdentity, externalUserId })).toBeNull();
    },
  );
});