fix(recovery): restore source removed by production documentation merge
This commit is contained in:
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* src/lib/security/ssrf-guard.ts
|
||||
* =================================
|
||||
* SSRF guard for outbound connections this backend opens to a caller-
|
||||
* supplied host. Today's one caller: `FabricOneLakeAdapter.getPool()`
|
||||
* (src/adapters/fabric-onelake-adapter.ts), whose `connection_config.
|
||||
* sqlEndpoint` arrives via `POST /api/0pt/sources/{sourceId}/query ->
|
||||
* source-query-service.ts` — a caller-supplied value that, before this
|
||||
* guard, only had its `http(s)://` scheme stripped (see `stripScheme` in
|
||||
* fabric-onelake-adapter.ts) before being handed straight to the `mssql`
|
||||
* TDS driver as the connection target. Nothing stopped a request from
|
||||
* pointing `sqlEndpoint` at 127.0.0.1, an RFC1918 address, or the
|
||||
* cloud-metadata link-local address (169.254.169.254) and having this
|
||||
* backend open a real outbound SQL connection there. That route requires a
|
||||
* valid Zitadel bearer token + tenant match (the P014 tenant guard,
|
||||
* src/http/tenant-guard.ts) today, so this is defense-in-depth rather than
|
||||
* the only control — worth closing anyway given it is the exact SSRF shape
|
||||
* found elsewhere in this estate (press0's fulltext-ingestion fetch path).
|
||||
*
|
||||
* The range-check logic (BLOCKED_V4_RANGES / isBlockedV4 / isBlockedV6) is
|
||||
* ported 1:1 from press0's `src/lib/security/ssrf-guard.ts`, built the same
|
||||
* night for the same class of bug against a `fetch()`-based URL there. This
|
||||
* module's public surface differs because the input here is a bare
|
||||
* `host[:port]` connection endpoint, not a fetchable URL — no scheme, path
|
||||
* or query is meaningful on the wire — so `extractConnectionHostname`
|
||||
* parses that shape instead of `new URL(...)`. The safety decision itself
|
||||
* is identical: resolve the hostname, reject any resolved address in a
|
||||
* private/loopback/link-local/cloud-metadata/unspecified range, and fail
|
||||
* closed (treat as unsafe) on resolution failure. Checking the *resolved*
|
||||
* address rather than string-matching the hostname is what stops a
|
||||
* public-looking hostname whose DNS record actually points at an internal
|
||||
* address — plain hostname allowlisting doesn't catch that.
|
||||
*
|
||||
* The DNS lookup is injectable (`lookupImpl`) — the same dependency-
|
||||
* injection pattern this file's caller already uses for `fetchImpl` — so
|
||||
* tests get a deterministic resolver instead of depending on real DNS.
|
||||
*/
|
||||
|
||||
import net from "node:net";
|
||||
import { promises as dns } from "node:dns";
|
||||
|
||||
export interface DnsLookupAddress {
|
||||
address: string;
|
||||
family: number;
|
||||
}
|
||||
|
||||
/** Matches the subset of `dns.promises.lookup(host, { all: true, verbatim: true })` this module needs. */
|
||||
export type DnsLookupFn = (hostname: string) => Promise<DnsLookupAddress[]>;
|
||||
|
||||
const defaultLookup: DnsLookupFn = (hostname) => dns.lookup(hostname, { all: true, verbatim: true });
|
||||
|
||||
const BLOCKED_V4_RANGES: ReadonlyArray<readonly [string, number]> = [
|
||||
["10.0.0.0", 8], // RFC1918 private
|
||||
["172.16.0.0", 12], // RFC1918 private
|
||||
["192.168.0.0", 16], // RFC1918 private
|
||||
["127.0.0.0", 8], // loopback
|
||||
["169.254.0.0", 16], // link-local (also cloud metadata: 169.254.169.254)
|
||||
["0.0.0.0", 8], // "this network" / unspecified
|
||||
];
|
||||
|
||||
function ipv4ToInt(ip: string): number {
|
||||
return (
|
||||
ip
|
||||
.split(".")
|
||||
.reduce((acc, octet) => (acc << 8) + (Number(octet) & 0xff), 0) >>> 0
|
||||
);
|
||||
}
|
||||
|
||||
export function isBlockedV4(ip: string): boolean {
|
||||
if (!net.isIPv4(ip)) return false;
|
||||
const ipInt = ipv4ToInt(ip);
|
||||
return BLOCKED_V4_RANGES.some(([base, bits]) => {
|
||||
const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
|
||||
return (ipInt & mask) === (ipv4ToInt(base) & mask);
|
||||
});
|
||||
}
|
||||
|
||||
function firstHextet(ip: string): number | null {
|
||||
const first = ip.split(":")[0];
|
||||
if (first === undefined) return null;
|
||||
if (first === "") return 0; // address starts with "::"
|
||||
const n = parseInt(first, 16);
|
||||
return Number.isNaN(n) ? null : n;
|
||||
}
|
||||
|
||||
export function isBlockedV6(ip: string): boolean {
|
||||
if (!net.isIPv6(ip)) return false;
|
||||
const lower = ip.toLowerCase();
|
||||
if (lower === "::1" || lower === "::") return true; // loopback / unspecified
|
||||
|
||||
// IPv4-mapped IPv6 (::ffff:a.b.c.d) — unwrap and re-check as v4, since this
|
||||
// is the standard way to smuggle a blocked v4 address past a v6-literal-
|
||||
// shaped filter.
|
||||
if (lower.startsWith("::ffff:")) {
|
||||
const v4 = lower.slice("::ffff:".length);
|
||||
if (net.isIPv4(v4)) return isBlockedV4(v4);
|
||||
}
|
||||
|
||||
const h = firstHextet(lower);
|
||||
if (h === null) return false;
|
||||
if (h >= 0xfc00 && h <= 0xfdff) return true; // fc00::/7 — unique local
|
||||
if (h >= 0xfe80 && h <= 0xfebf) return true; // fe80::/10 — link-local
|
||||
return false;
|
||||
}
|
||||
|
||||
function isBlockedAddress(address: string, family: number): boolean {
|
||||
if (family === 4) return isBlockedV4(address);
|
||||
if (family === 6) return isBlockedV6(address);
|
||||
return true; // unknown family — fail closed
|
||||
}
|
||||
|
||||
export type HostSafetyResult = { ok: true } | { ok: false; reason: string };
|
||||
|
||||
/**
|
||||
* Parses the bare connection-endpoint shape `FabricOneLakeConnectionConfig
|
||||
* .sqlEndpoint` takes: an optional `scheme://` prefix (already tolerated
|
||||
* elsewhere via `stripScheme`), a hostname or bracketed IPv6 literal, an
|
||||
* optional `:port`, and — defensively, even though a SQL endpoint should
|
||||
* never carry one — a path/query/fragment, which is discarded. Returns the
|
||||
* bare hostname, ready to resolve.
|
||||
*/
|
||||
export function extractConnectionHostname(rawEndpoint: string): string {
|
||||
let value = rawEndpoint.trim().replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "");
|
||||
value = value.split(/[/?#]/)[0] ?? "";
|
||||
|
||||
// Bracketed IPv6 literal, optionally with a port: "[::1]" or "[::1]:1433".
|
||||
const ipv6Match = value.match(/^\[([^\]]+)\](?::\d+)?$/);
|
||||
if (ipv6Match) return ipv6Match[1];
|
||||
|
||||
// A bare (unbracketed) IPv6 literal has no unambiguous port form — RFC
|
||||
// 3986 requires brackets for that precisely because the address itself is
|
||||
// full of colons. If the whole remaining value already parses as a valid
|
||||
// IPv6 address, return it as-is instead of trying to strip a "port" out
|
||||
// of one of its own colons (naive last-colon-splitting would truncate
|
||||
// "fe80::1" to "fe80:").
|
||||
if (net.isIP(value) === 6) return value;
|
||||
|
||||
const portMatch = value.match(/^(.+):(\d+)$/);
|
||||
if (portMatch) return portMatch[1];
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves `hostname` and checks every returned address against the blocked
|
||||
* ranges. Fails closed: DNS resolution errors or an empty answer are
|
||||
* treated as unsafe, same as press0's `isUrlSafeToFetch`.
|
||||
*/
|
||||
export async function checkHostnameSafety(
|
||||
hostname: string,
|
||||
lookupImpl: DnsLookupFn = defaultLookup,
|
||||
): Promise<HostSafetyResult> {
|
||||
if (!hostname) return { ok: false, reason: "empty_hostname" };
|
||||
|
||||
let addresses: DnsLookupAddress[];
|
||||
try {
|
||||
addresses = await lookupImpl(hostname);
|
||||
} catch {
|
||||
return { ok: false, reason: "dns_resolution_failed" };
|
||||
}
|
||||
|
||||
if (addresses.length === 0) {
|
||||
return { ok: false, reason: "dns_resolution_failed" };
|
||||
}
|
||||
|
||||
if (addresses.some((a) => isBlockedAddress(a.address, a.family))) {
|
||||
return { ok: false, reason: "blocked_address_range" };
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export class SsrfBlockedHostError extends Error {}
|
||||
|
||||
/**
|
||||
* Throws `SsrfBlockedHostError` if `rawEndpoint`'s hostname resolves to (or
|
||||
* literally is) a private/loopback/link-local/cloud-metadata/unspecified
|
||||
* address. Call this before opening the outbound connection — the check
|
||||
* itself never opens one.
|
||||
*/
|
||||
export async function assertConnectionHostIsSafe(rawEndpoint: string, lookupImpl?: DnsLookupFn): Promise<void> {
|
||||
const hostname = extractConnectionHostname(rawEndpoint);
|
||||
const result = await checkHostnameSafety(hostname, lookupImpl);
|
||||
if (!result.ok) {
|
||||
throw new SsrfBlockedHostError(
|
||||
`fabric_onelake_adapter: sqlEndpoint host "${hostname}" is blocked by the SSRF guard (${result.reason}) — ` +
|
||||
`refusing to open an outbound connection to a private/loopback/link-local/cloud-metadata/unspecified address`,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user