Files
0pt/src/adapters/fabric-onelake-adapter.ts
T

255 lines
11 KiB
TypeScript

/**
* src/adapters/fabric-onelake-adapter.ts
* ========================================
* Tenant-agnostic Azure Fabric / OneLake SQL analytics endpoint adapter
* (adapter_id = "fabric_onelake_sql" on a 0pt Source).
*
* Generalized from two proven patterns in v0-datahub:
* - scripts/ops/cloud-bootstrap.mjs `aadToken()` — Entra service-principal
* OAuth2 client-credentials flow (POST login.microsoftonline.com/{tenant}
* /oauth2/v2.0/token, grant_type=client_credentials).
* - lib/warehouse/fabric-sql.ts `buildConfig()` / `runFabricQuery()` — using
* that token as an `azure-active-directory-access-token` credential on a
* `mssql` TDS connection to the Fabric SQL analytics endpoint, and
* returning `result.recordset` as plain rows.
*
* Both of those originals hardcode ONE customer's tenant/client/secret/
* endpoint as module-level constants or env vars (AZ_SP_*, FABRIC_SQL_ENDPOINT,
* kv-pts-datahub, ...). Nothing here is hardcoded: tenantId, clientId,
* clientSecret, sqlEndpoint and database are always caller-supplied, because
* this is a SIAX platform capability — any SIAX customer registers their own
* Fabric/OneLake warehouse as a Source and queries it through this adapter.
*
* Dependency note: `mssql` (the TDS driver used by fabric-sql.ts) is NOT a
* declared dependency of this repo yet, and package.json/pnpm-lock.yaml
* already have unrelated uncommitted changes from a separate in-flight
* session — so it is deliberately not added here to avoid colliding with
* that work. The driver is loaded lazily via a non-literal dynamic import
* (see `loadDriver`) so:
* - this file has zero hard dependency at import/bundle time (Next.js/
* webpack cannot statically resolve a non-literal specifier, so it does
* not fail the build even though "mssql" isn't installed), and
* - `tsc --noEmit` does not attempt to resolve module types for it either
* (a widened `string`-typed specifier makes `import(...)` type as
* `Promise<any>` instead of triggering module resolution).
* Once `mssql` is added to package.json (`pnpm add mssql`), query() works
* against a real endpoint with no code change here. Until then, `query()`
* throws a clear, actionable error — see docs/P0_QUERY_SOURCE_FLOW.md.
*
* SSRF guard: `connection_config.sqlEndpoint` is caller-supplied per-request
* (via POST /api/0pt/sources/{sourceId}/query -> source-query-service.ts)
* and, until now, only had its scheme stripped before being handed to the
* `mssql` driver as the outbound connection target — no hostname allowlist
* or private/loopback/link-local/cloud-metadata check. `getPool()` now
* resolves and validates the endpoint via
* `src/lib/security/ssrf-guard.ts::assertConnectionHostIsSafe` *before*
* constructing the pool, closing that gap defense-in-depth (this route
* already requires a Zitadel bearer token + tenant match — see
* src/http/tenant-guard.ts).
*/
import { assertConnectionHostIsSafe, type DnsLookupFn } from "../lib/security/ssrf-guard";
const DEFAULT_SQL_SCOPE = "https://database.windows.net/.default";
const TOKEN_REFRESH_SKEW_MS = 60_000;
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
export interface FabricOneLakeCredentials {
/** Entra (Azure AD) tenant id the service-principal app registration lives in. */
tenantId: string;
/** Entra app (client) id — app-only, client-credentials grant. */
clientId: string;
/** Entra app client secret. Never logged, never persisted by this adapter. */
clientSecret: string;
}
export interface FabricOneLakeConnectionConfig {
credentials: FabricOneLakeCredentials;
/** Fabric SQL analytics endpoint host, e.g. "xxxx.datawarehouse.fabric.microsoft.com" (scheme optional). */
sqlEndpoint: string;
/** Target database / lakehouse SQL endpoint name, e.g. "lh_customer_datahub". */
database: string;
/** AAD scope used for the SQL token. Defaults to the Azure SQL / Fabric warehouse resource scope. */
scope?: string;
/** Per-request timeout passed to the mssql pool config. Default 30s. */
requestTimeoutMs?: number;
}
export interface FabricAccessToken {
accessToken: string;
expiresAtEpochMs: number;
}
export interface AdapterQueryResult<T = Record<string, unknown>> {
rows: T[];
rowCount: number;
durationMs: number;
}
/**
* OAuth2 client-credentials token acquisition for an Azure AD service
* principal — generalized 1:1 from v0-datahub's `aadToken()`. Exported
* standalone (not just as a private method) so it can be unit-tested and
* reused by callers that only need a token (e.g. to probe connectivity)
* without opening a SQL connection.
*/
export async function acquireFabricAccessToken(
credentials: FabricOneLakeCredentials,
scope: string = DEFAULT_SQL_SCOPE,
fetchImpl: typeof fetch = fetch,
): Promise<FabricAccessToken> {
const { tenantId, clientId, clientSecret } = credentials;
if (!tenantId || !clientId || !clientSecret) {
throw new Error("fabric_onelake_adapter: tenantId, clientId and clientSecret are all required");
}
const body = new URLSearchParams({
client_id: clientId,
client_secret: clientSecret,
grant_type: "client_credentials",
scope,
});
const res = await fetchImpl(`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body,
});
const json: { access_token?: string; expires_in?: number; error?: string; error_description?: string } = await res.json();
if (!res.ok || !json.access_token) {
throw new Error(
`fabric_onelake_adapter: AAD token request failed (scope=${scope}): ${json.error ?? res.status} ${json.error_description ?? ""}`.trim(),
);
}
const expiresInMs = (typeof json.expires_in === "number" ? json.expires_in : 3600) * 1000;
return { accessToken: json.access_token, expiresAtEpochMs: Date.now() + expiresInMs };
}
function stripScheme(endpoint: string): string {
return endpoint.replace(/^https?:\/\//, "").replace(/\/+$/, "");
}
/** Minimal shape of the pieces of the `mssql` module this adapter actually uses. Kept as a structural type, never imported from the real package (see file header). */
interface MssqlLike {
ConnectionPool: new (config: Record<string, unknown>) => {
connect(): Promise<unknown>;
request(): {
input(name: string, value: unknown): unknown;
query(text: string): Promise<{ recordset?: unknown[] }>;
};
close(): Promise<void>;
};
}
/**
* Adapter for Source.adapter_id === "fabric_onelake_sql". One instance holds
* one registered Source's connection config; nothing is shared across
* tenants/customers, and no config here ever falls back to an env var.
*/
export class FabricOneLakeAdapter {
private token: FabricAccessToken | null = null;
private pool: InstanceType<MssqlLike["ConnectionPool"]> | null = null;
constructor(
private readonly config: FabricOneLakeConnectionConfig,
private readonly fetchImpl: typeof fetch = fetch,
/**
* Injectable DNS resolver for the SSRF guard (see `getPool()`).
* Overridable for tests, same rationale as `fetchImpl`; defaults to the
* real `node:dns` resolver in production (undefined -> ssrf-guard's own
* default).
*/
private readonly dnsLookupImpl?: DnsLookupFn,
) {}
private async getToken(): Promise<string> {
if (this.token && this.token.expiresAtEpochMs - TOKEN_REFRESH_SKEW_MS > Date.now()) {
return this.token.accessToken;
}
this.token = await acquireFabricAccessToken(this.config.credentials, this.config.scope, this.fetchImpl);
return this.token.accessToken;
}
/**
* Loads the `mssql` TDS driver at call time via a *non-literal* specifier.
* `moduleName` is deliberately widened to `string` (not the literal
* `"mssql"`) so TypeScript types the result as `Promise<any>` instead of
* resolving module types, and so bundlers cannot statically inline the
* specifier into a build-time-resolved chunk. Overridable for tests.
*/
private async loadDriver(): Promise<MssqlLike> {
const moduleName: string = "mssql";
try {
const mod = await import(moduleName);
return (mod.default ?? mod) as MssqlLike;
} catch (err) {
throw new Error(
`fabric_onelake_adapter: "mssql" package is not installed/resolvable. Add it to package.json ` +
`(dependencies.mssql) to enable live Fabric SQL query execution. Original error: ` +
`${err instanceof Error ? err.message : String(err)}`,
);
}
}
private async getPool(): Promise<InstanceType<MssqlLike["ConnectionPool"]>> {
if (this.pool) return this.pool;
// SSRF guard: resolve + validate the caller-supplied sqlEndpoint before
// doing anything else — in particular before loadDriver()/getToken(), so
// a blocked target never gets as far as a real outbound connection
// attempt (or spends an AAD token exchange on a request that will be
// refused anyway). Throws SsrfBlockedHostError for a private/loopback/
// link-local/cloud-metadata/unspecified address, or an unresolvable host.
await assertConnectionHostIsSafe(this.config.sqlEndpoint, this.dnsLookupImpl);
const sql = await this.loadDriver();
const token = await this.getToken();
const poolConfig = {
server: stripScheme(this.config.sqlEndpoint),
database: this.config.database,
options: { encrypt: true, trustServerCertificate: false },
authentication: {
type: "azure-active-directory-access-token",
options: { token },
},
pool: { max: 1, min: 0, idleTimeoutMillis: 30_000 },
requestTimeout: this.config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
};
const pool = new sql.ConnectionPool(poolConfig);
await pool.connect();
this.pool = pool;
return pool;
}
/**
* Execute a query and return rows + timing. This adapter does NOT enforce
* row/time bounds itself — that is the job of the caller (see
* src/services/source-query-service.ts), which wraps this in a timeout and
* truncates the result for the synchronous path.
*/
async query<T = Record<string, unknown>>(queryText: string, params?: Record<string, unknown>): Promise<AdapterQueryResult<T>> {
const start = Date.now();
const pool = await this.getPool();
const request = pool.request();
if (params) {
for (const [key, value] of Object.entries(params)) {
request.input(key, value);
}
}
const result = await request.query(queryText);
const rows = (result.recordset ?? []) as T[];
return { rows, rowCount: rows.length, durationMs: Date.now() - start };
}
async close(): Promise<void> {
if (this.pool) {
await this.pool.close();
this.pool = null;
}
}
}
export function createFabricOneLakeAdapter(
config: FabricOneLakeConnectionConfig,
fetchImpl?: typeof fetch,
dnsLookupImpl?: DnsLookupFn,
): FabricOneLakeAdapter {
return new FabricOneLakeAdapter(config, fetchImpl, dnsLookupImpl);
}