@fntio/infra-client
Version:
Self-hosted AWS access portal: credential vending, target-account trust, and grant-driven private networking as CDK stacks and constructs.
179 lines (175 loc) • 6.19 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// lambdacode/network/sg-manager.ts
var sg_manager_exports = {};
__export(sg_manager_exports, {
MANAGED_RULE_DESC: () => MANAGED_RULE_DESC,
handler: () => handler
});
module.exports = __toCommonJS(sg_manager_exports);
var import_client_ec2 = require("@aws-sdk/client-ec2");
// lambdacode/network/naming.ts
var NODE_NAME_LABEL = "[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?";
var NODE_NAME_RE = new RegExp(`^${NODE_NAME_LABEL}$`);
var DEFAULT_RESOURCE_PREFIX = "infra-client";
var managedRuleDesc = (prefix) => `${prefix}:managed`;
// lambdacode/network/sg-manager.ts
var ec2 = new import_client_ec2.EC2Client({});
var CONNECTOR_SG_ID = process.env.CONNECTOR_SG_ID;
var VPC_ID = process.env.VPC_ID ?? "";
var MANAGED_RULE_DESC = managedRuleDesc(
process.env.RESOURCE_PREFIX ?? DEFAULT_RESOURCE_PREFIX
);
var SG_ID_RE = /^sg-[0-9a-f]{8,17}$/;
var log = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
function managedPorts(sg) {
const ports = /* @__PURE__ */ new Set();
for (const perm of sg.IpPermissions ?? []) {
if (perm.IpProtocol !== "tcp") continue;
if (perm.FromPort === void 0 || perm.FromPort !== perm.ToPort) continue;
for (const pair of perm.UserIdGroupPairs ?? []) {
if (pair.GroupId === CONNECTOR_SG_ID && pair.Description === MANAGED_RULE_DESC) {
ports.add(perm.FromPort);
}
}
}
return ports;
}
function coveredPorts(sg, wanted) {
const covered = /* @__PURE__ */ new Set();
for (const perm of sg.IpPermissions ?? []) {
if (perm.IpProtocol !== "tcp") continue;
if (perm.FromPort === void 0 || perm.ToPort === void 0) continue;
if (!(perm.UserIdGroupPairs ?? []).some((p) => p.GroupId === CONNECTOR_SG_ID)) {
continue;
}
for (const port of wanted) {
if (port >= perm.FromPort && port <= perm.ToPort) covered.add(port);
}
}
return covered;
}
var permFor = (port) => ({
IpProtocol: "tcp",
FromPort: port,
ToPort: port,
UserIdGroupPairs: [{ GroupId: CONNECTOR_SG_ID, Description: MANAGED_RULE_DESC }]
});
async function describeByIds(ids) {
const found = /* @__PURE__ */ new Map();
if (!ids.length) return found;
const res = await ec2.send(
new import_client_ec2.DescribeSecurityGroupsCommand({
Filters: [{ Name: "group-id", Values: ids }]
})
);
for (const sg of res.SecurityGroups ?? []) {
if (sg.GroupId) found.set(sg.GroupId, sg);
}
return found;
}
async function describeReferencing() {
const res = await ec2.send(
new import_client_ec2.DescribeSecurityGroupsCommand({
Filters: [{ Name: "ip-permission.group-id", Values: [CONNECTOR_SG_ID] }]
})
);
const found = /* @__PURE__ */ new Map();
for (const sg of res.SecurityGroups ?? []) {
if (sg.GroupId) found.set(sg.GroupId, sg);
}
return found;
}
var handler = async (event) => {
if (!SG_ID_RE.test(CONNECTOR_SG_ID ?? "")) {
throw new Error("CONNECTOR_SG_ID env is missing or malformed");
}
const statuses = {};
const desired = /* @__PURE__ */ new Map();
for (const rule of event?.rules ?? []) {
const id = rule?.securityGroupId ?? "";
if (!SG_ID_RE.test(id)) {
if (id) statuses[id] = { status: "invalid" };
continue;
}
const ports = (Array.isArray(rule.ports) ? rule.ports : []).filter(
(p) => Number.isInteger(p) && p >= 1 && p <= 65535
);
if (!ports.length) {
statuses[id] ??= { status: "invalid" };
continue;
}
const set = desired.get(id) ?? /* @__PURE__ */ new Set();
ports.forEach((p) => set.add(p));
desired.set(id, set);
}
const [byId, referencing] = await Promise.all([
describeByIds([...desired.keys()]),
describeReferencing()
]);
const groupIds = /* @__PURE__ */ new Set([...desired.keys(), ...referencing.keys()]);
for (const groupId of groupIds) {
const wanted = desired.get(groupId) ?? /* @__PURE__ */ new Set();
const sg = byId.get(groupId) ?? referencing.get(groupId);
if (!sg) {
statuses[groupId] = { status: "not-found" };
continue;
}
if (VPC_ID && sg.VpcId && sg.VpcId !== VPC_ID) {
statuses[groupId] = { status: "other-vpc" };
continue;
}
try {
const managed = managedPorts(sg);
const covered = coveredPorts(sg, wanted);
const toAdd = [...wanted].filter((p) => !covered.has(p));
const toRemove = [...managed].filter((p) => !wanted.has(p));
if (toAdd.length) {
await ec2.send(
new import_client_ec2.AuthorizeSecurityGroupIngressCommand({
GroupId: groupId,
IpPermissions: toAdd.map(permFor)
})
);
}
if (toRemove.length) {
await ec2.send(
new import_client_ec2.RevokeSecurityGroupIngressCommand({
GroupId: groupId,
IpPermissions: toRemove.map(permFor)
})
);
}
statuses[groupId] = { status: "ok", added: toAdd.length, removed: toRemove.length };
if (toAdd.length || toRemove.length) {
log("converged", { groupId, added: toAdd, removed: toRemove });
}
} catch (err) {
const message = err.message;
statuses[groupId] = { status: "error", error: message };
log("WARN: converge failed", { groupId, error: message });
}
}
return { statuses };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MANAGED_RULE_DESC,
handler
});