UNPKG

@fntio/infra-client

Version:

Self-hosted AWS access portal: credential vending, target-account trust, and grant-driven private networking as CDK stacks and constructs.

226 lines (225 loc) • 10.8 kB
"use strict"; /** Synth-time site validation. A site routes by IP alone, so CIDR overlap * WITHIN a site is silently ambiguous; overlap ACROSS sites is the point. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveDevShares = resolveDevShares; exports.sitePriority = sitePriority; exports.assertDisjointTailnetRanges = assertDisjointTailnetRanges; exports.assertValidResourcePrefix = assertValidResourcePrefix; exports.resolveSites = resolveSites; const naming_1 = require("../lambdacode/network/naming"); /** A bad cap must fail synth — the API clamps silently, which would hide the typo until a user hit it. */ function resolveDevShares(cfg) { if (!cfg) return undefined; const max = cfg.maxDurationHours ?? 8; if (!Number.isInteger(max) || max < 1 || max > 72) { throw new Error(`network.devShares.maxDurationHours must be an integer from 1 to 72 (got ${String(max)}).`); } const perOwner = cfg.maxActiveSharesPerOwner ?? 10; if (!Number.isInteger(perOwner) || perOwner < 1 || perOwner > 200) { throw new Error(`network.devShares.maxActiveSharesPerOwner must be an integer from 1 to 200 (got ${String(perOwner)}).`); } return { enabled: cfg.enabled === true, maxDurationHours: max, allowGroupTargets: cfg.allowGroupTargets !== false, maxActiveSharesPerOwner: perOwner, }; } /** FNV-1a of the id folded into 100–989 — depends on nothing but the id, so * a site keeps its priority for life. */ function sitePriority(id) { let h = 0x811c9dc5; for (let i = 0; i < id.length; i++) { h ^= id.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; } return 100 + (h % 890); } /** Strict IPv4 "a.b.c.d/nn" with host bits zeroed. A typo must not synth. */ function parseCidr(cidr, owner) { const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/.exec(cidr); if (!m) { throw new Error(`${owner}: "${cidr}" is not an IPv4 CIDR (a.b.c.d/nn).`); } const octets = m.slice(1, 5).map(Number); const prefix = Number(m[5]); if (octets.some((o) => o > 255) || prefix > 32) { throw new Error(`${owner}: "${cidr}" is not a valid IPv4 CIDR.`); } const ip = ((octets[0] << 24) | (octets[1] << 16) | (octets[2] << 8) | octets[3]) >>> 0; const mask = prefix === 0 ? 0 : (~0 << (32 - prefix)) >>> 0; return { base: (ip & mask) >>> 0, prefix }; } function overlaps(a, b) { const shorter = Math.min(a.prefix, b.prefix); const mask = shorter === 0 ? 0 : (~0 << (32 - shorter)) >>> 0; return ((a.base & mask) >>> 0) === ((b.base & mask) >>> 0); } /** Throws when ranges from DIFFERENT owners overlap; one owner's may nest * (same connector — not ambiguous). Callers scope this to ONE site. */ function assertDisjointTailnetRanges(owners) { const flat = owners.flatMap((o) => o.cidrs.map((cidr) => ({ owner: o.label, cidr, ...parseCidr(cidr, o.label) }))); for (let i = 0; i < flat.length; i++) { for (let j = i + 1; j < flat.length; j++) { const a = flat[i]; const b = flat[j]; if (a.owner === b.owner) continue; if (overlaps(a, b)) { throw new Error(`Tailnet CIDR overlap within one site: ${a.owner} (${a.cidr}) ` + `collides with ${b.owner} (${b.cidr}). A site routes by IP alone — ` + `traffic for the shared range would silently reach only one of ` + `them. Renumber one VPC, or move one of them to a different site.`); } } } } /** ≤15 chars: the longest derived Lambda name (per-site minter with a * 20-char site id) must fit AWS's 64-char limit. */ function assertValidResourcePrefix(prefix) { if (!/^[a-z][a-z0-9-]{0,14}$/.test(prefix)) { throw new Error(`resourcePrefix "${prefix}" is invalid — lowercase slug, letter-first, ` + `max 15 chars (longer would overflow Lambda's 64-char function-name ` + `limit on per-site minters). It is SET-ONCE: never change it after ` + `the first deploy.`); } } const ACCOUNT_RE = /^\d{12}$/; const IPV4_RE = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; /** AWS region names: eu-west-1, us-gov-west-1, ap-southeast-2. */ const REGION_RE = /^[a-z]{2}(-[a-z]+)+-\d+$/; /** Validate `network.sites` → deployment-ready sites, sorted by id. * `extraRangesByAccount` injects ranges CDK only knows elsewhere (testbed). */ function resolveSites(network, extraRangesByAccount = {}) { const ids = Object.keys(network.sites); if (ids.length === 0) { throw new Error("network.sites must define at least one site."); } if (!/^[a-z][a-z0-9-]*$/.test(network.subdomain)) { throw new Error(`network.subdomain "${network.subdomain}" must be a DNS label.`); } const accountToSite = new Map(); const priorityToSite = new Map(); const resolved = []; for (const id of [...ids].sort()) { if (!naming_1.SITE_ID_RE.test(id)) { throw new Error(`Site id "${id}" is invalid — lowercase DNS label, letter-first, ` + `max 20 chars. It becomes the permanent hostname <id>.` + `${network.subdomain}.${network.zoneName}.`); } const site = network.sites[id]; if (!site.accounts.length) { throw new Error(`Site "${id}" lists no accounts.`); } for (const account of site.accounts) { if (!ACCOUNT_RE.test(account)) { throw new Error(`Site "${id}": "${account}" is not a 12-digit account id.`); } const prior = accountToSite.get(account); if (prior) { throw new Error(`Account ${account} appears in sites "${prior}" AND "${id}" — an ` + `account belongs to exactly one site (its connector can only ` + `enroll into one control plane).`); } accountToSite.set(account, id); } const connectorVpcs = {}; for (const [account, entry] of Object.entries(site.connectorVpcs ?? {})) { if (!site.accounts.includes(account)) { throw new Error(`Site "${id}": connectorVpcs lists account ${account}, which is ` + `missing from the site's accounts list.`); } const where = `Site "${id}": connectorVpcs["${account}"]`; const list = (Array.isArray(entry) ? entry : [entry]); if (!list.length) { throw new Error(`${where} is an empty list — give it at least one VPC or drop the key.`); } const names = new Set(); const vpcIds = new Set(); let unnamed = 0; for (const vpc of list) { if (vpc.name !== undefined) (0, naming_1.assertConnectorName)(vpc.name, where); if (vpc.region !== undefined && !REGION_RE.test(vpc.region)) { throw new Error(`${where}.region "${vpc.region}" is not an AWS region name ` + `(e.g. eu-west-1). Omit it when the VPC is in the hub's region.`); } if (vpc.name === undefined) { if (++unnamed > 1) { throw new Error(`${where} lists more than one VPC without a name — every VPC ` + `of an account but one needs a name.`); } } else if (names.has(vpc.name)) { throw new Error(`${where} names two VPCs "${vpc.name}".`); } else { names.add(vpc.name); } if (vpcIds.has(vpc.vpcId)) { throw new Error(`${where} lists ${vpc.vpcId} twice.`); } vpcIds.add(vpc.vpcId); } connectorVpcs[account] = [...list]; } // A minter grant must belong to an account of THIS site — a foreign one // could enroll a connector into the wrong routing domain. for (const principal of site.connectorAccounts ?? []) { const arn = /^arn:aws:iam::(\d{12}):/.exec(principal); const account = arn ? arn[1] : ACCOUNT_RE.test(principal) ? principal : null; if (!account || !site.accounts.includes(account)) { throw new Error(`Site "${id}": connectorAccounts entry "${principal}" must be a ` + `12-digit account id or role ARN belonging to one of the site's ` + `accounts.`); } } for (const [domain, ips] of Object.entries(site.splitDns ?? {})) { for (const ip of ips) { const m = IPV4_RE.exec(ip); if (!m || m.slice(1).some((o) => Number(o) > 255)) { throw new Error(`Site "${id}": splitDns["${domain}"] value "${ip}" must be a ` + `bare IPv4 address — anything else would freeze the site's ` + `ACL policy at runtime.`); } } } // The site invariant itself: no two VPCs inside it may overlap — an // account's own VPCs included (each is its own owner). const owners = Object.entries(connectorVpcs).flatMap(([account, list]) => list.map((c) => ({ label: `site "${id}" account ${account} (${c.vpcId})`, cidrs: [...c.routes], }))); for (const [account, extra] of Object.entries(extraRangesByAccount)) { if (site.accounts.includes(account)) owners.push(extra); } assertDisjointTailnetRanges(owners); const priority = site.albPriority ?? sitePriority(id); if (!Number.isInteger(priority) || priority < 100 || priority > 989) { throw new Error(`Site "${id}": albPriority must be an integer in 100–989.`); } const holder = priorityToSite.get(priority); if (holder) { throw new Error(`Sites "${holder}" and "${id}" hash to the same ALB rule priority ` + `(${priority}) — set albPriority on the NEW site (never renumber ` + `a deployed one).`); } priorityToSite.set(priority, id); const fqdn = `${id}.${network.subdomain}.${network.zoneName}`; resolved.push({ id, displayName: site.displayName ?? id, fqdn, controlUrl: `https://${fqdn}`, priority, accounts: site.accounts, connectorAccounts: site.connectorAccounts ?? [], splitDns: site.splitDns ?? {}, connectorVpcs, }); } return resolved; }