@fntio/infra-client
Version:
Self-hosted AWS access portal: credential vending, target-account trust, and grant-driven private networking as CDK stacks and constructs.
209 lines (208 loc) • 11 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.VendingApi = void 0;
const cdk = __importStar(require("aws-cdk-lib"));
const constructs_1 = require("constructs");
const iam = __importStar(require("aws-cdk-lib/aws-iam"));
const app_function_1 = require("./app-function");
const runtime_1 = require("../plugins/runtime");
/** Lambda caps TOTAL env at 4 KB — bounded so a huge rolesByAccount can
* never fail the deploy (the checklist only shows the first few anyway). */
function boundedConfigAccounts(accounts) {
const kept = [];
for (const a of accounts) {
kept.push({ accountNumber: a.accountNumber, roles: a.roles.slice(0, 5) });
if (JSON.stringify(kept).length > 2500) {
kept.pop();
break;
}
}
return JSON.stringify(kept);
}
/** The Express vending app (lambdacode/api) in Lambda. Express owns routing
* AND auth, so no authorizer is needed at the gateway. */
class VendingApi extends constructs_1.Construct {
/** The Express app's Lambda — front it with API Gateway. */
handler;
constructor(scope, id, props) {
super(scope, id);
const { accountsTable, rolesTable, requestsTable, auditTable, groupsTable, resourcesTable, accessTable, revocationsTable, serviceUsersTable, } = props;
// One environment for the API and the report job: the job runs the API's own services on the same bundle.
const environment = {
ACCOUNTS_TABLE_NAME: accountsTable.tableName,
ROLES_TABLE_NAME: rolesTable.tableName,
REQUESTS_TABLE_NAME: requestsTable.tableName,
AUDIT_TABLE_NAME: auditTable.tableName,
AUDIT_RETENTION_DAYS: String(props.auditRetentionDays),
GROUPS_TABLE_NAME: groupsTable.tableName,
RESOURCES_TABLE_NAME: resourcesTable.tableName,
ACCESS_TABLE_NAME: accessTable.tableName,
REVOCATIONS_TABLE_NAME: revocationsTable.tableName,
SERVICE_USERS_TABLE_NAME: serviceUsersTable.tableName,
TOKENS_TABLE_NAME: props.tokensTable.tableName,
...(props.personalAccessTokens ? { PERSONAL_ACCESS_TOKENS: JSON.stringify(props.personalAccessTokens) } : {}),
...(props.roleSessionName ? { ROLE_SESSION_NAME: props.roleSessionName } : {}),
...(props.plugins
? (0, runtime_1.pluginRuntimeEnv)({ catalogTable: props.plugins.catalogTable, accountsTable }, props.plugins.discoveryRefreshSeconds)
: {}),
KMS_KEY_ID: props.signingKey.keyId,
ISSUER_URL: props.issuerUrl,
AUDIENCE: "sts.amazonaws.com",
// auth.ts accepts ID tokens from ANY app client of this pool.
USER_POOL_ID: props.userPool.userPoolId,
USER_POOL_CLIENT_ID: props.userPoolClientId,
PROJECT_NAME: props.projectName,
...(props.appUrl ? { APP_URL: props.appUrl } : {}),
WEB_BUCKET_NAME: props.webBucketName,
EMAIL_CONFIGURED: props.emailConfigured ? "1" : "0",
EMAIL_FROM: props.emailFrom ?? "",
...(props.configAccounts?.length
? { CONFIG_ACCOUNTS: boundedConfigAccounts(props.configAccounts) }
: {}),
NODE_ENV: "production",
// Absent → /network answers 501. NETWORK_CONTROL_URL = first site's
// URL, for shipped desktop shells that only know one control plane.
...(props.network
? {
NETWORK_SITES: JSON.stringify(props.network.sites),
NETWORK_CONTROL_URL: props.network.sites[0].controlUrl,
NETWORK_KEYMINTER_FN_NAME: props.network.keyMinterFnName,
NETWORK_RECONCILER_FN_NAME: props.network.reconcilerFnName,
...(props.network.devShares
? { DEV_SHARES: JSON.stringify(props.network.devShares) }
: {}),
}
: {}),
REPORTS_BUCKET: props.reportsBucket.bucketName,
...(props.accountDimensions ? { ACCOUNT_DIMENSIONS: JSON.stringify(props.accountDimensions) } : {}),
DASHBOARD_LAYOUT: props.dashboardLayout ?? "auto",
};
// The access report as a background job (lambdacode/api/services/reportJobs.ts): the same bundle with a
// 15-minute budget, invoked asynchronously by the API, writing to the private reports bucket.
// Fixed name, invoked BY NAME: a grant by reference would put the function's ARN in the shared role's
// policy while the function waits on that same policy — a CloudFormation cycle.
new app_function_1.AppFunction(this, "ReportJob", {
functionName: props.reportJobFunctionName,
description: "The portal's access-report job: builds the CSV the API hands out by link.",
asset: "api",
handler: "reportJob",
role: props.handlerRole,
timeout: cdk.Duration.minutes(15),
memorySize: 1024,
environment,
});
this.handler = new app_function_1.AppFunction(this, "Handler", {
description: "The portal API: access management, requests and credential vending.",
asset: "api", // bundled WITH real express node_modules — see the bundler
handler: "handler",
role: props.handlerRole,
timeout: cdk.Duration.seconds(10),
// CPU scales with memory: at Lambda's 128 MB default the Express + SDK cold start and the KMS→STS vend
// path were CPU-bound (throttle alarms at normal usage); 1024 MB is usually cost-neutral as duration drops.
memorySize: 1024,
environment: { ...environment, REPORT_JOB_FUNCTION: props.reportJobFunctionName },
});
this.handler.addToRolePolicy(new iam.PolicyStatement({
actions: ["lambda:InvokeFunction"],
resources: [
cdk.Stack.of(this).formatArn({
service: "lambda",
resource: "function",
resourceName: props.reportJobFunctionName,
arnFormat: cdk.ArnFormat.COLON_RESOURCE_NAME,
}),
],
}));
props.reportsBucket.grantReadWrite(this.handler);
// Deliberately no sts:AssumeRole — AssumeRoleWithWebIdentity needs no
// permission on the caller; the target role's trust policy authorizes it.
accountsTable.grantReadWriteData(this.handler);
rolesTable.grantReadWriteData(this.handler);
requestsTable.grantReadWriteData(this.handler);
auditTable.grantReadWriteData(this.handler);
groupsTable.grantReadWriteData(this.handler);
resourcesTable.grantReadWriteData(this.handler);
accessTable.grantReadWriteData(this.handler);
revocationsTable.grantReadWriteData(this.handler);
serviceUsersTable.grantReadWriteData(this.handler);
props.tokensTable.grantReadWriteData(this.handler);
props.plugins?.catalogTable.grantReadData(this.handler);
props.signingKey.grant(this.handler, "kms:Sign");
// Private network: device-minter invoke by NAME, not reference, so
// CredsStack deploys whether or not NetworkStack exists yet.
if (props.network) {
this.handler.addToRolePolicy(new iam.PolicyStatement({
actions: ["lambda:InvokeFunction"],
resources: [props.network.keyMinterFnName, props.network.reconcilerFnName].map((name) => cdk.Stack.of(this).formatArn({
service: "lambda",
resource: "function",
resourceName: name,
arnFormat: cdk.ArnFormat.COLON_RESOURCE_NAME,
})),
}));
}
// Cognito user admin for the /admin/users routes — scoped to THIS pool's
// ARN, and every route sits behind requireAuth + requireAdmin.
this.handler.addToRolePolicy(new iam.PolicyStatement({
actions: [
"cognito-idp:ListUsers",
"cognito-idp:ListUsersInGroup",
// Consistent sub → identity lookups (sign-up link, resend, MFA reset, email change).
"cognito-idp:AdminGetUser",
"cognito-idp:AdminCreateUser",
// A fresh temporary password behind "Copy sign-up link" (never a permanent one).
"cognito-idp:AdminSetUserPassword",
"cognito-idp:AdminUpdateUserAttributes",
"cognito-idp:AdminDeleteUser",
// Ends a deleted/demoted user's sessions at once (see auth.ts requireAdmin).
"cognito-idp:AdminUserGlobalSignOut",
"cognito-idp:AdminAddUserToGroup",
"cognito-idp:AdminRemoveUserFromGroup",
// Invite-time link of the email to each federated provider, discovered from the pool.
"cognito-idp:AdminLinkProviderForUser",
"cognito-idp:AdminDisableProviderForUser",
"cognito-idp:ListIdentityProviders",
// Runtime-created M2M clients can only ever get the `api/invoke`
// scope — never a human sign-in.
"cognito-idp:CreateUserPoolClient",
"cognito-idp:DeleteUserPoolClient",
"cognito-idp:DescribeUserPoolClient",
],
resources: [props.userPool.userPoolArn],
}));
}
}
exports.VendingApi = VendingApi;