import { describe, it, expect, vi, beforeEach } from "vitest"; import { acquireFabricAccessToken, type FabricOneLakeCredentials } from "@/src/adapters/fabric-onelake-adapter"; import type { DnsLookupFn } from "@/src/lib/security/ssrf-guard"; 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" } }); } /** * Deterministic stand-in for real DNS: every test in this file that opens a * pool now goes through the SSRF guard added to `getPool()`, so a fixed, * injected resolver keeps these tests hermetic (no live network dependency) * instead of relying on the test fixtures' fake hostnames actually * resolving. Returns a public, non-blocked address for any hostname unless * overridden — use `blockedDnsLookup` below to simulate a hostname that * resolves to a private/internal address. */ function publicDnsLookup(_hostname: string): ReturnType { return Promise.resolve([{ address: "20.91.151.2", family: 4 }]); } function blockedDnsLookup(address: string, family = 4): DnsLookupFn { return () => Promise.resolve([{ address, family }]); } 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, publicDnsLookup); 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, publicDnsLookup); 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, publicDnsLookup); await expect(adapter.query("SELECT 1")).rejects.toThrow(/mssql.*not installed/i); }); }); describe("FabricOneLakeAdapter.query — SSRF guard on connection_config.sqlEndpoint", () => { const CONFIG = { credentials: CREDS, sqlEndpoint: "https://my-endpoint.datawarehouse.fabric.microsoft.com/", database: "lh_test", }; beforeEach(() => { vi.resetModules(); vi.doUnmock("mssql"); }); function fakePoolFactory() { const queryMock = vi.fn(async () => ({ recordset: [{ ok: 1 }] })); const connectMock = vi.fn(async () => {}); const closeMock = vi.fn(async () => {}); class FakeConnectionPool { connect = connectMock; request() { return { input: vi.fn(), query: queryMock }; } close = closeMock; } return { FakeConnectionPool, queryMock, connectMock, closeMock }; } it("rejects a private/internal-IP sqlEndpoint before ever opening a TDS connection", async () => { const fetchMock = vi.fn(async () => jsonResponse({ access_token: "tok_ssrf", expires_in: 3600 })); const { FakeConnectionPool, connectMock } = fakePoolFactory(); vi.doMock("mssql", () => ({ default: { ConnectionPool: FakeConnectionPool } })); const { FabricOneLakeAdapter } = await import("@/src/adapters/fabric-onelake-adapter"); const { SsrfBlockedHostError } = await import("@/src/lib/security/ssrf-guard"); // An internal-looking hostname whose "DNS record" (mocked here) resolves // to an RFC1918 private address — the exact shape a caller-supplied // sqlEndpoint could take if pointed inward. const adapter = new FabricOneLakeAdapter( { ...CONFIG, sqlEndpoint: "internal-warehouse.corp.example.com" }, fetchMock as unknown as typeof fetch, blockedDnsLookup("10.1.2.3"), ); let caught: unknown; try { await adapter.query("SELECT 1"); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(SsrfBlockedHostError); expect((caught as Error).message).toMatch(/blocked_address_range/); // The guard must run before the outbound connection is opened at all — // fetch (AAD token exchange) and the TDS pool's connect() should never // have been reached. expect(fetchMock).not.toHaveBeenCalled(); expect(connectMock).not.toHaveBeenCalled(); }); it("rejects a literal loopback-IP sqlEndpoint (e.g. an attempt to reach 127.0.0.1) the same way", async () => { const fetchMock = vi.fn(async () => jsonResponse({ access_token: "tok_ssrf", expires_in: 3600 })); const { FakeConnectionPool, connectMock } = fakePoolFactory(); vi.doMock("mssql", () => ({ default: { ConnectionPool: FakeConnectionPool } })); const { FabricOneLakeAdapter } = await import("@/src/adapters/fabric-onelake-adapter"); const { SsrfBlockedHostError } = await import("@/src/lib/security/ssrf-guard"); const adapter = new FabricOneLakeAdapter( { ...CONFIG, sqlEndpoint: "http://127.0.0.1:1433" }, fetchMock as unknown as typeof fetch, // Real DNS resolution of a literal IP just returns that IP — this // fixture doesn't even need the injected mock to prove the point, but // stays consistent with the rest of this file's determinism. blockedDnsLookup("127.0.0.1"), ); await expect(adapter.query("SELECT 1")).rejects.toBeInstanceOf(SsrfBlockedHostError); expect(connectMock).not.toHaveBeenCalled(); }); it("does not false-block a normal external Fabric hostname — query still succeeds through the guard", async () => { const fetchMock = vi.fn(async () => jsonResponse({ access_token: "tok_ssrf_ok", expires_in: 3600 })); const { FakeConnectionPool, queryMock, connectMock } = fakePoolFactory(); 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, publicDnsLookup); const result = await adapter.query("SELECT 1"); expect(result.rows).toEqual([{ ok: 1 }]); expect(connectMock).toHaveBeenCalledTimes(1); expect(queryMock).toHaveBeenCalledTimes(1); }); });