@fntio/infra-client
Version:
Self-hosted AWS access portal: credential vending, target-account trust, and grant-driven private networking as CDK stacks and constructs.
141 lines (139 loc) • 5.99 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/headscale-apikey/handler.ts
var handler_exports = {};
__export(handler_exports, {
handler: () => handler,
timing: () => timing
});
module.exports = __toCommonJS(handler_exports);
var import_client_ecs = require("@aws-sdk/client-ecs");
var import_client_cloudwatch_logs = require("@aws-sdk/client-cloudwatch-logs");
var import_client_secrets_manager = require("@aws-sdk/client-secrets-manager");
var ecs = new import_client_ecs.ECSClient({});
var logsClient = new import_client_cloudwatch_logs.CloudWatchLogsClient({});
var secrets = new import_client_secrets_manager.SecretsManagerClient({});
var WAIT_TIMEOUT_MS = 8 * 6e4;
var KEY_CONTAINER = "headscale";
var timing = { poll: 15e3, logLag: 5e3 };
var log = (msg, extra = {}) => console.log(JSON.stringify({ msg, ...extra }));
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function currentSecret(name) {
try {
const v = await secrets.send(new import_client_secrets_manager.GetSecretValueCommand({ SecretId: name }));
return v.SecretString?.trim() || void 0;
} catch (err) {
if (err instanceof import_client_secrets_manager.ResourceNotFoundException) return void 0;
throw err;
}
}
async function storeSecret(name, value) {
try {
await secrets.send(
new import_client_secrets_manager.CreateSecretCommand({
Name: name,
SecretString: value,
Description: "Headscale admin API key (minted by the deploy)"
})
);
} catch (err) {
if (!(err instanceof import_client_secrets_manager.ResourceExistsException)) throw err;
await secrets.send(new import_client_secrets_manager.PutSecretValueCommand({ SecretId: name, SecretString: value }));
}
}
async function awaitBootstrapTask(p, deadline) {
while (Date.now() < deadline) {
const svc = (await ecs.send(
new import_client_ecs.DescribeServicesCommand({ cluster: p.ClusterArn, services: [p.ServiceName] })
)).services?.[0];
if ((svc?.runningCount ?? 0) >= 1) {
const arns = (await ecs.send(
new import_client_ecs.ListTasksCommand({
cluster: p.ClusterArn,
serviceName: p.ServiceName,
desiredStatus: "RUNNING"
})
)).taskArns ?? [];
if (arns.length) {
const tasks = (await ecs.send(new import_client_ecs.DescribeTasksCommand({ cluster: p.ClusterArn, tasks: arns }))).tasks ?? [];
tasks.sort((a, b) => (b.startedAt?.getTime() ?? 0) - (a.startedAt?.getTime() ?? 0));
const task = tasks[0];
const server = task?.containers?.find((c) => c.name === KEY_CONTAINER);
if (server?.lastStatus === "STOPPED") {
throw new Error(
`${KEY_CONTAINER} exited ${server.exitCode} in task ${task.taskArn} \u2014 see its log stream`
);
}
if (server?.lastStatus === "RUNNING" && server.healthStatus === "HEALTHY") {
return task.taskArn.split("/").pop();
}
}
}
await sleep(timing.poll);
}
throw new Error(`service ${p.ServiceName} never had a healthy ${KEY_CONTAINER} container in time`);
}
var KEY_RE = /^APIKEY="?([A-Za-z0-9_-]+\.[A-Za-z0-9_-]{16,})"?,?$/;
async function readMintedKey(p, taskId, deadline) {
let lines = [];
do {
await sleep(timing.logLag);
const events = await logsClient.send(
new import_client_cloudwatch_logs.GetLogEventsCommand({
logGroupName: p.LogGroupName,
logStreamName: `${p.StreamPrefix}/${KEY_CONTAINER}/${taskId}`,
startFromHead: true
})
);
lines = (events.events ?? []).map((e) => (e.message ?? "").trim()).filter(Boolean);
for (const line of [...lines].reverse()) {
const m = KEY_RE.exec(line);
if (m) return m[1];
}
await sleep(timing.poll);
} while (Date.now() < deadline);
throw new Error(`no API key in the ${KEY_CONTAINER} output of task ${taskId} (${lines.length} lines)`);
}
async function handler(event) {
const p = event.ResourceProperties;
const physical = `headscale-apikey-${p.SiteId ?? "unknown"}`;
if (event.RequestType === "Delete") {
return { PhysicalResourceId: physical, Data: { Source: "kept" } };
}
for (const k of ["SiteId", "SecretName", "ClusterArn", "ServiceName", "LogGroupName", "StreamPrefix"]) {
if (!p[k]) throw new Error(`HeadscaleApiKey: ${k} property is required`);
}
const rotated = event.RequestType === "Update" && !!p.Rotation && p.Rotation !== event.OldResourceProperties?.Rotation;
const existing = await currentSecret(p.SecretName);
if (existing && !rotated) {
log("api key adopted", { site: p.SiteId, secret: p.SecretName });
return { PhysicalResourceId: physical, Data: { Source: "existing" } };
}
const deadline = Date.now() + WAIT_TIMEOUT_MS;
const taskId = await awaitBootstrapTask(p, deadline);
const key = await readMintedKey(p, taskId, deadline);
await storeSecret(p.SecretName, key);
log(rotated ? "api key rotated" : "api key minted", { site: p.SiteId, secret: p.SecretName, taskId });
return { PhysicalResourceId: physical, Data: { Source: rotated ? "rotated" : "created" } };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
handler,
timing
});