Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

7.3 KB
Raw Blame
import { describe, expect, it, vi } from "vitest";
import { Providers } from "../provider_info_helpers";
import {
  buildCredential,
  displayNameChange,
  initialFormValues,
  resetCredentialFormOnProviderChange,
} from "./credential_form_helpers";
import type { CredentialItem } from "../networking";

/**
 * Build a minimal FormInstance stub that records calls. We don't depend
 * on the full Antd API surface — only the three methods the helper uses.
 */
function makeFormStub(initialFields: Record<string, unknown> = {}) {
  const fields: Record<string, unknown> = { ...initialFields };
  const stub = {
    getFieldValue: vi.fn((key: string) => fields[key]),
    setFieldValue: vi.fn((key: string, value: unknown) => {
      fields[key] = value;
    }),
    resetFields: vi.fn(() => {
      Object.keys(fields).forEach((k) => delete fields[k]);
    }),
  };
  return { stub: stub as unknown as Parameters<typeof resetCredentialFormOnProviderChange>[0], fields, calls: stub };
}

describe("resetCredentialFormOnProviderChange", () => {
  it("clears all fields when switching providers", () => {
    // Simulate the OpenAI->Google AI Studio leak: api_base picked up
    // OpenAI's default value and the user typed a custom URL.
    const { stub, fields, calls } = makeFormStub({
      credential_name: "my-prod-key",
      custom_llm_provider: "OpenAI",
      api_base: "https://api.openai.com/v1",
      api_key: "sk-stale-openai-key",
      organization: "org-leak",
    });
    const setSelectedProvider = vi.fn();

    resetCredentialFormOnProviderChange(stub, Providers.Google_AI_Studio, setSelectedProvider);

    expect(calls.resetFields).toHaveBeenCalledTimes(1);
    // Provider-specific fields must be gone so the next render starts
    // from the new provider's default_value, not OpenAI's leftover.
    expect(fields.api_base).toBeUndefined();
    expect(fields.api_key).toBeUndefined();
    expect(fields.organization).toBeUndefined();
  });

  it("preserves credential_name across the switch", () => {
    // credential_name is user-supplied metadata, not provider-specific.
    // The admin shouldn't have to retype it just because they re-picked
    // the provider.
    const { stub, fields } = makeFormStub({
      credential_name: "my-prod-key",
      custom_llm_provider: "OpenAI",
      api_base: "https://api.openai.com/v1",
    });

    resetCredentialFormOnProviderChange(stub, Providers.Google_AI_Studio, vi.fn());

    expect(fields.credential_name).toBe("my-prod-key");
  });

  it("preserves a display name typed before the provider was picked", () => {
    const { stub, fields } = makeFormStub({ credential_name: "my-prod-key", display_name: "Prod OpenAI" });

    resetCredentialFormOnProviderChange(stub, Providers.OpenAI, vi.fn());

    expect(fields.display_name).toBe("Prod OpenAI");
  });

  it("updates custom_llm_provider and selectedProvider state to the new value", () => {
    const { stub, fields } = makeFormStub({ credential_name: "x" });
    const setSelectedProvider = vi.fn();

    resetCredentialFormOnProviderChange(stub, Providers.Google_AI_Studio, setSelectedProvider);

    expect(fields.custom_llm_provider).toBe(Providers.Google_AI_Studio);
    expect(setSelectedProvider).toHaveBeenCalledExactlyOnceWith(Providers.Google_AI_Studio);
  });

  it("does not call setFieldValue('credential_name', undefined) when the name was unset", () => {
    // Edge case: brand-new modal with no name typed yet. We shouldn't
    // explicitly write `undefined` back into the form (Antd treats that
    // as a touched empty field, triggering the "required" validation
    // prematurely).
    const { stub, calls } = makeFormStub({});

    resetCredentialFormOnProviderChange(stub, Providers.Anthropic, vi.fn());

    const credentialNameCalls = calls.setFieldValue.mock.calls.filter(([key]) => key === "credential_name");
    expect(credentialNameCalls).toHaveLength(0);
  });
});

describe("buildCredential", () => {
  const submission = {
    credential_name: "openai-prod",
    custom_llm_provider: "openai",
    credential_values: { api_key: "sk-test" },
  };

  it.each([
    ["a label", "Prod OpenAI"],
    ["a cleared label", null],
  ])("sends %s as a top-level display_name, never as a credential value", (_, displayName) => {
    const credential = buildCredential({ ...submission, display_name: displayName }, submission.credential_values);

    expect(credential.display_name).toBe(displayName);
    expect(credential.credential_values).toEqual({ api_key: "sk-test" });
  });

  it("leaves display_name out when the form never set it", () => {
    expect(buildCredential(submission, submission.credential_values)).not.toHaveProperty("display_name");
  });

  it("keeps secret keys that share a name with top-level fields inside credential_values", () => {
    const credentialValues = { api_key: "sk-test", credential_name: "legacy-inner", display_name: "Legacy inner" };

    const credential = buildCredential({ ...submission, display_name: "Prod OpenAI" }, credentialValues);

    expect(credential.credential_name).toBe("openai-prod");
    expect(credential.display_name).toBe("Prod OpenAI");
    expect(credential.credential_values).toEqual(credentialValues);
  });
});

describe("displayNameChange", () => {
  const stored: CredentialItem = {
    credential_name: "openai-prod",
    display_name: "Prod",
    credential_values: {},
    credential_info: {},
  };

  it.each([
    ["sends a typed label as is", "  Prod OpenAI  ", { display_name: "  Prod OpenAI  " }],
    [
      "sends a long label without its own length check",
      "\u{1F600}".repeat(300),
      { display_name: "\u{1F600}".repeat(300) },
    ],
    ["omits a blank label", "", {}],
  ])("in add mode %s", (_, typed, expected) => {
    expect(displayNameChange(typed, null)).toEqual(expected);
  });

  it.each([
    ["omits an unchanged label", "Prod", {}],
    ["sends an edited label", "Staging", { display_name: "Staging" }],
    ["clears an emptied label with null", "", { display_name: null }],
    ["leaves whitespace for the server to reject", "   ", { display_name: "   " }],
  ])("in edit mode %s", (_, typed, expected) => {
    expect(displayNameChange(typed, stored)).toEqual(expected);
  });
});

describe("initialFormValues", () => {
  it("prefills the credential's own name, label, and provider over stored values that reuse those keys", () => {
    const credential: CredentialItem = {
      credential_name: "legacy-a",
      display_name: "Legacy A",
      credential_values: {
        api_key: "sk-a****",
        credential_name: "other-credential",
        display_name: "Inner label",
        custom_llm_provider: "anthropic",
      },
      credential_info: { custom_llm_provider: "openai" },
    };

    expect(initialFormValues(credential, null)).toEqual({
      api_key: "sk-a****",
      credential_name: "legacy-a",
      display_name: "Legacy A",
      custom_llm_provider: "openai",
    });
  });

  it("prefills an empty label when the credential has none and only the provider when adding", () => {
    const credential: CredentialItem = { credential_name: "plain", credential_values: {}, credential_info: {} };

    expect(initialFormValues(credential, null)).toMatchObject({ credential_name: "plain", display_name: "" });
    expect(initialFormValues(null, "OpenAI")).toEqual({ custom_llm_provider: "OpenAI" });
    expect(initialFormValues(null, null)).toBeUndefined();
  });
});