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.

238 lines (237 loc) • 11.9 kB
"use strict"; 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.OidcIssuer = void 0; const crypto = __importStar(require("crypto")); const fs = __importStar(require("fs")); const path = __importStar(require("path")); const cdk = __importStar(require("aws-cdk-lib")); const constructs_1 = require("constructs"); const cloudfront = __importStar(require("aws-cdk-lib/aws-cloudfront")); const origins = __importStar(require("aws-cdk-lib/aws-cloudfront-origins")); const iam = __importStar(require("aws-cdk-lib/aws-iam")); const kms = __importStar(require("aws-cdk-lib/aws-kms")); const logs = __importStar(require("aws-cdk-lib/aws-logs")); const route53 = __importStar(require("aws-cdk-lib/aws-route53")); const targets = __importStar(require("aws-cdk-lib/aws-route53-targets")); const s3 = __importStar(require("aws-cdk-lib/aws-s3")); const cr = __importStar(require("aws-cdk-lib/custom-resources")); const app_function_1 = require("./app-function"); const pkg_paths_1 = require("../pkg-paths"); const objects_1 = require("../../lambdacode/issuer/objects"); /** KMS signing key(s) plus the discovery document + JWKS as static objects: * a deploy-time custom resource writes them into a private bucket that * CloudFront serves on the stable custom domain. Nothing runs when STS * fetches them. The domain IS the issuer identity — recreating the * construct never changes it. */ class OidcIssuer extends constructs_1.Construct { /** Signs the vended web-identity tokens. Grant kms:Sign to whoever mints. */ signingKey; /** The public issuer URL — the `iss` claim of every minted token. Stable. */ url; constructor(scope, id, props) { super(scope, id); this.url = `https://${props.domainName}`; // Outside the zone the alias record can't be written. if (props.domainName !== props.zoneName && !props.domainName.endsWith(`.${props.zoneName}`)) { throw new Error(`issuer.domainName (${props.domainName}) must be issuer.zoneName or ` + `a subdomain of it (${props.zoneName}).`); } if (!props.keyVersions.includes(props.signerVersion)) { throw new Error(`issuer.signerVersion ${props.signerVersion} is not in keyVersions ` + `[${props.keyVersions}] — the active signer's key must be published ` + `in the JWKS or STS will reject every token.`); } if (new Set(props.keyVersions).size !== props.keyVersions.length) { throw new Error(`issuer.keyVersions has duplicates: [${props.keyVersions}]`); } // Explicit role so the key policies below can name it — an implicit // function role would come to life AFTER the keys. Keeps the logical id // of the retired JWKS Lambda's role, so no key policy changes principal. const publisherRole = new iam.Role(this, "JwksRole", { assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"), managedPolicies: [ iam.ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole"), ], }); // Replaces the default policy — its IAM delegation lets any principal // grant ITSELF kms:Sign and mint forgeable tokens. Named principals only. const keyPolicy = (allowSign) => new iam.PolicyDocument({ statements: [ new iam.PolicyStatement({ sid: "KeyAdministration", principals: [new iam.AccountRootPrincipal()], actions: [ "kms:Create*", "kms:Describe*", "kms:Enable*", "kms:List*", "kms:Put*", "kms:Update*", "kms:Revoke*", "kms:Disable*", "kms:Get*", "kms:Delete*", "kms:TagResource", "kms:UntagResource", "kms:ScheduleKeyDeletion", "kms:CancelKeyDeletion", ], resources: ["*"], }), new iam.PolicyStatement({ sid: "JwksRead", principals: [publisherRole], actions: ["kms:GetPublicKey"], resources: ["*"], }), ...(allowSign ? [ new iam.PolicyStatement({ sid: "VendSign", principals: [props.signerRole], actions: ["kms:Sign"], resources: ["*"], }), ] : []), ], }); const keysByVersion = new Map(); for (const version of props.keyVersions) { // Version 1 keeps the original "SigningKey" logical id so introducing // versioning never replaced the deployed key. const id = version === 1 ? "SigningKey" : `SigningKeyV${version}`; const key = new kms.Key(this, id, { keySpec: kms.KeySpec.RSA_2048, keyUsage: kms.KeyUsage.SIGN_VERIFY, // Older generations verify-only: nothing may Sign with them. policy: keyPolicy(version === props.signerVersion), // prod: RETAIN — deleting a signer invalidates every outstanding // vended token at once. removalPolicy: props.prod ? cdk.RemovalPolicy.RETAIN : cdk.RemovalPolicy.DESTROY, }); // A separate resource: adding it never replaces the key or its policy. key.addAlias(`alias/${props.resourcePrefix}-oidc-signing-v${version}`); keysByVersion.set(version, key); } this.signingKey = keysByVersion.get(props.signerVersion); // Contents are regenerated by every deploy — nothing to retain. const bucket = new s3.Bucket(this, "Bucket", { blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, enforceSSL: true, removalPolicy: cdk.RemovalPolicy.DESTROY, autoDeleteObjects: true, lifecycleRules: [{ abortIncompleteMultipartUploadAfter: cdk.Duration.days(7) }], serverAccessLogsBucket: props.accessLogsBucket, serverAccessLogsPrefix: props.accessLogsBucket && "s3/issuer/", }); // kms:GetPublicKey comes from the key policies' JwksRead statement alone. const publisher = new app_function_1.AppFunction(this, "Publisher", { description: "Deploy-time helper: publishes the credential issuer's discovery document and public keys.", asset: "issuer-publish", handler: "handler", role: publisherRole, timeout: cdk.Duration.seconds(60), }); // Exactly the three objects — no prefix wildcard. publisherRole.addToPrincipalPolicy(new iam.PolicyStatement({ actions: ["s3:PutObject"], resources: Object.values(objects_1.ISSUER_OBJECTS).map((key) => bucket.arnForObjects(key)), })); const provider = new cr.Provider(this, "PublishProvider", { onEventHandler: publisher, logGroup: new logs.LogGroup(this, "PublishProviderLogs", { retention: logs.RetentionDays.THREE_MONTHS, }), }); const documents = new cdk.CustomResource(this, "Documents", { serviceToken: provider.serviceToken, resourceType: "Custom::OidcIssuerDocuments", properties: { Bucket: bucket.bucketName, // Fixed value, never derived from the request host — the identity // can't drift even if the fronting changes. Issuer: this.url, // ALL generations — tokens signed before a rotation flip stay // verifiable. KeyIds: props.keyVersions.map((v) => keysByVersion.get(v).keyId), // Nothing else ever rewrites the objects, so a publisher change must // be an Update on its own. PublisherHash: crypto .createHash("sha256") .update(fs.readFileSync(path.join((0, pkg_paths_1.packageRoot)(), "assets", "issuer-publish", "index.js"))) .digest("hex"), }, }); const distribution = new cloudfront.Distribution(this, "Distribution", { comment: "OIDC issuer (discovery document + JWKS)", domainNames: [props.domainName], certificate: props.certificate, minimumProtocolVersion: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2021, webAclId: props.webAclArn, defaultRootObject: objects_1.ISSUER_OBJECTS.index, ...(props.accessLogsBucket ? { enableLogging: true, logBucket: props.accessLogsBucket, logFilePrefix: "cloudfront/issuer/", logIncludesCookies: false } : {}), defaultBehavior: { origin: origins.S3BucketOrigin.withOriginAccessControl(bucket), viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.HTTPS_ONLY, allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD, // Honors the objects' Cache-Control (5 minutes). cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED, responseHeadersPolicy: cloudfront.ResponseHeadersPolicy.SECURITY_HEADERS, }, }); const zone = route53.HostedZone.fromHostedZoneAttributes(this, "Zone", { hostedZoneId: props.hostedZoneId, zoneName: props.zoneName, }); const target = route53.RecordTarget.fromAlias(new targets.CloudFrontTarget(distribution)); // "AliasRecord" is the API Gateway alias's logical id — CloudFormation // updates the record in place, and only once the documents exist. for (const [id, Record] of [ ["AliasRecord", route53.ARecord], ["AliasRecordV6", route53.AaaaRecord], ]) { new Record(this, id, { zone, recordName: props.domainName, target }) .node.addDependency(documents); } } } exports.OidcIssuer = OidcIssuer;