@fntio/infra-client
Version:
Self-hosted AWS access portal: credential vending, target-account trust, and grant-driven private networking as CDK stacks and constructs.
192 lines (191 loc) • 9.7 kB
JavaScript
"use strict";
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.TailnetConnector = void 0;
const cdk = __importStar(require("aws-cdk-lib"));
const constructs_1 = require("constructs");
const ec2 = __importStar(require("aws-cdk-lib/aws-ec2"));
const ecs = __importStar(require("aws-cdk-lib/aws-ecs"));
const logs = __importStar(require("aws-cdk-lib/aws-logs"));
const mirrored_image_1 = require("./mirrored-image");
const scratch_tmpfs_1 = require("./scratch-tmpfs");
/** In-VPC subnet router, one per VPC; dials OUT only. Grants decide who may
* route here — the resource's SG still decides what the VPC accepts. */
class TailnetConnector extends constructs_1.Construct {
securityGroup;
constructor(scope, id, props) {
super(scope, id);
const cluster = new ecs.Cluster(this, "Cluster", {
vpc: props.vpc,
containerInsightsV2: props.containerInsights
? ecs.ContainerInsights.ENABLED
: ecs.ContainerInsights.DISABLED,
});
const taskDef = new ecs.FargateTaskDefinition(this, "TaskDef", {
cpu: 256,
memoryLimitMiB: 512,
});
// Both containers non-root on a read-only root, each with its own tmpfs.
// No shared task volume (a Fargate task volume is root-owned whatever the
// image says): the minted key crosses the task's loopback,
// which the two containers share. Userspace forwarding needs no privilege.
const NONROOT = "65534";
const HANDOFF_PORT = 9909;
const tailscale = taskDef.addContainer("tailscale", {
// Pinned: we ship this update train (same policy as the control plane).
image: (0, mirrored_image_1.taskImage)(this, "TailscaleImage", "ghcr.io/tailscale/tailscale:v1.98.9", props.mirrorImages, taskDef),
// Self-auth waits for the minted key on loopback (busybox nc, one
// connection), then hands off to the stock entrypoint — upstream image
// stays unmodified. stdin MUST be at EOF: this nc (1.10-compatible)
// exits only once both stdin and the peer have closed, so a held-open
// stdin hangs it (2026-10-09 crash loop). No key within five minutes =
// exit, so the task restarts.
entryPoint: [
"/bin/sh",
"-ec",
[
'echo "waiting for the auth key on 127.0.0.1:' + HANDOFF_PORT + '"',
`timeout 300 nc -l -s 127.0.0.1 -p ${HANDOFF_PORT} </dev/null >/tmp/key`,
'TS_AUTHKEY="$(cat /tmp/key)"',
"rm -f /tmp/key",
'[ -n "$TS_AUTHKEY" ] || { echo "no auth key received"; exit 1; }',
'echo "auth key received, starting tailscale"',
"export TS_AUTHKEY",
"exec /usr/local/bin/containerboot",
].join("\n"),
],
user: NONROOT,
readonlyRootFilesystem: true,
linuxParameters: (0, scratch_tmpfs_1.scratchTmpfs)(this, "TmpfsTailscale", 64),
environment: {
// Fargate grants no NET_ADMIN/tun device; userspace forwarding is fine
// for developer access, not bulk transfer.
TS_USERSPACE: "true",
TS_AUTH_ONCE: "true",
TS_HOSTNAME: props.hostname ?? "connector",
TS_ROUTES: props.routes.join(","),
TS_EXTRA_ARGS: `--login-server=${props.controlUrl}`,
TS_STATE_DIR: "/tmp/tailscale",
},
// A connector can stay on "could not connect to the ... relay server" after the relay map
// comes back, until restarted (#83). Unhealthy after ~5 min of it, so ECS replaces the task.
// A status read that fails (daemon not up yet) passes. An empty map replaces a running
// connector at most once: the new task has no home relay, a different warning, and passes.
healthCheck: {
command: [
"CMD-SHELL",
"! tailscale --socket=/tmp/tailscaled.sock status --json 2>/dev/null | grep -q 'could not connect to the'",
],
interval: cdk.Duration.seconds(60),
timeout: cdk.Duration.seconds(15),
retries: 5,
startPeriod: cdk.Duration.seconds(300),
},
logging: ecs.LogDrivers.awsLogs({
streamPrefix: "connector",
logRetention: logs.RetentionDays.ONE_MONTH,
}),
});
// Mint at boot with the task role; aws-cli image has grep/sed, no jq needed.
// bash for /dev/tcp: the key goes to the tailscale container's listener,
// retried for two minutes while it comes up (it is started first).
const init = taskDef.addContainer("mint-authkey", {
image: ecs.ContainerImage.fromRegistry("public.ecr.aws/aws-cli/aws-cli:2.15.17"),
essential: false,
user: NONROOT,
readonlyRootFilesystem: true,
linuxParameters: (0, scratch_tmpfs_1.scratchTmpfs)(this, "TmpfsMint", 16),
entryPoint: ["/usr/bin/bash", "-c"],
command: [
[
"set -e",
'aws lambda invoke --function-name "$MINTER_ARN"' +
" --cli-binary-format raw-in-base64-out" +
' --payload \'{"keyType":"connector"}\' /tmp/out.json >/dev/null',
// one-line JSON: {"key":"tskey-…","expiresAt":"…"}
"KEY=$(grep -oE '\"key\":\"[^\"]+\"' /tmp/out.json | head -1 | sed 's/\"key\":\"//;s/\"//')",
'test -n "$KEY"',
"rm -f /tmp/out.json",
"n=0",
`until (printf %s "$KEY" > /dev/tcp/127.0.0.1/${HANDOFF_PORT}) 2>/dev/null; do n=$((n+1)); [ $n -lt 120 ] || exit 1; sleep 1; done`,
'echo "auth key handed to tailscale after $n retries"',
].join("; "),
],
environment: {
// The uid has no passwd entry in this image; the CLI resolves ~ via HOME.
HOME: "/tmp",
MINTER_ARN: props.minter.functionArn,
// The MINTER's region (from its ARN), not this VPC's — Lambda answers for its own
// region's endpoint only, and the hub may sit elsewhere.
AWS_REGION: props.minter.env.region,
},
logging: ecs.LogDrivers.awsLogs({
streamPrefix: "connector-mint",
logRetention: logs.RetentionDays.ONE_MONTH,
}),
});
init.addContainerDependencies({
container: tailscale,
condition: ecs.ContainerDependencyCondition.START,
});
// Identity-policy half of the invoke. Cross-account minters also need the
// resource-policy half, granted hub-side (grantConnectorAccount).
props.minter.grantInvoke(taskDef.taskRole);
this.securityGroup = new ec2.SecurityGroup(this, "Sg", {
vpc: props.vpc,
// EC2 rejects non-ASCII in this field - plain hyphen only.
description: "Tailnet connector - no inbound; resource SGs allow FROM this to be reachable.",
allowAllOutbound: true,
});
new ecs.FargateService(this, "Service", {
cluster,
taskDefinition: taskDef,
desiredCount: 1,
securityGroups: [this.securityGroup],
// Public subnet + public IP: the connector needs outbound internet to
// reach the control plane/DERP, and target-account VPCs often have no NAT.
assignPublicIp: true,
vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC },
minHealthyPercent: 0,
maxHealthyPercent: 100,
circuitBreaker: { rollback: true },
});
new cdk.CfnOutput(this, "ConnectorSecurityGroupId", {
value: this.securityGroup.securityGroupId,
description: "Allow this SG in a resource's security group to make it reachable over the tailnet.",
});
}
}
exports.TailnetConnector = TailnetConnector;