@fntio/infra-client
Version:
Self-hosted AWS access portal: credential vending, target-account trust, and grant-driven private networking as CDK stacks and constructs.
611 lines (610 loc) • 33.1 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.CredsStack = void 0;
exports.resolveAlertEmails = resolveAlertEmails;
const cdk = __importStar(require("aws-cdk-lib"));
const naming_1 = require("../lambdacode/network/naming");
const web_stack_1 = require("./web-stack");
const apigw = __importStar(require("aws-cdk-lib/aws-apigateway"));
const wafv2 = __importStar(require("aws-cdk-lib/aws-wafv2"));
const web_acl_1 = require("./constructs/web-acl");
const cognito = __importStar(require("aws-cdk-lib/aws-cognito"));
const events = __importStar(require("aws-cdk-lib/aws-events"));
const iam = __importStar(require("aws-cdk-lib/aws-iam"));
const s3 = __importStar(require("aws-cdk-lib/aws-s3"));
const targets = __importStar(require("aws-cdk-lib/aws-events-targets"));
const logs = __importStar(require("aws-cdk-lib/aws-logs"));
const cr = __importStar(require("aws-cdk-lib/custom-resources"));
const app_function_1 = require("./constructs/app-function");
const audit_log_1 = require("./audit-log");
const plugin_api_1 = require("./plugins/plugin-api");
const plugin_catalog_activation_1 = require("./plugins/plugin-catalog-activation");
const runtime_1 = require("./plugins/runtime");
const monitoring_1 = require("./constructs/monitoring");
const oidc_issuer_1 = require("./constructs/oidc-issuer");
const vending_api_1 = require("./constructs/vending-api");
const api_throttle_1 = require("./api-throttle");
const federation_1 = require("./federation");
/** Cognito + issuer + vending API. The user pool and REST API stay at stack
* level so their CloudFormation identities survive internal refactors. */
const EMAIL_RE = /^[^\s@"]+@[^\s@"]+\.[^\s@"]+$/;
/** `alertEmail` as the list it stands for: trimmed, de-duplicated, every entry a real address.
* Throws at synth — a placeholder would leave every alarm pointed at nothing. */
function resolveAlertEmails(alertEmail) {
const list = [...new Set((typeof alertEmail === "string" ? [alertEmail] : alertEmail).map((e) => e.trim()))];
if (!list.length)
throw new Error("alertEmail is empty — alarms and the issuer canary need a recipient.");
for (const e of list) {
if (!EMAIL_RE.test(e) || /change-me/i.test(e)) {
throw new Error(`alertEmail (${e}) is not a real email address — alarms and the issuer canary notify it.`);
}
}
return list;
}
class CredsStack extends cdk.Stack {
/** Fronted by WebStack's CloudFront /api/* behavior (same-origin, no CORS). */
api;
/** Plugin routes + the shared authorizer; present only when plugins are on. */
pluginApi;
/** Other stacks hook their alarms here. */
alertTopic;
/** WebStack attaches the SPA client + domain here — their callback URLs
* need the CloudFront domain (avoids a circular stack ref). */
userPool;
constructor(scope, id, props) {
super(scope, id, props);
const { loginMethods } = props;
if (!props.projectName.trim()) {
throw new Error("projectName must be a non-empty display name — " +
"it is what users see in invite emails and the desktop app.");
}
const alertEmails = resolveAlertEmails(props.alertEmail);
if (loginMethods.password === false) {
throw new Error("loginMethods.password: false is not supported — Cognito requires " +
"password as a first-auth factor. Omit it or set true.");
}
// A prefix-domain RP id can never match the app origin — every passkey
// registration would throw SecurityError.
if (loginMethods.passkey && !props.passkeyDomain) {
throw new Error("loginMethods.passkey requires the `web` block — passkeys bind to " +
"the custom web domain as the relying-party id. Set `web`, or " +
"disable passkey until it exists.");
}
// Adaptive step-ups only exist with MFA at least optional on the pool.
if (loginMethods.threatProtection && !loginMethods.mfa) {
throw new Error('loginMethods.threatProtection needs mfa: "optional" or "required" — ' +
"its risky-sign-in step-ups are TOTP challenges.");
}
// Security Hub Cognito.5 evaluates PASSWORD-only pools — a silent default
// would change the pool and the web UI behind the config's back.
if (!loginMethods.passkey &&
!loginMethods.emailOtp &&
!loginMethods.mfa) {
throw new Error('loginMethods: a password-only pool must set mfa: "optional" or ' +
'"required" (Security Hub Cognito.5), or enable a passwordless ' +
"factor (passkey / emailOtp).");
}
// An address outside the domain deploys fine, then fails on every send.
if (props.email &&
!props.email.fromAddress.endsWith(`@${props.email.zoneName}`)) {
throw new Error(`email.fromAddress (${props.email.fromAddress}) must be an address ` +
`under email.zoneName (${props.email.zoneName}).`);
}
// Lowercased — the pool's sign-in alias is case-sensitive.
const firstAdminEmail = props.firstAdmin?.email.trim().toLowerCase();
if (firstAdminEmail !== undefined &&
(!EMAIL_RE.test(firstAdminEmail) || /change-me/i.test(firstAdminEmail))) {
throw new Error(`firstAdmin.email (${props.firstAdmin.email}) is not a real email ` +
`address — it receives the first admin invite.`);
}
const { accountsTable, rolesTable, requestsTable, auditTable, groupsTable, resourcesTable, accessTable, revocationsTable, serviceUsersTable, } = props;
const auditLog = { table: auditTable, retentionDays: props.auditRetentionDays ?? audit_log_1.DEFAULT_AUDIT_RETENTION_DAYS };
const ssoLabels = props.federation?.providers.map((p) => p.label).join(" or ");
const ssoLead = (how) => ssoLabels
? `<p>If your organization signs in with ${ssoLabels}, ${how} — you don't need a password.</p>`
: "";
const userPool = new cognito.UserPool(this, "UserPool", {
selfSignUpEnabled: false, // admins create users
signInAliases: { email: true },
// Cognito's own defaults, pinned so they can't drift.
passwordPolicy: {
minLength: 8,
requireLowercase: true,
requireUppercase: true,
requireDigits: true,
requireSymbols: true,
},
removalPolicy: props.prod
? cdk.RemovalPolicy.RETAIN
: cdk.RemovalPolicy.DESTROY,
// RETAIN only covers stack deletion, not a direct DeleteUserPool.
deletionProtection: !!props.prod,
email: props.email
? cognito.UserPoolEmail.withSES({
fromEmail: props.email.fromAddress,
fromName: props.email.fromName,
sesVerifiedDomain: props.email.zoneName,
})
: undefined,
// Cognito requires {username} + {####}, but {username} is the internal
// UUID — it rides in the link (#inv=…) or hides in an HTML comment. ONE
// template per pool, so with SSO configured it addresses both kinds of
// user: the provider button first, the password path as the fallback.
userInvitation: props.appUrl
? {
emailSubject: `Your ${props.projectName} invitation`,
emailBody: `<p>You've been invited to ${props.projectName}.</p>` +
ssoLead(`open <a href="${props.appUrl}/login">${props.appUrl}/login</a> and click <b>Sign in with ${ssoLabels}</b>`) +
`<p>${ssoLabels ? "Otherwise, " : ""}<a href="${props.appUrl}/login#inv={username}:{####}">${ssoLabels ? "set" : "Set"} your password</a> to get started.</p>` +
`<p>The set-password link expires in 7 days. If it has expired, ask your administrator to resend the invite.</p>`,
}
: {
emailSubject: `Your ${props.projectName} invitation`,
emailBody: `<p>You've been invited to ${props.projectName}.</p>` +
ssoLead(`click <b>Sign in with ${ssoLabels}</b> on the sign-in page`) +
`<p>${ssoLabels ? "Otherwise, sign" : "Sign"} in with your email address and this temporary password: {####}</p>` +
`<p>The password expires in 7 days. If it has expired, ask your administrator to resend the invite.</p>` +
`<!-- {username} -->`,
},
// One template for EVERY emailed code, password resets included — the
// copy must stay flow-neutral.
userVerification: {
emailSubject: `Your ${props.projectName} verification code`,
emailBody: `<p>Your ${props.projectName} verification code is {####}.</p>` +
`<p>If you didn't request a code, you can ignore this email.</p>`,
},
// ESSENTIALS covers email OTP, passkeys, and the branding designer;
// threat protection is PLUS-only.
featurePlan: loginMethods.threatProtection
? cognito.FeaturePlan.PLUS
: cognito.FeaturePlan.ESSENTIALS,
standardThreatProtectionMode: loginMethods.threatProtection
? cognito.StandardThreatProtectionMode.FULL_FUNCTION
: undefined,
customThreatProtectionMode: loginMethods.threatProtection
? cognito.CustomThreatProtectionMode.FULL_FUNCTION
: undefined,
signInPolicy: {
allowedFirstAuthFactors: {
password: true,
emailOtp: loginMethods.emailOtp ?? false,
passkey: loginMethods.passkey ?? false,
},
},
// Spread: EnabledMfas may not appear at all when MFA is off.
...(loginMethods.mfa
? {
mfa: loginMethods.mfa === "required"
? cognito.Mfa.REQUIRED
: cognito.Mfa.OPTIONAL,
// No SMS: it would need SNS, an origination number and sandbox exit.
mfaSecondFactor: { sms: false, otp: true },
}
: {}),
// The apex domain survives auth-host changes. Changing the RP id
// orphans every registered passkey.
passkeyRelyingPartyId: props.passkeyDomain ??
`creds-${this.account}.auth.${this.region}.amazoncognito.com`,
passkeyUserVerification: cognito.PasskeyUserVerification.PREFERRED,
// Mapped claims. MUTABLE is load-bearing: Cognito rewrites a mapped attribute on every
// sign-in whose value changed, and an immutable one lets the user in exactly once.
// Permanent for the pool's life — attributes can't be renamed or removed.
...(props.federation?.claimKeys.length
? {
customAttributes: Object.fromEntries(props.federation.claimKeys.map((c) => [
c.key,
new cognito.StringAttribute({ mutable: true, minLen: 0, maxLen: c.maxLen }),
])),
}
: {}),
});
this.userPool = userPool;
if (props.federation) {
// First federated sign-in of an identity: link it to the invited user with that email, or
// refuse (admins decide who gets in). No USER_POOL_ID env and a policy outside the role's
// default one — both would close a pool → trigger → pool dependency cycle.
const preSignUp = new app_function_1.AppFunction(this, "FederationPreSignUpFn", {
description: "Sign-in trigger: links a first single-sign-on login to the invited user with that email, or refuses it.",
asset: "federation-presignup",
// Cognito waits 5 s for a trigger, then retries — longer only does invisible work.
timeout: cdk.Duration.seconds(5),
});
new iam.Policy(this, "FederationPreSignUpPolicy", {
roles: [preSignUp.role],
statements: [
new iam.PolicyStatement({
// ListUsers: the last-resort case-insensitive scan for a mixed-case invite.
actions: ["cognito-idp:AdminGetUser", "cognito-idp:ListUsers", "cognito-idp:AdminLinkProviderForUser"],
resources: [userPool.userPoolArn],
}),
],
});
userPool.addTrigger(cognito.UserPoolOperation.PRE_SIGN_UP, preSignUp);
}
if (loginMethods.threatProtection) {
// Any MFA action on an attempt limits choice-based sign-in to the password
// (Cognito drops passkey and email code for that attempt), so a user without
// TOTP is downgraded, not stepped up. Medium risk — a new network — allows;
// only High keeps the step-up, and tells the user by email when the pool
// has a sender. Compromised-credential checks cover password sign-ins, not SRP.
const notify = !!props.email;
new cognito.CfnUserPoolRiskConfigurationAttachment(this, "RiskConfiguration", {
userPoolId: userPool.userPoolId,
clientId: "ALL",
compromisedCredentialsRiskConfiguration: {
actions: { eventAction: "BLOCK" },
eventFilter: ["SIGN_IN", "PASSWORD_CHANGE", "SIGN_UP"],
},
accountTakeoverRiskConfiguration: {
...(props.email
? {
notifyConfiguration: {
sourceArn: `arn:aws:ses:${this.region}:${this.account}:identity/${props.email.zoneName}`,
from: props.email.fromAddress,
},
}
: {}),
actions: {
lowAction: { eventAction: "NO_ACTION", notify: false },
mediumAction: { eventAction: "NO_ACTION", notify: false },
highAction: { eventAction: "MFA_IF_CONFIGURED", notify },
},
},
});
}
const userPoolClient = userPool.addClient("WebClient", {
// `user` = choice-based flow; userPassword/userSrp stay for scripts.
authFlows: { userPassword: true, userSrp: true, user: true },
// Explicit: federated providers register on the pool from WebStack and
// must never widen this scripts-only client.
supportedIdentityProviders: [cognito.UserPoolClientIdentityProvider.COGNITO],
// Its tokens carry the mapped claims like the SPA client's (read only, never write).
...(props.federation?.claimKeys.length
? {
readAttributes: (0, federation_1.readAttributes)(props.federation.claimKeys),
writeAttributes: (0, federation_1.writeAttributes)(props.federation.claimKeys, { claims: false }),
}
: {}),
// Without this CDK fills in OAuth defaults (implicit grant + an
// example.com callback) that nobody chose.
disableOAuth: true,
// This client id is published unauthenticated (/.well-known/infra-client), so like the SPA client it
// must answer "wrong credentials" for unknown and known addresses alike — the Cognito default (LEGACY)
// tells anyone which emails have an account.
preventUserExistenceErrors: true,
// Same session cap as the SPA client — Cognito's 30-day refresh default
// would outlive it.
idTokenValidity: cdk.Duration.hours(1),
accessTokenValidity: cdk.Duration.hours(1),
refreshTokenValidity: cdk.Duration.hours(web_stack_1.SESSION_HOURS),
});
// auth.ts requires exactly `api/invoke` on service-user tokens; the M2M
// clients themselves are created at runtime (serviceUsersService).
userPool.addResourceServer("ApiResourceServer", {
identifier: "api",
scopes: [
new cognito.ResourceServerScope({
scopeName: "invoke",
scopeDescription: "Call the vending API as a service user",
}),
],
});
// Admin = membership here, via the token's cognito:groups claim — no DB
// flag; requireAdmin checks this exact name.
const adminsGroup = new cognito.CfnUserPoolGroup(this, "AdminsGroup", {
userPoolId: userPool.userPoolId,
groupName: "admins",
description: "Users allowed to call admin-only API routes.",
});
// Mints the one account nothing else can; the handler is idempotent
// against the live pool (lambdacode/firstadmin/handler.ts).
if (props.firstAdmin) {
const firstAdminFn = new app_function_1.AppFunction(this, "FirstAdminFn", {
description: "Deploy-time helper: creates the first admin account and sends its invite.",
asset: "firstadmin",
timeout: cdk.Duration.seconds(30),
environment: { USER_POOL_ID: userPool.userPoolId, ...(0, audit_log_1.auditLogEnv)(auditLog) },
});
(0, audit_log_1.grantAuditLogWrite)(firstAdminFn, auditLog);
firstAdminFn.addToRolePolicy(new iam.PolicyStatement({
actions: [
"cognito-idp:AdminGetUser",
"cognito-idp:AdminCreateUser",
"cognito-idp:AdminAddUserToGroup",
// Tells a promotion of an existing user (an admin-grant row) from a no-op re-add.
"cognito-idp:AdminListGroupsForUser",
],
resources: [userPool.userPoolArn],
}));
const provider = new cr.Provider(this, "FirstAdminProvider", {
onEventHandler: firstAdminFn,
});
const firstAdmin = new cdk.CustomResource(this, "FirstAdmin", {
serviceToken: provider.serviceToken,
resourceType: "Custom::FirstAdmin",
properties: {
Email: firstAdminEmail,
Resend: props.firstAdmin.resend ?? 0,
// Bump when the handler's RESPONSE shape changes — a stale response
// has no new Data attribute for outputs to GetAtt.
SchemaVersion: "2",
},
});
// The group-add must find the group already created.
firstAdmin.node.addDependency(adminsGroup);
new cdk.CfnOutput(this, "FirstAdminEmail", {
value: firstAdminEmail,
});
// "suppressed" = created but the invite email failed (SES sandbox) —
// resend from the Users page; "blocked" = left untouched.
new cdk.CfnOutput(this, "FirstAdminInviteSent", {
value: firstAdmin.getAttString("InviteSent"),
});
}
// Created before the issuer: the signing key's policy names this role as
// the ONLY principal allowed kms:Sign.
const vendingRole = new iam.Role(this, "VendingApiRole", {
assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole"),
],
});
const issuer = new oidc_issuer_1.OidcIssuer(this, "Issuer", {
...props.issuer,
resourcePrefix: props.resourcePrefix,
signerRole: vendingRole,
prod: props.prod,
accessLogsBucket: props.accessLogsBucket,
});
// The branding route writes /branding.json into the site bucket, by name
// — WebStack deploys after us.
const siteBucketName = (0, web_stack_1.webBucketName)(props.resourcePrefix, this.account);
vendingRole.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ["s3:PutObject", "s3:GetObject"],
resources: [`arn:aws:s3:::${siteBucketName}/branding.json`],
}));
// Without ListBucket a missing overlay reads AccessDenied (branding saves
// 502); unconditioned — S3's 404-vs-403 check can't see s3:prefix reliably.
vendingRole.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ["s3:ListBucket"],
resources: [`arn:aws:s3:::${siteBucketName}`],
}));
// Access reports built in the background land here, behind presigned links; nothing lives past a week.
const reportsBucket = new s3.Bucket(this, "ReportsBucket", {
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
encryption: s3.BucketEncryption.S3_MANAGED,
enforceSSL: true,
removalPolicy: cdk.RemovalPolicy.DESTROY, // derived output, rebuilt on request
autoDeleteObjects: true,
lifecycleRules: [{ expiration: cdk.Duration.days(7), abortIncompleteMultipartUploadAfter: cdk.Duration.days(1) }],
// Same access-log bucket as every other hub bucket (Security Hub S3.9).
serverAccessLogsBucket: props.accessLogsBucket,
serverAccessLogsPrefix: props.accessLogsBucket && "s3/reports/",
});
const vendingApi = new vending_api_1.VendingApi(this, "VendingApi", {
handlerRole: vendingRole,
appUrl: props.appUrl,
webBucketName: siteBucketName,
reportsBucket,
reportJobFunctionName: `${props.resourcePrefix}-report-job`,
emailConfigured: Boolean(props.email),
emailFrom: props.email?.fromAddress,
configAccounts: props.configAccounts,
accountsTable,
rolesTable,
requestsTable,
auditTable,
auditRetentionDays: auditLog.retentionDays,
groupsTable,
resourcesTable,
accessTable,
revocationsTable,
serviceUsersTable,
tokensTable: props.tokensTable,
personalAccessTokens: props.personalAccessTokens,
roleSessionName: props.roleSessionName,
plugins: props.plugins && { discoveryRefreshSeconds: props.plugins.discoveryRefreshSeconds, catalogTable: props.plugins.catalogTable },
signingKey: issuer.signingKey,
issuerUrl: issuer.url,
userPool,
userPoolClientId: userPoolClient.userPoolClientId,
projectName: props.projectName,
network: props.networkSites?.length
? {
sites: props.networkSites,
keyMinterFnName: (0, naming_1.deviceKeyMinterFnName)(props.resourcePrefix),
reconcilerFnName: (0, naming_1.aclReconcilerFnName)(props.resourcePrefix),
devShares: props.devShares,
}
: undefined,
accountDimensions: props.accountDimensions,
dashboardLayout: props.dashboardLayout,
});
// Daily: raises reapprovals past 12 months, auto-revokes past the grace
// window.
const reapprovalSweeper = new app_function_1.AppFunction(this, "ReapprovalSweeper", {
description: "Daily access-review sweep: raises reapprovals that are due and revokes access past the grace period.",
asset: "reapproval",
handler: "handler",
timeout: cdk.Duration.minutes(5),
environment: {
ROLES_TABLE_NAME: rolesTable.tableName,
REQUESTS_TABLE_NAME: requestsTable.tableName,
RESOURCES_TABLE_NAME: resourcesTable.tableName,
ACCESS_TABLE_NAME: accessTable.tableName,
REVOCATIONS_TABLE_NAME: revocationsTable.tableName,
...(0, audit_log_1.auditLogEnv)(auditLog),
// Admin/service-user reviews are raise-only — the sweep never
// deletes or demotes on its own.
GROUPS_TABLE_NAME: groupsTable.tableName,
SERVICE_USERS_TABLE_NAME: serviceUsersTable.tableName,
USER_POOL_ID: userPool.userPoolId,
// Plugin reviews need the catalog AND the accounts catalog (binding availability).
...(props.plugins ? (0, runtime_1.pluginRuntimeEnv)({ catalogTable: props.plugins.catalogTable, accountsTable }) : {}),
NODE_ENV: "production",
},
});
if (props.plugins)
(0, runtime_1.grantPluginRuntimeRead)(reapprovalSweeper, { catalogTable: props.plugins.catalogTable, accountsTable });
requestsTable.grantReadWriteData(reapprovalSweeper);
rolesTable.grantReadData(reapprovalSweeper);
accessTable.grantReadWriteData(reapprovalSweeper);
resourcesTable.grantReadData(reapprovalSweeper);
revocationsTable.grantReadWriteData(reapprovalSweeper);
(0, audit_log_1.grantAuditLogWrite)(reapprovalSweeper, auditLog);
// Read-write: a lapsed group reapproval can delete a bundle-less group.
groupsTable.grantReadWriteData(reapprovalSweeper);
serviceUsersTable.grantReadData(reapprovalSweeper);
reapprovalSweeper.addToRolePolicy(new iam.PolicyStatement({
// The admin re-attestation reads the admins group membership.
actions: ["cognito-idp:ListUsersInGroup"],
resources: [userPool.userPoolArn],
}));
new events.Rule(this, "ReapprovalSchedule", {
description: "Daily periodic-reapproval sweep of standing grants.",
schedule: events.Schedule.rate(cdk.Duration.days(1)),
targets: [new targets.LambdaFunction(reapprovalSweeper)],
});
// No Cognito authorizer — the Express middleware validates the JWT itself.
const apiAccessLogs = new logs.LogGroup(this, "CredsApiAccessLogs", {
retention: logs.RetentionDays.THREE_MONTHS,
});
const throttle = props.apiThrottle ?? (0, api_throttle_1.resolveApiThrottle)();
const api = new apigw.LambdaRestApi(this, "CredsApi", {
restApiName: "creds-api",
handler: vendingApi.handler,
// The proxy is added by hand below: a proxying LambdaRestApi refuses explicit child resources, and the
// plugin routes need /api/... resources. addProxy() creates the same {proxy+} + ANY constructs (same
// logical ids) that proxy: true would.
proxy: false,
// Explicit: consumers with the disableCloudWatchRole feature flag would
// otherwise synth without the account role and fail at deploy.
cloudWatchRole: true,
deployOptions: {
stageName: "dev",
// Security Hub APIGateway.1/.3. ERROR level only — the app's own
// structured logs carry the detail — into the group API Gateway
// manages (negligible volume); traces stop at the gateway, no Lambda
// has active tracing.
loggingLevel: apigw.MethodLoggingLevel.ERROR,
tracingEnabled: true,
accessLogDestination: new apigw.LogGroupLogDestination(apiAccessLogs),
accessLogFormat: apigw.AccessLogFormat.jsonWithStandardFields({
caller: false,
httpMethod: true,
ip: true,
protocol: true,
requestTime: true,
resourcePath: true,
responseLength: true,
status: true,
user: false,
}),
// Deployment-wide ceiling; the per-token WAF rule is what bounds one leaked token.
throttlingRateLimit: throttle.rateLimit,
throttlingBurstLimit: throttle.burstLimit,
},
});
api.root.addProxy();
this.api = api;
if (props.plugins) {
this.pluginApi = new plugin_api_1.PluginApi(this, "PluginApi", {
api,
coreHandler: vendingApi.handler,
plugins: props.plugins.plugins,
runtime: {
userPoolId: userPool.userPoolId,
accessTable,
serviceUsersTable,
catalogTable: props.plugins.catalogTable,
accountsTable,
},
auditLog,
});
if (props.plugins.plugins.length) {
new plugin_catalog_activation_1.PluginCatalogActivation(this, "Plugins", {
plugins: props.plugins.plugins,
assetsBucket: props.plugins.assetsBucket,
pluginCatalogTable: props.plugins.catalogTable,
accessTable,
accountsTable,
revocationsTable,
auditLog,
apiStage: api.deploymentStage,
methodsByPlugin: this.pluginApi.methodsByPlugin,
owner: cdk.Aws.STACK_ID,
});
}
}
if (props.waf) {
const webAcl = new web_acl_1.WebAcl(this, "ApiWebAcl", {
scope: "REGIONAL",
name: `${props.resourcePrefix}-api`,
// Only here, not on CloudFront: every /api/* call lands on this stage
// anyway and direct execute-api callers are seen only here; a second
// counter would just disagree with this one. No path prefix — every
// request on the stage is an API call (the path starts with the stage).
tokenRateLimit: { limit: props.waf.perTokenRateLimit },
});
new wafv2.CfnWebACLAssociation(this, "ApiWebAclAssociation", {
resourceArn: api.deploymentStage.stageArn,
webAclArn: webAcl.arn,
});
}
const monitoring = new monitoring_1.Monitoring(this, "Monitoring", {
alertEmails,
vendingFn: vendingApi.handler,
issuerUrl: issuer.url,
signingKeyId: issuer.signingKey.keyId,
});
this.alertTopic = monitoring.topic;
new cdk.CfnOutput(this, "ApiUrl", { value: api.url });
new cdk.CfnOutput(this, "UserPoolId", { value: userPool.userPoolId });
new cdk.CfnOutput(this, "UserPoolClientId", {
value: userPoolClient.userPoolClientId,
});
new cdk.CfnOutput(this, "AccountsTableName", {
value: accountsTable.tableName,
});
new cdk.CfnOutput(this, "RolesTableName", { value: rolesTable.tableName });
new cdk.CfnOutput(this, "RequestsTableName", {
value: requestsTable.tableName,
});
new cdk.CfnOutput(this, "IssuerUrl", { value: issuer.url });
new cdk.CfnOutput(this, "KmsKeyId", { value: issuer.signingKey.keyId });
}
}
exports.CredsStack = CredsStack;