@fntio/infra-client
Version:
Self-hosted AWS access portal: credential vending, target-account trust, and grant-driven private networking as CDK stacks and constructs.
214 lines (213 loc) • 8.85 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.WebAcl = exports.COMMON_RULES_COUNT_ONLY = void 0;
exports.resolveWaf = resolveWaf;
const cdk = __importStar(require("aws-cdk-lib"));
const constructs_1 = require("constructs");
const logs = __importStar(require("aws-cdk-lib/aws-logs"));
const wafv2 = __importStar(require("aws-cdk-lib/aws-wafv2"));
function resolveWaf(config) {
if (config?.enabled === false)
return undefined;
const bounded = (field, value, unit) => {
if (!Number.isInteger(value) || value < 10 || value > 2_000_000_000) {
throw new Error(`waf.${field} (${value}) must be an integer from 10 to 2000000000 — ${unit}.`);
}
return value;
};
return {
rateLimit: bounded("rateLimit", config?.rateLimit ?? 5000, "/api/* requests per client IP per 5 minutes"),
perTokenRateLimit: bounded("perTokenRateLimit", config?.perTokenRateLimit ?? 2000, "API requests per bearer token per 5 minutes"),
};
}
/** CommonRuleSet rules that only COUNT here: the API is JSON with free
* text, URLs, bulk-import batches and SVG data-URI logos, all shape-checked
* server-side, and M2M clients may send no User-Agent. */
exports.COMMON_RULES_COUNT_ONLY = [
"NoUserAgent_HEADER",
"SizeRestrictions_BODY",
"GenericRFI_BODY",
"GenericLFI_BODY",
"CrossSiteScripting_BODY",
];
/** One WAFv2 web ACL: optional per-IP and per-token rate limits + the AWS managed baseline
* (IP reputation, known bad inputs, common rule set), logging blocks and
* counts to CloudWatch with credentials redacted. */
class WebAcl extends constructs_1.Construct {
arn;
constructor(scope, id, props) {
super(scope, id);
// Sampled requests are kept unredacted for 3 hours; the redacted log
// below is the only capture.
const visibility = (metricName) => ({
cloudWatchMetricsEnabled: true,
sampledRequestsEnabled: false,
metricName,
});
const managed = (name, countOnly) => ({
name,
overrideAction: props.observeOnly ? { count: {} } : { none: {} },
visibilityConfig: visibility(name),
statement: {
managedRuleGroupStatement: {
vendorName: "AWS",
name,
ruleActionOverrides: props.observeOnly
? undefined
: countOnly?.map((rule) => ({
name: rule,
actionToUse: { count: {} },
})),
},
},
});
const block429 = {
block: {
customResponse: {
responseCode: 429,
responseHeaders: [{ name: "Retry-After", value: "60" }],
},
},
};
const underPath = (pathPrefix) => pathPrefix === undefined
? undefined
: {
byteMatchStatement: {
fieldToMatch: { uriPath: {} },
positionalConstraint: "STARTS_WITH",
searchString: pathPrefix,
textTransformations: [{ priority: 0, type: "NONE" }],
},
};
const rateRules = [];
if (props.rateLimit) {
rateRules.push({
name: "RateLimit",
action: block429,
visibilityConfig: visibility("RateLimit"),
statement: {
rateBasedStatement: {
limit: props.rateLimit.limit,
evaluationWindowSec: 300,
aggregateKeyType: "IP",
scopeDownStatement: underPath(props.rateLimit.pathPrefix),
},
},
});
}
if (props.tokenRateLimit) {
rateRules.push({
name: "TokenRateLimit",
action: block429,
visibilityConfig: visibility("TokenRateLimit"),
statement: {
rateBasedStatement: {
limit: props.tokenRateLimit.limit,
evaluationWindowSec: 300,
aggregateKeyType: "CUSTOM_KEYS",
customKeys: [
{
header: {
name: "authorization",
textTransformations: [{ priority: 0, type: "NONE" }],
},
},
],
scopeDownStatement: underPath(props.tokenRateLimit.pathPrefix),
},
},
});
}
const acl = new wafv2.CfnWebACL(this, "Acl", {
name: props.name,
scope: props.scope,
defaultAction: { allow: {} },
visibilityConfig: visibility(props.name),
// Evaluated in array order.
rules: [
...rateRules,
managed("AWSManagedRulesAmazonIpReputationList"),
managed("AWSManagedRulesKnownBadInputsRuleSet"),
managed("AWSManagedRulesCommonRuleSet", exports.COMMON_RULES_COUNT_ONLY),
].map((rule, priority) => ({ ...rule, priority })),
});
if (props.scope === "CLOUDFRONT") {
// The distribution detaches only after this stack deploys, and deleting
// an attached ACL fails the update — orphan it; cleanup is in the README.
acl.applyRemovalPolicy(cdk.RemovalPolicy.RETAIN);
}
this.arn = acl.attrArn;
// WAF only delivers to groups named aws-waf-logs-*; a retained named
// group collides on re-create, so this one goes with the stack.
const logGroup = new logs.LogGroup(this, "Logs", {
logGroupName: `aws-waf-logs-${props.name}`,
retention: logs.RetentionDays.THREE_MONTHS,
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
new wafv2.CfnLoggingConfiguration(this, "Logging", {
resourceArn: acl.attrArn,
// WAF rejects the log group's own ARN (it ends in ":*").
logDestinationConfigs: [
cdk.Stack.of(this).formatArn({
service: "logs",
resource: "log-group",
resourceName: logGroup.logGroupName,
arnFormat: cdk.ArnFormat.COLON_RESOURCE_NAME,
}),
],
// Blocked requests carry bearer tokens.
redactedFields: [
{ singleHeader: { Name: "authorization" } },
{ singleHeader: { Name: "cookie" } },
],
// Allowed traffic would be a per-request ingestion bill for no signal.
loggingFilter: {
DefaultBehavior: "DROP",
Filters: [
{
Behavior: "KEEP",
Requirement: "MEETS_ANY",
Conditions: [
{ ActionCondition: { Action: "BLOCK" } },
{ ActionCondition: { Action: "COUNT" } },
],
},
],
},
});
}
}
exports.WebAcl = WebAcl;