Three new, tenant-agnostic P0 capabilities: - 0pt.query_source: bounded, timeout/row-capped ad-hoc SQL query execution against registered database sources, via a Fabric/OneLake adapter (Azure AD credential-based mssql connection), with AUD0 audit events and an app/api/0pt/sources/[sourceId]/query endpoint. - 0pt.document_ocr (document capture + extraction): mailbox-based document intake via Microsoft Graph, OCR/field extraction via Azure Document Intelligence, with capture/extraction API endpoints and services that never fabricate extracted values. - 0pt.write_external_record (external writeback): a generic writeback-adapter contract plus a concrete Odoo bills adapter that matches partners via Fabric, backing an external-writeback-service for pushing records to downstream systems of record. Known interim gaps: - src/adapters/local-blob-store.ts is an interim ST0RE substitute pending the real ST0RE artifact-store integration. - mssql is used by the Fabric/OneLake adapter but deliberately not yet added to package.json (pending `pnpm add mssql` once the concurrent session's package.json/dependency changes settle). A separate, concurrently-active session has unrelated in-flight changes in this same working tree (data-platform catalog/lineage/feature-store, dataset quality, lakehouse/Iceberg docs, deploy scaffolding, package.json/ pnpm-lock.yaml updates, etc.) — none of that is touched or included here. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
159 lines
7.2 KiB
TypeScript
159 lines
7.2 KiB
TypeScript
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<string, unknown> | null = null;
|
|
|
|
class FakeConnectionPool {
|
|
constructor(config: Record<string, unknown>) {
|
|
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);
|
|
});
|
|
});
|