.
This commit is contained in:
commit
08c0e9c107
33 files changed
+4312
No files matched your search
@@ -0,0 +1,261 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import {
|
||||
DEFAULT_INFISICAL_SITE_URL,
|
||||
type InfisicalEnvironment,
|
||||
type InfisicalSecretConfig,
|
||||
} from "../common/secret-manager.js";
|
||||
import { getKnownSecretKeys } from "../common/secret-manager.js";
|
||||
import { mergeDotenv, parseDotenv, type EnvTarget } from "../common/dotenv.js";
|
||||
import {
|
||||
buildMachineMetadata,
|
||||
type MachineMetadata,
|
||||
} from "./machine-metadata.js";
|
||||
|
||||
export interface ListenerConfig {
|
||||
enabled: boolean;
|
||||
host: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
export interface DaemonConfig {
|
||||
infisical: InfisicalSecretConfig;
|
||||
metadataPort: number;
|
||||
refreshIntervalMs: number;
|
||||
tokenSweepIntervalMs: number;
|
||||
allowSecretsBundle: boolean;
|
||||
secretAllowlist: readonly string[];
|
||||
allowedHosts: readonly string[];
|
||||
lanListener: ListenerConfig;
|
||||
linkLocalListener: ListenerConfig;
|
||||
machineEnvConfigPath: string;
|
||||
machineMetadata: MachineMetadata;
|
||||
}
|
||||
|
||||
const DEFAULT_METADATA_PORT = 8675;
|
||||
const DEFAULT_REFRESH_INTERVAL_SEC = 60;
|
||||
const DEFAULT_TOKEN_SWEEP_INTERVAL_SEC = 60;
|
||||
const LINK_LOCAL_ADDRESS = "169.254.169.254";
|
||||
|
||||
function defaultConfigPath(platform: NodeJS.Platform): string {
|
||||
if (platform === "darwin") return "/usr/local/etc/machine-env-service/env";
|
||||
return "/etc/machine-env-service/env";
|
||||
}
|
||||
|
||||
function boolFromEnv(
|
||||
value: string | undefined,
|
||||
defaultValue: boolean,
|
||||
): boolean {
|
||||
if (value === undefined || value.trim() === "") return defaultValue;
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (["1", "true", "yes", "on"].includes(normalized)) return true;
|
||||
if (["0", "false", "no", "off"].includes(normalized)) return false;
|
||||
throw new Error(`Invalid boolean value: ${value}`);
|
||||
}
|
||||
|
||||
function intFromEnv(
|
||||
key: string,
|
||||
value: string | undefined,
|
||||
defaultValue: number,
|
||||
options: { min: number; max?: number },
|
||||
): number {
|
||||
if (value === undefined || value.trim() === "") return defaultValue;
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
if (!Number.isInteger(parsed)) throw new Error(`${key} must be an integer`);
|
||||
if (parsed < options.min) throw new Error(`${key} must be >= ${options.min}`);
|
||||
if (options.max !== undefined && parsed > options.max) {
|
||||
throw new Error(`${key} must be <= ${options.max}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function required(env: EnvTarget, key: string): string {
|
||||
const value = env[key]?.trim();
|
||||
if (!value) throw new Error(`Missing required environment variable: ${key}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseEnvironment(value: string | undefined): InfisicalEnvironment {
|
||||
const normalized = value?.trim();
|
||||
if (
|
||||
normalized === "dev" ||
|
||||
normalized === "staging" ||
|
||||
normalized === "prod"
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
throw new Error("INFISICAL_ENVIRONMENT must be one of: dev, staging, prod");
|
||||
}
|
||||
|
||||
function parseList(value: string | undefined): string[] {
|
||||
if (!value) return [];
|
||||
return value
|
||||
.split(/[,\s]+/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function firstConfiguredList(
|
||||
env: EnvTarget,
|
||||
keys: readonly string[],
|
||||
): string[] {
|
||||
for (const key of keys) {
|
||||
const parsed = parseList(env[key]);
|
||||
if (parsed.length > 0) return parsed;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function currentIpv4Hosts(): string[] {
|
||||
const hosts = new Set<string>();
|
||||
|
||||
for (const addresses of Object.values(os.networkInterfaces())) {
|
||||
for (const address of addresses ?? []) {
|
||||
if (address.family !== "IPv4") continue;
|
||||
hosts.add(address.address);
|
||||
}
|
||||
}
|
||||
|
||||
return [...hosts];
|
||||
}
|
||||
|
||||
function normalizeHost(host: string): string {
|
||||
const trimmed = host.trim().toLowerCase();
|
||||
if (!trimmed) return trimmed;
|
||||
if (trimmed.startsWith("[")) {
|
||||
const closingBracket = trimmed.indexOf("]");
|
||||
return closingBracket === -1 ? trimmed : trimmed.slice(1, closingBracket);
|
||||
}
|
||||
|
||||
const colon = trimmed.lastIndexOf(":");
|
||||
if (colon === -1) return trimmed;
|
||||
|
||||
const maybePort = trimmed.slice(colon + 1);
|
||||
if (/^\d+$/.test(maybePort)) return trimmed.slice(0, colon);
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function buildAllowedHosts(env: EnvTarget, metadataPort: number): string[] {
|
||||
const configured = firstConfiguredList(env, [
|
||||
"METADATA_ALLOWED_HOSTS",
|
||||
"ALLOWED_HOSTS",
|
||||
]);
|
||||
const hosts = new Set(
|
||||
[
|
||||
LINK_LOCAL_ADDRESS,
|
||||
"localhost",
|
||||
"127.0.0.1",
|
||||
"host.docker.internal",
|
||||
...currentIpv4Hosts(),
|
||||
...configured,
|
||||
].map(normalizeHost),
|
||||
);
|
||||
|
||||
hosts.add(normalizeHost(`${LINK_LOCAL_ADDRESS}:80`));
|
||||
hosts.add(normalizeHost(`127.0.0.1:${metadataPort}`));
|
||||
return [...hosts].filter(Boolean).sort();
|
||||
}
|
||||
|
||||
function warnIfWeakConfigFilePermissions(filePath: string): void {
|
||||
try {
|
||||
const stat = fs.statSync(filePath);
|
||||
if ((stat.mode & 0o077) !== 0) {
|
||||
console.warn(
|
||||
`[Config] ${filePath} is readable by group/others. Recommended mode is 0600.`,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// Permission checks are best effort only; required values are validated below.
|
||||
}
|
||||
}
|
||||
|
||||
function loadMachineEnvFile(env: EnvTarget): string {
|
||||
const configuredPath = env["MACHINE_ENV_CONFIG"]?.trim();
|
||||
const filePath = path.resolve(
|
||||
configuredPath || defaultConfigPath(process.platform),
|
||||
);
|
||||
|
||||
if (!fs.existsSync(filePath)) {
|
||||
if (configuredPath) {
|
||||
console.warn(`[Config] MACHINE_ENV_CONFIG not found: ${filePath}`);
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
|
||||
mergeDotenv(env, parseDotenv(fs.readFileSync(filePath, "utf8")));
|
||||
warnIfWeakConfigFilePermissions(filePath);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
export function loadConfig(env: EnvTarget = process.env): DaemonConfig {
|
||||
const machineEnvConfigPath = loadMachineEnvFile(env);
|
||||
const metadataPort = intFromEnv(
|
||||
"METADATA_PORT",
|
||||
env["METADATA_PORT"],
|
||||
DEFAULT_METADATA_PORT,
|
||||
{
|
||||
min: 1,
|
||||
max: 65535,
|
||||
},
|
||||
);
|
||||
const refreshIntervalSec = intFromEnv(
|
||||
"REFRESH_INTERVAL_SEC",
|
||||
env["REFRESH_INTERVAL_SEC"],
|
||||
DEFAULT_REFRESH_INTERVAL_SEC,
|
||||
{ min: 1 },
|
||||
);
|
||||
const tokenSweepIntervalSec = intFromEnv(
|
||||
"TOKEN_SWEEP_INTERVAL_SEC",
|
||||
env["TOKEN_SWEEP_INTERVAL_SEC"],
|
||||
DEFAULT_TOKEN_SWEEP_INTERVAL_SEC,
|
||||
{ min: 1 },
|
||||
);
|
||||
const configuredAllowlist = firstConfiguredList(env, [
|
||||
"KNOWN_SECRET_KEYS",
|
||||
"EXPOSED_SECRET_KEYS",
|
||||
"SECRET_ALLOWLIST",
|
||||
"SECRET_WHITELIST",
|
||||
]);
|
||||
const secretAllowlist =
|
||||
configuredAllowlist.length > 0
|
||||
? configuredAllowlist
|
||||
: [...getKnownSecretKeys()];
|
||||
|
||||
if (secretAllowlist.length === 0) {
|
||||
console.warn(
|
||||
"[Config] No secret allowlist configured; metadata secret routes will be empty.",
|
||||
);
|
||||
}
|
||||
const infisicalEnvironment = parseEnvironment(env["INFISICAL_ENVIRONMENT"]);
|
||||
|
||||
return {
|
||||
infisical: {
|
||||
accessToken: required(env, "INFISICAL_ACCESS_TOKEN"),
|
||||
projectId: required(env, "INFISICAL_PROJECT_ID"),
|
||||
environment: infisicalEnvironment,
|
||||
siteUrl: env["INFISICAL_SITE_URL"]?.trim() || DEFAULT_INFISICAL_SITE_URL,
|
||||
},
|
||||
metadataPort,
|
||||
refreshIntervalMs: refreshIntervalSec * 1000,
|
||||
tokenSweepIntervalMs: tokenSweepIntervalSec * 1000,
|
||||
allowSecretsBundle: boolFromEnv(env["ALLOW_SECRETS_BUNDLE"], false),
|
||||
secretAllowlist,
|
||||
allowedHosts: buildAllowedHosts(env, metadataPort),
|
||||
lanListener: {
|
||||
enabled: boolFromEnv(env["LAN_LISTENER_ENABLED"], true),
|
||||
host: env["LAN_LISTENER_HOST"]?.trim() || "0.0.0.0",
|
||||
port: metadataPort,
|
||||
},
|
||||
linkLocalListener: {
|
||||
enabled: boolFromEnv(env["LINK_LOCAL_LISTENER_ENABLED"], true),
|
||||
host: env["LINK_LOCAL_HOST"]?.trim() || LINK_LOCAL_ADDRESS,
|
||||
port: intFromEnv("LINK_LOCAL_PORT", env["LINK_LOCAL_PORT"], 80, {
|
||||
min: 1,
|
||||
max: 65535,
|
||||
}),
|
||||
},
|
||||
machineEnvConfigPath,
|
||||
machineMetadata: buildMachineMetadata(env, infisicalEnvironment),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from "node:http";
|
||||
|
||||
export function getSingleHeader(headers: IncomingHttpHeaders, name: string): string | undefined {
|
||||
const value = headers[name.toLowerCase()];
|
||||
if (Array.isArray(value)) return value[0];
|
||||
return value;
|
||||
}
|
||||
|
||||
export function sendText(
|
||||
res: ServerResponse,
|
||||
statusCode: number,
|
||||
body = "",
|
||||
headers: Record<string, string> = {},
|
||||
): void {
|
||||
res.writeHead(statusCode, {
|
||||
"Content-Type": "text/plain; charset=utf-8",
|
||||
"Cache-Control": "no-store",
|
||||
...headers,
|
||||
});
|
||||
res.end(body);
|
||||
}
|
||||
|
||||
export function sendJson(res: ServerResponse, statusCode: number, body: unknown): void {
|
||||
res.writeHead(statusCode, {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Cache-Control": "no-store",
|
||||
});
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
export function requestPath(req: IncomingMessage): string {
|
||||
const url = new URL(req.url ?? "/", "http://metadata.local");
|
||||
return url.pathname;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import crypto from "node:crypto";
|
||||
import type { InfisicalEnvironment } from "../common/secret-manager.js";
|
||||
import type { EnvTarget } from "../common/dotenv.js";
|
||||
|
||||
export interface MachineMetadata {
|
||||
hostname: string;
|
||||
localHostname: string;
|
||||
localIpv4: string;
|
||||
mac: string;
|
||||
machineId: string;
|
||||
environment: InfisicalEnvironment;
|
||||
role: string | undefined;
|
||||
tags: Record<string, string>;
|
||||
userData: string | undefined;
|
||||
}
|
||||
|
||||
export interface InstanceIdentityDocument {
|
||||
documentVersion: string;
|
||||
service: "machine-env-service";
|
||||
machineId: string;
|
||||
hostname: string;
|
||||
localHostname: string;
|
||||
localIpV4: string;
|
||||
mac: string;
|
||||
environment: InfisicalEnvironment;
|
||||
role?: string;
|
||||
tags: Record<string, string>;
|
||||
}
|
||||
|
||||
interface PrimaryNetworkIdentity {
|
||||
localIpv4: string;
|
||||
mac: string;
|
||||
}
|
||||
|
||||
function readFirstExistingFile(paths: readonly string[]): string | undefined {
|
||||
for (const filePath of paths) {
|
||||
try {
|
||||
const value = fs.readFileSync(filePath, "utf8").trim();
|
||||
if (value) return value;
|
||||
} catch {
|
||||
// Missing OS-specific identity files are expected on some platforms.
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function resolvePrimaryNetworkIdentity(): PrimaryNetworkIdentity {
|
||||
for (const addresses of Object.values(os.networkInterfaces())) {
|
||||
for (const address of addresses ?? []) {
|
||||
if (address.family !== "IPv4" || address.internal) continue;
|
||||
return {
|
||||
localIpv4: address.address,
|
||||
mac: address.mac || "00:00:00:00:00:00",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
localIpv4: "127.0.0.1",
|
||||
mac: "00:00:00:00:00:00",
|
||||
};
|
||||
}
|
||||
|
||||
function fallbackMachineId(hostname: string, localIpv4: string, mac: string): string {
|
||||
return crypto
|
||||
.createHash("sha256")
|
||||
.update(`${hostname}|${localIpv4}|${mac}`)
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
function parseTags(value: string | undefined): Record<string, string> {
|
||||
const tags: Record<string, string> = {};
|
||||
if (!value) return tags;
|
||||
|
||||
for (const rawPair of value.split(/[,\n]/)) {
|
||||
const pair = rawPair.trim();
|
||||
if (!pair) continue;
|
||||
|
||||
const separator = pair.indexOf("=");
|
||||
if (separator <= 0) continue;
|
||||
|
||||
const key = pair.slice(0, separator).trim();
|
||||
const tagValue = pair.slice(separator + 1).trim();
|
||||
if (!key || key.includes("/")) continue;
|
||||
|
||||
tags[key] = tagValue;
|
||||
}
|
||||
|
||||
return tags;
|
||||
}
|
||||
|
||||
function readUserData(env: EnvTarget): string | undefined {
|
||||
const inline = env["USER_DATA"] ?? env["MACHINE_USER_DATA"] ?? env["METADATA_USER_DATA"];
|
||||
if (inline !== undefined) return inline;
|
||||
|
||||
const filePath = env["USER_DATA_FILE"] ?? env["MACHINE_USER_DATA_FILE"] ?? env["METADATA_USER_DATA_FILE"];
|
||||
if (!filePath?.trim()) return undefined;
|
||||
|
||||
try {
|
||||
return fs.readFileSync(filePath.trim(), "utf8");
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.warn(`[Config] Failed to read user-data file ${filePath}: ${message}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function buildMachineMetadata(
|
||||
env: EnvTarget,
|
||||
environment: InfisicalEnvironment,
|
||||
): MachineMetadata {
|
||||
const hostname = env["MACHINE_HOSTNAME"]?.trim() || os.hostname();
|
||||
const network = resolvePrimaryNetworkIdentity();
|
||||
const localIpv4 = env["MACHINE_LOCAL_IPV4"]?.trim() || network.localIpv4;
|
||||
const mac = env["MACHINE_MAC"]?.trim() || network.mac;
|
||||
const machineId =
|
||||
env["MACHINE_ID"]?.trim() ||
|
||||
readFirstExistingFile(["/etc/machine-id", "/var/lib/dbus/machine-id"]) ||
|
||||
fallbackMachineId(hostname, localIpv4, mac);
|
||||
|
||||
return {
|
||||
hostname,
|
||||
localHostname: env["MACHINE_LOCAL_HOSTNAME"]?.trim() || hostname,
|
||||
localIpv4,
|
||||
mac,
|
||||
machineId,
|
||||
environment,
|
||||
role: env["MACHINE_ROLE"]?.trim() || env["METADATA_ROLE"]?.trim() || undefined,
|
||||
tags: parseTags(env["MACHINE_TAGS"] ?? env["METADATA_TAGS"]),
|
||||
userData: readUserData(env),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildInstanceIdentityDocument(
|
||||
metadata: MachineMetadata,
|
||||
): InstanceIdentityDocument {
|
||||
return {
|
||||
documentVersion: "2026-05-01",
|
||||
service: "machine-env-service",
|
||||
machineId: metadata.machineId,
|
||||
hostname: metadata.hostname,
|
||||
localHostname: metadata.localHostname,
|
||||
localIpV4: metadata.localIpv4,
|
||||
mac: metadata.mac,
|
||||
environment: metadata.environment,
|
||||
...(metadata.role ? { role: metadata.role } : {}),
|
||||
tags: metadata.tags,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env node
|
||||
import { loadEnvironmentFromNodeEnv } from "../common/env-loader.js";
|
||||
import { loadConfig } from "./config.js";
|
||||
import { MetadataServer } from "./server.js";
|
||||
import { SecretCache } from "./store/secret-cache.js";
|
||||
import { TokenStore } from "./store/token-store.js";
|
||||
|
||||
async function run(): Promise<void> {
|
||||
if (!process.env["MACHINE_ENV_CONFIG"]) {
|
||||
loadEnvironmentFromNodeEnv();
|
||||
}
|
||||
|
||||
const config = loadConfig();
|
||||
const secretCache = new SecretCache({
|
||||
infisical: config.infisical,
|
||||
allowlist: config.secretAllowlist,
|
||||
refreshIntervalMs: config.refreshIntervalMs,
|
||||
});
|
||||
const tokenStore = new TokenStore(config.tokenSweepIntervalMs);
|
||||
const server = new MetadataServer({ config, secretCache, tokenStore });
|
||||
|
||||
tokenStore.start();
|
||||
await secretCache.start();
|
||||
await server.start();
|
||||
|
||||
const shutdown = async (signal: NodeJS.Signals): Promise<void> => {
|
||||
console.info(`[Main] Received ${signal}; shutting down.`);
|
||||
process.off("SIGTERM", onSigterm);
|
||||
process.off("SIGINT", onSigint);
|
||||
|
||||
try {
|
||||
await server.stop();
|
||||
secretCache.stop();
|
||||
tokenStore.stop();
|
||||
process.exitCode = 0;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(`[Main] Shutdown failed: ${message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
};
|
||||
|
||||
const onSigterm = (): void => void shutdown("SIGTERM");
|
||||
const onSigint = (): void => void shutdown("SIGINT");
|
||||
|
||||
process.on("SIGTERM", onSigterm);
|
||||
process.on("SIGINT", onSigint);
|
||||
}
|
||||
|
||||
run().catch((error: unknown) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(`[Main] Failed to start: ${message}`);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { getSingleHeader, requestPath, sendText } from "../http-utils.js";
|
||||
|
||||
export interface SsrfGuardOptions {
|
||||
allowedHosts: readonly string[];
|
||||
}
|
||||
|
||||
function normalizeHost(host: string): string {
|
||||
const trimmed = host.trim().toLowerCase();
|
||||
if (!trimmed) return trimmed;
|
||||
if (trimmed.startsWith("[")) {
|
||||
const closingBracket = trimmed.indexOf("]");
|
||||
return closingBracket === -1 ? trimmed : trimmed.slice(1, closingBracket);
|
||||
}
|
||||
|
||||
const colon = trimmed.lastIndexOf(":");
|
||||
if (colon === -1) return trimmed;
|
||||
|
||||
const maybePort = trimmed.slice(colon + 1);
|
||||
if (/^\d+$/.test(maybePort)) return trimmed.slice(0, colon);
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
export function ssrfGuard(
|
||||
req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
options: SsrfGuardOptions,
|
||||
): boolean {
|
||||
if (getSingleHeader(req.headers, "x-forwarded-for") !== undefined) {
|
||||
sendText(res, 403);
|
||||
return false;
|
||||
}
|
||||
|
||||
const host = getSingleHeader(req.headers, "host");
|
||||
if (!host || !options.allowedHosts.includes(normalizeHost(host))) {
|
||||
sendText(res, 403);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (requestPath(req) === "/latest/api/token" && req.method !== "PUT") {
|
||||
res.setHeader("Allow", "PUT");
|
||||
sendText(res, 405);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { getSingleHeader, sendText } from "../http-utils.js";
|
||||
import type { TokenStore } from "../store/token-store.js";
|
||||
|
||||
const TOKEN_HEADER = "x-aws-ec2-metadata-token";
|
||||
|
||||
export function requireMetadataToken(
|
||||
req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
tokenStore: TokenStore,
|
||||
): boolean {
|
||||
const token = getSingleHeader(req.headers, TOKEN_HEADER);
|
||||
if (!tokenStore.validate(token)) {
|
||||
sendText(res, 401);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { requestPath, sendJson, sendText } from "../http-utils.js";
|
||||
import {
|
||||
buildInstanceIdentityDocument,
|
||||
type MachineMetadata,
|
||||
} from "../machine-metadata.js";
|
||||
|
||||
const DYNAMIC_ROOT = "/latest/dynamic/";
|
||||
const INSTANCE_IDENTITY_ROOT = "/latest/dynamic/instance-identity/";
|
||||
|
||||
export function handleDynamicRequest(
|
||||
req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
metadata: MachineMetadata,
|
||||
): void {
|
||||
if (req.method !== "GET") {
|
||||
res.setHeader("Allow", "GET");
|
||||
sendText(res, 405);
|
||||
return;
|
||||
}
|
||||
|
||||
const pathname = requestPath(req);
|
||||
if (pathname === "/latest/dynamic") {
|
||||
sendText(res, 301, "", { Location: DYNAMIC_ROOT });
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === DYNAMIC_ROOT) {
|
||||
sendText(res, 200, "instance-identity/\n");
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/dynamic/instance-identity") {
|
||||
sendText(res, 301, "", { Location: INSTANCE_IDENTITY_ROOT });
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === INSTANCE_IDENTITY_ROOT) {
|
||||
sendText(res, 200, "document\n");
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/dynamic/instance-identity/document") {
|
||||
sendJson(res, 200, buildInstanceIdentityDocument(metadata));
|
||||
return;
|
||||
}
|
||||
|
||||
sendText(res, 404);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { requestPath, sendText } from "../http-utils.js";
|
||||
import type { MachineMetadata } from "../machine-metadata.js";
|
||||
import type { SecretCache } from "../store/secret-cache.js";
|
||||
import {
|
||||
handleSecretsBundle,
|
||||
handleSecretsDirectory,
|
||||
handleSecretValue,
|
||||
} from "./secrets.js";
|
||||
|
||||
const META_DATA_ROOT = "/latest/meta-data/";
|
||||
const SECRETS_PREFIX = "/latest/meta-data/secrets/";
|
||||
const TAGS_PREFIX = "/latest/meta-data/tags/";
|
||||
const INSTANCE_TAGS_PREFIX = "/latest/meta-data/tags/instance/";
|
||||
|
||||
export interface MetadataRouteOptions {
|
||||
cache: SecretCache;
|
||||
allowSecretsBundle: boolean;
|
||||
machineMetadata: MachineMetadata;
|
||||
}
|
||||
|
||||
function listRootEntries(options: MetadataRouteOptions): string {
|
||||
const entries = [
|
||||
"environment",
|
||||
"hostname",
|
||||
"local-hostname",
|
||||
"local-ipv4",
|
||||
"mac",
|
||||
"machine-id",
|
||||
"secrets/",
|
||||
"tags/",
|
||||
];
|
||||
|
||||
if (options.machineMetadata.role) entries.push("role");
|
||||
if (options.allowSecretsBundle) entries.push("secrets-bundle");
|
||||
return `${entries.sort().join("\n")}\n`;
|
||||
}
|
||||
|
||||
function decodePathSegment(segment: string): string | null {
|
||||
try {
|
||||
const decoded = decodeURIComponent(segment);
|
||||
if (!decoded || decoded.includes("/")) return null;
|
||||
return decoded;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function sendOptionalText(res: ServerResponse, value: string | undefined): void {
|
||||
if (value === undefined) {
|
||||
sendText(res, 404);
|
||||
return;
|
||||
}
|
||||
|
||||
sendText(res, 200, value);
|
||||
}
|
||||
|
||||
function handleTagsRequest(
|
||||
pathname: string,
|
||||
res: ServerResponse,
|
||||
metadata: MachineMetadata,
|
||||
): boolean {
|
||||
if (pathname === "/latest/meta-data/tags") {
|
||||
sendText(res, 301, "", { Location: TAGS_PREFIX });
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pathname === TAGS_PREFIX) {
|
||||
sendText(res, 200, "instance/\n");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/meta-data/tags/instance") {
|
||||
sendText(res, 301, "", { Location: INSTANCE_TAGS_PREFIX });
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pathname === INSTANCE_TAGS_PREFIX) {
|
||||
const keys = Object.keys(metadata.tags).sort();
|
||||
sendText(res, 200, keys.length === 0 ? "" : `${keys.join("\n")}\n`);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pathname.startsWith(INSTANCE_TAGS_PREFIX)) {
|
||||
const key = decodePathSegment(pathname.slice(INSTANCE_TAGS_PREFIX.length));
|
||||
if (!key) {
|
||||
sendText(res, 404);
|
||||
return true;
|
||||
}
|
||||
|
||||
sendOptionalText(res, metadata.tags[key]);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pathname.startsWith(TAGS_PREFIX)) {
|
||||
const key = decodePathSegment(pathname.slice(TAGS_PREFIX.length));
|
||||
if (!key || key === "instance") {
|
||||
sendText(res, 404);
|
||||
return true;
|
||||
}
|
||||
|
||||
sendOptionalText(res, metadata.tags[key]);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function handleMetadataRequest(
|
||||
req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
options: MetadataRouteOptions,
|
||||
): void {
|
||||
if (req.method !== "GET") {
|
||||
res.setHeader("Allow", "GET");
|
||||
sendText(res, 405);
|
||||
return;
|
||||
}
|
||||
|
||||
const pathname = requestPath(req);
|
||||
if (pathname === "/latest/meta-data") {
|
||||
sendText(res, 301, "", { Location: META_DATA_ROOT });
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === META_DATA_ROOT) {
|
||||
sendText(res, 200, listRootEntries(options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/meta-data/environment") {
|
||||
sendText(res, 200, options.machineMetadata.environment);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/meta-data/hostname") {
|
||||
sendText(res, 200, options.machineMetadata.hostname);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/meta-data/local-hostname") {
|
||||
sendText(res, 200, options.machineMetadata.localHostname);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/meta-data/local-ipv4") {
|
||||
sendText(res, 200, options.machineMetadata.localIpv4);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/meta-data/mac") {
|
||||
sendText(res, 200, options.machineMetadata.mac);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/meta-data/machine-id") {
|
||||
sendText(res, 200, options.machineMetadata.machineId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/meta-data/role") {
|
||||
sendOptionalText(res, options.machineMetadata.role);
|
||||
return;
|
||||
}
|
||||
|
||||
if (handleTagsRequest(pathname, res, options.machineMetadata)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === SECRETS_PREFIX) {
|
||||
handleSecretsDirectory(res, options.cache);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname.startsWith(SECRETS_PREFIX)) {
|
||||
handleSecretValue(pathname, res, options.cache);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/meta-data/secrets-bundle") {
|
||||
handleSecretsBundle(res, options.cache, options.allowSecretsBundle);
|
||||
return;
|
||||
}
|
||||
|
||||
sendText(res, 404);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { ServerResponse } from "node:http";
|
||||
import { sendJson, sendText } from "../http-utils.js";
|
||||
import type { SecretCache } from "../store/secret-cache.js";
|
||||
|
||||
const SECRETS_PREFIX = "/latest/meta-data/secrets/";
|
||||
|
||||
function decodeSecretKey(rawKey: string): string | null {
|
||||
try {
|
||||
const decoded = decodeURIComponent(rawKey);
|
||||
if (!decoded || decoded.includes("/")) return null;
|
||||
return decoded;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function handleSecretsDirectory(res: ServerResponse, cache: SecretCache): void {
|
||||
const keys = cache.list();
|
||||
sendText(res, 200, keys.length === 0 ? "" : `${keys.join("\n")}\n`);
|
||||
}
|
||||
|
||||
export function handleSecretValue(pathname: string, res: ServerResponse, cache: SecretCache): void {
|
||||
const rawKey = pathname.slice(SECRETS_PREFIX.length);
|
||||
const key = decodeSecretKey(rawKey);
|
||||
if (!key || !cache.isAllowed(key)) {
|
||||
sendText(res, 404);
|
||||
return;
|
||||
}
|
||||
|
||||
const value = cache.get(key);
|
||||
if (value === undefined) {
|
||||
sendText(res, 404);
|
||||
return;
|
||||
}
|
||||
|
||||
sendText(res, 200, value);
|
||||
}
|
||||
|
||||
export function handleSecretsBundle(
|
||||
res: ServerResponse,
|
||||
cache: SecretCache,
|
||||
enabled: boolean,
|
||||
): void {
|
||||
if (!enabled) {
|
||||
sendText(res, 404);
|
||||
return;
|
||||
}
|
||||
|
||||
sendJson(res, 200, cache.bundle());
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { getSingleHeader, sendText } from "../http-utils.js";
|
||||
import {
|
||||
MAX_TOKEN_TTL_SECONDS,
|
||||
MIN_TOKEN_TTL_SECONDS,
|
||||
type TokenStore,
|
||||
} from "../store/token-store.js";
|
||||
|
||||
const TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds";
|
||||
|
||||
function parseTokenTtl(req: IncomingMessage): number | null {
|
||||
const raw = getSingleHeader(req.headers, TTL_HEADER);
|
||||
if (!raw) return null;
|
||||
|
||||
const ttl = Number.parseInt(raw, 10);
|
||||
if (!Number.isInteger(ttl) || String(ttl) !== raw.trim()) return null;
|
||||
if (ttl < MIN_TOKEN_TTL_SECONDS || ttl > MAX_TOKEN_TTL_SECONDS) return null;
|
||||
return ttl;
|
||||
}
|
||||
|
||||
export function handleTokenRequest(
|
||||
req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
tokenStore: TokenStore,
|
||||
): void {
|
||||
if (req.method !== "PUT") {
|
||||
res.setHeader("Allow", "PUT");
|
||||
sendText(res, 405);
|
||||
return;
|
||||
}
|
||||
|
||||
const ttl = parseTokenTtl(req);
|
||||
if (ttl === null) {
|
||||
sendText(res, 400);
|
||||
return;
|
||||
}
|
||||
|
||||
sendText(res, 200, tokenStore.issue(ttl));
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { sendText } from "../http-utils.js";
|
||||
import type { MachineMetadata } from "../machine-metadata.js";
|
||||
|
||||
export function handleUserDataRequest(
|
||||
req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
metadata: MachineMetadata,
|
||||
): void {
|
||||
if (req.method !== "GET") {
|
||||
res.setHeader("Allow", "GET");
|
||||
sendText(res, 405);
|
||||
return;
|
||||
}
|
||||
|
||||
if (metadata.userData === undefined) {
|
||||
sendText(res, 404);
|
||||
return;
|
||||
}
|
||||
|
||||
sendText(res, 200, metadata.userData);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import http, { type IncomingMessage, type Server, type ServerResponse } from "node:http";
|
||||
import type { DaemonConfig, ListenerConfig } from "./config.js";
|
||||
import { requestPath, sendText } from "./http-utils.js";
|
||||
import { ssrfGuard } from "./middleware/ssrf-guard.js";
|
||||
import { requireMetadataToken } from "./middleware/token-auth.js";
|
||||
import { handleDynamicRequest } from "./routes/dynamic.js";
|
||||
import { handleMetadataRequest } from "./routes/metadata.js";
|
||||
import { handleTokenRequest } from "./routes/token.js";
|
||||
import { handleUserDataRequest } from "./routes/user-data.js";
|
||||
import type { SecretCache } from "./store/secret-cache.js";
|
||||
import type { TokenStore } from "./store/token-store.js";
|
||||
|
||||
export interface MetadataServerOptions {
|
||||
config: DaemonConfig;
|
||||
secretCache: SecretCache;
|
||||
tokenStore: TokenStore;
|
||||
}
|
||||
|
||||
interface RunningServer {
|
||||
name: string;
|
||||
server: Server;
|
||||
}
|
||||
|
||||
export class MetadataServer {
|
||||
private readonly servers: RunningServer[] = [];
|
||||
private closing = false;
|
||||
|
||||
constructor(private readonly options: MetadataServerOptions) {}
|
||||
|
||||
async start(): Promise<void> {
|
||||
const listeners = [
|
||||
{ name: "link-local", config: this.options.config.linkLocalListener },
|
||||
{ name: "lan", config: this.options.config.lanListener },
|
||||
];
|
||||
|
||||
for (const listener of listeners) {
|
||||
if (!listener.config.enabled) continue;
|
||||
await this.listen(listener.name, listener.config);
|
||||
}
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.closing = true;
|
||||
await Promise.all(
|
||||
this.servers.map(
|
||||
({ server }) =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => {
|
||||
if (error) reject(error);
|
||||
else resolve();
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
this.servers.length = 0;
|
||||
}
|
||||
|
||||
private async listen(name: string, config: ListenerConfig): Promise<void> {
|
||||
const server = http.createServer((req, res) => this.handleRequest(req, res));
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const onError = (error: Error): void => {
|
||||
server.off("listening", onListening);
|
||||
reject(error);
|
||||
};
|
||||
const onListening = (): void => {
|
||||
server.off("error", onError);
|
||||
resolve();
|
||||
};
|
||||
|
||||
server.once("error", onError);
|
||||
server.once("listening", onListening);
|
||||
server.listen(config.port, config.host);
|
||||
});
|
||||
|
||||
this.servers.push({ name, server });
|
||||
console.info(`[Server] ${name} listener ready on ${config.host}:${config.port}`);
|
||||
}
|
||||
|
||||
private handleRequest(req: IncomingMessage, res: ServerResponse): void {
|
||||
if (this.closing) {
|
||||
sendText(res, 503);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ssrfGuard(req, res, { allowedHosts: this.options.config.allowedHosts })) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pathname = requestPath(req);
|
||||
if (pathname === "/latest/api/token") {
|
||||
handleTokenRequest(req, res, this.options.tokenStore);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/meta-data" || pathname.startsWith("/latest/meta-data/")) {
|
||||
if (!requireMetadataToken(req, res, this.options.tokenStore)) return;
|
||||
handleMetadataRequest(req, res, {
|
||||
cache: this.options.secretCache,
|
||||
allowSecretsBundle: this.options.config.allowSecretsBundle,
|
||||
machineMetadata: this.options.config.machineMetadata,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/dynamic" || pathname.startsWith("/latest/dynamic/")) {
|
||||
if (!requireMetadataToken(req, res, this.options.tokenStore)) return;
|
||||
handleDynamicRequest(req, res, this.options.config.machineMetadata);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/latest/user-data") {
|
||||
if (!requireMetadataToken(req, res, this.options.tokenStore)) return;
|
||||
handleUserDataRequest(req, res, this.options.config.machineMetadata);
|
||||
return;
|
||||
}
|
||||
|
||||
sendText(res, 404);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import {
|
||||
fetchInfisicalSecrets,
|
||||
type InfisicalSecretConfig,
|
||||
type RawSecretMap,
|
||||
} from "../../common/secret-manager.js";
|
||||
|
||||
export interface SecretCacheOptions {
|
||||
infisical: InfisicalSecretConfig;
|
||||
allowlist: readonly string[];
|
||||
refreshIntervalMs: number;
|
||||
}
|
||||
|
||||
export class SecretCache {
|
||||
private readonly allowedKeys: Set<string>;
|
||||
private secrets = new Map<string, string>();
|
||||
private refreshTimer: NodeJS.Timeout | undefined;
|
||||
private refreshInFlight: Promise<void> | undefined;
|
||||
|
||||
lastRefreshAt: Date | undefined;
|
||||
lastError: Error | undefined;
|
||||
|
||||
constructor(private readonly options: SecretCacheOptions) {
|
||||
this.allowedKeys = new Set(options.allowlist);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
await this.refresh();
|
||||
if (this.refreshTimer) return;
|
||||
|
||||
this.refreshTimer = setInterval(() => {
|
||||
void this.refresh();
|
||||
}, this.options.refreshIntervalMs);
|
||||
this.refreshTimer.unref();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (!this.refreshTimer) return;
|
||||
clearInterval(this.refreshTimer);
|
||||
this.refreshTimer = undefined;
|
||||
}
|
||||
|
||||
async refresh(): Promise<void> {
|
||||
if (this.refreshInFlight) return this.refreshInFlight;
|
||||
|
||||
this.refreshInFlight = this.fetchAndSwap()
|
||||
.catch((error: unknown) => {
|
||||
this.lastError = error instanceof Error ? error : new Error(String(error));
|
||||
console.error(`[SecretCache] Refresh failed: ${this.lastError.message}`);
|
||||
})
|
||||
.finally(() => {
|
||||
this.refreshInFlight = undefined;
|
||||
});
|
||||
|
||||
return this.refreshInFlight;
|
||||
}
|
||||
|
||||
get(key: string): string | undefined {
|
||||
if (!this.allowedKeys.has(key)) return undefined;
|
||||
return this.secrets.get(key);
|
||||
}
|
||||
|
||||
isAllowed(key: string): boolean {
|
||||
return this.allowedKeys.has(key);
|
||||
}
|
||||
|
||||
list(): string[] {
|
||||
return [...this.secrets.keys()].sort();
|
||||
}
|
||||
|
||||
bundle(): RawSecretMap {
|
||||
return Object.fromEntries([...this.secrets.entries()].sort(([left], [right]) => left.localeCompare(right)));
|
||||
}
|
||||
|
||||
private async fetchAndSwap(): Promise<void> {
|
||||
const fetched = await fetchInfisicalSecrets(this.options.infisical, this.options.allowlist);
|
||||
const next = new Map<string, string>();
|
||||
|
||||
for (const key of this.allowedKeys) {
|
||||
const value = fetched.raw[key];
|
||||
if (value !== undefined) next.set(key, value);
|
||||
}
|
||||
|
||||
this.secrets = next;
|
||||
this.lastError = undefined;
|
||||
this.lastRefreshAt = new Date();
|
||||
console.info(`[SecretCache] Loaded ${this.secrets.size} allowed secret(s).`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import crypto from "node:crypto";
|
||||
|
||||
export const MIN_TOKEN_TTL_SECONDS = 1;
|
||||
export const MAX_TOKEN_TTL_SECONDS = 21_600;
|
||||
|
||||
export class TokenStore {
|
||||
private readonly tokens = new Map<string, number>();
|
||||
private sweepTimer: NodeJS.Timeout | undefined;
|
||||
|
||||
constructor(private readonly sweepIntervalMs: number) {}
|
||||
|
||||
start(): void {
|
||||
if (this.sweepTimer) return;
|
||||
this.sweepTimer = setInterval(() => this.sweepExpired(), this.sweepIntervalMs);
|
||||
this.sweepTimer.unref();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (!this.sweepTimer) return;
|
||||
clearInterval(this.sweepTimer);
|
||||
this.sweepTimer = undefined;
|
||||
this.tokens.clear();
|
||||
}
|
||||
|
||||
issue(ttlSeconds: number): string {
|
||||
if (ttlSeconds < MIN_TOKEN_TTL_SECONDS || ttlSeconds > MAX_TOKEN_TTL_SECONDS) {
|
||||
throw new Error(
|
||||
`Token TTL must be between ${MIN_TOKEN_TTL_SECONDS} and ${MAX_TOKEN_TTL_SECONDS} seconds`,
|
||||
);
|
||||
}
|
||||
|
||||
const token = crypto.randomBytes(32).toString("base64url");
|
||||
this.tokens.set(token, Date.now() + ttlSeconds * 1000);
|
||||
return token;
|
||||
}
|
||||
|
||||
validate(token: string | undefined): boolean {
|
||||
if (!token) return false;
|
||||
const expiresAt = this.tokens.get(token);
|
||||
if (!expiresAt) return false;
|
||||
|
||||
if (expiresAt <= Date.now()) {
|
||||
this.tokens.delete(token);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
sweepExpired(now = Date.now()): number {
|
||||
let removed = 0;
|
||||
for (const [token, expiresAt] of this.tokens) {
|
||||
if (expiresAt > now) continue;
|
||||
this.tokens.delete(token);
|
||||
removed += 1;
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user