masterplan-lock / check (push) Successful in 7s
CI (SIAX Cloud) / security (push) Successful in 19s
Security Scan (SIAX Cloud) / security (push) Successful in 27s
CI (SIAX Cloud) / quality (push) Successful in 33s
CI (SIAX Cloud) / integration (push) Successful in 46s
masterplan-lock / check (pull_request) Successful in 4s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 16s
CI (SIAX Cloud) / security (pull_request) Successful in 17s
CI (SIAX Cloud) / quality (pull_request) Successful in 35s
CI (SIAX Cloud) / integration (pull_request) Successful in 1m11s
connection_config.sqlEndpoint on POST /api/0pt/sources/{sourceId}/query
was passed straight from the request body to the mssql TDS driver as the
outbound connection target, with only its http(s):// scheme stripped —
no hostname allowlist or private/loopback/link-local/cloud-metadata
guard. This route already requires a Zitadel bearer token + tenant match
(P014 tenant guard), so this was not anonymously exploitable, but it is
the exact SSRF shape found and exploited-in-principle elsewhere in this
estate tonight (press0), so it's worth closing as defense-in-depth.
Adds src/lib/security/ssrf-guard.ts: resolves the endpoint's hostname
and rejects any address in a private/loopback/link-local/cloud-metadata/
unspecified range (RFC1918, 127.0.0.0/8, 169.254.0.0/16 incl. the
169.254.169.254 metadata address, ::1, fc00::/7, fe80::/10, IPv4-mapped
IPv6), failing closed on DNS resolution errors. The range-check logic is
ported 1:1 from press0's src/lib/security/ssrf-guard.ts built the same
night for the same bug class against a fetch()-based URL there; this
module's surface differs because sqlEndpoint is a bare host[:port], not
a fetchable URL. The DNS lookup is injectable (mirrors this adapter's
existing fetchImpl pattern) so tests are hermetic.
FabricOneLakeAdapter.getPool() now calls the guard before loadDriver()/
getToken()/opening the TDS pool, so a blocked target never reaches a
real outbound connection attempt or spends an AAD token exchange.
Tests: new tests/p0/fabric-onelake-ssrf-guard.test.ts unit-tests the
guard module directly (range boundaries, IPv4-mapped-IPv6 bypass
attempt, fail-closed on DNS failure/empty answer). New adapter-level
tests in tests/p0/fabric-onelake-adapter.test.ts prove (a) a
private-IP-resolving sqlEndpoint is rejected before fetch/connect is
ever called, (b) a literal loopback sqlEndpoint is rejected the same
way, and (c) a normal external Fabric hostname still passes the guard
and completes the query — the guard doesn't false-block legitimate
targets. Existing adapter tests are updated to inject a deterministic
DNS resolver so they stay hermetic instead of depending on real DNS.
Full suite: 997 passed, 0 failed, 184 skipped (self-skipping realinfra
tests with no live backend this run). typecheck and lint clean on all
touched files.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
272 lines
12 KiB
TypeScript
272 lines
12 KiB
TypeScript
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<DnsLookupFn> {
|
|
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<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, 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);
|
|
});
|
|
});
|