import { describe, it, expect, vi, beforeEach } from "vitest"; import { acquireFabricAccessToken, type FabricOneLakeCredentials } from "@/src/adapters/fabric-onelake-adapter"; const CREDS: FabricOneLakeCredentials = { tenantId: "tenant-a", clientId: "client-a", clientSecret: "secret-a" }; function jsonResponse(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); } describe("acquireFabricAccessToken — OAuth client-credentials flow", () => { it("posts client_credentials grant to the caller's tenant AAD endpoint with the default Fabric SQL scope", async () => { let capturedUrl = ""; let capturedBody = ""; const fetchMock = vi.fn(async (url: unknown, init: unknown) => { capturedUrl = String(url); capturedBody = String((init as RequestInit).body); return jsonResponse({ access_token: "tok_123", expires_in: 3600 }); }); const token = await acquireFabricAccessToken(CREDS, undefined, fetchMock as unknown as typeof fetch); expect(capturedUrl).toBe("https://login.microsoftonline.com/tenant-a/oauth2/v2.0/token"); const params = new URLSearchParams(capturedBody); expect(params.get("client_id")).toBe("client-a"); expect(params.get("client_secret")).toBe("secret-a"); expect(params.get("grant_type")).toBe("client_credentials"); expect(params.get("scope")).toBe("https://database.windows.net/.default"); expect(token.accessToken).toBe("tok_123"); expect(token.expiresAtEpochMs).toBeGreaterThan(Date.now()); }); it("uses a caller-supplied scope instead of the default (e.g. OneLake storage)", async () => { let capturedBody = ""; const fetchMock = vi.fn(async (_url: unknown, init: unknown) => { capturedBody = String((init as RequestInit).body); return jsonResponse({ access_token: "tok_storage", expires_in: 3600 }); }); await acquireFabricAccessToken(CREDS, "https://storage.azure.com/.default", fetchMock as unknown as typeof fetch); expect(new URLSearchParams(capturedBody).get("scope")).toBe("https://storage.azure.com/.default"); }); it("never hardcodes a tenant — different credentials hit different tenant token URLs", async () => { const seenUrls: string[] = []; const fetchMock = vi.fn(async (url: unknown) => { seenUrls.push(String(url)); return jsonResponse({ access_token: "t", expires_in: 3600 }); }); await acquireFabricAccessToken({ tenantId: "tenant-x", clientId: "c", clientSecret: "s" }, undefined, fetchMock as unknown as typeof fetch); await acquireFabricAccessToken({ tenantId: "tenant-y", clientId: "c", clientSecret: "s" }, undefined, fetchMock as unknown as typeof fetch); expect(seenUrls).toEqual([ "https://login.microsoftonline.com/tenant-x/oauth2/v2.0/token", "https://login.microsoftonline.com/tenant-y/oauth2/v2.0/token", ]); }); it("throws a descriptive error when AAD rejects the credentials", async () => { const fetchMock = vi.fn(async () => jsonResponse({ error: "invalid_client", error_description: "bad secret" }, 401)); await expect(acquireFabricAccessToken(CREDS, undefined, fetchMock as unknown as typeof fetch)).rejects.toThrow(/invalid_client/); }); it("rejects locally (no network call) when tenantId/clientId/clientSecret are missing", async () => { const fetchMock = vi.fn(); await expect( acquireFabricAccessToken({ tenantId: "", clientId: "c", clientSecret: "s" }, undefined, fetchMock as unknown as typeof fetch), ).rejects.toThrow(/required/); expect(fetchMock).not.toHaveBeenCalled(); }); }); describe("FabricOneLakeAdapter.query — TDS execution via a mocked mssql driver", () => { const CONFIG = { credentials: CREDS, sqlEndpoint: "https://my-endpoint.datawarehouse.fabric.microsoft.com/", database: "lh_test", }; beforeEach(() => { vi.resetModules(); vi.doUnmock("mssql"); }); it("acquires a token, opens a pooled TDS connection with azure-active-directory-access-token auth, runs the query, and returns rows", async () => { const fetchMock = vi.fn(async () => jsonResponse({ access_token: "tok_query", expires_in: 3600 })); const queryMock = vi.fn(async () => ({ recordset: [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }] })); const inputMock = vi.fn(); const connectMock = vi.fn(async () => {}); const closeMock = vi.fn(async () => {}); let capturedConfig: Record | null = null; class FakeConnectionPool { constructor(config: Record) { capturedConfig = config; } connect = connectMock; request() { return { input: inputMock, query: queryMock }; } close = closeMock; } vi.doMock("mssql", () => ({ default: { ConnectionPool: FakeConnectionPool } })); const { FabricOneLakeAdapter } = await import("@/src/adapters/fabric-onelake-adapter"); const adapter = new FabricOneLakeAdapter(CONFIG, fetchMock as unknown as typeof fetch); const result = await adapter.query("SELECT * FROM dbo.customers WHERE id > @minId", { minId: 1 }); expect(result.rows).toEqual([{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }]); expect(result.rowCount).toBe(2); expect(result.durationMs).toBeGreaterThanOrEqual(0); expect(inputMock).toHaveBeenCalledWith("minId", 1); expect(connectMock).toHaveBeenCalledTimes(1); expect(capturedConfig).toMatchObject({ server: "my-endpoint.datawarehouse.fabric.microsoft.com", database: "lh_test", authentication: { type: "azure-active-directory-access-token", options: { token: "tok_query" } }, }); await adapter.close(); expect(closeMock).toHaveBeenCalledTimes(1); }); it("reuses the cached token across calls and only re-authenticates once", async () => { const fetchMock = vi.fn(async () => jsonResponse({ access_token: "tok_cached", expires_in: 3600 })); const queryMock = vi.fn(async () => ({ recordset: [] })); class FakeConnectionPool { connect = vi.fn(async () => {}); request() { return { input: vi.fn(), query: queryMock }; } close = vi.fn(async () => {}); } vi.doMock("mssql", () => ({ default: { ConnectionPool: FakeConnectionPool } })); const { FabricOneLakeAdapter } = await import("@/src/adapters/fabric-onelake-adapter"); const adapter = new FabricOneLakeAdapter(CONFIG, fetchMock as unknown as typeof fetch); await adapter.query("SELECT 1"); await adapter.query("SELECT 2"); expect(fetchMock).toHaveBeenCalledTimes(1); expect(queryMock).toHaveBeenCalledTimes(2); }); it("throws a clear, actionable error when the mssql driver is not installed/resolvable", async () => { const fetchMock = vi.fn(async () => jsonResponse({ access_token: "tok_x", expires_in: 3600 })); // No vi.doMock("mssql", ...) here — this repo does not declare "mssql" as a // dependency (see fabric-onelake-adapter.ts header), so the real dynamic // import genuinely fails, exercising the adapter's real error path. const { FabricOneLakeAdapter } = await import("@/src/adapters/fabric-onelake-adapter"); const adapter = new FabricOneLakeAdapter(CONFIG, fetchMock as unknown as typeof fetch); await expect(adapter.query("SELECT 1")).rejects.toThrow(/mssql.*not installed/i); }); });