Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

test: add unit tests for API authentication and key resolution

Khuram Niazc60663134591
diff --git a/__tests__/api-auth-contract.spec.ts b/__tests__/api-auth-contract.spec.ts
new file mode 100644
index 0000000..f574e16
--- /dev/null
+++ b/__tests__/api-auth-contract.spec.ts
@@ -0,0 +1,77 @@
+// Contract tests: every session-guarded API route must reject anonymous
+// requests. This locks in the defense-in-depth `auth()` check each handler
+// performs on top of the middleware matcher (see src/middleware.ts).
+
+vi.mock("@/auth", () => ({
+ auth: vi.fn(),
+}));
+
+// NextResponse.json uses Response.json() internally; provide a working stub.
+vi.mock("next/server", () => ({
+ NextResponse: {
+ json: (data: unknown, init?: { status?: number }) => ({
+ status: init?.status ?? 200,
+ json: async () => data,
+ }),
+ },
+}));
+
+import { auth } from "@/auth";
+
+import { POST as verifyApiKey } from "@/app/api/settings/api-keys/verify/route";
+import { POST as exportJobs } from "@/app/api/jobs/export/route";
+import { POST as cancelAutomation } from "@/app/api/automations/[id]/cancel/route";
+import { POST as clearLogs } from "@/app/api/automations/[id]/logs/clear/route";
+import {
+ GET as getResume,
+ POST as postResume,
+} from "@/app/api/profile/resume/route";
+import { POST as reviewResume } from "@/app/api/ai/resume/review/route";
+
+const anonAuth = () => (auth as any).mockResolvedValue(null);
+
+// Minimal Request stub — guarded handlers return 401 before touching the body.
+const req = () => ({ json: async () => ({}), url: "http://localhost/x" }) as any;
+const params = { params: Promise.resolve({ id: "automation-1" }) };
+
+describe("API auth contract: guarded routes reject anonymous requests", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ anonAuth();
+ });
+
+ it("POST /api/settings/api-keys/verify -> 401", async () => {
+ const res = await verifyApiKey(req());
+ expect(res.status).toBe(401);
+ });
+
+ it("POST /api/jobs/export -> 401", async () => {
+ const res = await exportJobs();
+ expect(res.status).toBe(401);
+ });
+
+ it("POST /api/automations/[id]/cancel -> 401", async () => {
+ const res = await cancelAutomation(req(), params);
+ expect(res.status).toBe(401);
+ });
+
+ it("POST /api/automations/[id]/logs/clear -> 401", async () => {
+ const res = await clearLogs(req(), params);
+ expect(res.status).toBe(401);
+ });
+
+ it("GET /api/profile/resume -> 401", async () => {
+ const res = await getResume(req());
+ expect(res!.status).toBe(401);
+ });
+
+ it("POST /api/profile/resume -> 401", async () => {
+ const res = await postResume(req());
+ expect(res!.status).toBe(401);
+ });
+
+ it("POST /api/ai/resume/review -> 401", async () => {
+ const res = await reviewResume(req());
+ expect(res.status).toBe(401);
+ });
+});
diff --git a/__tests__/api-key-resolver.spec.ts b/__tests__/api-key-resolver.spec.ts
new file mode 100644
index 0000000..65eb202
--- /dev/null
+++ b/__tests__/api-key-resolver.spec.ts
@@ -0,0 +1,128 @@
+// Unit tests for resolveApiKey: db (per-user) -> env var -> provider default.
+
+const mockFindUnique = vi.fn();
+const mockUpdate = vi.fn(() => ({ catch: () => {} }));
+
+vi.mock("@/lib/db", () => ({
+ default: {
+ apiKey: {
+ findUnique: (...args: unknown[]) => mockFindUnique(...args),
+ update: (...args: unknown[]) => mockUpdate(...args),
+ },
+ },
+}));
+
+vi.mock("@/lib/encryption", () => ({
+ decrypt: (key: string, iv: string) => `decrypted(${key},${iv})`,
+}));
+
+vi.mock("@/lib/ai/provider-registry", () => ({
+ PROVIDER_REGISTRY: {
+ openai: { envVar: "OPENAI_API_KEY" },
+ ollama: { defaultCredential: "ollama-default" },
+ deepseek: { envVar: "DEEPSEEK_API_KEY", defaultCredential: "ds-default" },
+ },
+}));
+
+import { resolveApiKey } from "@/lib/api-key-resolver";
+
+describe("resolveApiKey", () => {
+ const OLD_ENV = process.env;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ process.env = { ...OLD_ENV };
+ delete process.env.OPENAI_API_KEY;
+ delete process.env.DEEPSEEK_API_KEY;
+ delete process.env.RAPIDAPI_KEY;
+ });
+
+ afterAll(() => {
+ process.env = OLD_ENV;
+ });
+
+ it("returns the decrypted per-user key when one exists", async () => {
+ mockFindUnique.mockResolvedValue({
+ id: "k1",
+ encryptedKey: "cipher",
+ iv: "saltiv",
+ });
+
+ const result = await resolveApiKey("user-1", "openai");
+
+ expect(result).toBe("decrypted(cipher,saltiv)");
+ expect(mockUpdate).toHaveBeenCalledWith({
+ where: { id: "k1" },
+ data: { lastUsedAt: expect.any(Date) },
+ });
+ });
+
+ it("returns the raw key when iv is empty (unencrypted legacy record)", async () => {
+ mockFindUnique.mockResolvedValue({
+ id: "k2",
+ encryptedKey: "plaintext-key",
+ iv: "",
+ });
+
+ const result = await resolveApiKey("user-1", "openai");
+
+ expect(result).toBe("plaintext-key");
+ });
+
+ it("falls back to the provider env var when the user has no key", async () => {
+ mockFindUnique.mockResolvedValue(null);
+ process.env.OPENAI_API_KEY = "env-openai";
+
+ const result = await resolveApiKey("user-1", "openai");
+
+ expect(result).toBe("env-openai");
+ });
+
+ it("resolves the rapidapi extra env var (not in the registry)", async () => {
+ process.env.RAPIDAPI_KEY = "rapid-123";
+
+ const result = await resolveApiKey(undefined, "rapidapi");
+
+ expect(result).toBe("rapid-123");
+ expect(mockFindUnique).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the provider default credential", async () => {
+ const result = await resolveApiKey(undefined, "ollama");
+
+ expect(result).toBe("ollama-default");
+ });
+
+ it("prefers the env var over the default credential", async () => {
+ mockFindUnique.mockResolvedValue(null);
+ process.env.DEEPSEEK_API_KEY = "env-ds";
+
+ const result = await resolveApiKey("user-1", "deepseek");
+
+ expect(result).toBe("env-ds");
+ });
+
+ it("returns undefined when nothing resolves", async () => {
+ const result = await resolveApiKey(undefined, "unknown-provider");
+
+ expect(result).toBeUndefined();
+ });
+
+ it("falls through to env var when the db lookup throws", async () => {
+ mockFindUnique.mockRejectedValue(new Error("db down"));
+ process.env.OPENAI_API_KEY = "env-openai";
+
+ const result = await resolveApiKey("user-1", "openai");
+
+ expect(result).toBe("env-openai");
+ });
+
+ it("skips the db lookup entirely when no userId is given", async () => {
+ process.env.OPENAI_API_KEY = "env-openai";
+
+ const result = await resolveApiKey(undefined, "openai");
+
+ expect(result).toBe("env-openai");
+ expect(mockFindUnique).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/checkOllamaConnection.spec.ts b/__tests__/checkOllamaConnection.spec.ts
new file mode 100644
index 0000000..2a4f541
--- /dev/null
+++ b/__tests__/checkOllamaConnection.spec.ts
@@ -0,0 +1,51 @@
+// Unit tests for checkOllamaConnection: non-ollama short-circuit, reachable,
+// unreachable, and thrown-error branches.
+
+import { checkOllamaConnection } from "@/utils/ai.utils";
+import { AiProvider } from "@/models/ai.model";
+
+describe("checkOllamaConnection", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("returns connected without fetching for non-Ollama providers", async () => {
+ const fetchSpy = vi.fn();
+ global.fetch = fetchSpy as any;
+
+ const result = await checkOllamaConnection(AiProvider.OPENAI);
+
+ expect(result).toEqual({ isConnected: true });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("returns connected when the tags endpoint responds ok", async () => {
+ global.fetch = vi.fn().mockResolvedValue({ ok: true }) as any;
+
+ const result = await checkOllamaConnection(AiProvider.OLLAMA);
+
+ expect(result).toEqual({ isConnected: true });
+ expect(global.fetch).toHaveBeenCalledWith(
+ "/api/ai/ollama/tags",
+ expect.any(Object),
+ );
+ });
+
+ it("returns disconnected when the tags endpoint responds not-ok", async () => {
+ global.fetch = vi.fn().mockResolvedValue({ ok: false }) as any;
+
+ const result = await checkOllamaConnection(AiProvider.OLLAMA);
+
+ expect(result.isConnected).toBe(false);
+ expect(result.error).toContain("not responding");
+ });
+
+ it("returns disconnected with the error message when fetch throws", async () => {
+ global.fetch = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")) as any;
+
+ const result = await checkOllamaConnection(AiProvider.OLLAMA);
+
+ expect(result.isConnected).toBe(false);
+ expect(result.error).toContain("ECONNREFUSED");
+ });
+});
diff --git a/__tests__/localstorage.utils.spec.ts b/__tests__/localstorage.utils.spec.ts
new file mode 100644
index 0000000..02bb037
--- /dev/null
+++ b/__tests__/localstorage.utils.spec.ts
@@ -0,0 +1,31 @@
+// Tests for the localStorage helpers with their SSR guard.
+
+import {
+ saveToLocalStorage,
+ getFromLocalStorage,
+} from "@/utils/localstorage.utils";
+
+describe("localStorage helpers", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ it("round-trips a value through save/get", () => {
+ saveToLocalStorage("prefs", { theme: "dark", count: 3 });
+
+ expect(getFromLocalStorage("prefs", null)).toEqual({
+ theme: "dark",
+ count: 3,
+ });
+ });
+
+ it("returns the default when the key is absent", () => {
+ expect(getFromLocalStorage("missing", "fallback")).toBe("fallback");
+ });
+
+ it("serializes non-object values", () => {
+ saveToLocalStorage("n", 42);
+ expect(localStorage.getItem("n")).toBe("42");
+ expect(getFromLocalStorage("n", 0)).toBe(42);
+ });
+});
diff --git a/__tests__/verify-api-key-route.spec.ts b/__tests__/verify-api-key-route.spec.ts
new file mode 100644
index 0000000..64ed565
--- /dev/null
+++ b/__tests__/verify-api-key-route.spec.ts
@@ -0,0 +1,83 @@
+// Tests for POST /api/settings/api-keys/verify: validation, provider lookup,
+// verifier success, and connection-error message shaping.
+
+vi.mock("@/auth", () => ({ auth: vi.fn() }));
+
+vi.mock("next/server", () => ({
+ NextResponse: {
+ json: (data: unknown, init?: { status?: number }) => ({
+ status: init?.status ?? 200,
+ json: async () => data,
+ }),
+ },
+}));
+
+const mockVerifier = vi.fn();
+vi.mock("@/lib/ai/provider-registry.server", () => ({
+ PROVIDER_VERIFIERS: {
+ get openai() {
+ return mockVerifier;
+ },
+ },
+}));
+
+import { POST } from "@/app/api/settings/api-keys/verify/route";
+import { auth } from "@/auth";
+
+const authed = () =>
+ (auth as any).mockResolvedValue({ user: { id: "user-1" } });
+const req = (body: unknown) => ({ json: async () => body }) as any;
+
+describe("POST /api/settings/api-keys/verify", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ authed();
+ });
+
+ it("returns 400 when provider or key is missing", async () => {
+ const res = await POST(req({ provider: "openai" }));
+ const data = await res.json();
+
+ expect(res.status).toBe(400);
+ expect(data.error).toContain("required");
+ });
+
+ it("returns 400 for an unknown provider", async () => {
+ const res = await POST(req({ provider: "nope", key: "k" }));
+ const data = await res.json();
+
+ expect(res.status).toBe(400);
+ expect(data.error).toBe("Unknown provider");
+ });
+
+ it("returns the verifier result on success", async () => {
+ mockVerifier.mockResolvedValue({ success: true, models: ["gpt-4o"] });
+
+ const res = await POST(req({ provider: "openai", key: "sk-live" }));
+ const data = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(data).toEqual({ success: true, models: ["gpt-4o"] });
+ expect(mockVerifier).toHaveBeenCalledWith("sk-live");
+ });
+
+ it("maps connection failures to a friendly message", async () => {
+ mockVerifier.mockRejectedValue(new Error("fetch failed"));
+
+ const res = await POST(req({ provider: "openai", key: "sk-live" }));
+ const data = await res.json();
+
+ expect(data.success).toBe(false);
+ expect(data.error).toBe("Cannot connect to openai service");
+ });
+
+ it("passes through other verifier error messages", async () => {
+ mockVerifier.mockRejectedValue(new Error("Invalid API key"));
+
+ const res = await POST(req({ provider: "openai", key: "sk-bad" }));
+ const data = await res.json();
+
+ expect(data.success).toBe(false);
+ expect(data.error).toBe("Invalid API key");
+ });
+});
diff --git a/package.json b/package.json
index 0eadd34..83b2e23 100644
--- a/package.json
+++ b/package.json
@@ -10,6 +10,7 @@
"test": "vitest run",
"test:e2e": "npx playwright test",
"test:watch": "vitest",
+ "test:coverage": "vitest run --coverage",
"eval:resume-review": "promptfoo eval --config evals/resume-review/promptfooconfig.yaml",
"eval:job-match": "promptfoo eval --config evals/job-match/promptfooconfig.yaml",
"eval:automation-match": "promptfoo eval --config evals/job-match/automation.promptfooconfig.yaml",