@fntio/infra-client
Version:
Self-hosted AWS access portal: credential vending, target-account trust, and grant-driven private networking as CDK stacks and constructs.
255 lines (254 loc) • 12.6 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.MAX_CLAIM_LEN = exports.MAX_PROVIDERS = exports.MAX_CUSTOM_ATTRIBUTES = void 0;
exports.resolveFederation = resolveFederation;
exports.clientSecretReference = clientSecretReference;
exports.readAttributes = readAttributes;
exports.writeAttributes = writeAttributes;
exports.providerAttributeMapping = providerAttributeMapping;
exports.federationAppConfig = federationAppConfig;
const cdk = __importStar(require("aws-cdk-lib"));
const cognito = __importStar(require("aws-cdk-lib/aws-cognito"));
/** The keys CDK's AttributeMapping accepts (minus `custom`, which `claims` drives). Typed against
* CDK so a typo fails tsc, not a deploy. */
const STANDARD_ATTRIBUTE_KEYS = [
"address",
"birthdate",
"email",
"familyName",
"gender",
"givenName",
"locale",
"middleName",
"fullname",
"nickname",
"phoneNumber",
"profilePicture",
"preferredUsername",
"profilePage",
"timezone",
"lastUpdateTime",
"website",
];
const isStandardAttributeKey = (k) => STANDARD_ATTRIBUTE_KEYS.includes(k);
/** Names Cognito reserves for its built-in social providers and itself. */
const RESERVED_NAMES = new Set(["COGNITO", "Facebook", "Google", "LoginWithAmazon", "SignInWithApple"].map((n) => n.toLowerCase()));
// Cognito (and CDK) require 3–32 characters for a provider name.
const NAME_RE = /^[A-Za-z][A-Za-z0-9-]{2,31}$/;
// `custom:` + 1–20 chars; lowercase so the key doubles as a JSON/env-safe identifier.
const CLAIM_KEY_RE = /^[a-z][a-z0-9_]{0,19}$/;
const SCOPE_RE = /^[A-Za-z0-9._:/-]+$/;
const SECRET_ARN_RE = /^arn:aws(?:-[a-z]+)*:secretsmanager:([a-z0-9-]+):\d{12}:secret:[^\s]+$/;
// Labels only (an intranet host may be a single label); no scheme, path or port.
const HOST_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
/** Standard attribute names a custom claim must not shadow (confusing in the token). */
const STANDARD_ATTRIBUTE_NAMES = new Set([
"address", "birthdate", "email", "email_verified", "family_name", "gender", "given_name", "locale",
"middle_name", "name", "nickname", "phone_number", "phone_number_verified", "picture",
"preferred_username", "profile", "sub", "updated_at", "website", "zoneinfo", "identities",
]);
exports.MAX_CUSTOM_ATTRIBUTES = 50;
/** Cognito links at most 5 identities to a user; each provider may cost two (the invite-time
* email link plus the trigger's subject link on a mismatch), so two providers is the safe ceiling. */
exports.MAX_PROVIDERS = 2;
exports.MAX_CLAIM_LEN = 2048;
const DEFAULT_CLAIM_LEN = 256;
const DEFAULT_SCOPES = ["openid", "profile", "email"];
/** Validate + default `loginMethods.federation`; `undefined` when absent or empty. Every
* rule here fails a deploy or a sign-in later, silently. */
function resolveFederation(federation, region) {
if (!federation || federation.length === 0)
return undefined;
if (federation.length > exports.MAX_PROVIDERS) {
throw new Error(`loginMethods.federation lists ${federation.length} providers; at most ${exports.MAX_PROVIDERS} are supported — Cognito links at most 5 identities to one user and each provider may use two. Open an issue if you need more.`);
}
const providers = [];
const seenNames = new Set();
for (const p of federation) {
const at = `loginMethods.federation["${String(p?.name)}"]`;
if (typeof p?.name !== "string" || !NAME_RE.test(p.name)) {
throw new Error(`${at}.name must be 3–32 letters, digits or "-" and start with a letter (it names the Cognito provider and prefixes auto-created usernames).`);
}
if (RESERVED_NAMES.has(p.name.toLowerCase())) {
throw new Error(`${at}.name "${p.name}" is reserved by Cognito for its built-in providers.`);
}
if (seenNames.has(p.name.toLowerCase())) {
throw new Error(`${at}: provider names must be unique (case-insensitive).`);
}
seenNames.add(p.name.toLowerCase());
if (p.type !== "oidc") {
throw new Error(`${at}.type "${String(p.type)}" is not supported yet — only "oidc" is.`);
}
let issuer;
try {
issuer = new URL(p.issuerUrl);
}
catch {
throw new Error(`${at}.issuerUrl ("${p.issuerUrl}") is not a URL.`);
}
if (issuer.protocol !== "https:" || issuer.search || issuer.hash || issuer.username) {
throw new Error(`${at}.issuerUrl must be a plain https:// URL (no query, fragment or credentials).`);
}
if (!p.clientId?.trim()) {
throw new Error(`${at}.clientId is required.`);
}
const arn = SECRET_ARN_RE.exec(p.clientSecretArn ?? "");
if (!arn) {
throw new Error(`${at}.clientSecretArn must be a full Secrets Manager secret ARN.`);
}
if (arn[1] !== region) {
throw new Error(`${at}.clientSecretArn is in ${arn[1]} but the deployment is in ${region} — CloudFormation only resolves secrets from the stack's own region.`);
}
const scopes = [...(p.scopes ?? DEFAULT_SCOPES)];
if (!scopes.includes("openid")) {
throw new Error(`${at}.scopes must include "openid" — without it the provider issues no ID token.`);
}
for (const s of scopes) {
if (!SCOPE_RE.test(s))
throw new Error(`${at}.scopes: "${s}" is not a valid scope name.`);
}
const mapping = {};
for (const [key, claim] of Object.entries({ email: "email", ...(p.attributeMapping ?? {}) })) {
if (!isStandardAttributeKey(key)) {
throw new Error(`${at}.attributeMapping."${key}" is not a standard attribute — one of ${STANDARD_ATTRIBUTE_KEYS.join(", ")}.`);
}
if (typeof claim !== "string" || !claim.trim()) {
throw new Error(`${at}.attributeMapping.${key} must name a provider claim.`);
}
mapping[key] = claim.trim();
}
if (!mapping.email) {
throw new Error(`${at}.attributeMapping.email cannot be empty — email links federated sign-ins to invited users.`);
}
const claims = [];
for (const [key, c] of Object.entries(p.claims ?? {})) {
if (!CLAIM_KEY_RE.test(key)) {
throw new Error(`${at}.claims."${key}": keys are 1–20 chars of a–z, 0–9, "_" starting with a letter.`);
}
if (STANDARD_ATTRIBUTE_NAMES.has(key)) {
throw new Error(`${at}.claims."${key}" shadows a standard attribute — pick another key.`);
}
if (!c?.from?.trim()) {
throw new Error(`${at}.claims.${key}.from must name the provider claim to copy.`);
}
const maxLen = c.maxLen ?? DEFAULT_CLAIM_LEN;
if (!Number.isInteger(maxLen) || maxLen < 1 || maxLen > exports.MAX_CLAIM_LEN) {
throw new Error(`${at}.claims.${key}.maxLen must be an integer 1–${exports.MAX_CLAIM_LEN}.`);
}
const label = (c.label ?? key).trim();
if (!label || label.length > 40) {
throw new Error(`${at}.claims.${key}.label must be 1–40 characters.`);
}
claims.push({ key, from: c.from.trim(), maxLen, label });
}
const hosts = [issuer.hostname.toLowerCase()];
for (const h of p.allowedHosts ?? []) {
const host = h.trim().toLowerCase();
if (!HOST_RE.test(host)) {
throw new Error(`${at}.allowedHosts: "${h}" is not a hostname (no scheme, path or port).`);
}
if (!hosts.includes(host))
hosts.push(host);
}
providers.push({
name: p.name,
label: (p.label ?? p.name).trim() || p.name,
issuerUrl: p.issuerUrl,
clientId: p.clientId.trim(),
clientSecretArn: p.clientSecretArn,
clientSecretVersionId: p.clientSecretVersionId?.trim() || undefined,
scopes,
attributeMapping: mapping,
claims,
hosts,
});
}
const byKey = new Map();
for (const p of providers) {
for (const c of p.claims) {
const prev = byKey.get(c.key);
byKey.set(c.key, prev ? { ...prev, maxLen: Math.max(prev.maxLen, c.maxLen) } : c);
}
}
if (byKey.size > exports.MAX_CUSTOM_ATTRIBUTES) {
throw new Error(`loginMethods.federation declares ${byKey.size} distinct claim keys; Cognito allows ${exports.MAX_CUSTOM_ATTRIBUTES} custom attributes per pool.`);
}
return { providers, claimKeys: [...byKey.values()] };
}
/** `{{resolve:secretsmanager:…}}` for the provider's client secret — resolved by CloudFormation
* at deploy, so the plaintext is in neither the synthesized template nor the repo. */
function clientSecretReference(p) {
return cdk.SecretValue.secretsManager(p.clientSecretArn, {
versionId: p.clientSecretVersionId,
}).unsafeUnwrap();
}
// Listing attributes REPLACES Cognito's all-attributes default, so every standard one stays
// listed; the *_verified flags are read-only by Cognito's rule.
const STANDARD_MASK = Object.fromEntries(STANDARD_ATTRIBUTE_KEYS.map((k) => [k, true]));
/** Every standard attribute plus the mapped claims — what a client may read into ID tokens. */
function readAttributes(claimKeys) {
return new cognito.ClientAttributes()
.withStandardAttributes({ ...STANDARD_MASK, emailVerified: true, phoneNumberVerified: true })
.withCustomAttributes(...claimKeys.map((c) => c.key));
}
/** Every standard attribute, plus the mapped claims ONLY for the federation client: Cognito
* writes a mapped attribute through the signing-in client, and that same permission lets a
* user's self-service call set it — so no client a local session can hold gets it. */
function writeAttributes(claimKeys, opts) {
const attrs = new cognito.ClientAttributes().withStandardAttributes(STANDARD_MASK);
return opts.claims ? attrs.withCustomAttributes(...claimKeys.map((c) => c.key)) : attrs;
}
/** CDK AttributeMapping for one provider: the standard keys plus `custom:<key>` for each claim. */
function providerAttributeMapping(p) {
const standard = {};
for (const [key, claim] of Object.entries(p.attributeMapping)) {
if (claim && isStandardAttributeKey(key))
standard[key] = cognito.ProviderAttribute.other(claim);
}
const custom = p.claims.length
? Object.fromEntries(p.claims.map((c) => [`custom:${c.key}`, cognito.ProviderAttribute.other(c.from)]))
: undefined;
return { ...standard, ...(custom ? { custom } : {}) };
}
/** What config.json carries — public ids only (the frontend's login buttons + labels, the
* desktop shell's navigation allowlist). */
function federationAppConfig(f, clientId) {
return {
clientId,
providers: f.providers.map((p) => ({ name: p.name, label: p.label, hosts: [...p.hosts] })),
claims: f.claimKeys.map((c) => ({ key: c.key, label: c.label })),
};
}