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.

301 lines (300 loc) • 15.6 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.DataStack = void 0; const cdk = __importStar(require("aws-cdk-lib")); const dynamodb = __importStar(require("aws-cdk-lib/aws-dynamodb")); const iam = __importStar(require("aws-cdk-lib/aws-iam")); const s3 = __importStar(require("aws-cdk-lib/aws-s3")); const route53 = __importStar(require("aws-cdk-lib/aws-route53")); const ses = __importStar(require("aws-cdk-lib/aws-ses")); const app_table_1 = require("./constructs/app-table"); /** The DynamoDB tables — separate from CredsStack so durable data outlives * compute redeploys. */ class DataStack extends cdk.Stack { accountsTable; rolesTable; requestsTable; auditTable; groupsTable; resourcesTable; /** Access model v2: grants stored exactly as granted — principal → target, * plus member#/pref# rows; `byTarget` = who holds X. */ accessTable; revocationsTable; /** clientId → name + rotation state; grants live in Access under `user#<clientId>`. */ serviceUsersTable; /** Personal access tokens: tokenId → owner, scopes, expiry and the SHA-256 of the secret (never the secret). * Always present, like the plugin catalog, so switching the feature never adds or removes an export. */ tokensTable; /** Plugin catalog (Epic 5): deployment-written records, keyed by pluginId. Always present so enabling or * disabling the feature never adds or removes a cross-stack export; unused until `plugins.enabled`. */ pluginCatalogTable; /** Plugin UIs under immutable `<id>/<version>-<hash>/` prefixes: uploaded by CredsStack's registrations * (so a record can depend on its upload), served by WebStack's /plugin-assets/* behavior, never touched * by the site deploy's prune. */ pluginAssetsBucket; /** Server-access logs of every hub bucket and the standard logs of both CloudFront distributions * (Security Hub S3.9, CloudFront.5). ACL-based ownership: that is what CloudFront's standard logging * and S3 log delivery write with, and it keeps the other stacks free of a cross-stack bucket-policy * reference back into this one. The one bucket that logs nowhere — AWS says to suppress S3.9 on it. */ accessLogsBucket; constructor(scope, id, props) { super(scope, id, props); const prod = props?.prod ?? false; if (props?.email) { const { hostedZoneId, zoneName, dmarcReportEmail } = props.email; const zone = route53.HostedZone.fromHostedZoneAttributes(this, "EmailZone", { hostedZoneId, zoneName, }); // Auto-creates DKIM + MAIL FROM records. SES verifies async (minutes) — // the first CredsStack deploy can race it (README "Email deliverability"). new ses.EmailIdentity(this, "EmailIdentity", { identity: ses.Identity.publicHostedZone(zone), mailFromDomain: `mail.${zoneName}`, }); // Receivers ignore cross-org DMARC reports without an authorizing TXT // (see warning below); parent/child of the zone approximates same-org. const reportDomain = dmarcReportEmail?.split("@")[1]?.toLowerCase(); const zoneLower = zoneName.toLowerCase(); const sameOrg = !!reportDomain && (reportDomain === zoneLower || zoneLower.endsWith(`.${reportDomain}`) || reportDomain.endsWith(`.${zoneLower}`)); if (dmarcReportEmail && !sameOrg) { cdk.Annotations.of(this).addWarningV2("infra-client:dmarc-cross-domain-rua", `DMARC reports for ${zoneName} go to ${dmarcReportEmail} — a ` + `cross-domain rua needs a "${zoneName}._report._dmarc.<recipient ` + `domain>" TXT record on the recipient's zone, or receivers drop ` + `the reports.`); } new route53.TxtRecord(this, "DmarcRecord", { zone, recordName: `_dmarc.${zoneName}`, values: [ `v=DMARC1; p=quarantine;${dmarcReportEmail ? ` rua=mailto:${dmarcReportEmail}` : ""}`, ], }); } this.accountsTable = new app_table_1.AppTable(this, "AccountsTable", { partitionKey: { name: "accountNumber", type: dynamodb.AttributeType.STRING, }, prod, }); // roleArn lives here as an attribute — the single source of truth vending assumes. this.rolesTable = new app_table_1.AppTable(this, "RolesTable", { partitionKey: { name: "accountNumber", type: dynamodb.AttributeType.STRING, }, sortKey: { name: "roleName", type: dynamodb.AttributeType.STRING }, prod, }); this.accessTable = new app_table_1.AppTable(this, "AccessTable", { partitionKey: { name: "principal", type: dynamodb.AttributeType.STRING }, sortKey: { name: "target", type: dynamodb.AttributeType.STRING }, // Only dev-share rows carry `ttl` (expiry + a day); every other row lives until deleted. timeToLiveAttribute: "ttl", prod, }); this.accessTable.addGlobalSecondaryIndex({ indexName: "byTarget", partitionKey: { name: "target", type: dynamodb.AttributeType.STRING }, sortKey: { name: "principal", type: dynamodb.AttributeType.STRING }, }); // A request never confers access — approving one writes an Access row, and // vending reads only Access. this.requestsTable = new app_table_1.AppTable(this, "RequestsTable", { partitionKey: { name: "requestId", type: dynamodb.AttributeType.STRING }, prod, }); this.requestsTable.addGlobalSecondaryIndex({ indexName: "byUser", partitionKey: { name: "userId", type: dynamodb.AttributeType.STRING }, sortKey: { name: "createdAt", type: dynamodb.AttributeType.STRING }, }); // All pending requests share one byStatus partition — fine at tens of // rows; shard before volume makes it hot. this.requestsTable.addGlobalSecondaryIndex({ indexName: "byStatus", partitionKey: { name: "status", type: dynamodb.AttributeType.STRING }, sortKey: { name: "createdAt", type: dynamodb.AttributeType.STRING }, }); // Append-only activity log (services/auditService.ts); never read for an access decision — Access stays // the only gate. TTL bounds retention (default 400 days > the annual review; config `audit.retentionDays`). this.auditTable = new app_table_1.AppTable(this, "AuditTable", { partitionKey: { name: "eventId", type: dynamodb.AttributeType.STRING }, timeToLiveAttribute: "expiresAt", prod, }); this.auditTable.addGlobalSecondaryIndex({ indexName: "byUser", partitionKey: { name: "userId", type: dynamodb.AttributeType.STRING }, sortKey: { name: "at", type: dynamodb.AttributeType.STRING }, }); this.auditTable.addGlobalSecondaryIndex({ indexName: "byDay", partitionKey: { name: "day", type: dynamodb.AttributeType.STRING }, sortKey: { name: "at", type: dynamodb.AttributeType.STRING }, }); // Who did it (byUser = whom it was done to). Sparse: only rows with an actor. this.auditTable.addGlobalSecondaryIndex({ indexName: "byActor", partitionKey: { name: "actorId", type: dynamodb.AttributeType.STRING }, sortKey: { name: "at", type: dynamodb.AttributeType.STRING }, }); // Group identity only — memberships and grant bundles live in the Access // table; this table never decides access. this.groupsTable = new app_table_1.AppTable(this, "GroupsTable", { partitionKey: { name: "groupId", type: dynamodb.AttributeType.STRING }, prod, }); // PK is a generated uuid so grants survive renames/re-addressing; `cidr` // is the ACL destination (README "Resource catalog"). this.resourcesTable = new app_table_1.AppTable(this, "ResourcesTable", { partitionKey: { name: "resourceId", type: dynamodb.AttributeType.STRING }, prod, }); // The clientId doubles as the access-table principal (a token's `sub` IS // the client id); this table never decides access. this.serviceUsersTable = new app_table_1.AppTable(this, "ServiceUsersTable", { partitionKey: { name: "clientId", type: dynamodb.AttributeType.STRING }, prod, }); // Revoking a token deletes its row; the API reads it strongly consistent on every request. TTL drops a row a // week after expiry, once the bell's "expired" notice is over. this.tokensTable = new app_table_1.AppTable(this, "TokensTable", { partitionKey: { name: "tokenId", type: dynamodb.AttributeType.STRING }, timeToLiveAttribute: "ttl", prod, }); this.tokensTable.addGlobalSecondaryIndex({ indexName: "byOwner", partitionKey: { name: "ownerId", type: dynamodb.AttributeType.STRING }, sortKey: { name: "createdAt", type: dynamodb.AttributeType.STRING }, }); // A revoke DELETES the grant row, so each revoke path writes a notice // here. Informational only — never read for an access decision. this.revocationsTable = new app_table_1.AppTable(this, "RevocationsTable", { partitionKey: { name: "userId", type: dynamodb.AttributeType.STRING }, sortKey: { name: "noticeId", type: dynamodb.AttributeType.STRING }, timeToLiveAttribute: "ttl", prod, }); new cdk.CfnOutput(this, "AccountsTableName", { value: this.accountsTable.tableName, }); new cdk.CfnOutput(this, "RolesTableName", { value: this.rolesTable.tableName, }); new cdk.CfnOutput(this, "RequestsTableName", { value: this.requestsTable.tableName, }); new cdk.CfnOutput(this, "AuditTableName", { value: this.auditTable.tableName, }); new cdk.CfnOutput(this, "GroupsTableName", { value: this.groupsTable.tableName, }); new cdk.CfnOutput(this, "ResourcesTableName", { value: this.resourcesTable.tableName, }); new cdk.CfnOutput(this, "AccessTableName", { value: this.accessTable.tableName, }); new cdk.CfnOutput(this, "RevocationsTableName", { value: this.revocationsTable.tableName, }); this.pluginCatalogTable = new app_table_1.AppTable(this, "PluginCatalogTable", { partitionKey: { name: "pluginId", type: dynamodb.AttributeType.STRING }, prod, }); this.accessLogsBucket = new s3.Bucket(this, "AccessLogsBucket", { blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, enforceSSL: true, encryption: s3.BucketEncryption.S3_MANAGED, objectOwnership: s3.ObjectOwnership.OBJECT_WRITER, accessControl: s3.BucketAccessControl.LOG_DELIVERY_WRITE, lifecycleRules: [ { expiration: cdk.Duration.days(90), abortIncompleteMultipartUploadAfter: cdk.Duration.days(7) }, ], removalPolicy: prod ? cdk.RemovalPolicy.RETAIN : cdk.RemovalPolicy.DESTROY, autoDeleteObjects: !prod, }); this.pluginAssetsBucket = new s3.Bucket(this, "PluginAssetsBucket", { blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, enforceSSL: true, removalPolicy: cdk.RemovalPolicy.DESTROY, // redeployable build output autoDeleteObjects: true, lifecycleRules: [{ abortIncompleteMultipartUploadAfter: cdk.Duration.days(7) }], serverAccessLogsBucket: this.accessLogsBucket, serverAccessLogsPrefix: "s3/plugin-assets/", }); // CloudFront (OAC) is the only reader. The distribution lives in WebStack, which cannot write this policy // without a stack cycle, so the grant names any distribution of this account. this.pluginAssetsBucket.addToResourcePolicy(new iam.PolicyStatement({ actions: ["s3:GetObject"], resources: [this.pluginAssetsBucket.arnForObjects("*")], principals: [new iam.ServicePrincipal("cloudfront.amazonaws.com")], conditions: { ArnLike: { "AWS:SourceArn": `arn:${cdk.Aws.PARTITION}:cloudfront::${cdk.Aws.ACCOUNT_ID}:distribution/*` } }, })); // The other stacks reference the table and bucket only while plugins are ON. Exporting them explicitly keeps // the exports alive when the feature is switched off, so DataStack (deployed first) never fails with // "export in use by CredsStack/WebStack" on that transition. for (const value of [ this.pluginCatalogTable.tableName, this.pluginCatalogTable.tableArn, this.pluginAssetsBucket.bucketName, this.pluginAssetsBucket.bucketArn, ]) { this.exportValue(value); } // Removing a table another stack still imports fails DataStack with "export in use" (DataStack // deploys first): drop the consumers' references in one release and the table in the next (the // 0.1.18 → 0.2.0 removal of the access-model-v1 tables). new cdk.CfnOutput(this, "PluginCatalogTableName", { value: this.pluginCatalogTable.tableName, }); new cdk.CfnOutput(this, "ServiceUsersTableName", { value: this.serviceUsersTable.tableName, }); new cdk.CfnOutput(this, "TokensTableName", { value: this.tokensTable.tableName, }); } } exports.DataStack = DataStack;